@ai-devkit/agent-manager 0.43.0 → 0.44.0

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 (444) hide show
  1. package/package.json +8 -3
  2. package/.swcrc +0 -27
  3. package/dist/__tests__/AgentManager.test.js +0 -1727
  4. package/dist/__tests__/AgentManager.test.js.map +0 -1
  5. package/dist/__tests__/adapters/IncrementalSessionRefresh.test.js +0 -486
  6. package/dist/__tests__/adapters/IncrementalSessionRefresh.test.js.map +0 -1
  7. package/dist/__tests__/adapters/adapterProcessImports.test.js +0 -52
  8. package/dist/__tests__/adapters/adapterProcessImports.test.js.map +0 -1
  9. package/dist/__tests__/adapters/adapterSnapshotCandidates.test.js +0 -247
  10. package/dist/__tests__/adapters/adapterSnapshotCandidates.test.js.map +0 -1
  11. package/dist/__tests__/capacity/anthropic.test.js +0 -115
  12. package/dist/__tests__/capacity/anthropic.test.js.map +0 -1
  13. package/dist/__tests__/capacity/boundaries.test.js +0 -45
  14. package/dist/__tests__/capacity/boundaries.test.js.map +0 -1
  15. package/dist/__tests__/capacity/claude.test.js +0 -485
  16. package/dist/__tests__/capacity/claude.test.js.map +0 -1
  17. package/dist/__tests__/capacity/codex.test.js +0 -339
  18. package/dist/__tests__/capacity/codex.test.js.map +0 -1
  19. package/dist/__tests__/capacity/devin.test.js +0 -239
  20. package/dist/__tests__/capacity/devin.test.js.map +0 -1
  21. package/dist/__tests__/capacity/index.test.js +0 -53
  22. package/dist/__tests__/capacity/index.test.js.map +0 -1
  23. package/dist/__tests__/capacity/openai.test.js +0 -687
  24. package/dist/__tests__/capacity/openai.test.js.map +0 -1
  25. package/dist/__tests__/capacity/wham.test.js +0 -159
  26. package/dist/__tests__/capacity/wham.test.js.map +0 -1
  27. package/dist/__tests__/capacity/zai.test.js +0 -212
  28. package/dist/__tests__/capacity/zai.test.js.map +0 -1
  29. package/dist/__tests__/fixtures.test.js +0 -218
  30. package/dist/__tests__/fixtures.test.js.map +0 -1
  31. package/dist/__tests__/harnesses/BoundedSummarySkip.test.js +0 -568
  32. package/dist/__tests__/harnesses/BoundedSummarySkip.test.js.map +0 -1
  33. package/dist/__tests__/harnesses/SessionSummaryEquivalence.test.js +0 -1089
  34. package/dist/__tests__/harnesses/SessionSummaryEquivalence.test.js.map +0 -1
  35. package/dist/__tests__/harnesses/antigravity/AntigravityCliAdapter.subprocess.test.js +0 -143
  36. package/dist/__tests__/harnesses/antigravity/AntigravityCliAdapter.subprocess.test.js.map +0 -1
  37. package/dist/__tests__/harnesses/antigravity/AntigravityCliAdapter.test.js +0 -462
  38. package/dist/__tests__/harnesses/antigravity/AntigravityCliAdapter.test.js.map +0 -1
  39. package/dist/__tests__/harnesses/builtinAdapters.test.js +0 -33
  40. package/dist/__tests__/harnesses/builtinAdapters.test.js.map +0 -1
  41. package/dist/__tests__/harnesses/claude/ClaudeAgentMapper.test.js +0 -79
  42. package/dist/__tests__/harnesses/claude/ClaudeAgentMapper.test.js.map +0 -1
  43. package/dist/__tests__/harnesses/claude/ClaudeCodeAdapter.test.js +0 -1881
  44. package/dist/__tests__/harnesses/claude/ClaudeCodeAdapter.test.js.map +0 -1
  45. package/dist/__tests__/harnesses/claude/ClaudeSessionLocator.test.js +0 -425
  46. package/dist/__tests__/harnesses/claude/ClaudeSessionLocator.test.js.map +0 -1
  47. package/dist/__tests__/harnesses/claude/ClaudeSessionParser.test.js +0 -314
  48. package/dist/__tests__/harnesses/claude/ClaudeSessionParser.test.js.map +0 -1
  49. package/dist/__tests__/harnesses/claude/durable/ClaudeCliProbe.test.js +0 -49
  50. package/dist/__tests__/harnesses/claude/durable/ClaudeCliProbe.test.js.map +0 -1
  51. package/dist/__tests__/harnesses/claude/durable/ClaudePrintAgent.integration.test.js +0 -76
  52. package/dist/__tests__/harnesses/claude/durable/ClaudePrintAgent.integration.test.js.map +0 -1
  53. package/dist/__tests__/harnesses/claude/durable/ClaudePrintAgentService.test.js +0 -173
  54. package/dist/__tests__/harnesses/claude/durable/ClaudePrintAgentService.test.js.map +0 -1
  55. package/dist/__tests__/harnesses/claude/durable/ClaudePrintRunner.test.js +0 -181
  56. package/dist/__tests__/harnesses/claude/durable/ClaudePrintRunner.test.js.map +0 -1
  57. package/dist/__tests__/harnesses/codex/CodexAdapter.test.js +0 -685
  58. package/dist/__tests__/harnesses/codex/CodexAdapter.test.js.map +0 -1
  59. package/dist/__tests__/harnesses/codex/CodexSessionLocator.test.js +0 -463
  60. package/dist/__tests__/harnesses/codex/CodexSessionLocator.test.js.map +0 -1
  61. package/dist/__tests__/harnesses/codex/CodexSessionMapping.test.js +0 -86
  62. package/dist/__tests__/harnesses/codex/CodexSessionMapping.test.js.map +0 -1
  63. package/dist/__tests__/harnesses/codex/CodexSessionParser.test.js +0 -254
  64. package/dist/__tests__/harnesses/codex/CodexSessionParser.test.js.map +0 -1
  65. package/dist/__tests__/harnesses/codex/durable/CodexCliProbe.test.js +0 -121
  66. package/dist/__tests__/harnesses/codex/durable/CodexCliProbe.test.js.map +0 -1
  67. package/dist/__tests__/harnesses/codex/durable/CodexDurableAgentRepository.test.js +0 -84
  68. package/dist/__tests__/harnesses/codex/durable/CodexDurableAgentRepository.test.js.map +0 -1
  69. package/dist/__tests__/harnesses/codex/durable/CodexPrintAgent.integration.test.js +0 -128
  70. package/dist/__tests__/harnesses/codex/durable/CodexPrintAgent.integration.test.js.map +0 -1
  71. package/dist/__tests__/harnesses/codex/durable/CodexPrintAgentService.test.js +0 -246
  72. package/dist/__tests__/harnesses/codex/durable/CodexPrintAgentService.test.js.map +0 -1
  73. package/dist/__tests__/harnesses/codex/durable/CodexPrintRunner.test.js +0 -384
  74. package/dist/__tests__/harnesses/codex/durable/CodexPrintRunner.test.js.map +0 -1
  75. package/dist/__tests__/harnesses/copilot/CopilotAdapter.test.js +0 -659
  76. package/dist/__tests__/harnesses/copilot/CopilotAdapter.test.js.map +0 -1
  77. package/dist/__tests__/harnesses/copilot/CopilotRefreshIO.test.js +0 -290
  78. package/dist/__tests__/harnesses/copilot/CopilotRefreshIO.test.js.map +0 -1
  79. package/dist/__tests__/harnesses/devin/DevinAdapter.test.js +0 -597
  80. package/dist/__tests__/harnesses/devin/DevinAdapter.test.js.map +0 -1
  81. package/dist/__tests__/harnesses/devin/DevinAgentMapper.test.js +0 -99
  82. package/dist/__tests__/harnesses/devin/DevinAgentMapper.test.js.map +0 -1
  83. package/dist/__tests__/harnesses/devin/DevinSessionLocator.test.js +0 -192
  84. package/dist/__tests__/harnesses/devin/DevinSessionLocator.test.js.map +0 -1
  85. package/dist/__tests__/harnesses/devin/DevinSessionParser.test.js +0 -407
  86. package/dist/__tests__/harnesses/devin/DevinSessionParser.test.js.map +0 -1
  87. package/dist/__tests__/harnesses/devin/fixtures.js +0 -95
  88. package/dist/__tests__/harnesses/devin/fixtures.js.map +0 -1
  89. package/dist/__tests__/harnesses/gemini/GeminiCliAdapter.test.js +0 -1454
  90. package/dist/__tests__/harnesses/gemini/GeminiCliAdapter.test.js.map +0 -1
  91. package/dist/__tests__/harnesses/gemini/GeminiSessionJsonl.test.js +0 -491
  92. package/dist/__tests__/harnesses/gemini/GeminiSessionJsonl.test.js.map +0 -1
  93. package/dist/__tests__/harnesses/gemini/GeminiSessionLocator.test.js +0 -399
  94. package/dist/__tests__/harnesses/gemini/GeminiSessionLocator.test.js.map +0 -1
  95. package/dist/__tests__/harnesses/grok/GrokAgentMapper.test.js +0 -56
  96. package/dist/__tests__/harnesses/grok/GrokAgentMapper.test.js.map +0 -1
  97. package/dist/__tests__/harnesses/grok/GrokCliAdapter.test.js +0 -421
  98. package/dist/__tests__/harnesses/grok/GrokCliAdapter.test.js.map +0 -1
  99. package/dist/__tests__/harnesses/grok/GrokIncrementalRefresh.test.js +0 -167
  100. package/dist/__tests__/harnesses/grok/GrokIncrementalRefresh.test.js.map +0 -1
  101. package/dist/__tests__/harnesses/grok/GrokSessionLocator.test.js +0 -133
  102. package/dist/__tests__/harnesses/grok/GrokSessionLocator.test.js.map +0 -1
  103. package/dist/__tests__/harnesses/grok/GrokSessionParser.test.js +0 -301
  104. package/dist/__tests__/harnesses/grok/GrokSessionParser.test.js.map +0 -1
  105. package/dist/__tests__/harnesses/kiro/KiroAdapter.test.js +0 -662
  106. package/dist/__tests__/harnesses/kiro/KiroAdapter.test.js.map +0 -1
  107. package/dist/__tests__/harnesses/muse/MuseAdapter.test.js +0 -247
  108. package/dist/__tests__/harnesses/muse/MuseAdapter.test.js.map +0 -1
  109. package/dist/__tests__/harnesses/muse/MuseAgentMapper.test.js +0 -81
  110. package/dist/__tests__/harnesses/muse/MuseAgentMapper.test.js.map +0 -1
  111. package/dist/__tests__/harnesses/muse/MuseSessionLocator.test.js +0 -185
  112. package/dist/__tests__/harnesses/muse/MuseSessionLocator.test.js.map +0 -1
  113. package/dist/__tests__/harnesses/muse/MuseSessionParser.test.js +0 -328
  114. package/dist/__tests__/harnesses/muse/MuseSessionParser.test.js.map +0 -1
  115. package/dist/__tests__/harnesses/opencode/OpenCodeAdapter.test.js +0 -213
  116. package/dist/__tests__/harnesses/opencode/OpenCodeAdapter.test.js.map +0 -1
  117. package/dist/__tests__/harnesses/opencode/OpenCodeAgentMapper.test.js +0 -108
  118. package/dist/__tests__/harnesses/opencode/OpenCodeAgentMapper.test.js.map +0 -1
  119. package/dist/__tests__/harnesses/opencode/OpenCodeSessionLocator.test.js +0 -94
  120. package/dist/__tests__/harnesses/opencode/OpenCodeSessionLocator.test.js.map +0 -1
  121. package/dist/__tests__/harnesses/opencode/OpenCodeSessionParser.test.js +0 -147
  122. package/dist/__tests__/harnesses/opencode/OpenCodeSessionParser.test.js.map +0 -1
  123. package/dist/__tests__/harnesses/pi/PiAdapter.test.js +0 -367
  124. package/dist/__tests__/harnesses/pi/PiAdapter.test.js.map +0 -1
  125. package/dist/__tests__/harnesses/pi/PiDiscoveryIO.test.js +0 -382
  126. package/dist/__tests__/harnesses/pi/PiDiscoveryIO.test.js.map +0 -1
  127. package/dist/__tests__/harnesses/pi/PiSessionParser.test.js +0 -416
  128. package/dist/__tests__/harnesses/pi/PiSessionParser.test.js.map +0 -1
  129. package/dist/__tests__/harnesses/pi/PiSessionTracker.test.js +0 -108
  130. package/dist/__tests__/harnesses/pi/PiSessionTracker.test.js.map +0 -1
  131. package/dist/__tests__/harnesses/pi/durable/PiCliProbe.test.js +0 -70
  132. package/dist/__tests__/harnesses/pi/durable/PiCliProbe.test.js.map +0 -1
  133. package/dist/__tests__/harnesses/pi/durable/PiDurableAgentRepository.test.js +0 -43
  134. package/dist/__tests__/harnesses/pi/durable/PiDurableAgentRepository.test.js.map +0 -1
  135. package/dist/__tests__/harnesses/pi/durable/PiPrintAgentService.test.js +0 -192
  136. package/dist/__tests__/harnesses/pi/durable/PiPrintAgentService.test.js.map +0 -1
  137. package/dist/__tests__/harnesses/pi/durable/PiPrintProtocol.test.js +0 -119
  138. package/dist/__tests__/harnesses/pi/durable/PiPrintProtocol.test.js.map +0 -1
  139. package/dist/__tests__/harnesses/pi/durable/PiPrintRunner.test.js +0 -382
  140. package/dist/__tests__/harnesses/pi/durable/PiPrintRunner.test.js.map +0 -1
  141. package/dist/__tests__/harnesses/pi/durable/PiStreamParser.test.js +0 -34
  142. package/dist/__tests__/harnesses/pi/durable/PiStreamParser.test.js.map +0 -1
  143. package/dist/__tests__/harnesses/readiness/AgentReadiness.test.js +0 -446
  144. package/dist/__tests__/harnesses/readiness/AgentReadiness.test.js.map +0 -1
  145. package/dist/__tests__/harnesses/runtimeProfiles.test.js +0 -101
  146. package/dist/__tests__/harnesses/runtimeProfiles.test.js.map +0 -1
  147. package/dist/__tests__/print/DurableAgent.test.js +0 -15
  148. package/dist/__tests__/print/DurableAgent.test.js.map +0 -1
  149. package/dist/__tests__/print/DurableAgentRepository.sqlite.test.js +0 -186
  150. package/dist/__tests__/print/DurableAgentRepository.sqlite.test.js.map +0 -1
  151. package/dist/__tests__/print/DurableAgentRepository.test.js +0 -249
  152. package/dist/__tests__/print/DurableAgentRepository.test.js.map +0 -1
  153. package/dist/__tests__/readiness-fixtures.test.js +0 -54
  154. package/dist/__tests__/readiness-fixtures.test.js.map +0 -1
  155. package/dist/__tests__/runtime/AgentRuntime.test.js +0 -13
  156. package/dist/__tests__/runtime/AgentRuntime.test.js.map +0 -1
  157. package/dist/__tests__/runtime/HerdrAgentDiscovery.test.js +0 -164
  158. package/dist/__tests__/runtime/HerdrAgentDiscovery.test.js.map +0 -1
  159. package/dist/__tests__/runtime/HerdrAgentRuntime.test.js +0 -488
  160. package/dist/__tests__/runtime/HerdrAgentRuntime.test.js.map +0 -1
  161. package/dist/__tests__/runtime/ManagedAgentRuntime.test.js +0 -637
  162. package/dist/__tests__/runtime/ManagedAgentRuntime.test.js.map +0 -1
  163. package/dist/__tests__/terminal/GhosttyBackend.test.js +0 -334
  164. package/dist/__tests__/terminal/GhosttyBackend.test.js.map +0 -1
  165. package/dist/__tests__/terminal/TerminalFocusManager.test.js +0 -253
  166. package/dist/__tests__/terminal/TerminalFocusManager.test.js.map +0 -1
  167. package/dist/__tests__/terminal/TmuxManager.test.js +0 -168
  168. package/dist/__tests__/terminal/TmuxManager.test.js.map +0 -1
  169. package/dist/__tests__/terminal/TtyWriter.test.js +0 -386
  170. package/dist/__tests__/terminal/TtyWriter.test.js.map +0 -1
  171. package/dist/__tests__/utils/AgentRegistry.test.js +0 -636
  172. package/dist/__tests__/utils/AgentRegistry.test.js.map +0 -1
  173. package/dist/__tests__/utils/IncrementalJsonlSummary.test.js +0 -650
  174. package/dist/__tests__/utils/IncrementalJsonlSummary.test.js.map +0 -1
  175. package/dist/__tests__/utils/agent-requests.test.js +0 -90
  176. package/dist/__tests__/utils/agent-requests.test.js.map +0 -1
  177. package/dist/__tests__/utils/conversationTail.bench.test.js +0 -258
  178. package/dist/__tests__/utils/conversationTail.bench.test.js.map +0 -1
  179. package/dist/__tests__/utils/conversationTailParity.test.js +0 -588
  180. package/dist/__tests__/utils/conversationTailParity.test.js.map +0 -1
  181. package/dist/__tests__/utils/jsonlTail.test.js +0 -360
  182. package/dist/__tests__/utils/jsonlTail.test.js.map +0 -1
  183. package/dist/__tests__/utils/matching.test.js +0 -324
  184. package/dist/__tests__/utils/matching.test.js.map +0 -1
  185. package/dist/__tests__/utils/matchingConstants.test.js +0 -35
  186. package/dist/__tests__/utils/matchingConstants.test.js.map +0 -1
  187. package/dist/__tests__/utils/process.test.js +0 -818
  188. package/dist/__tests__/utils/process.test.js.map +0 -1
  189. package/dist/__tests__/utils/session.test.js +0 -175
  190. package/dist/__tests__/utils/session.test.js.map +0 -1
  191. package/project.json +0 -29
  192. package/scripts/benchmark-cold-start.mjs +0 -350
  193. package/src/AgentManager.ts +0 -559
  194. package/src/__tests__/AgentManager.test.ts +0 -1578
  195. package/src/__tests__/adapters/IncrementalSessionRefresh.test.ts +0 -437
  196. package/src/__tests__/adapters/adapterProcessImports.test.ts +0 -58
  197. package/src/__tests__/adapters/adapterSnapshotCandidates.test.ts +0 -243
  198. package/src/__tests__/capacity/anthropic.test.ts +0 -105
  199. package/src/__tests__/capacity/boundaries.test.ts +0 -36
  200. package/src/__tests__/capacity/claude.test.ts +0 -462
  201. package/src/__tests__/capacity/codex.test.ts +0 -311
  202. package/src/__tests__/capacity/devin.test.ts +0 -210
  203. package/src/__tests__/capacity/fixtures/claude-credentials.json +0 -7
  204. package/src/__tests__/capacity/fixtures/claude-usage-malformed.json +0 -1
  205. package/src/__tests__/capacity/fixtures/claude-usage-partial.json +0 -15
  206. package/src/__tests__/capacity/fixtures/claude-usage.json +0 -63
  207. package/src/__tests__/capacity/fixtures/devin-config.json +0 -6
  208. package/src/__tests__/capacity/fixtures/devin-credentials.toml +0 -4
  209. package/src/__tests__/capacity/fixtures/devin-quota-nonplan.json +0 -5
  210. package/src/__tests__/capacity/fixtures/devin-quota.json +0 -10
  211. package/src/__tests__/capacity/fixtures/openai-auth.json +0 -6
  212. package/src/__tests__/capacity/fixtures/openai-codex-auth.json +0 -9
  213. package/src/__tests__/capacity/fixtures/openai-usage-completions.json +0 -67
  214. package/src/__tests__/capacity/fixtures/openai-usage-responses.json +0 -20
  215. package/src/__tests__/capacity/fixtures/wham-usage.json +0 -45
  216. package/src/__tests__/capacity/fixtures/zai-auth.json +0 -6
  217. package/src/__tests__/capacity/fixtures/zai-quota-invalid.json +0 -7
  218. package/src/__tests__/capacity/fixtures/zai-quota.json +0 -38
  219. package/src/__tests__/capacity/index.test.ts +0 -54
  220. package/src/__tests__/capacity/openai.test.ts +0 -571
  221. package/src/__tests__/capacity/wham.test.ts +0 -122
  222. package/src/__tests__/capacity/zai.test.ts +0 -151
  223. package/src/__tests__/fixtures.test.ts +0 -245
  224. package/src/__tests__/harnesses/BoundedSummarySkip.test.ts +0 -496
  225. package/src/__tests__/harnesses/SessionSummaryEquivalence.test.ts +0 -726
  226. package/src/__tests__/harnesses/antigravity/AntigravityCliAdapter.subprocess.test.ts +0 -133
  227. package/src/__tests__/harnesses/antigravity/AntigravityCliAdapter.test.ts +0 -396
  228. package/src/__tests__/harnesses/builtinAdapters.test.ts +0 -33
  229. package/src/__tests__/harnesses/claude/ClaudeAgentMapper.test.ts +0 -84
  230. package/src/__tests__/harnesses/claude/ClaudeCodeAdapter.test.ts +0 -1793
  231. package/src/__tests__/harnesses/claude/ClaudeSessionLocator.test.ts +0 -423
  232. package/src/__tests__/harnesses/claude/ClaudeSessionParser.test.ts +0 -300
  233. package/src/__tests__/harnesses/claude/durable/ClaudeCliProbe.test.ts +0 -34
  234. package/src/__tests__/harnesses/claude/durable/ClaudePrintAgent.integration.test.ts +0 -61
  235. package/src/__tests__/harnesses/claude/durable/ClaudePrintAgentService.test.ts +0 -129
  236. package/src/__tests__/harnesses/claude/durable/ClaudePrintRunner.test.ts +0 -152
  237. package/src/__tests__/harnesses/codex/CodexAdapter.test.ts +0 -652
  238. package/src/__tests__/harnesses/codex/CodexSessionLocator.test.ts +0 -419
  239. package/src/__tests__/harnesses/codex/CodexSessionMapping.test.ts +0 -63
  240. package/src/__tests__/harnesses/codex/CodexSessionParser.test.ts +0 -192
  241. package/src/__tests__/harnesses/codex/durable/CodexCliProbe.test.ts +0 -80
  242. package/src/__tests__/harnesses/codex/durable/CodexDurableAgentRepository.test.ts +0 -65
  243. package/src/__tests__/harnesses/codex/durable/CodexPrintAgent.integration.test.ts +0 -104
  244. package/src/__tests__/harnesses/codex/durable/CodexPrintAgentService.test.ts +0 -201
  245. package/src/__tests__/harnesses/codex/durable/CodexPrintRunner.test.ts +0 -299
  246. package/src/__tests__/harnesses/copilot/CopilotAdapter.test.ts +0 -614
  247. package/src/__tests__/harnesses/copilot/CopilotRefreshIO.test.ts +0 -270
  248. package/src/__tests__/harnesses/devin/DevinAdapter.test.ts +0 -290
  249. package/src/__tests__/harnesses/devin/DevinAgentMapper.test.ts +0 -101
  250. package/src/__tests__/harnesses/devin/DevinSessionLocator.test.ts +0 -139
  251. package/src/__tests__/harnesses/devin/DevinSessionParser.test.ts +0 -212
  252. package/src/__tests__/harnesses/devin/fixtures.ts +0 -144
  253. package/src/__tests__/harnesses/gemini/GeminiCliAdapter.test.ts +0 -1336
  254. package/src/__tests__/harnesses/gemini/GeminiSessionJsonl.test.ts +0 -402
  255. package/src/__tests__/harnesses/gemini/GeminiSessionLocator.test.ts +0 -396
  256. package/src/__tests__/harnesses/grok/GrokAgentMapper.test.ts +0 -57
  257. package/src/__tests__/harnesses/grok/GrokCliAdapter.test.ts +0 -376
  258. package/src/__tests__/harnesses/grok/GrokIncrementalRefresh.test.ts +0 -170
  259. package/src/__tests__/harnesses/grok/GrokSessionLocator.test.ts +0 -106
  260. package/src/__tests__/harnesses/grok/GrokSessionParser.test.ts +0 -230
  261. package/src/__tests__/harnesses/kiro/KiroAdapter.test.ts +0 -552
  262. package/src/__tests__/harnesses/muse/MuseAdapter.test.ts +0 -197
  263. package/src/__tests__/harnesses/muse/MuseAgentMapper.test.ts +0 -83
  264. package/src/__tests__/harnesses/muse/MuseSessionLocator.test.ts +0 -177
  265. package/src/__tests__/harnesses/muse/MuseSessionParser.test.ts +0 -279
  266. package/src/__tests__/harnesses/opencode/OpenCodeAdapter.test.ts +0 -215
  267. package/src/__tests__/harnesses/opencode/OpenCodeAgentMapper.test.ts +0 -101
  268. package/src/__tests__/harnesses/opencode/OpenCodeSessionLocator.test.ts +0 -84
  269. package/src/__tests__/harnesses/opencode/OpenCodeSessionParser.test.ts +0 -149
  270. package/src/__tests__/harnesses/pi/PiAdapter.test.ts +0 -325
  271. package/src/__tests__/harnesses/pi/PiDiscoveryIO.test.ts +0 -337
  272. package/src/__tests__/harnesses/pi/PiSessionParser.test.ts +0 -280
  273. package/src/__tests__/harnesses/pi/PiSessionTracker.test.ts +0 -79
  274. package/src/__tests__/harnesses/pi/durable/PiCliProbe.test.ts +0 -50
  275. package/src/__tests__/harnesses/pi/durable/PiDurableAgentRepository.test.ts +0 -33
  276. package/src/__tests__/harnesses/pi/durable/PiPrintAgentService.test.ts +0 -138
  277. package/src/__tests__/harnesses/pi/durable/PiPrintProtocol.test.ts +0 -71
  278. package/src/__tests__/harnesses/pi/durable/PiPrintRunner.test.ts +0 -252
  279. package/src/__tests__/harnesses/pi/durable/PiStreamParser.test.ts +0 -26
  280. package/src/__tests__/harnesses/readiness/AgentReadiness.test.ts +0 -362
  281. package/src/__tests__/harnesses/runtimeProfiles.test.ts +0 -123
  282. package/src/__tests__/print/DurableAgent.test.ts +0 -15
  283. package/src/__tests__/print/DurableAgentRepository.sqlite.test.ts +0 -128
  284. package/src/__tests__/print/DurableAgentRepository.test.ts +0 -184
  285. package/src/__tests__/readiness-fixtures.test.ts +0 -79
  286. package/src/__tests__/runtime/AgentRuntime.test.ts +0 -8
  287. package/src/__tests__/runtime/HerdrAgentDiscovery.test.ts +0 -131
  288. package/src/__tests__/runtime/HerdrAgentRuntime.test.ts +0 -377
  289. package/src/__tests__/runtime/ManagedAgentRuntime.test.ts +0 -590
  290. package/src/__tests__/terminal/GhosttyBackend.test.ts +0 -271
  291. package/src/__tests__/terminal/TerminalFocusManager.test.ts +0 -280
  292. package/src/__tests__/terminal/TmuxManager.test.ts +0 -185
  293. package/src/__tests__/terminal/TtyWriter.test.ts +0 -454
  294. package/src/__tests__/utils/AgentRegistry.test.ts +0 -532
  295. package/src/__tests__/utils/IncrementalJsonlSummary.test.ts +0 -414
  296. package/src/__tests__/utils/agent-requests.test.ts +0 -94
  297. package/src/__tests__/utils/conversationTail.bench.test.ts +0 -193
  298. package/src/__tests__/utils/conversationTailParity.test.ts +0 -365
  299. package/src/__tests__/utils/jsonlTail.test.ts +0 -317
  300. package/src/__tests__/utils/matching.test.ts +0 -234
  301. package/src/__tests__/utils/matchingConstants.test.ts +0 -40
  302. package/src/__tests__/utils/process.test.ts +0 -596
  303. package/src/__tests__/utils/session.test.ts +0 -158
  304. package/src/adapters/AgentAdapter.ts +0 -255
  305. package/src/capacity/index.ts +0 -127
  306. package/src/capacity/providers/anthropic.ts +0 -198
  307. package/src/capacity/providers/devin.ts +0 -121
  308. package/src/capacity/providers/openai-platform.ts +0 -150
  309. package/src/capacity/providers/openai-subscription.ts +0 -184
  310. package/src/capacity/providers/zai.ts +0 -155
  311. package/src/capacity/sources/claude.ts +0 -30
  312. package/src/capacity/sources/codex.ts +0 -251
  313. package/src/capacity/sources/devin.ts +0 -49
  314. package/src/capacity/sources/pi.ts +0 -131
  315. package/src/capacity/types.ts +0 -29
  316. package/src/database/connection.ts +0 -96
  317. package/src/database/index.ts +0 -7
  318. package/src/database/migrations/001_initial.sql +0 -12
  319. package/src/database/migrations/002_pins.sql +0 -1
  320. package/src/database/migrations/003_durable_agents.sql +0 -43
  321. package/src/database/migrations/004_codex_durable_sessions.sql +0 -1
  322. package/src/database/migrations/005_agent_runtime.sql +0 -2
  323. package/src/database/schema.ts +0 -64
  324. package/src/durable/DurableAgent.ts +0 -139
  325. package/src/durable/DurableAgentRepository.ts +0 -485
  326. package/src/durable/process.ts +0 -29
  327. package/src/durable/run.ts +0 -84
  328. package/src/durable/utils.ts +0 -66
  329. package/src/fixtures/bundle.ts +0 -130
  330. package/src/fixtures/capture.ts +0 -364
  331. package/src/harnesses/antigravity/AntigravityAgentMapper.ts +0 -34
  332. package/src/harnesses/antigravity/AntigravityCliAdapter.ts +0 -126
  333. package/src/harnesses/antigravity/AntigravitySessionLocator.ts +0 -75
  334. package/src/harnesses/antigravity/AntigravitySessionParser.ts +0 -252
  335. package/src/harnesses/claude/ClaudeAgentMapper.ts +0 -55
  336. package/src/harnesses/claude/ClaudeCodeAdapter.ts +0 -175
  337. package/src/harnesses/claude/ClaudeSessionLocator.ts +0 -358
  338. package/src/harnesses/claude/ClaudeSessionParser.ts +0 -524
  339. package/src/harnesses/claude/credentials.ts +0 -122
  340. package/src/harnesses/claude/durable/ClaudeCliProbe.ts +0 -57
  341. package/src/harnesses/claude/durable/ClaudePrintAgentService.ts +0 -79
  342. package/src/harnesses/claude/durable/ClaudePrintRunner.ts +0 -102
  343. package/src/harnesses/claude/durable/ClaudeStreamParser.ts +0 -108
  344. package/src/harnesses/claude/readiness.ts +0 -69
  345. package/src/harnesses/codex/CodexAdapter.ts +0 -337
  346. package/src/harnesses/codex/CodexAgentMapper.ts +0 -26
  347. package/src/harnesses/codex/CodexSessionLocator.ts +0 -509
  348. package/src/harnesses/codex/CodexSessionMapping.ts +0 -89
  349. package/src/harnesses/codex/CodexSessionParser.ts +0 -462
  350. package/src/harnesses/codex/credentials.ts +0 -81
  351. package/src/harnesses/codex/durable/CodexCliProbe.ts +0 -68
  352. package/src/harnesses/codex/durable/CodexPrintAgentService.ts +0 -79
  353. package/src/harnesses/codex/durable/CodexPrintRunner.ts +0 -104
  354. package/src/harnesses/codex/durable/CodexStreamParser.ts +0 -117
  355. package/src/harnesses/codex/readiness.ts +0 -72
  356. package/src/harnesses/copilot/CopilotAdapter.ts +0 -161
  357. package/src/harnesses/copilot/CopilotAgentMapper.ts +0 -27
  358. package/src/harnesses/copilot/CopilotSessionLocator.ts +0 -161
  359. package/src/harnesses/copilot/CopilotSessionParser.ts +0 -380
  360. package/src/harnesses/copilot/readiness.ts +0 -33
  361. package/src/harnesses/devin/DevinAdapter.ts +0 -212
  362. package/src/harnesses/devin/DevinAgentMapper.ts +0 -39
  363. package/src/harnesses/devin/DevinSessionLocator.ts +0 -230
  364. package/src/harnesses/devin/DevinSessionParser.ts +0 -227
  365. package/src/harnesses/devin/credentials.ts +0 -88
  366. package/src/harnesses/devin/readiness.ts +0 -36
  367. package/src/harnesses/gemini/GeminiAgentMapper.ts +0 -27
  368. package/src/harnesses/gemini/GeminiCliAdapter.ts +0 -272
  369. package/src/harnesses/gemini/GeminiSessionLocator.ts +0 -394
  370. package/src/harnesses/gemini/GeminiSessionParser.ts +0 -395
  371. package/src/harnesses/gemini/fileSignature.ts +0 -10
  372. package/src/harnesses/grok/GrokAgentMapper.ts +0 -32
  373. package/src/harnesses/grok/GrokCliAdapter.ts +0 -126
  374. package/src/harnesses/grok/GrokSessionLocator.ts +0 -179
  375. package/src/harnesses/grok/GrokSessionParser.ts +0 -251
  376. package/src/harnesses/index.ts +0 -32
  377. package/src/harnesses/kiro/KiroAdapter.ts +0 -143
  378. package/src/harnesses/kiro/KiroAgentMapper.ts +0 -34
  379. package/src/harnesses/kiro/KiroSessionLocator.ts +0 -143
  380. package/src/harnesses/kiro/KiroSessionParser.ts +0 -376
  381. package/src/harnesses/muse/MuseAdapter.ts +0 -157
  382. package/src/harnesses/muse/MuseAgentMapper.ts +0 -33
  383. package/src/harnesses/muse/MuseSessionLocator.ts +0 -286
  384. package/src/harnesses/muse/MuseSessionParser.ts +0 -435
  385. package/src/harnesses/muse/readiness.ts +0 -38
  386. package/src/harnesses/opencode/OpenCodeAdapter.ts +0 -110
  387. package/src/harnesses/opencode/OpenCodeAgentMapper.ts +0 -49
  388. package/src/harnesses/opencode/OpenCodeSessionLocator.ts +0 -151
  389. package/src/harnesses/opencode/OpenCodeSessionParser.ts +0 -146
  390. package/src/harnesses/opencode/readiness.ts +0 -48
  391. package/src/harnesses/pi/PiAdapter.ts +0 -197
  392. package/src/harnesses/pi/PiAgentMapper.ts +0 -27
  393. package/src/harnesses/pi/PiSessionLocator.ts +0 -288
  394. package/src/harnesses/pi/PiSessionParser.ts +0 -488
  395. package/src/harnesses/pi/PiSessionTracker.ts +0 -87
  396. package/src/harnesses/pi/credentials.ts +0 -129
  397. package/src/harnesses/pi/durable/PiCliProbe.ts +0 -56
  398. package/src/harnesses/pi/durable/PiPrintAgentService.ts +0 -77
  399. package/src/harnesses/pi/durable/PiPrintProtocol.ts +0 -41
  400. package/src/harnesses/pi/durable/PiPrintRunner.ts +0 -95
  401. package/src/harnesses/pi/durable/PiStreamParser.ts +0 -94
  402. package/src/harnesses/pi/readiness.ts +0 -104
  403. package/src/harnesses/readiness/AgentReadiness.ts +0 -91
  404. package/src/harnesses/readiness/checks.ts +0 -336
  405. package/src/harnesses/readiness/types.ts +0 -90
  406. package/src/harnesses/runtimeProfiles.ts +0 -105
  407. package/src/harnesses/shared.ts +0 -124
  408. package/src/index.ts +0 -71
  409. package/src/runtime/ManagedAgentRuntime.ts +0 -253
  410. package/src/runtime/RuntimeFactory.ts +0 -13
  411. package/src/runtime/errors.ts +0 -50
  412. package/src/runtime/herdr/HerdrAgentDiscovery.ts +0 -166
  413. package/src/runtime/herdr/HerdrAgentRuntime.ts +0 -216
  414. package/src/runtime/herdr/HerdrCliClient.ts +0 -78
  415. package/src/runtime/herdr/HerdrErrors.ts +0 -9
  416. package/src/runtime/herdr/HerdrResponseParsers.ts +0 -86
  417. package/src/runtime/herdr/HerdrRuntimeRef.ts +0 -41
  418. package/src/runtime/tmux/PidPolling.ts +0 -34
  419. package/src/runtime/tmux/TmuxAgentRuntime.ts +0 -113
  420. package/src/runtime/tmux/TmuxManager.ts +0 -102
  421. package/src/runtime/tmux/TmuxRuntimeRef.ts +0 -9
  422. package/src/runtime/types.ts +0 -56
  423. package/src/terminal/TerminalFocusManager.ts +0 -52
  424. package/src/terminal/TtyWriter.ts +0 -26
  425. package/src/terminal/backends/ghostty.ts +0 -180
  426. package/src/terminal/backends/index.ts +0 -23
  427. package/src/terminal/backends/iterm2.ts +0 -126
  428. package/src/terminal/backends/shared.ts +0 -47
  429. package/src/terminal/backends/terminal-app.ts +0 -122
  430. package/src/terminal/backends/tmux.ts +0 -62
  431. package/src/terminal/backends/wezterm.ts +0 -65
  432. package/src/terminal/types.ts +0 -23
  433. package/src/utils/AgentRegistry.ts +0 -351
  434. package/src/utils/IncrementalJsonlSummary.ts +0 -306
  435. package/src/utils/agent-requests.ts +0 -28
  436. package/src/utils/applescript.ts +0 -10
  437. package/src/utils/jsonlTail.ts +0 -349
  438. package/src/utils/matching.ts +0 -96
  439. package/src/utils/matchingConstants.ts +0 -15
  440. package/src/utils/process.ts +0 -604
  441. package/src/utils/session.ts +0 -144
  442. package/src/utils/sortAgents.ts +0 -54
  443. package/tsconfig.json +0 -11
  444. package/vitest.config.ts +0 -20
@@ -1,1793 +0,0 @@
1
- /**
2
- * Tests for ClaudeCodeAdapter
3
- */
4
-
5
- import type { MockedFunction } from "vitest";
6
- import * as fs from "fs";
7
- import * as path from "path";
8
-
9
- import { ClaudeCodeAdapter } from "../../../harnesses/claude/ClaudeCodeAdapter.js";
10
- import type { ProcessInfo } from "../../../adapters/AgentAdapter.js";
11
- import { AgentStatus } from "../../../adapters/AgentAdapter.js";
12
- import {
13
- listAgentProcesses,
14
- enrichProcesses,
15
- captureProcessSnapshot,
16
- } from "../../../utils/process.js";
17
- import { batchGetSessionFileBirthtimes } from "../../../utils/session.js";
18
- import type { SessionFile } from "../../../utils/session.js";
19
- import { matchProcessesToSessions, generateAgentName } from "../../../utils/matching.js";
20
- import type { MatchResult } from "../../../utils/matching.js";
21
- import * as os from "os";
22
- vi.mock("../../../utils/process.js", async (importOriginal) => {
23
- const actual = (await importOriginal()) as typeof import("../../../utils/process.js");
24
- return {
25
- ...actual,
26
- listAgentProcesses: vi.fn(),
27
- enrichProcesses: vi.fn(),
28
- captureProcessSnapshot: vi.fn(),
29
- };
30
- });
31
-
32
- vi.mock("../../../utils/session.js", async () => {
33
- const actual = (await vi.importActual(
34
- "../../../utils/session",
35
- )) as typeof import("../../../utils/session");
36
- return {
37
- ...actual,
38
- batchGetSessionFileBirthtimes: vi.fn(),
39
- };
40
- });
41
-
42
- vi.mock("../../../utils/matching.js", () => ({
43
- matchProcessesToSessions: vi.fn(),
44
- generateAgentName: vi.fn(),
45
- }));
46
-
47
- const mockedListAgentProcesses = listAgentProcesses as MockedFunction<typeof listAgentProcesses>;
48
- const mockedEnrichProcesses = enrichProcesses as MockedFunction<typeof enrichProcesses>;
49
- const mockedCaptureProcessSnapshot = captureProcessSnapshot as MockedFunction<
50
- typeof captureProcessSnapshot
51
- >;
52
- const mockedBatchGetSessionFileBirthtimes = batchGetSessionFileBirthtimes as MockedFunction<
53
- typeof batchGetSessionFileBirthtimes
54
- >;
55
- const mockedMatchProcessesToSessions = matchProcessesToSessions as MockedFunction<
56
- typeof matchProcessesToSessions
57
- >;
58
- const mockedGenerateAgentName = generateAgentName as MockedFunction<typeof generateAgentName>;
59
- describe("ClaudeCodeAdapter", () => {
60
- let adapter: ClaudeCodeAdapter;
61
-
62
- beforeEach(() => {
63
- adapter = new ClaudeCodeAdapter();
64
- mockedListAgentProcesses.mockReset();
65
- mockedEnrichProcesses.mockReset();
66
- mockedCaptureProcessSnapshot.mockReset();
67
- mockedBatchGetSessionFileBirthtimes.mockReset();
68
- mockedMatchProcessesToSessions.mockReset();
69
- mockedGenerateAgentName.mockReset();
70
- // Default: enrichProcesses returns what it receives
71
- mockedEnrichProcesses.mockImplementation((procs) => procs);
72
- // Compatibility shim for standalone adapter discovery; the manager captures once and slices by name.
73
- mockedCaptureProcessSnapshot.mockImplementation(async (names) =>
74
- enrichProcesses(names.flatMap((name) => listAgentProcesses(name))),
75
- );
76
- // Default: generateAgentName returns "folder (pid)"
77
- mockedGenerateAgentName.mockImplementation((cwd, pid) => {
78
- const folder = path.basename(cwd) || "unknown";
79
- return `${folder} (${pid})`;
80
- });
81
- });
82
-
83
- describe("initialization", () => {
84
- it("should create adapter with correct type", () => {
85
- expect(adapter.type).toBe("claude");
86
- });
87
- });
88
-
89
- describe("canHandle", () => {
90
- it("should return true for claude processes", () => {
91
- const processInfo = {
92
- pid: 12345,
93
- command: "claude",
94
- cwd: "/test",
95
- tty: "ttys001",
96
- };
97
-
98
- expect(adapter.canHandle(processInfo)).toBe(true);
99
- });
100
-
101
- it("should return true for claude executable with full path", () => {
102
- const processInfo = {
103
- pid: 12345,
104
- command: "/usr/local/bin/claude --some-flag",
105
- cwd: "/test",
106
- tty: "ttys001",
107
- };
108
-
109
- expect(adapter.canHandle(processInfo)).toBe(true);
110
- });
111
-
112
- it("should return true for CLAUDE (case-insensitive)", () => {
113
- const processInfo = {
114
- pid: 12345,
115
- command: "/usr/local/bin/CLAUDE --continue",
116
- cwd: "/test",
117
- tty: "ttys001",
118
- };
119
-
120
- expect(adapter.canHandle(processInfo)).toBe(true);
121
- });
122
-
123
- it("should return false for non-claude processes", () => {
124
- const processInfo = {
125
- pid: 12345,
126
- command: "node",
127
- cwd: "/test",
128
- tty: "ttys001",
129
- };
130
-
131
- expect(adapter.canHandle(processInfo)).toBe(false);
132
- });
133
-
134
- it("should return true for claude installed under a path containing spaces", () => {
135
- const root = fs.mkdtempSync(path.join(os.tmpdir(), "claude-spaces-"));
136
- try {
137
- const executable = path.join(root, "Applications", "Some App.app", "Contents", "claude");
138
- fs.mkdirSync(path.dirname(executable), { recursive: true });
139
- fs.writeFileSync(executable, "");
140
-
141
- expect(
142
- adapter.canHandle({
143
- pid: 12345,
144
- command: `${executable} --resume abc --append-system-prompt be brief/codex`,
145
- cwd: "/test",
146
- tty: "ttys001",
147
- }),
148
- ).toBe(true);
149
- } finally {
150
- fs.rmSync(root, { recursive: true, force: true });
151
- }
152
- });
153
-
154
- it("should return false when claude only appears in an argument containing spaces", () => {
155
- expect(
156
- adapter.canHandle({
157
- pid: 12345,
158
- command: "/usr/bin/vim My Notes/claude",
159
- cwd: "/test",
160
- tty: "ttys001",
161
- }),
162
- ).toBe(false);
163
- });
164
-
165
- it('should return false for processes with "claude" only in path arguments', () => {
166
- const processInfo = {
167
- pid: 12345,
168
- command: "/usr/local/bin/node /path/to/claude-worktree/node_modules/nx/start.js",
169
- cwd: "/test",
170
- tty: "ttys001",
171
- };
172
-
173
- expect(adapter.canHandle(processInfo)).toBe(false);
174
- });
175
- });
176
-
177
- describe("detectAgents", () => {
178
- it("should return empty array if no claude processes running", async () => {
179
- mockedListAgentProcesses.mockReturnValue([]);
180
-
181
- const agents = await adapter.detectAgents();
182
- expect(agents).toEqual([]);
183
- expect(mockedListAgentProcesses).toHaveBeenCalledWith("claude");
184
- });
185
-
186
- it("should return process-only agents when no sessions discovered", async () => {
187
- const processes: ProcessInfo[] = [
188
- { pid: 777, command: "claude", cwd: "/project/app", tty: "ttys001" },
189
- ];
190
- mockedListAgentProcesses.mockReturnValue(processes);
191
- mockedEnrichProcesses.mockReturnValue(processes);
192
-
193
- // No projects dir → discoverSessions returns []
194
- (adapter as any).projectsDir = "/nonexistent/path";
195
-
196
- const agents = await adapter.detectAgents();
197
- expect(agents).toHaveLength(1);
198
- expect(agents[0]).toMatchObject({
199
- type: "claude",
200
- status: AgentStatus.RUNNING,
201
- pid: 777,
202
- projectPath: "/project/app",
203
- sessionId: "pid-777",
204
- summary: "Claude Code process running",
205
- });
206
- });
207
-
208
- it("should detect agents with matched sessions", async () => {
209
- const processes: ProcessInfo[] = [
210
- {
211
- pid: 12345,
212
- command: "claude",
213
- cwd: "/Users/test/my-project",
214
- tty: "ttys001",
215
- startTime: new Date("2026-03-18T23:18:01.000Z"),
216
- },
217
- ];
218
- mockedListAgentProcesses.mockReturnValue(processes);
219
- mockedEnrichProcesses.mockReturnValue(processes);
220
-
221
- // Set up projects dir with encoded directory name
222
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "claude-test-"));
223
- const projectsDir = path.join(tmpDir, "projects");
224
- // Claude encodes /Users/test/my-project → -Users-test-my-project
225
- const projDir = path.join(projectsDir, "-Users-test-my-project");
226
- fs.mkdirSync(projDir, { recursive: true });
227
-
228
- // Create session file
229
- const sessionFile = path.join(projDir, "session-1.jsonl");
230
- fs.writeFileSync(
231
- sessionFile,
232
- [
233
- JSON.stringify({
234
- type: "user",
235
- timestamp: "2026-03-18T23:18:44Z",
236
- cwd: "/Users/test/my-project",
237
- message: { content: "Investigate failing tests" },
238
- }),
239
- JSON.stringify({ type: "assistant", timestamp: "2026-03-18T23:19:00Z" }),
240
- ].join("\n"),
241
- );
242
-
243
- (adapter as any).projectsDir = projectsDir;
244
-
245
- const sessionFiles: SessionFile[] = [
246
- {
247
- sessionId: "session-1",
248
- filePath: sessionFile,
249
- projectDir: projDir,
250
- birthtimeMs: new Date("2026-03-18T23:18:44Z").getTime(),
251
- resolvedCwd: "",
252
- },
253
- ];
254
- mockedBatchGetSessionFileBirthtimes.mockReturnValue(sessionFiles);
255
-
256
- const matches: MatchResult[] = [
257
- {
258
- process: processes[0],
259
- session: { ...sessionFiles[0], resolvedCwd: "/Users/test/my-project" },
260
- deltaMs: 43000,
261
- },
262
- ];
263
- mockedMatchProcessesToSessions.mockReturnValue(matches);
264
-
265
- const agents = await adapter.detectAgents();
266
-
267
- expect(agents).toHaveLength(1);
268
- expect(agents[0]).toMatchObject({
269
- type: "claude",
270
- status: AgentStatus.WAITING,
271
- pid: 12345,
272
- projectPath: "/Users/test/my-project",
273
- sessionId: "session-1",
274
- });
275
- expect(agents[0].summary).toContain("Investigate failing tests");
276
-
277
- fs.rmSync(tmpDir, { recursive: true, force: true });
278
- });
279
-
280
- it("should fall back to process-only for unmatched processes", async () => {
281
- const processes: ProcessInfo[] = [
282
- { pid: 100, command: "claude", cwd: "/project-a", tty: "ttys001", startTime: new Date() },
283
- { pid: 200, command: "claude", cwd: "/project-b", tty: "ttys002", startTime: new Date() },
284
- ];
285
- mockedListAgentProcesses.mockReturnValue(processes);
286
- mockedEnrichProcesses.mockReturnValue(processes);
287
-
288
- // Set up projects dir with encoded directory names
289
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "claude-test-"));
290
- const projectsDir = path.join(tmpDir, "projects");
291
- // /project-a → -project-a, /project-b → -project-b
292
- const projDirA = path.join(projectsDir, "-project-a");
293
- const projDirB = path.join(projectsDir, "-project-b");
294
- fs.mkdirSync(projDirA, { recursive: true });
295
- fs.mkdirSync(projDirB, { recursive: true });
296
-
297
- const sessionFile = path.join(projDirA, "only-session.jsonl");
298
- fs.writeFileSync(
299
- sessionFile,
300
- JSON.stringify({ type: "assistant", timestamp: "2026-03-18T23:19:00Z" }),
301
- );
302
-
303
- (adapter as any).projectsDir = projectsDir;
304
-
305
- const sessionFiles: SessionFile[] = [
306
- {
307
- sessionId: "only-session",
308
- filePath: sessionFile,
309
- projectDir: projDirA,
310
- birthtimeMs: Date.now(),
311
- resolvedCwd: "",
312
- },
313
- ];
314
- mockedBatchGetSessionFileBirthtimes.mockReturnValue(sessionFiles);
315
-
316
- // Only process 100 matches
317
- const matches: MatchResult[] = [
318
- {
319
- process: processes[0],
320
- session: { ...sessionFiles[0], resolvedCwd: "/project-a" },
321
- deltaMs: 5000,
322
- },
323
- ];
324
- mockedMatchProcessesToSessions.mockReturnValue(matches);
325
-
326
- const agents = await adapter.detectAgents();
327
- expect(agents).toHaveLength(2);
328
-
329
- const matched = agents.find((a) => a.pid === 100);
330
- const unmatched = agents.find((a) => a.pid === 200);
331
- expect(matched?.sessionId).toBe("only-session");
332
- expect(unmatched?.sessionId).toBe("pid-200");
333
- expect(unmatched?.status).toBe(AgentStatus.RUNNING);
334
-
335
- fs.rmSync(tmpDir, { recursive: true, force: true });
336
- });
337
-
338
- it("should handle process with empty cwd in process-only fallback", async () => {
339
- const processes: ProcessInfo[] = [{ pid: 300, command: "claude", cwd: "", tty: "ttys003" }];
340
- mockedListAgentProcesses.mockReturnValue(processes);
341
- mockedEnrichProcesses.mockReturnValue(processes);
342
-
343
- (adapter as any).projectsDir = "/nonexistent";
344
-
345
- const agents = await adapter.detectAgents();
346
- expect(agents).toHaveLength(1);
347
- expect(agents[0]).toMatchObject({
348
- pid: 300,
349
- sessionId: "pid-300",
350
- summary: "Claude Code process running",
351
- projectPath: "",
352
- });
353
- });
354
-
355
- it("should match via --resume <uuid> in command line and skip PID-file/legacy", async () => {
356
- const sessionId = "0555f803-7eca-4fc6-a1e0-34dbf86b33b2";
357
- const processes: ProcessInfo[] = [
358
- {
359
- pid: 41920,
360
- command: `claude --resume ${sessionId}`,
361
- cwd: "/project/resumed",
362
- tty: "ttys001",
363
- startTime: new Date(),
364
- },
365
- ];
366
- mockedListAgentProcesses.mockReturnValue(processes);
367
- mockedEnrichProcesses.mockReturnValue(processes);
368
-
369
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "claude-resume-"));
370
- const projectsDir = path.join(tmpDir, "projects");
371
- const projDir = path.join(projectsDir, "-project-resumed");
372
- fs.mkdirSync(projDir, { recursive: true });
373
-
374
- const jsonlPath = path.join(projDir, `${sessionId}.jsonl`);
375
- fs.writeFileSync(
376
- jsonlPath,
377
- [
378
- JSON.stringify({
379
- type: "user",
380
- timestamp: new Date().toISOString(),
381
- cwd: "/project/resumed",
382
- message: { content: "resumed conversation" },
383
- }),
384
- JSON.stringify({ type: "assistant", timestamp: new Date().toISOString() }),
385
- ].join("\n"),
386
- );
387
-
388
- (adapter as any).projectsDir = projectsDir;
389
- (adapter as any).sessionsDir = path.join(tmpDir, "sessions"); // empty — no PID file
390
-
391
- const agents = await adapter.detectAgents();
392
-
393
- // Legacy matching helpers must NOT have been consulted — resume match was authoritative
394
- expect(mockedBatchGetSessionFileBirthtimes).not.toHaveBeenCalled();
395
- expect(mockedMatchProcessesToSessions).not.toHaveBeenCalled();
396
-
397
- expect(agents).toHaveLength(1);
398
- expect(agents[0]).toMatchObject({
399
- type: "claude",
400
- pid: 41920,
401
- sessionId,
402
- projectPath: "/project/resumed",
403
- });
404
- expect(agents[0].summary).toContain("resumed conversation");
405
-
406
- fs.rmSync(tmpDir, { recursive: true, force: true });
407
- });
408
-
409
- it("should fall through when --resume points to a JSONL that does not exist", async () => {
410
- const processes: ProcessInfo[] = [
411
- {
412
- pid: 41921,
413
- command: "claude --resume aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
414
- cwd: "/project/missing",
415
- tty: "ttys001",
416
- startTime: new Date(),
417
- },
418
- ];
419
- mockedListAgentProcesses.mockReturnValue(processes);
420
- mockedEnrichProcesses.mockReturnValue(processes);
421
-
422
- // No projects dir, no PID file → both matchers fail → process-only
423
- (adapter as any).projectsDir = "/nonexistent";
424
- (adapter as any).sessionsDir = "/nonexistent";
425
-
426
- const agents = await adapter.detectAgents();
427
-
428
- expect(agents).toHaveLength(1);
429
- expect(agents[0].sessionId).toBe("pid-41921");
430
- expect(agents[0].status).toBe(AgentStatus.RUNNING);
431
- });
432
-
433
- it("should use PID file for direct match and skip legacy matching for that process", async () => {
434
- const startTime = new Date();
435
- const processes: ProcessInfo[] = [
436
- { pid: 55001, command: "claude", cwd: "/project/direct", tty: "ttys001", startTime },
437
- ];
438
- mockedListAgentProcesses.mockReturnValue(processes);
439
- mockedEnrichProcesses.mockReturnValue(processes);
440
-
441
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "claude-pid-test-"));
442
- const sessionsDir = path.join(tmpDir, "sessions");
443
- const projectsDir = path.join(tmpDir, "projects");
444
- const projDir = path.join(projectsDir, "-project-direct");
445
- fs.mkdirSync(sessionsDir, { recursive: true });
446
- fs.mkdirSync(projDir, { recursive: true });
447
-
448
- const sessionId = "pid-file-session";
449
- const jsonlPath = path.join(projDir, `${sessionId}.jsonl`);
450
- fs.writeFileSync(
451
- jsonlPath,
452
- [
453
- JSON.stringify({
454
- type: "user",
455
- timestamp: new Date().toISOString(),
456
- cwd: "/project/direct",
457
- message: { content: "hello from pid file" },
458
- }),
459
- JSON.stringify({ type: "assistant", timestamp: new Date().toISOString() }),
460
- ].join("\n"),
461
- );
462
-
463
- fs.writeFileSync(
464
- path.join(sessionsDir, "55001.json"),
465
- JSON.stringify({
466
- pid: 55001,
467
- sessionId,
468
- cwd: "/project/direct",
469
- startedAt: startTime.getTime(),
470
- kind: "interactive",
471
- entrypoint: "cli",
472
- }),
473
- );
474
-
475
- (adapter as any).sessionsDir = sessionsDir;
476
- (adapter as any).projectsDir = projectsDir;
477
-
478
- const agents = await adapter.detectAgents();
479
-
480
- // Legacy matching utilities should NOT have been called (all processes matched via PID file)
481
- expect(mockedBatchGetSessionFileBirthtimes).not.toHaveBeenCalled();
482
- expect(mockedMatchProcessesToSessions).not.toHaveBeenCalled();
483
-
484
- expect(agents).toHaveLength(1);
485
- expect(agents[0]).toMatchObject({
486
- type: "claude",
487
- pid: 55001,
488
- sessionId,
489
- projectPath: "/project/direct",
490
- status: AgentStatus.WAITING,
491
- });
492
- expect(agents[0].summary).toContain("hello from pid file");
493
-
494
- fs.rmSync(tmpDir, { recursive: true, force: true });
495
- });
496
-
497
- it("should prefer PID-file live status over JSONL-derived status and surface waitingFor in summary", async () => {
498
- const startTime = new Date();
499
- const processes: ProcessInfo[] = [
500
- { pid: 55050, command: "claude", cwd: "/project/wait", tty: "ttys001", startTime },
501
- ];
502
- mockedListAgentProcesses.mockReturnValue(processes);
503
- mockedEnrichProcesses.mockReturnValue(processes);
504
-
505
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "claude-pid-wait-"));
506
- const sessionsDir = path.join(tmpDir, "sessions");
507
- const projectsDir = path.join(tmpDir, "projects");
508
- const projDir = path.join(projectsDir, "-project-wait");
509
- fs.mkdirSync(sessionsDir, { recursive: true });
510
- fs.mkdirSync(projDir, { recursive: true });
511
-
512
- const sessionId = "wait-session";
513
- const jsonlPath = path.join(projDir, `${sessionId}.jsonl`);
514
- // PID file's live status must win over JSONL-derived status.
515
- fs.writeFileSync(
516
- jsonlPath,
517
- [
518
- JSON.stringify({
519
- type: "user",
520
- timestamp: new Date().toISOString(),
521
- cwd: "/project/wait",
522
- message: { content: "/reddit-commenter" },
523
- }),
524
- JSON.stringify({
525
- type: "permission-mode",
526
- timestamp: new Date().toISOString(),
527
- permissionMode: "default",
528
- }),
529
- ].join("\n"),
530
- );
531
-
532
- fs.writeFileSync(
533
- path.join(sessionsDir, "55050.json"),
534
- JSON.stringify({
535
- pid: 55050,
536
- sessionId,
537
- cwd: "/project/wait",
538
- startedAt: startTime.getTime(),
539
- kind: "interactive",
540
- entrypoint: "cli",
541
- status: "waiting",
542
- waitingFor: "approve Read",
543
- }),
544
- );
545
-
546
- (adapter as any).sessionsDir = sessionsDir;
547
- (adapter as any).projectsDir = projectsDir;
548
-
549
- const agents = await adapter.detectAgents();
550
-
551
- expect(agents).toHaveLength(1);
552
- expect(agents[0].status).toBe(AgentStatus.WAITING);
553
- expect(agents[0].summary).toContain("/reddit-commenter");
554
- expect(agents[0].summary).toContain("waiting for approve Read");
555
-
556
- fs.rmSync(tmpDir, { recursive: true, force: true });
557
- });
558
-
559
- it('should resolve PID-file status: "idle" to AgentStatus.IDLE even when JSONL would say UNKNOWN', async () => {
560
- const startTime = new Date();
561
- const processes: ProcessInfo[] = [
562
- { pid: 55051, command: "claude", cwd: "/project/idle", tty: "ttys001", startTime },
563
- ];
564
- mockedListAgentProcesses.mockReturnValue(processes);
565
- mockedEnrichProcesses.mockReturnValue(processes);
566
-
567
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "claude-pid-idle-"));
568
- const sessionsDir = path.join(tmpDir, "sessions");
569
- const projectsDir = path.join(tmpDir, "projects");
570
- const projDir = path.join(projectsDir, "-project-idle");
571
- fs.mkdirSync(sessionsDir, { recursive: true });
572
- fs.mkdirSync(projDir, { recursive: true });
573
-
574
- const sessionId = "idle-session";
575
- const jsonlPath = path.join(projDir, `${sessionId}.jsonl`);
576
- fs.writeFileSync(
577
- jsonlPath,
578
- [
579
- JSON.stringify({
580
- type: "user",
581
- timestamp: new Date().toISOString(),
582
- cwd: "/project/idle",
583
- message: { content: "hello" },
584
- }),
585
- JSON.stringify({
586
- type: "permission-mode",
587
- timestamp: new Date().toISOString(),
588
- permissionMode: "default",
589
- }),
590
- ].join("\n"),
591
- );
592
-
593
- fs.writeFileSync(
594
- path.join(sessionsDir, "55051.json"),
595
- JSON.stringify({
596
- pid: 55051,
597
- sessionId,
598
- cwd: "/project/idle",
599
- startedAt: startTime.getTime(),
600
- kind: "interactive",
601
- entrypoint: "cli",
602
- status: "idle",
603
- }),
604
- );
605
-
606
- (adapter as any).sessionsDir = sessionsDir;
607
- (adapter as any).projectsDir = projectsDir;
608
-
609
- const agents = await adapter.detectAgents();
610
-
611
- expect(agents).toHaveLength(1);
612
- expect(agents[0].status).toBe(AgentStatus.IDLE);
613
- // No waitingFor in PID file → summary is just the last user message
614
- expect(agents[0].summary).toBe("hello");
615
-
616
- fs.rmSync(tmpDir, { recursive: true, force: true });
617
- });
618
-
619
- it("should fall back to JSONL-derived status when PID-file status is missing or unrecognized", async () => {
620
- const startTime = new Date();
621
- const processes: ProcessInfo[] = [
622
- { pid: 55052, command: "claude", cwd: "/project/legacy", tty: "ttys001", startTime },
623
- ];
624
- mockedListAgentProcesses.mockReturnValue(processes);
625
- mockedEnrichProcesses.mockReturnValue(processes);
626
-
627
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "claude-pid-nostat-"));
628
- const sessionsDir = path.join(tmpDir, "sessions");
629
- const projectsDir = path.join(tmpDir, "projects");
630
- const projDir = path.join(projectsDir, "-project-legacy");
631
- fs.mkdirSync(sessionsDir, { recursive: true });
632
- fs.mkdirSync(projDir, { recursive: true });
633
-
634
- const sessionId = "legacy-session";
635
- const jsonlPath = path.join(projDir, `${sessionId}.jsonl`);
636
- // Last entry is assistant → JSONL parser yields WAITING.
637
- fs.writeFileSync(
638
- jsonlPath,
639
- [
640
- JSON.stringify({
641
- type: "user",
642
- timestamp: new Date().toISOString(),
643
- cwd: "/project/legacy",
644
- message: { content: "do the thing" },
645
- }),
646
- JSON.stringify({ type: "assistant", timestamp: new Date().toISOString() }),
647
- ].join("\n"),
648
- );
649
-
650
- // PID file with unrecognized status string — adapter must ignore it and use parser
651
- fs.writeFileSync(
652
- path.join(sessionsDir, "55052.json"),
653
- JSON.stringify({
654
- pid: 55052,
655
- sessionId,
656
- cwd: "/project/legacy",
657
- startedAt: startTime.getTime(),
658
- kind: "interactive",
659
- entrypoint: "cli",
660
- status: "fantastical-future-state",
661
- }),
662
- );
663
-
664
- (adapter as any).sessionsDir = sessionsDir;
665
- (adapter as any).projectsDir = projectsDir;
666
-
667
- const agents = await adapter.detectAgents();
668
-
669
- expect(agents).toHaveLength(1);
670
- expect(agents[0].status).toBe(AgentStatus.WAITING);
671
-
672
- fs.rmSync(tmpDir, { recursive: true, force: true });
673
- });
674
-
675
- it("should pick up live status from PID file even when matched via --resume", async () => {
676
- const sessionId = "aaaaaaaa-1111-2222-3333-444444444444";
677
- const startTime = new Date();
678
- const processes: ProcessInfo[] = [
679
- {
680
- pid: 55053,
681
- command: `claude --resume ${sessionId}`,
682
- cwd: "/project/resume-wait",
683
- tty: "ttys001",
684
- startTime,
685
- },
686
- ];
687
- mockedListAgentProcesses.mockReturnValue(processes);
688
- mockedEnrichProcesses.mockReturnValue(processes);
689
-
690
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "claude-resume-wait-"));
691
- const sessionsDir = path.join(tmpDir, "sessions");
692
- const projectsDir = path.join(tmpDir, "projects");
693
- const projDir = path.join(projectsDir, "-project-resume-wait");
694
- fs.mkdirSync(sessionsDir, { recursive: true });
695
- fs.mkdirSync(projDir, { recursive: true });
696
-
697
- const jsonlPath = path.join(projDir, `${sessionId}.jsonl`);
698
- fs.writeFileSync(
699
- jsonlPath,
700
- [
701
- JSON.stringify({
702
- type: "user",
703
- timestamp: new Date().toISOString(),
704
- cwd: "/project/resume-wait",
705
- message: { content: "resumed work" },
706
- }),
707
- JSON.stringify({
708
- type: "permission-mode",
709
- timestamp: new Date().toISOString(),
710
- permissionMode: "default",
711
- }),
712
- ].join("\n"),
713
- );
714
-
715
- fs.writeFileSync(
716
- path.join(sessionsDir, "55053.json"),
717
- JSON.stringify({
718
- pid: 55053,
719
- sessionId,
720
- cwd: "/project/resume-wait",
721
- startedAt: startTime.getTime(),
722
- kind: "interactive",
723
- entrypoint: "cli",
724
- status: "waiting",
725
- waitingFor: "approve Bash",
726
- }),
727
- );
728
-
729
- (adapter as any).sessionsDir = sessionsDir;
730
- (adapter as any).projectsDir = projectsDir;
731
-
732
- const agents = await adapter.detectAgents();
733
-
734
- expect(agents).toHaveLength(1);
735
- expect(agents[0].status).toBe(AgentStatus.WAITING);
736
- expect(agents[0].summary).toContain("resumed work");
737
- expect(agents[0].summary).toContain("waiting for approve Bash");
738
-
739
- fs.rmSync(tmpDir, { recursive: true, force: true });
740
- });
741
-
742
- it("should fall back to process-only when direct-matched JSONL becomes unreadable", async () => {
743
- const startTime = new Date();
744
- const processes: ProcessInfo[] = [
745
- { pid: 66001, command: "claude", cwd: "/project/gone", tty: "ttys001", startTime },
746
- ];
747
- mockedListAgentProcesses.mockReturnValue(processes);
748
- mockedEnrichProcesses.mockReturnValue(processes);
749
-
750
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "claude-gone-"));
751
- const sessionsDir = path.join(tmpDir, "sessions");
752
- const projectsDir = path.join(tmpDir, "projects");
753
- const projDir = path.join(projectsDir, "-project-gone");
754
- fs.mkdirSync(sessionsDir, { recursive: true });
755
- fs.mkdirSync(projDir, { recursive: true });
756
-
757
- const sessionId = "gone-session";
758
- const jsonlPath = path.join(projDir, `${sessionId}.jsonl`);
759
- fs.writeFileSync(
760
- jsonlPath,
761
- JSON.stringify({ type: "assistant", timestamp: new Date().toISOString() }),
762
- );
763
- fs.writeFileSync(
764
- path.join(sessionsDir, "66001.json"),
765
- JSON.stringify({
766
- pid: 66001,
767
- sessionId,
768
- cwd: "/project/gone",
769
- startedAt: startTime.getTime(),
770
- kind: "interactive",
771
- entrypoint: "cli",
772
- }),
773
- );
774
-
775
- (adapter as any).sessionsDir = sessionsDir;
776
- (adapter as any).projectsDir = projectsDir;
777
-
778
- // Simulate JSONL disappearing between existence check and read
779
- vi.spyOn((adapter as any).parser, "readSessionIncremental").mockReturnValueOnce(null);
780
-
781
- const agents = await adapter.detectAgents();
782
-
783
- // matchedPids.delete called → process falls back to IDLE
784
- expect(agents).toHaveLength(1);
785
- expect(agents[0].sessionId).toBe("pid-66001");
786
- expect(agents[0].status).toBe(AgentStatus.RUNNING);
787
-
788
- fs.rmSync(tmpDir, { recursive: true, force: true });
789
- vi.restoreAllMocks();
790
- });
791
-
792
- it("should fall back to process-only when legacy-matched JSONL becomes unreadable", async () => {
793
- const startTime = new Date();
794
- const processes: ProcessInfo[] = [
795
- { pid: 66002, command: "claude", cwd: "/project/legacy-gone", tty: "ttys001", startTime },
796
- ];
797
- mockedListAgentProcesses.mockReturnValue(processes);
798
- mockedEnrichProcesses.mockReturnValue(processes);
799
-
800
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "claude-lgone-"));
801
- const projectsDir = path.join(tmpDir, "projects");
802
- const projDir = path.join(projectsDir, "-project-legacy-gone");
803
- fs.mkdirSync(projDir, { recursive: true });
804
-
805
- const sessionId = "legacy-gone-session";
806
- const jsonlPath = path.join(projDir, `${sessionId}.jsonl`);
807
- fs.writeFileSync(
808
- jsonlPath,
809
- JSON.stringify({ type: "assistant", timestamp: new Date().toISOString() }),
810
- );
811
-
812
- // No PID file → process goes to legacy fallback
813
- (adapter as any).sessionsDir = path.join(tmpDir, "no-sessions");
814
- (adapter as any).projectsDir = projectsDir;
815
-
816
- const legacySessionFile = {
817
- sessionId,
818
- filePath: jsonlPath,
819
- projectDir: projDir,
820
- birthtimeMs: startTime.getTime(),
821
- resolvedCwd: "/project/legacy-gone",
822
- };
823
- mockedBatchGetSessionFileBirthtimes.mockReturnValue([legacySessionFile]);
824
- mockedMatchProcessesToSessions.mockReturnValue([
825
- { process: processes[0], session: legacySessionFile, deltaMs: 500 },
826
- ]);
827
-
828
- // Simulate JSONL disappearing between match and read
829
- vi.spyOn((adapter as any).parser, "readSessionIncremental").mockReturnValueOnce(null);
830
-
831
- const agents = await adapter.detectAgents();
832
-
833
- expect(agents).toHaveLength(1);
834
- expect(agents[0].sessionId).toBe("pid-66002");
835
- expect(agents[0].status).toBe(AgentStatus.RUNNING);
836
-
837
- fs.rmSync(tmpDir, { recursive: true, force: true });
838
- vi.restoreAllMocks();
839
- });
840
-
841
- it("should mix direct PID-file matches and legacy matches across processes", async () => {
842
- const startTime = new Date();
843
- const processes: ProcessInfo[] = [
844
- { pid: 55002, command: "claude", cwd: "/project/alpha", tty: "ttys001", startTime },
845
- { pid: 55003, command: "claude", cwd: "/project/beta", tty: "ttys002", startTime },
846
- ];
847
- mockedListAgentProcesses.mockReturnValue(processes);
848
- mockedEnrichProcesses.mockReturnValue(processes);
849
-
850
- const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "claude-mix-test-"));
851
- const sessionsDir = path.join(tmpDir, "sessions");
852
- const projectsDir = path.join(tmpDir, "projects");
853
- const projAlpha = path.join(projectsDir, "-project-alpha");
854
- const projBeta = path.join(projectsDir, "-project-beta");
855
- fs.mkdirSync(sessionsDir, { recursive: true });
856
- fs.mkdirSync(projAlpha, { recursive: true });
857
- fs.mkdirSync(projBeta, { recursive: true });
858
-
859
- // PID file only for process 55002
860
- const directSessionId = "direct-session";
861
- const directJsonl = path.join(projAlpha, `${directSessionId}.jsonl`);
862
- fs.writeFileSync(
863
- directJsonl,
864
- [
865
- JSON.stringify({
866
- type: "user",
867
- timestamp: new Date().toISOString(),
868
- cwd: "/project/alpha",
869
- message: { content: "direct question" },
870
- }),
871
- JSON.stringify({ type: "assistant", timestamp: new Date().toISOString() }),
872
- ].join("\n"),
873
- );
874
- fs.writeFileSync(
875
- path.join(sessionsDir, "55002.json"),
876
- JSON.stringify({
877
- pid: 55002,
878
- sessionId: directSessionId,
879
- cwd: "/project/alpha",
880
- startedAt: startTime.getTime(),
881
- kind: "interactive",
882
- entrypoint: "cli",
883
- }),
884
- );
885
-
886
- // Legacy session file for process 55003
887
- const legacySessionId = "legacy-session";
888
- const legacyJsonl = path.join(projBeta, `${legacySessionId}.jsonl`);
889
- fs.writeFileSync(
890
- legacyJsonl,
891
- [
892
- JSON.stringify({
893
- type: "user",
894
- timestamp: new Date().toISOString(),
895
- cwd: "/project/beta",
896
- message: { content: "legacy question" },
897
- }),
898
- JSON.stringify({ type: "assistant", timestamp: new Date().toISOString() }),
899
- ].join("\n"),
900
- );
901
-
902
- (adapter as any).sessionsDir = sessionsDir;
903
- (adapter as any).projectsDir = projectsDir;
904
-
905
- // Mock legacy matching for process 55003
906
- const legacySessionFile = {
907
- sessionId: legacySessionId,
908
- filePath: legacyJsonl,
909
- projectDir: projBeta,
910
- birthtimeMs: startTime.getTime(),
911
- resolvedCwd: "/project/beta",
912
- };
913
- mockedBatchGetSessionFileBirthtimes.mockReturnValue([legacySessionFile]);
914
- mockedMatchProcessesToSessions.mockReturnValue([
915
- { process: processes[1], session: legacySessionFile, deltaMs: 1000 },
916
- ]);
917
-
918
- const agents = await adapter.detectAgents();
919
-
920
- // Legacy matching called only for fallback process (55003)
921
- expect(mockedMatchProcessesToSessions).toHaveBeenCalledTimes(1);
922
- expect(mockedMatchProcessesToSessions.mock.calls[0][0]).toEqual([processes[1]]);
923
-
924
- expect(agents).toHaveLength(2);
925
- const alpha = agents.find((a) => a.pid === 55002);
926
- const beta = agents.find((a) => a.pid === 55003);
927
- expect(alpha?.sessionId).toBe(directSessionId);
928
- expect(beta?.sessionId).toBe(legacySessionId);
929
-
930
- fs.rmSync(tmpDir, { recursive: true, force: true });
931
- });
932
- });
933
-
934
- describe("helper methods", () => {
935
- describe("determineStatus", () => {
936
- it('should return "unknown" for sessions with no last entry type', () => {
937
- const determineStatus = (adapter as any).parser.determineStatus.bind(
938
- (adapter as any).parser,
939
- );
940
-
941
- const session = {
942
- sessionId: "test",
943
- projectPath: "/test",
944
- sessionStart: new Date(),
945
- lastActive: new Date(),
946
- isInterrupted: false,
947
- };
948
-
949
- expect(determineStatus(session)).toBe(AgentStatus.UNKNOWN);
950
- });
951
-
952
- it('should return "waiting" for assistant entries', () => {
953
- const determineStatus = (adapter as any).parser.determineStatus.bind(
954
- (adapter as any).parser,
955
- );
956
-
957
- const session = {
958
- sessionId: "test",
959
- projectPath: "/test",
960
- sessionStart: new Date(),
961
- lastActive: new Date(),
962
- lastEntryType: "assistant",
963
- isInterrupted: false,
964
- };
965
-
966
- expect(determineStatus(session)).toBe(AgentStatus.WAITING);
967
- });
968
-
969
- it('should return "waiting" for user interruption', () => {
970
- const determineStatus = (adapter as any).parser.determineStatus.bind(
971
- (adapter as any).parser,
972
- );
973
-
974
- const session = {
975
- sessionId: "test",
976
- projectPath: "/test",
977
- sessionStart: new Date(),
978
- lastActive: new Date(),
979
- lastEntryType: "user",
980
- isInterrupted: true,
981
- };
982
-
983
- expect(determineStatus(session)).toBe(AgentStatus.WAITING);
984
- });
985
-
986
- it('should return "running" for user/progress entries', () => {
987
- const determineStatus = (adapter as any).parser.determineStatus.bind(
988
- (adapter as any).parser,
989
- );
990
-
991
- const session = {
992
- sessionId: "test",
993
- projectPath: "/test",
994
- sessionStart: new Date(),
995
- lastActive: new Date(),
996
- lastEntryType: "user",
997
- isInterrupted: false,
998
- };
999
-
1000
- expect(determineStatus(session)).toBe(AgentStatus.RUNNING);
1001
- });
1002
-
1003
- it("should not override status based on age (process is running)", () => {
1004
- const determineStatus = (adapter as any).parser.determineStatus.bind(
1005
- (adapter as any).parser,
1006
- );
1007
-
1008
- const oldDate = new Date(Date.now() - 10 * 60 * 1000);
1009
- const session = {
1010
- sessionId: "test",
1011
- projectPath: "/test",
1012
- sessionStart: oldDate,
1013
- lastActive: oldDate,
1014
- lastEntryType: "assistant",
1015
- isInterrupted: false,
1016
- };
1017
-
1018
- expect(determineStatus(session)).toBe(AgentStatus.WAITING);
1019
- });
1020
-
1021
- it('should return "idle" for system entries', () => {
1022
- const determineStatus = (adapter as any).parser.determineStatus.bind(
1023
- (adapter as any).parser,
1024
- );
1025
-
1026
- const session = {
1027
- sessionId: "test",
1028
- projectPath: "/test",
1029
- sessionStart: new Date(),
1030
- lastActive: new Date(),
1031
- lastEntryType: "system",
1032
- isInterrupted: false,
1033
- };
1034
-
1035
- expect(determineStatus(session)).toBe(AgentStatus.IDLE);
1036
- });
1037
-
1038
- it('should return "running" for thinking entries', () => {
1039
- const determineStatus = (adapter as any).parser.determineStatus.bind(
1040
- (adapter as any).parser,
1041
- );
1042
-
1043
- const session = {
1044
- sessionId: "test",
1045
- projectPath: "/test",
1046
- sessionStart: new Date(),
1047
- lastActive: new Date(),
1048
- lastEntryType: "thinking",
1049
- isInterrupted: false,
1050
- };
1051
-
1052
- expect(determineStatus(session)).toBe(AgentStatus.RUNNING);
1053
- });
1054
-
1055
- it('should return "running" for progress entries', () => {
1056
- const determineStatus = (adapter as any).parser.determineStatus.bind(
1057
- (adapter as any).parser,
1058
- );
1059
-
1060
- const session = {
1061
- sessionId: "test",
1062
- projectPath: "/test",
1063
- sessionStart: new Date(),
1064
- lastActive: new Date(),
1065
- lastEntryType: "progress",
1066
- isInterrupted: false,
1067
- };
1068
-
1069
- expect(determineStatus(session)).toBe(AgentStatus.RUNNING);
1070
- });
1071
-
1072
- it('should return "unknown" for unrecognized entry types', () => {
1073
- const determineStatus = (adapter as any).parser.determineStatus.bind(
1074
- (adapter as any).parser,
1075
- );
1076
-
1077
- const session = {
1078
- sessionId: "test",
1079
- projectPath: "/test",
1080
- sessionStart: new Date(),
1081
- lastActive: new Date(),
1082
- lastEntryType: "some_other_type",
1083
- isInterrupted: false,
1084
- };
1085
-
1086
- expect(determineStatus(session)).toBe(AgentStatus.UNKNOWN);
1087
- });
1088
- });
1089
-
1090
- describe("extractUserMessageText", () => {
1091
- it("should extract plain string content", () => {
1092
- const extract = (adapter as any).parser["extractUserMessageText"].bind(
1093
- (adapter as any).parser,
1094
- );
1095
- expect(extract("hello world")).toBe("hello world");
1096
- });
1097
-
1098
- it("should extract text from array content blocks", () => {
1099
- const extract = (adapter as any).parser["extractUserMessageText"].bind(
1100
- (adapter as any).parser,
1101
- );
1102
-
1103
- const content = [
1104
- { type: "tool_result", content: "some result" },
1105
- { type: "text", text: "user question" },
1106
- ];
1107
- expect(extract(content)).toBe("user question");
1108
- });
1109
-
1110
- it("should return undefined for empty/null content", () => {
1111
- const extract = (adapter as any).parser["extractUserMessageText"].bind(
1112
- (adapter as any).parser,
1113
- );
1114
-
1115
- expect(extract(undefined)).toBeUndefined();
1116
- expect(extract("")).toBeUndefined();
1117
- expect(extract([])).toBeUndefined();
1118
- });
1119
-
1120
- it("should parse command-message tags", () => {
1121
- const extract = (adapter as any).parser["extractUserMessageText"].bind(
1122
- (adapter as any).parser,
1123
- );
1124
-
1125
- const msg =
1126
- "<command-message><command-name>commit</command-name><command-args>fix bug</command-args></command-message>";
1127
- expect(extract(msg)).toBe("commit fix bug");
1128
- });
1129
-
1130
- it("should parse command-message without args", () => {
1131
- const extract = (adapter as any).parser["extractUserMessageText"].bind(
1132
- (adapter as any).parser,
1133
- );
1134
-
1135
- const msg = "<command-message><command-name>help</command-name></command-message>";
1136
- expect(extract(msg)).toBe("help");
1137
- });
1138
-
1139
- it("should extract ARGUMENTS from skill expansion", () => {
1140
- const extract = (adapter as any).parser["extractUserMessageText"].bind(
1141
- (adapter as any).parser,
1142
- );
1143
-
1144
- const msg =
1145
- "Base directory for this skill: /some/path\n\nSome instructions\n\nARGUMENTS: implement the feature";
1146
- expect(extract(msg)).toBe("implement the feature");
1147
- });
1148
-
1149
- it("should return undefined for skill expansion without ARGUMENTS", () => {
1150
- const extract = (adapter as any).parser["extractUserMessageText"].bind(
1151
- (adapter as any).parser,
1152
- );
1153
-
1154
- const msg = "Base directory for this skill: /some/path\n\nSome instructions only";
1155
- expect(extract(msg)).toBeUndefined();
1156
- });
1157
-
1158
- it("should filter noise messages", () => {
1159
- const extract = (adapter as any).parser["extractUserMessageText"].bind(
1160
- (adapter as any).parser,
1161
- );
1162
-
1163
- expect(extract("[Request interrupted by user]")).toBeUndefined();
1164
- expect(extract("Tool loaded.")).toBeUndefined();
1165
- expect(
1166
- extract("This session is being continued from a previous conversation"),
1167
- ).toBeUndefined();
1168
- });
1169
- });
1170
-
1171
- describe("parseCommandMessage", () => {
1172
- it("should return undefined for malformed command-message", () => {
1173
- const parse = (adapter as any).parser["parseCommandMessage"].bind((adapter as any).parser);
1174
- expect(parse("<command-message>no tags</command-message>")).toBeUndefined();
1175
- });
1176
- });
1177
- });
1178
-
1179
- describe("file I/O methods", () => {
1180
- let tmpDir: string;
1181
-
1182
- beforeEach(() => {
1183
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "claude-test-"));
1184
- });
1185
-
1186
- afterEach(() => {
1187
- fs.rmSync(tmpDir, { recursive: true, force: true });
1188
- });
1189
-
1190
- describe("readSession", () => {
1191
- it("should parse session file with timestamps, cwd, and entry type", () => {
1192
- const readSession = (adapter as any).parser.readSession.bind((adapter as any).parser);
1193
-
1194
- const filePath = path.join(tmpDir, "test-session.jsonl");
1195
- const lines = [
1196
- JSON.stringify({ type: "user", timestamp: "2026-03-10T10:00:00Z", cwd: "/my/project" }),
1197
- JSON.stringify({ type: "assistant", timestamp: "2026-03-10T10:01:00Z" }),
1198
- ];
1199
- fs.writeFileSync(filePath, lines.join("\n"));
1200
-
1201
- const session = readSession(filePath, "/my/project");
1202
- expect(session).toMatchObject({
1203
- sessionId: "test-session",
1204
- projectPath: "/my/project",
1205
- lastCwd: "/my/project",
1206
- lastEntryType: "assistant",
1207
- isInterrupted: false,
1208
- });
1209
- expect(session.sessionStart.toISOString()).toBe("2026-03-10T10:00:00.000Z");
1210
- expect(session.lastActive.toISOString()).toBe("2026-03-10T10:01:00.000Z");
1211
- });
1212
-
1213
- it("should detect user interruption", () => {
1214
- const readSession = (adapter as any).parser.readSession.bind((adapter as any).parser);
1215
-
1216
- const filePath = path.join(tmpDir, "interrupted.jsonl");
1217
- const lines = [
1218
- JSON.stringify({
1219
- type: "user",
1220
- timestamp: "2026-03-10T10:00:00Z",
1221
- message: {
1222
- content: [{ type: "text", text: "[Request interrupted by user for tool use]" }],
1223
- },
1224
- }),
1225
- ];
1226
- fs.writeFileSync(filePath, lines.join("\n"));
1227
-
1228
- const session = readSession(filePath, "/test");
1229
- expect(session.isInterrupted).toBe(true);
1230
- expect(session.lastEntryType).toBe("user");
1231
- });
1232
-
1233
- it("should return session with defaults for empty file", () => {
1234
- const readSession = (adapter as any).parser.readSession.bind((adapter as any).parser);
1235
-
1236
- const filePath = path.join(tmpDir, "empty.jsonl");
1237
- fs.writeFileSync(filePath, "");
1238
-
1239
- const session = readSession(filePath, "/test");
1240
- expect(session).not.toBeNull();
1241
- expect(session.lastEntryType).toBeUndefined();
1242
- });
1243
-
1244
- it("should return null for non-existent file", () => {
1245
- const readSession = (adapter as any).parser.readSession.bind((adapter as any).parser);
1246
- expect(readSession(path.join(tmpDir, "nonexistent.jsonl"), "/test")).toBeNull();
1247
- });
1248
-
1249
- it("should skip metadata entry types for lastEntryType", () => {
1250
- const readSession = (adapter as any).parser.readSession.bind((adapter as any).parser);
1251
-
1252
- const filePath = path.join(tmpDir, "metadata-test.jsonl");
1253
- const lines = [
1254
- JSON.stringify({
1255
- type: "user",
1256
- timestamp: "2026-03-10T10:00:00Z",
1257
- message: { content: "hello" },
1258
- }),
1259
- JSON.stringify({ type: "assistant", timestamp: "2026-03-10T10:01:00Z" }),
1260
- JSON.stringify({ type: "last-prompt", timestamp: "2026-03-10T10:02:00Z" }),
1261
- JSON.stringify({ type: "file-history-snapshot", timestamp: "2026-03-10T10:03:00Z" }),
1262
- ];
1263
- fs.writeFileSync(filePath, lines.join("\n"));
1264
-
1265
- const session = readSession(filePath, "/test");
1266
- expect(session.lastEntryType).toBe("assistant");
1267
- });
1268
-
1269
- it("should parse snapshot.timestamp from file-history-snapshot first entry", () => {
1270
- const readSession = (adapter as any).parser.readSession.bind((adapter as any).parser);
1271
-
1272
- const filePath = path.join(tmpDir, "snapshot-ts.jsonl");
1273
- const lines = [
1274
- JSON.stringify({
1275
- type: "file-history-snapshot",
1276
- snapshot: { timestamp: "2026-03-10T09:55:00Z", files: [] },
1277
- }),
1278
- JSON.stringify({
1279
- type: "user",
1280
- timestamp: "2026-03-10T10:00:00Z",
1281
- message: { content: "test" },
1282
- }),
1283
- JSON.stringify({ type: "assistant", timestamp: "2026-03-10T10:01:00Z" }),
1284
- ];
1285
- fs.writeFileSync(filePath, lines.join("\n"));
1286
-
1287
- const session = readSession(filePath, "/test");
1288
- expect(session.sessionStart.toISOString()).toBe("2026-03-10T09:55:00.000Z");
1289
- expect(session.lastActive.toISOString()).toBe("2026-03-10T10:01:00.000Z");
1290
- });
1291
-
1292
- it("should extract lastUserMessage from session entries", () => {
1293
- const readSession = (adapter as any).parser.readSession.bind((adapter as any).parser);
1294
-
1295
- const filePath = path.join(tmpDir, "user-msg.jsonl");
1296
- const lines = [
1297
- JSON.stringify({
1298
- type: "user",
1299
- timestamp: "2026-03-10T10:00:00Z",
1300
- message: { content: "first question" },
1301
- }),
1302
- JSON.stringify({ type: "assistant", timestamp: "2026-03-10T10:01:00Z" }),
1303
- JSON.stringify({
1304
- type: "user",
1305
- timestamp: "2026-03-10T10:02:00Z",
1306
- message: { content: [{ type: "text", text: "second question" }] },
1307
- }),
1308
- JSON.stringify({ type: "assistant", timestamp: "2026-03-10T10:03:00Z" }),
1309
- ];
1310
- fs.writeFileSync(filePath, lines.join("\n"));
1311
-
1312
- const session = readSession(filePath, "/test");
1313
- expect(session.lastUserMessage).toBe("second question");
1314
- });
1315
-
1316
- it("should use lastCwd as projectPath when projectPath is empty", () => {
1317
- const readSession = (adapter as any).parser.readSession.bind((adapter as any).parser);
1318
-
1319
- const filePath = path.join(tmpDir, "no-project.jsonl");
1320
- const lines = [
1321
- JSON.stringify({
1322
- type: "user",
1323
- timestamp: "2026-03-10T10:00:00Z",
1324
- cwd: "/derived/path",
1325
- message: { content: "test" },
1326
- }),
1327
- ];
1328
- fs.writeFileSync(filePath, lines.join("\n"));
1329
-
1330
- const session = readSession(filePath, "");
1331
- expect(session.projectPath).toBe("/derived/path");
1332
- });
1333
-
1334
- it("should handle malformed JSON lines gracefully", () => {
1335
- const readSession = (adapter as any).parser.readSession.bind((adapter as any).parser);
1336
-
1337
- const filePath = path.join(tmpDir, "malformed.jsonl");
1338
- const lines = [
1339
- "not json",
1340
- JSON.stringify({ type: "assistant", timestamp: "2026-03-10T10:00:00Z" }),
1341
- ];
1342
- fs.writeFileSync(filePath, lines.join("\n"));
1343
-
1344
- const session = readSession(filePath, "/test");
1345
- expect(session).not.toBeNull();
1346
- expect(session.lastEntryType).toBe("assistant");
1347
- });
1348
- });
1349
- });
1350
-
1351
- describe("getConversation", () => {
1352
- let tmpDir: string;
1353
-
1354
- beforeEach(() => {
1355
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "claude-conv-"));
1356
- });
1357
-
1358
- afterEach(() => {
1359
- fs.rmSync(tmpDir, { recursive: true, force: true });
1360
- });
1361
-
1362
- function writeJsonl(lines: object[]): string {
1363
- const filePath = path.join(tmpDir, "session.jsonl");
1364
- fs.writeFileSync(filePath, lines.map((l) => JSON.stringify(l)).join("\n"));
1365
- return filePath;
1366
- }
1367
-
1368
- it("should parse user and assistant text messages", () => {
1369
- const filePath = writeJsonl([
1370
- { type: "user", timestamp: "2026-03-27T10:00:00Z", message: { content: "Hello" } },
1371
- {
1372
- type: "assistant",
1373
- timestamp: "2026-03-27T10:00:05Z",
1374
- message: { content: [{ type: "text", text: "Hi there!" }] },
1375
- },
1376
- ]);
1377
-
1378
- const messages = adapter.getConversation(filePath);
1379
- expect(messages).toHaveLength(2);
1380
- expect(messages[0]).toEqual({
1381
- role: "user",
1382
- content: "Hello",
1383
- timestamp: "2026-03-27T10:00:00Z",
1384
- });
1385
- expect(messages[1]).toEqual({
1386
- role: "assistant",
1387
- content: "Hi there!",
1388
- timestamp: "2026-03-27T10:00:05Z",
1389
- });
1390
- });
1391
-
1392
- it("should skip metadata entry types", () => {
1393
- const filePath = writeJsonl([
1394
- { type: "file-history-snapshot", timestamp: "2026-03-27T10:00:00Z", snapshot: {} },
1395
- { type: "last-prompt", timestamp: "2026-03-27T10:00:00Z" },
1396
- { type: "user", timestamp: "2026-03-27T10:00:01Z", message: { content: "Fix bug" } },
1397
- ]);
1398
-
1399
- const messages = adapter.getConversation(filePath);
1400
- expect(messages).toHaveLength(1);
1401
- expect(messages[0].content).toBe("Fix bug");
1402
- });
1403
-
1404
- it("should skip progress and thinking entries", () => {
1405
- const filePath = writeJsonl([
1406
- { type: "user", timestamp: "2026-03-27T10:00:00Z", message: { content: "Hello" } },
1407
- { type: "progress", timestamp: "2026-03-27T10:00:01Z", data: {} },
1408
- { type: "thinking", timestamp: "2026-03-27T10:00:02Z" },
1409
- {
1410
- type: "assistant",
1411
- timestamp: "2026-03-27T10:00:03Z",
1412
- message: { content: [{ type: "text", text: "Done" }] },
1413
- },
1414
- ]);
1415
-
1416
- const messages = adapter.getConversation(filePath);
1417
- expect(messages).toHaveLength(2);
1418
- expect(messages[0].role).toBe("user");
1419
- expect(messages[1].role).toBe("assistant");
1420
- });
1421
-
1422
- it("should include system messages", () => {
1423
- const filePath = writeJsonl([
1424
- {
1425
- type: "system",
1426
- timestamp: "2026-03-27T10:00:00Z",
1427
- message: { content: "System initialized" },
1428
- },
1429
- ]);
1430
-
1431
- const messages = adapter.getConversation(filePath);
1432
- expect(messages).toHaveLength(1);
1433
- expect(messages[0]).toEqual({
1434
- role: "system",
1435
- content: "System initialized",
1436
- timestamp: "2026-03-27T10:00:00Z",
1437
- });
1438
- });
1439
-
1440
- it("should skip tool_use and tool_result blocks in default mode", () => {
1441
- const filePath = writeJsonl([
1442
- {
1443
- type: "assistant",
1444
- timestamp: "2026-03-27T10:00:00Z",
1445
- message: {
1446
- content: [
1447
- { type: "text", text: "Let me read the file." },
1448
- { type: "tool_use", name: "Read", input: { file_path: "/src/app.ts" } },
1449
- ],
1450
- },
1451
- },
1452
- {
1453
- type: "user",
1454
- timestamp: "2026-03-27T10:00:01Z",
1455
- message: {
1456
- content: [
1457
- { type: "tool_result", tool_use_id: "toolu_1", content: "file contents here" },
1458
- ],
1459
- },
1460
- },
1461
- ]);
1462
-
1463
- const messages = adapter.getConversation(filePath);
1464
- expect(messages).toHaveLength(1);
1465
- expect(messages[0].content).toBe("Let me read the file.");
1466
- });
1467
-
1468
- it("should include tool_use and tool_result blocks in verbose mode", () => {
1469
- const filePath = writeJsonl([
1470
- {
1471
- type: "assistant",
1472
- timestamp: "2026-03-27T10:00:00Z",
1473
- message: {
1474
- content: [
1475
- { type: "text", text: "Let me read the file." },
1476
- { type: "tool_use", name: "Read", input: { file_path: "/src/app.ts" } },
1477
- ],
1478
- },
1479
- },
1480
- {
1481
- type: "user",
1482
- timestamp: "2026-03-27T10:00:01Z",
1483
- message: {
1484
- content: [
1485
- { type: "tool_result", tool_use_id: "toolu_1", content: "file contents here" },
1486
- ],
1487
- },
1488
- },
1489
- ]);
1490
-
1491
- const messages = adapter.getConversation(filePath, { verbose: true });
1492
- expect(messages).toHaveLength(2);
1493
- expect(messages[0].content).toContain("[Tool: Read]");
1494
- expect(messages[0].content).toContain("/src/app.ts");
1495
- expect(messages[1].content).toContain("[Tool Result]");
1496
- });
1497
-
1498
- it("should handle tool_result errors in verbose mode", () => {
1499
- const filePath = writeJsonl([
1500
- {
1501
- type: "user",
1502
- timestamp: "2026-03-27T10:00:00Z",
1503
- message: {
1504
- content: [
1505
- {
1506
- type: "tool_result",
1507
- tool_use_id: "toolu_1",
1508
- content: "Something went wrong",
1509
- is_error: true,
1510
- },
1511
- ],
1512
- },
1513
- },
1514
- ]);
1515
-
1516
- const messages = adapter.getConversation(filePath, { verbose: true });
1517
- expect(messages).toHaveLength(1);
1518
- expect(messages[0].content).toContain("[Tool Error]");
1519
- });
1520
-
1521
- it("should handle malformed JSON lines gracefully", () => {
1522
- const filePath = path.join(tmpDir, "malformed.jsonl");
1523
- fs.writeFileSync(
1524
- filePath,
1525
- [
1526
- JSON.stringify({
1527
- type: "user",
1528
- timestamp: "2026-03-27T10:00:00Z",
1529
- message: { content: "Hello" },
1530
- }),
1531
- "this is not valid json",
1532
- JSON.stringify({
1533
- type: "assistant",
1534
- timestamp: "2026-03-27T10:00:01Z",
1535
- message: { content: [{ type: "text", text: "World" }] },
1536
- }),
1537
- ].join("\n"),
1538
- );
1539
-
1540
- const messages = adapter.getConversation(filePath);
1541
- expect(messages).toHaveLength(2);
1542
- });
1543
-
1544
- it("should return empty array for missing file", () => {
1545
- const messages = adapter.getConversation("/nonexistent/path.jsonl");
1546
- expect(messages).toEqual([]);
1547
- });
1548
-
1549
- it("should return empty array for empty file", () => {
1550
- const filePath = path.join(tmpDir, "empty.jsonl");
1551
- fs.writeFileSync(filePath, "");
1552
-
1553
- const messages = adapter.getConversation(filePath);
1554
- expect(messages).toEqual([]);
1555
- });
1556
-
1557
- it("should filter noise messages from user entries", () => {
1558
- const filePath = writeJsonl([
1559
- {
1560
- type: "user",
1561
- timestamp: "2026-03-27T10:00:00Z",
1562
- message: { content: [{ type: "text", text: "[Request interrupted by user]" }] },
1563
- },
1564
- { type: "user", timestamp: "2026-03-27T10:00:01Z", message: { content: "Tool loaded." } },
1565
- { type: "user", timestamp: "2026-03-27T10:00:02Z", message: { content: "Real question" } },
1566
- ]);
1567
-
1568
- const messages = adapter.getConversation(filePath);
1569
- expect(messages).toHaveLength(1);
1570
- expect(messages[0].content).toBe("Real question");
1571
- });
1572
- });
1573
-
1574
- describe("listSessions", () => {
1575
- let tmpDir: string;
1576
- let projectsDir: string;
1577
-
1578
- beforeEach(() => {
1579
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "claude-list-"));
1580
- projectsDir = path.join(tmpDir, "projects");
1581
- fs.mkdirSync(projectsDir, { recursive: true });
1582
- (adapter as any).projectsDir = projectsDir;
1583
- });
1584
-
1585
- afterEach(() => {
1586
- fs.rmSync(tmpDir, { recursive: true, force: true });
1587
- });
1588
-
1589
- function writeSession(projectDir: string, sessionId: string, lines: object[]): string {
1590
- fs.mkdirSync(projectDir, { recursive: true });
1591
- const filePath = path.join(projectDir, `${sessionId}.jsonl`);
1592
- fs.writeFileSync(filePath, lines.map((l) => JSON.stringify(l)).join("\n"));
1593
- return filePath;
1594
- }
1595
-
1596
- it("returns empty when projects dir does not exist", async () => {
1597
- fs.rmSync(projectsDir, { recursive: true, force: true });
1598
- const result = await adapter.listSessions();
1599
- expect(result).toEqual([]);
1600
- });
1601
-
1602
- it("returns sessions from a single cwd-scoped project dir", async () => {
1603
- const cwd = "/Users/test/proj";
1604
- const projDir = path.join(projectsDir, "-Users-test-proj");
1605
- const filePath = writeSession(projDir, "sess-1", [
1606
- {
1607
- type: "user",
1608
- timestamp: "2025-01-01T00:00:00Z",
1609
- cwd,
1610
- message: { content: "first prompt" },
1611
- },
1612
- { type: "assistant", timestamp: "2025-01-01T00:01:00Z" },
1613
- ]);
1614
-
1615
- const result = await adapter.listSessions({ cwd });
1616
-
1617
- expect(result).toHaveLength(1);
1618
- expect(result[0]).toMatchObject({
1619
- type: "claude",
1620
- sessionId: "sess-1",
1621
- cwd,
1622
- firstUserMessage: "first prompt",
1623
- sessionFilePath: filePath,
1624
- });
1625
- expect(result[0].lastActive).toBeInstanceOf(Date);
1626
- expect(result[0].startedAt).toBeInstanceOf(Date);
1627
- });
1628
-
1629
- it("lists sessions from all project dirs when no cwd filter", async () => {
1630
- const cwdA = "/Users/test/proj-a";
1631
- const cwdB = "/Users/test/proj-b";
1632
- writeSession(path.join(projectsDir, "-Users-test-proj-a"), "a", [
1633
- {
1634
- type: "user",
1635
- timestamp: "2025-01-01T00:00:00Z",
1636
- cwd: cwdA,
1637
- message: { content: "msg-a" },
1638
- },
1639
- ]);
1640
- writeSession(path.join(projectsDir, "-Users-test-proj-b"), "b", [
1641
- {
1642
- type: "user",
1643
- timestamp: "2025-01-02T00:00:00Z",
1644
- cwd: cwdB,
1645
- message: { content: "msg-b" },
1646
- },
1647
- ]);
1648
-
1649
- const result = await adapter.listSessions();
1650
-
1651
- expect(result).toHaveLength(2);
1652
- expect(result.map((r) => r.sessionId).sort()).toEqual(["a", "b"]);
1653
- const cwds = result.map((r) => r.cwd).sort();
1654
- expect(cwds).toEqual([cwdA, cwdB]);
1655
- });
1656
-
1657
- it("finds an exact session ID without returning other project sessions", async () => {
1658
- const wantedPath = writeSession(path.join(projectsDir, "-repo-a"), "wanted", [
1659
- {
1660
- type: "user",
1661
- timestamp: "2025-01-01T00:00:00Z",
1662
- cwd: "/repo-a",
1663
- message: { content: "wanted prompt" },
1664
- },
1665
- ]);
1666
- writeSession(path.join(projectsDir, "-repo-b"), "other", [
1667
- {
1668
- type: "user",
1669
- timestamp: "2025-01-01T00:00:00Z",
1670
- cwd: "/repo-b",
1671
- message: { content: "other prompt" },
1672
- },
1673
- ]);
1674
-
1675
- await expect(adapter.findSessionsById("wanted")).resolves.toEqual([
1676
- expect.objectContaining({ sessionId: "wanted", sessionFilePath: wantedPath }),
1677
- ]);
1678
- });
1679
-
1680
- it("drops sessions whose recorded cwd does not match opts.cwd (strict equality)", async () => {
1681
- const cwdReal = "/Users/test/foo";
1682
- const cwdRequested = "/Users/test/foo/sub";
1683
- writeSession(path.join(projectsDir, "-Users-test-foo"), "s", [
1684
- {
1685
- type: "user",
1686
- timestamp: "2025-01-01T00:00:00Z",
1687
- cwd: cwdReal,
1688
- message: { content: "hi" },
1689
- },
1690
- ]);
1691
-
1692
- // Encoded dir for the requested cwd doesn't exist → return []
1693
- const result = await adapter.listSessions({ cwd: cwdRequested });
1694
- expect(result).toEqual([]);
1695
- });
1696
-
1697
- it("drops sessions whose recorded cwd disagrees with the encoded dir", async () => {
1698
- // Edge case: encoded dir lookup matches, but session content
1699
- // records a different cwd. Strict-equality filter must reject.
1700
- const requested = "/Users/test/proj";
1701
- const projDir = path.join(projectsDir, "-Users-test-proj");
1702
- writeSession(projDir, "s", [
1703
- {
1704
- type: "user",
1705
- timestamp: "2025-01-01T00:00:00Z",
1706
- cwd: "/different/path",
1707
- message: { content: "mismatch" },
1708
- },
1709
- ]);
1710
-
1711
- const result = await adapter.listSessions({ cwd: requested });
1712
- expect(result).toEqual([]);
1713
- });
1714
-
1715
- it("finds sessions whose recorded cwd lives in a different encoded dir (worktree case)", async () => {
1716
- // Real-world case: Claude Code is launched in /repo, then chdirs into
1717
- // /repo/.worktrees/feature. The session file is stored under the
1718
- // ENCODED launch dir, but its content records the worktree path.
1719
- // listSessions({ cwd: worktree }) must still find it.
1720
- const launchDir = path.join(projectsDir, "-repo");
1721
- const worktreeCwd = "/repo/.worktrees/feature";
1722
- writeSession(launchDir, "wt", [
1723
- {
1724
- type: "user",
1725
- timestamp: "2025-01-01T00:00:00Z",
1726
- cwd: worktreeCwd,
1727
- message: { content: "in worktree" },
1728
- },
1729
- ]);
1730
-
1731
- const result = await adapter.listSessions({ cwd: worktreeCwd });
1732
- expect(result).toHaveLength(1);
1733
- expect(result[0]).toMatchObject({
1734
- sessionId: "wt",
1735
- cwd: worktreeCwd,
1736
- firstUserMessage: "in worktree",
1737
- });
1738
- });
1739
-
1740
- it("skips malformed session files", async () => {
1741
- const cwd = "/Users/test/p";
1742
- const projDir = path.join(projectsDir, "-Users-test-p");
1743
- fs.mkdirSync(projDir, { recursive: true });
1744
- fs.writeFileSync(path.join(projDir, "bad.jsonl"), "not valid json");
1745
- writeSession(projDir, "good", [
1746
- { type: "user", timestamp: "2025-01-01T00:00:00Z", cwd, message: { content: "ok" } },
1747
- ]);
1748
-
1749
- const result = await adapter.listSessions({ cwd });
1750
- expect(result).toHaveLength(1);
1751
- expect(result[0].sessionId).toBe("good");
1752
- });
1753
-
1754
- it("captures first user message after filtering noise", async () => {
1755
- const cwd = "/Users/test/q";
1756
- writeSession(path.join(projectsDir, "-Users-test-q"), "s", [
1757
- {
1758
- type: "user",
1759
- timestamp: "2025-01-01T00:00:00Z",
1760
- cwd,
1761
- message: { content: "Tool loaded." },
1762
- },
1763
- {
1764
- type: "user",
1765
- timestamp: "2025-01-01T00:00:01Z",
1766
- cwd,
1767
- message: { content: "real first prompt" },
1768
- },
1769
- {
1770
- type: "user",
1771
- timestamp: "2025-01-01T00:00:02Z",
1772
- cwd,
1773
- message: { content: "second prompt" },
1774
- },
1775
- ]);
1776
-
1777
- const result = await adapter.listSessions({ cwd });
1778
- expect(result).toHaveLength(1);
1779
- expect(result[0].firstUserMessage).toBe("real first prompt");
1780
- });
1781
-
1782
- it("returns empty firstUserMessage when no user message exists", async () => {
1783
- const cwd = "/Users/test/empty";
1784
- writeSession(path.join(projectsDir, "-Users-test-empty"), "s", [
1785
- { type: "assistant", timestamp: "2025-01-01T00:00:00Z" },
1786
- ]);
1787
-
1788
- const result = await adapter.listSessions({ cwd });
1789
- expect(result).toHaveLength(1);
1790
- expect(result[0].firstUserMessage).toBe("");
1791
- });
1792
- });
1793
- });