@edspencer/paddock 0.0.1 → 0.56.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 (294) hide show
  1. package/README.md +69 -0
  2. package/install-notice.mjs +29 -0
  3. package/package.json +58 -5
  4. package/packages/server/dist/adoptable.d.ts +127 -0
  5. package/packages/server/dist/adoptable.js +315 -0
  6. package/packages/server/dist/app.d.ts +67 -0
  7. package/packages/server/dist/app.js +325 -0
  8. package/packages/server/dist/archive.d.ts +42 -0
  9. package/packages/server/dist/archive.js +125 -0
  10. package/packages/server/dist/attachments-config.d.ts +114 -0
  11. package/packages/server/dist/attachments-config.js +165 -0
  12. package/packages/server/dist/attachments-hint.d.ts +53 -0
  13. package/packages/server/dist/attachments-hint.js +140 -0
  14. package/packages/server/dist/attachments.d.ts +33 -0
  15. package/packages/server/dist/attachments.js +117 -0
  16. package/packages/server/dist/auth.d.ts +84 -0
  17. package/packages/server/dist/auth.js +247 -0
  18. package/packages/server/dist/background.d.ts +36 -0
  19. package/packages/server/dist/background.js +137 -0
  20. package/packages/server/dist/bind-safety.d.ts +56 -0
  21. package/packages/server/dist/bind-safety.js +51 -0
  22. package/packages/server/dist/brand.d.ts +44 -0
  23. package/packages/server/dist/brand.js +88 -0
  24. package/packages/server/dist/chat-dto.d.ts +210 -0
  25. package/packages/server/dist/chat-dto.js +308 -0
  26. package/packages/server/dist/cli/import-chats.d.ts +21 -0
  27. package/packages/server/dist/cli/import-chats.js +197 -0
  28. package/packages/server/dist/cli/paddock.d.ts +2 -0
  29. package/packages/server/dist/cli/paddock.js +247 -0
  30. package/packages/server/dist/concurrency.d.ts +57 -0
  31. package/packages/server/dist/concurrency.js +71 -0
  32. package/packages/server/dist/config.d.ts +512 -0
  33. package/packages/server/dist/config.js +593 -0
  34. package/packages/server/dist/curation-config.d.ts +55 -0
  35. package/packages/server/dist/curation-config.js +64 -0
  36. package/packages/server/dist/event-bus.d.ts +87 -0
  37. package/packages/server/dist/event-bus.js +48 -0
  38. package/packages/server/dist/git.d.ts +128 -0
  39. package/packages/server/dist/git.js +446 -0
  40. package/packages/server/dist/github-auth.d.ts +44 -0
  41. package/packages/server/dist/github-auth.js +169 -0
  42. package/packages/server/dist/herdctl-agent-config.d.ts +98 -0
  43. package/packages/server/dist/herdctl-agent-config.js +331 -0
  44. package/packages/server/dist/herdctl-agent-names.d.ts +172 -0
  45. package/packages/server/dist/herdctl-agent-names.js +228 -0
  46. package/packages/server/dist/herdctl-jobs-index.d.ts +65 -0
  47. package/packages/server/dist/herdctl-jobs-index.js +225 -0
  48. package/packages/server/dist/herdctl-jobs.d.ts +98 -0
  49. package/packages/server/dist/herdctl-jobs.js +225 -0
  50. package/packages/server/dist/herdctl.d.ts +572 -0
  51. package/packages/server/dist/herdctl.js +1218 -0
  52. package/packages/server/dist/hook-config.d.ts +217 -0
  53. package/packages/server/dist/hook-config.js +224 -0
  54. package/packages/server/dist/http-bytes.d.ts +24 -0
  55. package/packages/server/dist/http-bytes.js +52 -0
  56. package/packages/server/dist/index.d.ts +1 -0
  57. package/packages/server/dist/index.js +14 -0
  58. package/packages/server/dist/instance-config.d.ts +135 -0
  59. package/packages/server/dist/instance-config.js +345 -0
  60. package/packages/server/dist/localcommand.d.ts +23 -0
  61. package/packages/server/dist/localcommand.js +140 -0
  62. package/packages/server/dist/management-auth.d.ts +99 -0
  63. package/packages/server/dist/management-auth.js +165 -0
  64. package/packages/server/dist/management-config.d.ts +164 -0
  65. package/packages/server/dist/management-config.js +286 -0
  66. package/packages/server/dist/management-mcp-server.d.ts +20 -0
  67. package/packages/server/dist/management-mcp-server.js +95 -0
  68. package/packages/server/dist/management-metadata.d.ts +67 -0
  69. package/packages/server/dist/management-metadata.js +56 -0
  70. package/packages/server/dist/management-ops.d.ts +110 -0
  71. package/packages/server/dist/management-ops.js +449 -0
  72. package/packages/server/dist/management-policy.d.ts +172 -0
  73. package/packages/server/dist/management-policy.js +259 -0
  74. package/packages/server/dist/message-provenance.d.ts +112 -0
  75. package/packages/server/dist/message-provenance.js +260 -0
  76. package/packages/server/dist/models.d.ts +164 -0
  77. package/packages/server/dist/models.js +208 -0
  78. package/packages/server/dist/openapi.d.ts +66 -0
  79. package/packages/server/dist/openapi.js +183 -0
  80. package/packages/server/dist/parent-detach.d.ts +30 -0
  81. package/packages/server/dist/parent-detach.js +109 -0
  82. package/packages/server/dist/preload.d.ts +43 -0
  83. package/packages/server/dist/preload.js +55 -0
  84. package/packages/server/dist/project-files.d.ts +76 -0
  85. package/packages/server/dist/project-files.js +191 -0
  86. package/packages/server/dist/project-mime.d.ts +35 -0
  87. package/packages/server/dist/project-mime.js +55 -0
  88. package/packages/server/dist/project-paths.d.ts +88 -0
  89. package/packages/server/dist/project-paths.js +126 -0
  90. package/packages/server/dist/project-types.d.ts +316 -0
  91. package/packages/server/dist/project-types.js +48 -0
  92. package/packages/server/dist/projects.d.ts +202 -0
  93. package/packages/server/dist/projects.js +894 -0
  94. package/packages/server/dist/queued-message.d.ts +35 -0
  95. package/packages/server/dist/queued-message.js +116 -0
  96. package/packages/server/dist/read-state.d.ts +46 -0
  97. package/packages/server/dist/read-state.js +139 -0
  98. package/packages/server/dist/recovery-config.d.ts +111 -0
  99. package/packages/server/dist/recovery-config.js +105 -0
  100. package/packages/server/dist/recovery.d.ts +262 -0
  101. package/packages/server/dist/recovery.js +490 -0
  102. package/packages/server/dist/resume-drain.d.ts +122 -0
  103. package/packages/server/dist/resume-drain.js +158 -0
  104. package/packages/server/dist/route-context.d.ts +168 -0
  105. package/packages/server/dist/route-context.js +39 -0
  106. package/packages/server/dist/route-errors.d.ts +8 -0
  107. package/packages/server/dist/route-errors.js +13 -0
  108. package/packages/server/dist/routes/chats.d.ts +12 -0
  109. package/packages/server/dist/routes/chats.js +1406 -0
  110. package/packages/server/dist/routes/git.d.ts +13 -0
  111. package/packages/server/dist/routes/git.js +236 -0
  112. package/packages/server/dist/routes/mcp.d.ts +83 -0
  113. package/packages/server/dist/routes/mcp.js +250 -0
  114. package/packages/server/dist/routes/meta.d.ts +15 -0
  115. package/packages/server/dist/routes/meta.js +447 -0
  116. package/packages/server/dist/routes/projects.d.ts +25 -0
  117. package/packages/server/dist/routes/projects.js +736 -0
  118. package/packages/server/dist/routes/triggers.d.ts +21 -0
  119. package/packages/server/dist/routes/triggers.js +324 -0
  120. package/packages/server/dist/routes/workspace-mount.d.ts +48 -0
  121. package/packages/server/dist/routes/workspace-mount.js +32 -0
  122. package/packages/server/dist/routes.d.ts +26 -0
  123. package/packages/server/dist/routes.js +29 -0
  124. package/packages/server/dist/run-provenance.d.ts +109 -0
  125. package/packages/server/dist/run-provenance.js +206 -0
  126. package/packages/server/dist/runs.d.ts +92 -0
  127. package/packages/server/dist/runs.js +72 -0
  128. package/packages/server/dist/schedule-config.d.ts +68 -0
  129. package/packages/server/dist/schedule-config.js +75 -0
  130. package/packages/server/dist/schedule-session.d.ts +34 -0
  131. package/packages/server/dist/schedule-session.js +120 -0
  132. package/packages/server/dist/self-mcp-descriptions.d.ts +20 -0
  133. package/packages/server/dist/self-mcp-descriptions.js +145 -0
  134. package/packages/server/dist/self-mcp-read.d.ts +15 -0
  135. package/packages/server/dist/self-mcp-read.js +97 -0
  136. package/packages/server/dist/self-mcp-triggers.d.ts +30 -0
  137. package/packages/server/dist/self-mcp-triggers.js +144 -0
  138. package/packages/server/dist/self-mcp-types.d.ts +248 -0
  139. package/packages/server/dist/self-mcp-types.js +10 -0
  140. package/packages/server/dist/self-mcp-util.d.ts +73 -0
  141. package/packages/server/dist/self-mcp-util.js +157 -0
  142. package/packages/server/dist/self-mcp-write.d.ts +35 -0
  143. package/packages/server/dist/self-mcp-write.js +215 -0
  144. package/packages/server/dist/self-mcp.d.ts +95 -0
  145. package/packages/server/dist/self-mcp.js +448 -0
  146. package/packages/server/dist/send-file-mcp.d.ts +46 -0
  147. package/packages/server/dist/send-file-mcp.js +281 -0
  148. package/packages/server/dist/session-hub.d.ts +186 -0
  149. package/packages/server/dist/session-hub.js +291 -0
  150. package/packages/server/dist/spawn-capability.d.ts +99 -0
  151. package/packages/server/dist/spawn-capability.js +106 -0
  152. package/packages/server/dist/star.d.ts +26 -0
  153. package/packages/server/dist/star.js +94 -0
  154. package/packages/server/dist/start.d.ts +1 -0
  155. package/packages/server/dist/start.js +21 -0
  156. package/packages/server/dist/subagents.d.ts +337 -0
  157. package/packages/server/dist/subagents.js +626 -0
  158. package/packages/server/dist/sweep.d.ts +122 -0
  159. package/packages/server/dist/sweep.js +696 -0
  160. package/packages/server/dist/tooldetails.d.ts +33 -0
  161. package/packages/server/dist/tooldetails.js +466 -0
  162. package/packages/server/dist/transcribe.d.ts +69 -0
  163. package/packages/server/dist/transcribe.js +119 -0
  164. package/packages/server/dist/transcripts.d.ts +42 -0
  165. package/packages/server/dist/transcripts.js +164 -0
  166. package/packages/server/dist/trigger-config.d.ts +278 -0
  167. package/packages/server/dist/trigger-config.js +417 -0
  168. package/packages/server/dist/trigger-runtime.d.ts +94 -0
  169. package/packages/server/dist/trigger-runtime.js +82 -0
  170. package/packages/server/dist/trigger-session.d.ts +34 -0
  171. package/packages/server/dist/trigger-session.js +122 -0
  172. package/packages/server/dist/triggers.d.ts +83 -0
  173. package/packages/server/dist/triggers.js +124 -0
  174. package/packages/server/dist/trusted-proxy.d.ts +57 -0
  175. package/packages/server/dist/trusted-proxy.js +157 -0
  176. package/packages/server/dist/turn-notice.d.ts +154 -0
  177. package/packages/server/dist/turn-notice.js +271 -0
  178. package/packages/server/dist/unread.d.ts +36 -0
  179. package/packages/server/dist/unread.js +123 -0
  180. package/packages/server/dist/usage.d.ts +66 -0
  181. package/packages/server/dist/usage.js +243 -0
  182. package/packages/server/dist/wake-injection.d.ts +156 -0
  183. package/packages/server/dist/wake-injection.js +136 -0
  184. package/packages/server/dist/whisper-local.d.ts +9 -0
  185. package/packages/server/dist/whisper-local.js +122 -0
  186. package/packages/server/dist/ws-context.d.ts +158 -0
  187. package/packages/server/dist/ws-context.js +1 -0
  188. package/packages/server/dist/ws-protocol.d.ts +423 -0
  189. package/packages/server/dist/ws-protocol.js +251 -0
  190. package/packages/server/dist/ws-self-mcp.d.ts +52 -0
  191. package/packages/server/dist/ws-self-mcp.js +28 -0
  192. package/packages/server/dist/ws-triggers.d.ts +29 -0
  193. package/packages/server/dist/ws-triggers.js +261 -0
  194. package/packages/server/dist/ws-turn.d.ts +86 -0
  195. package/packages/server/dist/ws-turn.js +751 -0
  196. package/packages/server/dist/ws.d.ts +62 -0
  197. package/packages/server/dist/ws.js +1024 -0
  198. package/packages/server/package.json +6 -0
  199. package/packages/web/dist/assets/InstanceConfigPage-4cQGTj9Y.js +2 -0
  200. package/packages/web/dist/assets/MarkdownRenderer-CJZFLj_8.js +30 -0
  201. package/packages/web/dist/assets/ProjectRedirect-BHwVbbqB.js +2 -0
  202. package/packages/web/dist/assets/ProjectView-BOvuAITg.js +13 -0
  203. package/packages/web/dist/assets/ProjectsGrid-BCojZOGY.js +2 -0
  204. package/packages/web/dist/assets/arc-BVyxvnkl.js +2 -0
  205. package/packages/web/dist/assets/architectureDiagram-3BPJPVTR-Cd9Puqg1.js +37 -0
  206. package/packages/web/dist/assets/bash-I8pq0VWm.js +2 -0
  207. package/packages/web/dist/assets/blockDiagram-GPEHLZMM-B_AQt_Rx.js +133 -0
  208. package/packages/web/dist/assets/c-D2F1sQUL.js +2 -0
  209. package/packages/web/dist/assets/c4Diagram-AAUBKEIU-7e0TQtXB.js +11 -0
  210. package/packages/web/dist/assets/channel-C_1aISNn.js +2 -0
  211. package/packages/web/dist/assets/chunk-2J33WTMH-Dz4WZmUZ.js +2 -0
  212. package/packages/web/dist/assets/chunk-4BX2VUAB-DVWYldo6.js +2 -0
  213. package/packages/web/dist/assets/chunk-55IACEB6-BIMrizQd.js +2 -0
  214. package/packages/web/dist/assets/chunk-727SXJPM-CL2q9fF1.js +207 -0
  215. package/packages/web/dist/assets/chunk-AQP2D5EJ-BSq3HlQ9.js +232 -0
  216. package/packages/web/dist/assets/chunk-FMBD7UC4-Bgt64pLE.js +16 -0
  217. package/packages/web/dist/assets/chunk-ND2GUHAM-C8Pr2A38.js +2 -0
  218. package/packages/web/dist/assets/chunk-QZHKN3VN-BAOqh-MN.js +2 -0
  219. package/packages/web/dist/assets/classDiagram-4FO5ZUOK-B8JE7cHJ.js +2 -0
  220. package/packages/web/dist/assets/classDiagram-v2-Q7XG4LA2-B8JE7cHJ.js +2 -0
  221. package/packages/web/dist/assets/core-lJeGACQg.js +4 -0
  222. package/packages/web/dist/assets/cose-bilkent-S5V4N54A-BF4tameA.js +2 -0
  223. package/packages/web/dist/assets/cpp-Bm3ii6kY.js +2 -0
  224. package/packages/web/dist/assets/csharp-BNpuYZMG.js +2 -0
  225. package/packages/web/dist/assets/css-DazXZka4.js +2 -0
  226. package/packages/web/dist/assets/cytoscape.esm-CUqq0XTU.js +332 -0
  227. package/packages/web/dist/assets/dagre-BM42HDAG-DdsLM6ql.js +5 -0
  228. package/packages/web/dist/assets/defaultLocale-DX6XiGOO.js +2 -0
  229. package/packages/web/dist/assets/diagram-2AECGRRQ-BQ78S_RM.js +44 -0
  230. package/packages/web/dist/assets/diagram-5GNKFQAL-CAKE6nHE.js +11 -0
  231. package/packages/web/dist/assets/diagram-KO2AKTUF-fEvHRXgr.js +4 -0
  232. package/packages/web/dist/assets/diagram-LMA3HP47-CtWsgeSm.js +25 -0
  233. package/packages/web/dist/assets/diagram-OG6HWLK6-Buog8k7_.js +25 -0
  234. package/packages/web/dist/assets/erDiagram-TEJ5UH35-CWvVVPZS.js +86 -0
  235. package/packages/web/dist/assets/flowDiagram-I6XJVG4X-DsCGXtp4.js +163 -0
  236. package/packages/web/dist/assets/format-DamJQ9LO.js +2 -0
  237. package/packages/web/dist/assets/ganttDiagram-6RSMTGT7-CsdwIvvC.js +293 -0
  238. package/packages/web/dist/assets/gitGraphDiagram-PVQCEYII-hZvrX1sD.js +107 -0
  239. package/packages/web/dist/assets/go-BPx_y7j8.js +2 -0
  240. package/packages/web/dist/assets/graph-BlwPajkw.js +2 -0
  241. package/packages/web/dist/assets/index-CGbZdrm8.js +71 -0
  242. package/packages/web/dist/assets/index-DJDQ210-.css +1 -0
  243. package/packages/web/dist/assets/infoDiagram-5YYISTIA-nE_Vtz_l.js +3 -0
  244. package/packages/web/dist/assets/ini-B3BVgEsG.js +2 -0
  245. package/packages/web/dist/assets/init-Gi6I4Gst.js +2 -0
  246. package/packages/web/dist/assets/ishikawaDiagram-YF4QCWOH-2Nlqs0oH.js +71 -0
  247. package/packages/web/dist/assets/java-B5VKqtH2.js +2 -0
  248. package/packages/web/dist/assets/javascript-BKRaQes9.js +2 -0
  249. package/packages/web/dist/assets/journeyDiagram-JHISSGLW-mjU1fMc4.js +140 -0
  250. package/packages/web/dist/assets/json-DIYVocXf.js +2 -0
  251. package/packages/web/dist/assets/kanban-definition-UN3LZRKU-C_9xNaa3.js +90 -0
  252. package/packages/web/dist/assets/katex-C5jXJg4s.js +258 -0
  253. package/packages/web/dist/assets/kotlin-Cw-eF_bm.js +3 -0
  254. package/packages/web/dist/assets/lastTab-CU1zsF0j.js +2 -0
  255. package/packages/web/dist/assets/layout-Boy8vhSP.js +2 -0
  256. package/packages/web/dist/assets/linear-BxKd91ho.js +2 -0
  257. package/packages/web/dist/assets/mermaid.core-C-CuhD8I.js +310 -0
  258. package/packages/web/dist/assets/mindmap-definition-RKZ34NQL-Bs6yfcZv.js +97 -0
  259. package/packages/web/dist/assets/ordinal-Cboi1Yqb.js +2 -0
  260. package/packages/web/dist/assets/php-CRdd4dfS.js +3 -0
  261. package/packages/web/dist/assets/pieDiagram-4H26LBE5-DNdqX7O5.js +31 -0
  262. package/packages/web/dist/assets/python-kSlZHhJb.js +2 -0
  263. package/packages/web/dist/assets/quadrantDiagram-W4KKPZXB-ZMJl9OdZ.js +8 -0
  264. package/packages/web/dist/assets/queued-LamEU0GH.js +2 -0
  265. package/packages/web/dist/assets/requirementDiagram-4Y6WPE33-RmxMdm2q.js +85 -0
  266. package/packages/web/dist/assets/ruby-7T4ktxyv.js +2 -0
  267. package/packages/web/dist/assets/rust-HC3MBUhY.js +2 -0
  268. package/packages/web/dist/assets/sankeyDiagram-5OEKKPKP-OAAhWcfK.js +41 -0
  269. package/packages/web/dist/assets/scss-DZLA7YXz.js +2 -0
  270. package/packages/web/dist/assets/sequenceDiagram-3UESZ5HK-BWF7rCyN.js +163 -0
  271. package/packages/web/dist/assets/sql-BC88IN-V.js +2 -0
  272. package/packages/web/dist/assets/stateDiagram-AJRCARHV-M3b_zqqo.js +2 -0
  273. package/packages/web/dist/assets/stateDiagram-v2-BHNVJYJU-CI7saFDa.js +2 -0
  274. package/packages/web/dist/assets/swift-Dn8kKO_1.js +2 -0
  275. package/packages/web/dist/assets/timeline-definition-PNZ67QCA-BpOCh63N.js +121 -0
  276. package/packages/web/dist/assets/typescript-C2FFdlUC.js +2 -0
  277. package/packages/web/dist/assets/vennDiagram-CIIHVFJN-D_iPH45Q.js +35 -0
  278. package/packages/web/dist/assets/wardley-L42UT6IY-DVD9I2Om.js +174 -0
  279. package/packages/web/dist/assets/wardleyDiagram-YWT4CUSO-Bn1IKwjn.js +79 -0
  280. package/packages/web/dist/assets/xml-BXBhIUeX.js +2 -0
  281. package/packages/web/dist/assets/xychartDiagram-2RQKCTM6-DwtI0bkR.js +8 -0
  282. package/packages/web/dist/assets/yaml-drsDnIKT.js +2 -0
  283. package/packages/web/dist/favicon.ico +0 -0
  284. package/packages/web/dist/fonts/inter-latin.woff2 +0 -0
  285. package/packages/web/dist/fonts/jetbrains-mono-latin.woff2 +0 -0
  286. package/packages/web/dist/icons/apple-touch-icon.png +0 -0
  287. package/packages/web/dist/icons/favicon-16.png +0 -0
  288. package/packages/web/dist/icons/favicon-32.png +0 -0
  289. package/packages/web/dist/icons/icon-192.png +0 -0
  290. package/packages/web/dist/icons/icon-512.png +0 -0
  291. package/packages/web/dist/icons/maskable-512.png +0 -0
  292. package/packages/web/dist/index.html +56 -0
  293. package/packages/web/dist/manifest.webmanifest +32 -0
  294. package/packages/web/dist/sw.js +139 -0
@@ -0,0 +1,1218 @@
1
+ /**
2
+ * HerdctlService — REAL wrapper around @herdctl/core's FleetManager.
3
+ *
4
+ * This module is NOT a stub: it imports and constructs the public
5
+ * @herdctl/core API (paddock depends on ^5.27.0). It is the single seam between
6
+ * paddock and herdctl, so that any remaining gaps in the public API are isolated
7
+ * here. See docs/INTEGRATION.md for the verified call-by-call contract.
8
+ *
9
+ * As of @herdctl/core 5.11.0 the four prior app-layer workarounds are GONE —
10
+ * paddock now uses the first-class APIs:
11
+ *
12
+ * - **Runtime agents:** `fleet.addAgent({...})` / `fleet.removeAgent(name)`
13
+ * register/unregister a project's keeper + sweeper agents in memory. No more
14
+ * generate-per-agent-yaml + regenerate-herdctl.yaml + `reload()` dance. The
15
+ * FleetManager boots from a minimal zero-agent config (fleet + defaults only)
16
+ * and every agent is added programmatically. `addAgent` validates the config,
17
+ * deep-merges fleet `defaults`, resolves the working_directory to an absolute
18
+ * path, and wires it into the scheduler so it is immediately triggerable and
19
+ * shows up in `getFleetStatus()` / `getAgentInfo()`.
20
+ *
21
+ * - **Sessions:** `fleet.getAgentSessions(name, {limit})` and
22
+ * `fleet.getAgentSessionMessages(name, sessionId)` derive the agent's
23
+ * working_directory + Docker mode from the loaded config — no hand-rolled
24
+ * SessionDiscoveryService keyed on working dirs.
25
+ *
26
+ * - **Streaming:** `trigger(agent, schedule?, { onMessage, prompt, resume })`.
27
+ * `onMessage(msg: SDKMessage)` fires per SDK message; the returned
28
+ * TriggerResult carries the final `sessionId`. New chat = `resume: null`;
29
+ * resume = `resume: <sessionId>`. This is the `batch` drive-mode path; the
30
+ * default `session` mode instead drives `openChatSession`, which ALWAYS runs
31
+ * the SDK runtime regardless of the agent's `runtime` field (see #585).
32
+ *
33
+ * - **Delete / rename a chat:** `fleet.deleteSession(name, sessionId)` removes
34
+ * the transcript (and invalidates the discovery cache), and
35
+ * `fleet.setSessionName(name, sessionId, customName)` sets a custom name —
36
+ * both keyed by agent name, no deep imports.
37
+ *
38
+ * Freshness note: `fleet.getAgentSessions` uses the FleetManager's internal
39
+ * SessionDiscoveryService, which has a 30s directory cache. A brand-new
40
+ * project's transcript dir does not exist until its first turn, and the
41
+ * discovery service does NOT cache a missing directory — so the first session
42
+ * of a project surfaces immediately. `deleteSession`/`setSessionName` invalidate
43
+ * the cache internally. The one nuance vs. the prior code: a *second* new chat
44
+ * created in an already-listed project within 30s may take up to the cache TTL
45
+ * to appear (the prior code invalidated a private cache we can no longer reach).
46
+ * That last nuance is now closed too: core exposes `fleet.invalidateSessions(name)`
47
+ * and paddock calls it after each turn (`ws-turn.ts`) and around fork/promote.
48
+ */
49
+ import { FleetManager, countPendingAsyncQueueEntries, getCliSessionFile, } from "@herdctl/core";
50
+ import { consumeResumedTurn, consumeBackgroundTurns } from "./resume-drain.js";
51
+ import { createSDKMessageHandler } from "@herdctl/chat";
52
+ import { promises as fs } from "node:fs";
53
+ import { randomUUID } from "node:crypto";
54
+ import path from "node:path";
55
+ import { DEFAULT_MODEL } from "./models.js";
56
+ import { ensureProjectChats, projectChatsDir } from "./transcripts.js";
57
+ import { triggerRunsOnOwnAgent, isCuratorTrigger, } from "./trigger-config.js";
58
+ import { buildAgentConfig, buildSweeperConfig, sweeperWorkingDir, buildTriggerConfig, ensureConfigFile as writeBootConfigFile, } from "./herdctl-agent-config.js";
59
+ import * as jobs from "./herdctl-jobs.js";
60
+ import { JobsDirIndex } from "./herdctl-jobs-index.js";
61
+ import { AdoptableIndex } from "./adoptable.js";
62
+ /**
63
+ * The name/visibility helpers + tool/model constants are pure (they only read
64
+ * their arguments, no fleet/cfg/session state), so they live in a sibling module
65
+ * for readability + isolated unit-testing (issue #403). Re-exported here so every
66
+ * external importer keeps resolving them via `./herdctl.js` unchanged.
67
+ */
68
+ export { keeperAgentName, keeperSlugFromAgent, SWEEPER_PREFIX, sweeperAgentName, HOOK_AGENT_PREFIX, hookAgentName, TRIGGER_AGENT_PREFIX, triggerAgentName, visibleProjectAgentNames, BROWSER_MCP_TOOL, DENIED_TOOLS, browserMcpServers, KEEPER_MAX_CONCURRENT, KEEPER_SESSION_TIMEOUT, } from "./herdctl-agent-names.js";
69
+ import { keeperAgentName, sweeperAgentName, hookAgentName, triggerAgentName, visibleProjectAgentNames, } from "./herdctl-agent-names.js";
70
+ /**
71
+ * Slice a Claude Code transcript to the PREFIX up to and including the message
72
+ * turn anchored at `cutUuid` (issue #451 — fork/revert from a point). Returns the
73
+ * sliced JSONL, or null if no record carries that uuid.
74
+ *
75
+ * A logical turn spans several JSONL records: one assistant message is written as
76
+ * one record per content block (text, tool_use, …), all sharing one `message.id`
77
+ * but each with its own `uuid`; a tool_use is then answered by a `type:"user"`
78
+ * `tool_result` record. To keep the kept prefix internally consistent (no
79
+ * assistant tool_use left without its result, which would break resume), after
80
+ * the anchor record we greedily absorb (a) further records of the same
81
+ * `message.id` — the anchor message's sibling blocks — and (b) immediately
82
+ * following `type:"user"` tool_result records answering them, stopping at the
83
+ * next genuine new turn. This is exact for plain chat turns (the primary case);
84
+ * for deeply interleaved tool turns the boundary is a safe over-include.
85
+ *
86
+ * `endOnCompletedAssistant` (used by REVERT, #451): when the anchor is one of the
87
+ * USER's own prompts, don't keep it as a dangling un-answered trailing turn —
88
+ * Paddock's resume-drain would replay that as a phantom turn on the next resume
89
+ * and the model would read the prompt as stale backlog. Instead, land the cut on
90
+ * the last COMPLETED assistant turn before that prompt (a record with a terminal
91
+ * `stop_reason`), so "revert to one of my messages" rewinds to the AI's reply
92
+ * just before it and the next message continues cleanly. Fork leaves this off so
93
+ * a fork from a user message keeps it (the fork's keeper answers it).
94
+ */
95
+ const TERMINAL_STOP = new Set(["end_turn", "stop_sequence", "max_tokens"]);
96
+ export function sliceTranscriptAtUuid(raw, cutUuid, endOnCompletedAssistant = false) {
97
+ const lines = raw.split("\n");
98
+ const meta = lines.map((ln) => {
99
+ const t = ln.trim();
100
+ if (!t)
101
+ return null;
102
+ try {
103
+ const o = JSON.parse(t);
104
+ const content = o.message?.content;
105
+ const hasToolResult = Array.isArray(content) &&
106
+ content.some((b) => b?.type === "tool_result");
107
+ const stop = o.message?.stop_reason;
108
+ return {
109
+ uuid: typeof o.uuid === "string" ? o.uuid : undefined,
110
+ type: o.type,
111
+ mid: typeof o.message?.id === "string" ? o.message.id : undefined,
112
+ hasToolResult,
113
+ // A completed assistant turn — safe boundary to end a reverted transcript on.
114
+ terminalAssistant: o.type === "assistant" && typeof stop === "string" && TERMINAL_STOP.has(stop),
115
+ };
116
+ }
117
+ catch {
118
+ return null;
119
+ }
120
+ });
121
+ let idx = -1;
122
+ let anchorMid;
123
+ for (let i = 0; i < meta.length; i++) {
124
+ if (meta[i]?.uuid === cutUuid) {
125
+ idx = i;
126
+ anchorMid = meta[i].mid;
127
+ break;
128
+ }
129
+ }
130
+ if (idx === -1)
131
+ return null;
132
+ // Revert to one of the user's own prompts → rewind to the last completed
133
+ // assistant turn before it, rather than leaving a dangling un-answered prompt.
134
+ if (endOnCompletedAssistant && meta[idx].type === "user" && !meta[idx].hasToolResult) {
135
+ for (let b = idx - 1; b >= 0; b--) {
136
+ if (meta[b]?.terminalAssistant) {
137
+ return lines.slice(0, b + 1).join("\n") + "\n";
138
+ }
139
+ }
140
+ // No completed assistant turn precedes it (e.g. the first user message): fall
141
+ // through to the normal inclusive slice — there's no cleaner boundary.
142
+ }
143
+ let end = idx;
144
+ for (let j = idx + 1; j < meta.length; j++) {
145
+ const m = meta[j];
146
+ if (m === null) {
147
+ // Blank line — includable filler; keep scanning.
148
+ end = j;
149
+ continue;
150
+ }
151
+ if (anchorMid && m.mid === anchorMid) {
152
+ end = j; // a sibling content block of the anchor's assistant message
153
+ continue;
154
+ }
155
+ if (m.type === "user" && m.hasToolResult) {
156
+ end = j; // a tool_result answering a kept tool_use
157
+ continue;
158
+ }
159
+ break;
160
+ }
161
+ return lines.slice(0, end + 1).join("\n") + "\n";
162
+ }
163
+ export class HerdctlService {
164
+ cfg;
165
+ fleet = null;
166
+ started = false;
167
+ /**
168
+ * The model currently registered for each agent (keyed by agent name). Lets
169
+ * `ensureAgentModel` skips a re-registration when the
170
+ * requested model already matches the live agent config.
171
+ *
172
+ * SINGLE-USER CAVEAT: the keeper is one shared agent per project, so the
173
+ * model is last-write-wins across concurrent chats of the same project — if
174
+ * two chats of the same project pick different models, whichever triggered
175
+ * last wins for both. Acceptable for paddock's single-user POC; a clean
176
+ * per-trigger model override is a herdctl follow-up.
177
+ */
178
+ agentModels = new Map();
179
+ /**
180
+ * Each agent's working directory (the keeper's cwd), recorded at
181
+ * registration. Used to resolve the `claude` CLI transcript for a resume so we
182
+ * can measure its pending async-input-queue depth (the resume self-interrupt
183
+ * fix's residue gate — see {@link residueDepthFor} + `./resume-drain.ts`).
184
+ */
185
+ agentWorkingDirs = new Map();
186
+ /**
187
+ * Live session-mode turns keyed by the synthetic turn id we hand back as the
188
+ * `jobId` (Paddock#111). `openChatSession` creates no herdctl job record, so
189
+ * there's no core `jobId` to cancel via `cancelJob`; instead we register the
190
+ * live {@link RuntimeSession} here and Stop → `session.interrupt()` (see
191
+ * {@link cancel}). Entries are removed when the turn's stream ends.
192
+ */
193
+ liveSessions = new Map();
194
+ /**
195
+ * Incremental index of `<stateDir>/jobs`, backing the unread-badge reads
196
+ * (`lastTurnCompletedAt*`) — one per service, reused across requests so a warm
197
+ * scan only parses records it has never seen (#529). See
198
+ * `./herdctl-jobs-index.ts` for the invariant it rests on and its invalidation.
199
+ *
200
+ * Built lazily on first read, like the job-record helpers it replaced: unit
201
+ * tests construct this service against a partial config with no `stateDir`,
202
+ * and must keep being able to.
203
+ */
204
+ jobsIndexOrNull = null;
205
+ get jobsIndex() {
206
+ return (this.jobsIndexOrNull ??= new JobsDirIndex(this.cfg.stateDir));
207
+ }
208
+ constructor(cfg) {
209
+ this.cfg = cfg;
210
+ }
211
+ /**
212
+ * Construct + initialize the FleetManager against a minimal zero-agent
213
+ * config (fleet + defaults only). Agents are then registered programmatically
214
+ * via `fleet.addAgent(...)` — a keeper + sweeper for each workspace, the root
215
+ * included. No per-agent yaml files; no `reload()`.
216
+ */
217
+ async init(projects) {
218
+ await this.ensureConfigFile();
219
+ this.fleet = new FleetManager({
220
+ configPath: this.cfg.herdctlConfigPath,
221
+ stateDir: this.cfg.stateDir,
222
+ // Per-deployment gate for programmatic schedule mutation (issue #265 / DD-7,
223
+ // herdctl#376). OFF by default: an instance opts in (PADDOCK_SCHEDULE_MUTATION)
224
+ // before herdctl's runtime schedule-mutation APIs can add or remove a
225
+ // schedule at runtime. Declaring schedules in project.yaml is unaffected.
226
+ allowScheduleMutation: this.cfg.scheduleMutationEnabled,
227
+ // Hand the engine the SAME Claude home paddock resolved (#588). Omitting
228
+ // it makes the engine fall back to `os.homedir()/.claude` while paddock
229
+ // honours `CLAUDE_HOME`, so discovery, adoption and paddock's `.chats/`
230
+ // symlinks would resolve against different directories — sessions list
231
+ // from one home and open empty from the other. Masked whenever the two
232
+ // coincide, which is why it must be explicit.
233
+ claudeHomePath: this.cfg.claudeHome,
234
+ });
235
+ await this.fleet.initialize();
236
+ // Register a keeper + sweeper for every existing project, recording each
237
+ // keeper's resolved model so per-chat overrides can short-circuit later.
238
+ // ensureProjectChats relocates this project's transcripts into <dir>/.chats
239
+ // (migrating any existing real transcript dir) so the project is portable.
240
+ for (const project of projects) {
241
+ // Symlink Claude's encoded transcript dir for the keeper's cwd (workingDir)
242
+ // at the .chats store in the metadata dir — so repo-backed transcripts stay
243
+ // out of the external checkout's working tree (issue #187). For a notebook
244
+ // project workingDir === dir, so this is the classic behavior.
245
+ await ensureProjectChats(project.workingDir, project.dir, this.cfg.claudeHome);
246
+ await this.ensureSweeperHome(project);
247
+ await this.fleet.addAgent(this.keeperAgentConfig(project), { replace: true });
248
+ await this.fleet.addAgent(this.sweeperAgentConfig(project), { replace: true });
249
+ // Register each EVENT trigger as its own agent `trigger-<slug>-<name>` (Epic T /
250
+ // T1). Schedule triggers ride the keeper's forwarded `schedules` block (above);
251
+ // webhook triggers are reserved.
252
+ await this.registerTriggerAgents(project);
253
+ this.agentModels.set(keeperAgentName(project.slug), project.model ?? DEFAULT_MODEL);
254
+ this.agentWorkingDirs.set(keeperAgentName(project.slug), project.workingDir);
255
+ }
256
+ }
257
+ /** Start the scheduler (keeper agents currently have no schedules, but this
258
+ * keeps the fleet "running" for status + future cron curators). */
259
+ async start() {
260
+ if (!this.fleet)
261
+ throw new Error("HerdctlService not initialized");
262
+ if (this.started)
263
+ return;
264
+ await this.fleet.start();
265
+ this.started = true;
266
+ // Warm the jobs index off the critical path (#529). It is incremental, so
267
+ // the expensive full parse only ever happens once per process — doing it at
268
+ // boot rather than inside the user's first `GET /api/projects` is the
269
+ // difference between a ~1.1 s first paint and a ~40 ms one. Fire-and-forget:
270
+ // a failure here is invisible, since every read rebuilds what it needs.
271
+ void this.jobsIndex.read().catch(() => undefined);
272
+ }
273
+ async stop() {
274
+ if (this.fleet && this.started) {
275
+ await this.fleet.stop({ waitForJobs: false }).catch(() => undefined);
276
+ this.started = false;
277
+ }
278
+ }
279
+ /** Expose the raw FleetManager (events, advanced ops) to callers that need it. */
280
+ get manager() {
281
+ if (!this.fleet)
282
+ throw new Error("HerdctlService not initialized");
283
+ return this.fleet;
284
+ }
285
+ /**
286
+ * Is a `claude` SUBPROCESS still alive on this session at the SDK/reaper layer
287
+ * (issue #397)? Consults herdctl's `SessionReaper` via the fleet's session
288
+ * lifecycle manager: `true` while the reaper is keeping a session open for a
289
+ * killed background task (keepAlive) or holding it through its re-invocation
290
+ * grace. Paddock's recovery engine treats this as a busy signal so it never
291
+ * fires a COMPETING resume into a session a prior subprocess still holds live
292
+ * (which the SDK resolves by interrupting the in-flight turn). Null-safe: with
293
+ * no fleet, no session-lifecycle manager (batch mode / reaper disabled), or any
294
+ * error, returns `false` — the pre-#397 behaviour.
295
+ */
296
+ isSdkSessionLive(sessionId) {
297
+ try {
298
+ return this.fleet?.getSessionLifecycle()?.reaper.isSessionLive(sessionId) ?? false;
299
+ }
300
+ catch {
301
+ return false;
302
+ }
303
+ }
304
+ async fleetStatus() {
305
+ return this.manager.getFleetStatus();
306
+ }
307
+ async agents() {
308
+ return this.manager.getAgentInfo();
309
+ }
310
+ /**
311
+ * Register (or replace) a project's keeper + sweeper agents at runtime. Uses
312
+ * `fleet.addAgent` (replace: true), so a re-create or rename of the same slug
313
+ * is idempotent. The new agents are immediately triggerable and visible in
314
+ * fleet status — no yaml + reload round-trip.
315
+ */
316
+ async ensureProjectAgent(project) {
317
+ if (!this.fleet)
318
+ return;
319
+ await ensureProjectChats(project.workingDir, project.dir, this.cfg.claudeHome);
320
+ await this.ensureSweeperHome(project);
321
+ await this.fleet.addAgent(this.keeperAgentConfig(project), { replace: true });
322
+ await this.fleet.addAgent(this.sweeperAgentConfig(project), { replace: true });
323
+ // Re-register the project's EVENT-trigger agents (Epic T / T1) from the live
324
+ // record (schedule triggers ride the keeper's forwarded `schedules` block above;
325
+ // webhook triggers are reserved).
326
+ await this.registerTriggerAgents(project);
327
+ // Record the keeper's resolved model so per-chat overrides can detect a
328
+ // no-op. ensureProjectAgent re-registers at project.model (the persisted
329
+ // default), so a model change via PATCH takes effect here too.
330
+ this.agentModels.set(keeperAgentName(project.slug), project.model ?? DEFAULT_MODEL);
331
+ this.agentWorkingDirs.set(keeperAgentName(project.slug), project.workingDir);
332
+ }
333
+ /**
334
+ * Register (or replace) every trigger a project declares that runs on its OWN scoped
335
+ * agent `trigger-<slug>-<name>` (Epic T). Idempotent (`addAgent` replace:true). Which triggers
336
+ * get a scoped agent is decided by {@link triggerRunsOnOwnAgent}: EVENT triggers
337
+ * always; SCHEDULE triggers only when they declare a non-empty `run.tools` allow-list
338
+ * (T2 — an unscoped schedule still rides the keeper's forwarded `schedules` block and
339
+ * runs as the keeper); webhook triggers are reserved (no ingress). A scoped schedule
340
+ * ALSO keeps its keeper `schedules` entry — that is only the cron TIMING; the fired
341
+ * turn executes on this scoped agent. A trigger-less project is a no-op. Called at
342
+ * boot ({@link init}) and on every {@link ensureProjectAgent}.
343
+ */
344
+ async registerTriggerAgents(project) {
345
+ if (!this.fleet)
346
+ return;
347
+ for (const [name, trigger] of Object.entries(project.triggers ?? {})) {
348
+ // The post-turn CURATOR (event/afterTurn) trigger, T5, never runs as its own
349
+ // agent — SweepService executes it via the project's `sweeper-<slug>` agent.
350
+ // Registering a `trigger-<slug>-<name>` for it would be a dead, never-fired agent.
351
+ if (!triggerRunsOnOwnAgent(trigger) || isCuratorTrigger(trigger))
352
+ continue;
353
+ await this.fleet.addAgent(this.triggerAgentConfig(project, name, trigger), { replace: true });
354
+ }
355
+ }
356
+ /**
357
+ * Register (or replace) ONE trigger's scoped agent at runtime (Epic T) — the herdctl
358
+ * half of a trigger mutation (the Paddock half persists it via
359
+ * `ProjectStore.setTrigger`). Idempotent; immediately fireable. Consumed by
360
+ * {@link import("./triggers.js").TriggerService}. A no-op for a trigger that does NOT
361
+ * run on its own agent ({@link triggerRunsOnOwnAgent}) — an unscoped schedule arms via
362
+ * the keeper re-register; a webhook is reserved.
363
+ */
364
+ async ensureTriggerAgent(project, name, trigger) {
365
+ if (!this.fleet)
366
+ return;
367
+ // The curator (event/afterTurn) trigger, T5, is executed by SweepService (via the
368
+ // `sweeper-<slug>` agent), not as its own agent — so never register one for it.
369
+ if (!triggerRunsOnOwnAgent(trigger) || isCuratorTrigger(trigger))
370
+ return;
371
+ await this.fleet.addAgent(this.triggerAgentConfig(project, name, trigger), { replace: true });
372
+ }
373
+ /**
374
+ * Unregister one event trigger's agent at runtime (Epic T / T1) — the inverse of
375
+ * {@link ensureTriggerAgent}. Never throws if the agent is already gone.
376
+ */
377
+ async removeTriggerAgent(slug, name) {
378
+ if (!this.fleet)
379
+ return;
380
+ await this.fleet.removeAgent(triggerAgentName(slug, name)).catch(() => undefined);
381
+ }
382
+ /**
383
+ * Ensure a project's keeper agent is registered at `model`, re-registering it
384
+ * (addAgent replace:true) only when the model actually changed. Used by the
385
+ * WS chat path to honor a per-chat model override before triggering.
386
+ *
387
+ * No herdctl per-trigger model API exists yet, so a model override is applied
388
+ * by re-registering the (single, shared) keeper agent. See the `agentModels`
389
+ * single-user caveat: this is last-write-wins across concurrent chats of the
390
+ * same project.
391
+ */
392
+ async ensureAgentModel(project, model) {
393
+ if (!this.fleet)
394
+ return;
395
+ const name = keeperAgentName(project.slug);
396
+ if (this.agentModels.get(name) === model)
397
+ return;
398
+ await this.fleet.addAgent(this.keeperAgentConfig(project, model), { replace: true });
399
+ this.agentModels.set(name, model);
400
+ }
401
+ /**
402
+ * Force the FleetManager's session-discovery cache to drop its cached listing
403
+ * for an agent, so a brand-new chat surfaces immediately (rather than waiting
404
+ * out the 30s directory cache). New public API in @herdctl/core 5.12.0. No-op
405
+ * and never throws if the fleet isn't ready.
406
+ */
407
+ invalidateSessions(agentName) {
408
+ if (!this.fleet)
409
+ return;
410
+ this.fleet.invalidateSessions(agentName);
411
+ }
412
+ // --- native-chat adoption (#588) ---------------------------------------
413
+ /**
414
+ * Detector for a project's importable native Claude Code chats, with its own
415
+ * mtime-keyed cache. Lazy for the same reason {@link jobsIndex} is: unit tests
416
+ * construct this service against a partial config.
417
+ */
418
+ adoptableIndexOrNull = null;
419
+ get adoptableIndex() {
420
+ return (this.adoptableIndexOrNull ??= new AdoptableIndex(this.cfg.claudeHome, this.cfg.stateDir));
421
+ }
422
+ /** What `project` could import right now (see `./adoptable.ts`). */
423
+ async listAdoptable(project) {
424
+ return this.adoptableIndex.adoptableFor(this.manager, project, keeperAgentName(project.slug));
425
+ }
426
+ /**
427
+ * Drop the cached adoptable summary for a workspace (or all of them).
428
+ *
429
+ * The workspace key may be `""` (the root), so this forwards the argument
430
+ * as-is — `if (!slug)` here would silently clear the WRONG thing.
431
+ */
432
+ invalidateAdoptable(projectKey) {
433
+ this.adoptableIndexOrNull?.invalidate(projectKey);
434
+ }
435
+ /**
436
+ * Import a project's native Claude Code chats.
437
+ *
438
+ * With `sourceCwd`, imports that one source; without, every source detection
439
+ * currently offers. `mode` defaults to `copy`, which never mutates the user's
440
+ * original `~/.claude` transcripts and preserves their mtimes; `move` and
441
+ * `link` exist for the CLI and nothing in the web UI should reach them.
442
+ *
443
+ * ## Honouring the noise filter
444
+ *
445
+ * Detection withholds empty and slash-command-only transcripts, but the engine
446
+ * adopts a whole SOURCE — it has no "adopt these ids" call. Left alone, that
447
+ * means the header offers 2 chats and the import brings in 4, including a
448
+ * zero-byte stub. So anything the engine adopted that detection had withheld is
449
+ * released again ({@link FleetManager.unadoptSession}) and reported in
450
+ * `skipped` under the filter's own reason, and — in `copy` mode only — the copy
451
+ * this call just placed is removed.
452
+ *
453
+ * That deletion is deliberately narrow. It happens only when all of: the mode
454
+ * is `copy` (in `move` the original is GONE, so the copy is the user's only
455
+ * remaining copy and must never be touched); the engine reported the id as
456
+ * newly `adopted` in THIS call, so it placed the file here and did not find one
457
+ * (`destination-exists` is a skip, not an adopt); and the destination path
458
+ * differs from the source, so an in-place adoption can never delete an
459
+ * original. The result is that a withheld session is left exactly as it was
460
+ * before the import.
461
+ *
462
+ * Afterwards the herdctl session cache, the jobs index and the adoptable cache
463
+ * are all dropped, so the imported chats list on the very next request — the
464
+ * same trio {@link promoteSession} invalidates for the same reason.
465
+ */
466
+ async adoptChats(project, opts = {}) {
467
+ const agent = keeperAgentName(project.slug);
468
+ const mode = opts.mode ?? "copy";
469
+ const dryRun = opts.dryRun ?? false;
470
+ const summary = await this.listAdoptable(project);
471
+ const sources = opts.sourceCwd !== undefined
472
+ ? [opts.sourceCwd]
473
+ : summary.sources.map((s) => s.sourceCwd);
474
+ // sessionId -> why detection withheld it.
475
+ const withheld = new Map(summary.filtered.map((f) => [f.sessionId, f.reason]));
476
+ const adopted = [];
477
+ const skipped = [];
478
+ for (const fromWorkingDir of sources) {
479
+ // Sequential, not parallel: each source re-scans the adoption store, so a
480
+ // session offered by two sources is adopted by the first and reported
481
+ // `already-adopted` by the second instead of racing to place the same file.
482
+ const result = await this.manager.adoptSessionsFrom(agent, {
483
+ fromWorkingDir,
484
+ mode,
485
+ dryRun,
486
+ });
487
+ skipped.push(...result.skipped);
488
+ for (const sessionId of result.adopted) {
489
+ const reason = withheld.get(sessionId);
490
+ if (reason === undefined) {
491
+ adopted.push(sessionId);
492
+ continue;
493
+ }
494
+ skipped.push({ sessionId, reason });
495
+ if (dryRun)
496
+ continue;
497
+ await this.releaseWithheld(agent, project, fromWorkingDir, sessionId, mode);
498
+ }
499
+ }
500
+ // A dry run wrote nothing, so there is nothing to invalidate — and dropping
501
+ // caches would misrepresent it as a state change.
502
+ if (!dryRun && adopted.length > 0) {
503
+ this.invalidateSessions(agent);
504
+ this.jobsIndexOrNull?.invalidate();
505
+ this.invalidateAdoptable(project.slug);
506
+ }
507
+ // A session adopted from one source and then met again in the NEXT source
508
+ // (its fresh copy now sits in the project's own transcript folder) comes back
509
+ // as `already-adopted`. That is true per-source, but as a RESULT it reads as
510
+ // "imported 7, skipped 5" for an import of 7. A session this call imported is
511
+ // never also reported as skipped by it.
512
+ const done = new Set(adopted);
513
+ return { adopted, skipped: skipped.filter((s) => !done.has(s.sessionId)) };
514
+ }
515
+ /**
516
+ * Undo the adoption of a session detection had withheld, restoring the state
517
+ * that existed before this import. See {@link adoptChats} for why the file
518
+ * removal is safe and why it is limited to `copy` mode.
519
+ */
520
+ async releaseWithheld(agent, project, fromWorkingDir, sessionId, mode) {
521
+ await this.manager.unadoptSession(agent, sessionId).catch(() => undefined);
522
+ if (mode !== "copy")
523
+ return;
524
+ const home = this.cfg.claudeHome;
525
+ const placed = getCliSessionFile(project.workingDir, sessionId, home);
526
+ const origin = getCliSessionFile(fromWorkingDir, sessionId, home);
527
+ // In-place adoption placed nothing; `origin` IS the user's file.
528
+ if (path.resolve(placed) === path.resolve(origin))
529
+ return;
530
+ await fs.rm(placed, { force: true }).catch(() => undefined);
531
+ }
532
+ /**
533
+ * Unregister a project's keeper + sweeper (+ any event-hook) agents at runtime.
534
+ * Uses `fleet.removeAgent`, the inverse of ensureProjectAgent. Running jobs are
535
+ * unaffected; the scheduler stops triggering the removed agents. `hookNames` are
536
+ * the project's declared hook names (from its DTO) so their `hook-<slug>-<name>`
537
+ * agents are torn down too — caller passes `Object.keys(project.hooks ?? {})`.
538
+ */
539
+ async removeProjectAgent(slug, hookNames = [], triggerNames = []) {
540
+ if (!this.fleet)
541
+ return;
542
+ await this.fleet.removeAgent(keeperAgentName(slug)).catch(() => undefined);
543
+ await this.fleet.removeAgent(sweeperAgentName(slug)).catch(() => undefined);
544
+ for (const name of hookNames) {
545
+ await this.fleet.removeAgent(hookAgentName(slug, name)).catch(() => undefined);
546
+ }
547
+ // Event triggers (Epic T / T1) register their own `trigger-<slug>-<name>` agent —
548
+ // tear those down too; schedule/webhook trigger names contribute no agent, so
549
+ // removeAgent is a harmless no-op for them.
550
+ for (const name of triggerNames) {
551
+ await this.fleet.removeAgent(triggerAgentName(slug, name)).catch(() => undefined);
552
+ }
553
+ }
554
+ /**
555
+ * Delete a single chat (session) by agent name + session id. The FleetManager
556
+ * resolves the agent's working directory, removes the transcript JSONL, and
557
+ * invalidates the discovery cache so the list reflects it immediately.
558
+ * Validates the sessionId (rejects path traversal). Returns true if a
559
+ * transcript file was removed, false if none existed.
560
+ */
561
+ async deleteSession(agentName, sessionId) {
562
+ return this.manager.deleteSession(agentName, sessionId);
563
+ }
564
+ /**
565
+ * Set (or clear) a chat's custom display name. Writes through the fleet's
566
+ * shared SessionMetadataStore so a subsequent getAgentSessions reflects it
567
+ * immediately. Pass null/empty to clear.
568
+ */
569
+ async renameSession(agentName, sessionId, name) {
570
+ await this.manager.setSessionName(agentName, sessionId, name);
571
+ }
572
+ /**
573
+ * Trigger an agent with a prompt and stream output via onMessage.
574
+ * Returns the TriggerResult (carries the final sessionId).
575
+ */
576
+ async chat(agentName, opts) {
577
+ return this.manager.trigger(agentName, undefined, {
578
+ prompt: opts.prompt,
579
+ resume: opts.resume,
580
+ triggerType: opts.triggerType ?? "web",
581
+ onMessage: opts.onMessage,
582
+ onJobCreated: opts.onJobCreated,
583
+ injectedMcpServers: opts.injectedMcpServers,
584
+ });
585
+ }
586
+ /**
587
+ * Pending async-input-queue depth of a resumed session's `claude` transcript —
588
+ * the residue gate for the resume self-interrupt drain (see `./resume-drain.ts`
589
+ * and {@link drainBacklogThenConsume}). Resolves the agent's CLI transcript from
590
+ * its recorded working directory. Returns 0 (→ no drain, original fast path) for
591
+ * an unknown agent or any read error, so a detection failure never changes turn
592
+ * behavior. Public so the ws.ts wake consumer can gate on it too.
593
+ */
594
+ async residueDepthFor(agentName, sessionId) {
595
+ const workingDir = this.agentWorkingDirs.get(agentName);
596
+ if (!workingDir)
597
+ return 0;
598
+ try {
599
+ return await countPendingAsyncQueueEntries(getCliSessionFile(workingDir, sessionId));
600
+ }
601
+ catch {
602
+ return 0;
603
+ }
604
+ }
605
+ /**
606
+ * Session-mode counterpart to {@link chat} (Paddock#111). Drives the turn
607
+ * through a persistent, herdctl-managed `openChatSession` (`manageLifecycle:
608
+ * true`) instead of a one-shot `trigger()`, so a `ScheduleWakeup` / `/loop` the
609
+ * turn leaves behind is captured by the reaper (herdctl#307) and re-fired
610
+ * through the scheduler — i.e. cross-turn autonomy actually works. The turn
611
+ * itself streams identically (same `onMessage` shape), so callers are unchanged.
612
+ *
613
+ * Contract differences from {@link chat}:
614
+ * - No herdctl job record exists, so the returned `jobId` is a synthetic turn
615
+ * id we register in {@link liveSessions}; Stop maps to `session.interrupt()`
616
+ * via {@link cancel}.
617
+ * - We do NOT `close()` the session: it's managed, so the reaper tears it down
618
+ * when idle (and captures its wakeups on the Stop hook). Per the core
619
+ * contract, the message stream ending IS the reap.
620
+ */
621
+ async chatSession(agentName, opts) {
622
+ const startedAt = new Date().toISOString();
623
+ const turnId = randomUUID();
624
+ const isResume = typeof opts.resume === "string";
625
+ let session;
626
+ try {
627
+ session = await this.manager.openChatSession(agentName, {
628
+ resume: opts.resume,
629
+ prompt: opts.prompt,
630
+ manageLifecycle: true,
631
+ injectedMcpServers: opts.injectedMcpServers,
632
+ // Stream assistant text token-by-token: the SDK emits `stream_event` /
633
+ // `text_delta` chunks that the translator surfaces as incremental
634
+ // `chat:response` frames (edspencer/herdctl#382, paddock#315).
635
+ includePartialMessages: true,
636
+ });
637
+ }
638
+ catch (err) {
639
+ return {
640
+ jobId: turnId,
641
+ agentName,
642
+ scheduleName: null,
643
+ startedAt,
644
+ prompt: opts.prompt,
645
+ success: false,
646
+ error: err instanceof Error ? err : new Error(String(err)),
647
+ };
648
+ }
649
+ this.liveSessions.set(turnId, session);
650
+ // Surface the synthetic id as the turn's jobId so the client renders Stop and
651
+ // a subsequent chat:cancel routes back to this live session.
652
+ opts.onJobCreated?.(turnId);
653
+ let sessionId = isResume ? opts.resume : null;
654
+ let success = false;
655
+ let error;
656
+ try {
657
+ // Gap A — survival parity. BOTH fresh and resume now consume via the
658
+ // NON-CLOSING consumeResumedTurn, which drives the stream with a manual
659
+ // iterator and stops on the primary turn's terminal `result` WITHOUT calling
660
+ // iterator.return() — leaving teardown to the reaper ("managed" session).
661
+ // The fresh path used to use `for await … break`, and a `break` invokes the
662
+ // iterator's `.return()`, which tears down the `claude` subprocess — killing
663
+ // any background task the fresh FIRST turn launched, bypassing the reaper's
664
+ // keepAlive (decideReap keeps a session alive while it holds background work).
665
+ // On a fresh session the async-input queue is empty, so residueProbe returns
666
+ // 0 and this breaks right after the first result exactly like the old fast
667
+ // path — just without the close, so a fresh-turn bg task now SURVIVES. A
668
+ // resume additionally drains any stale async-input backlog first (the #427
669
+ // resume self-interrupt fix). The reaper owns teardown after we return.
670
+ const consumed = await consumeResumedTurn(session, {
671
+ residueProbe: () => this.residueDepthFor(agentName, sessionId ?? opts.resume ?? ""),
672
+ onMessage: opts.onMessage,
673
+ onSessionId: (id) => {
674
+ sessionId = id;
675
+ },
676
+ log: (msg) =>
677
+ // eslint-disable-next-line no-console
678
+ console.log(`[resume-drain] chatSession ${agentName} (${sessionId ?? opts.resume}): ${msg}`),
679
+ });
680
+ success = consumed.success;
681
+ if (consumed.sessionId)
682
+ sessionId = consumed.sessionId;
683
+ // Gap B — keep delivering autonomous background-completion turns. The reaper
684
+ // may hold this (managed) session open because the turn launched continuous
685
+ // background work; when a task completes, its re-invocation turn arrives
686
+ // LATER on this SAME stream. Detach a consumer over the handed-back iterator
687
+ // so those turns reach the live UI (via onBackgroundMessage) instead of only
688
+ // landing in the transcript — and so the stream keeps advancing, feeding the
689
+ // reaper its `activity`/`background_tasks_changed` signals. Detached (`void`)
690
+ // so THIS call still returns the moment the primary turn is done; it ends
691
+ // itself when the reaper reaps the idle session (stream yields `done`).
692
+ if (opts.onBackgroundMessage) {
693
+ void consumeBackgroundTurns(consumed.iterator, consumed.pending, opts.onBackgroundMessage, opts.onBackgroundDone);
694
+ }
695
+ }
696
+ catch (err) {
697
+ error = err instanceof Error ? err : new Error(String(err));
698
+ }
699
+ finally {
700
+ this.liveSessions.delete(turnId);
701
+ }
702
+ return {
703
+ jobId: turnId,
704
+ agentName,
705
+ scheduleName: null,
706
+ startedAt,
707
+ prompt: opts.prompt,
708
+ success,
709
+ sessionId: sessionId ?? undefined,
710
+ error,
711
+ };
712
+ }
713
+ /**
714
+ * Register the consumer that drives scheduler-fired session wakes (Paddock#111
715
+ * gap 3). herdctl resumes the woken session (`manageLifecycle: true`) and hands
716
+ * it here; the handler must consume the stream onto the hub/transcript so the
717
+ * autonomous turn is visible even though no client is watching. A no-op if the
718
+ * fleet has no lifecycle manager. Safe to call before/after {@link init}.
719
+ */
720
+ onSessionWake(handler) {
721
+ this.manager.setSessionWakeHandler(handler);
722
+ }
723
+ /**
724
+ * Register the resolver herdctl calls to RE-ESTABLISH this session's in-process
725
+ * injected MCP servers when a scheduler-fired wake resumes an idle/reaped session
726
+ * (edspencer/herdctl#390, wired in @herdctl/core 5.22.1). The wake path drives the
727
+ * turn inside herdctl (a `ScheduleWakeup` / `/loop` / `CronCreate` re-fire), so it
728
+ * bypasses Paddock's per-turn injection — without this the resumed `claude`
729
+ * subprocess re-spawns with the `mcp__paddock*__*` tools "allowed" but UNBACKED,
730
+ * so they vanish from the catalog for the whole autonomous stretch (the "MCP flap").
731
+ * The resolver is SYNCHRONOUS (herdctl threads its result into `openChatSession`
732
+ * before the subprocess spawns) and MUST NOT throw — herdctl catches + logs a throw
733
+ * and degrades to no-injection, but we return `undefined` (safe no-injection default)
734
+ * rather than rely on that. A no-op if the fleet has no lifecycle manager; safe to
735
+ * call before/after {@link init}. Thin passthrough, mirroring {@link onSessionWake}.
736
+ */
737
+ setResolveInjectedMcpServers(resolve) {
738
+ this.manager.setResolveInjectedMcpServers(resolve);
739
+ }
740
+ /**
741
+ * Register the consumer that OWNS execution of a fired schedule (issue #265 /
742
+ * DD-1, herdctl#375). When set, herdctl routes every scheduler-fired trigger
743
+ * (interval / cron / forced "trigger now") here instead of running it headless
744
+ * via its built-in ScheduleExecutor — so Paddock runs the turn on its OWN hub /
745
+ * resume path (`startAgentTurn`), keeping the scheduled chat visible + re-attachable
746
+ * (and never `isSidechain`-hidden). A no-op fallback to headless applies if no
747
+ * handler is registered. Thin passthrough, mirroring {@link onSessionWake}.
748
+ */
749
+ onScheduleTrigger(handler) {
750
+ this.manager.setScheduleTriggerHandler(handler);
751
+ }
752
+ /**
753
+ * The runtime state of a project keeper's schedules (issue #266 / D4) — the
754
+ * live `ScheduleInfo` herdctl tracks (status, `lastRunAt`/`nextRunAt`,
755
+ * `lastError`) for the schedules Paddock forwarded into the keeper agent. The
756
+ * D4 UI merges this with the project.yaml declaration (which carries the
757
+ * Paddock-only `prompt`/`promptFile`/`resume_session`) for the list view. A
758
+ * schedule-less keeper (or one herdctl hasn't finished arming) yields `[]`;
759
+ * errors are swallowed to `[]` so the settings pane degrades to the declared
760
+ * definitions rather than failing to render.
761
+ */
762
+ async listAgentSchedules(project) {
763
+ const agent = keeperAgentName(project.slug);
764
+ const all = await this.manager.getSchedules().catch(() => []);
765
+ return all.filter((s) => s.agentName === agent);
766
+ }
767
+ /**
768
+ * Run a slash command (e.g. `/compact`) against an agent's chat session.
769
+ *
770
+ * Unlike {@link chat}, which sends the text as a one-shot prompt via
771
+ * `trigger()`, this drives herdctl's streaming session (`openChatSession`) —
772
+ * the only mode in which the SDK dispatches slash commands and exposes control
773
+ * requests. The command runs against the resumed `sessionId`, so `/compact`
774
+ * compacts the real chat history. SDK messages stream via `onMessage` (same
775
+ * shape as {@link chat}); resolves when the turn completes, then closes the
776
+ * session. Returns the resolved session id.
777
+ */
778
+ async runCommand(agentName, opts) {
779
+ const isResume = typeof opts.resume === "string";
780
+ const session = await this.manager.openChatSession(agentName, {
781
+ resume: opts.resume,
782
+ // Stream the command's assistant text token-by-token (paddock#315).
783
+ includePartialMessages: true,
784
+ });
785
+ let sessionId = isResume ? opts.resume : null;
786
+ try {
787
+ // Gap A parity: BOTH branches consume via the non-closing consumeResumedTurn
788
+ // (no `for await … break`, whose break would iterator.return() and close the
789
+ // CLI mid-consume). Send the command first — it queues behind any stale
790
+ // async-input backlog the CLI replays — then consume with the queue-drain
791
+ // break rule so a backlog turn's `result` can't tear the command turn down.
792
+ // No backlog (the fresh case) → breaks right after the first result. NOTE:
793
+ // unlike chatSession, runCommand opens WITHOUT manageLifecycle, so the reaper
794
+ // does NOT own this session; we still close() it explicitly in `finally`, so
795
+ // a slash-command turn's teardown is unchanged — this only unifies HOW we
796
+ // stop consuming.
797
+ await session.send(opts.command);
798
+ const consumed = await consumeResumedTurn(session, {
799
+ residueProbe: () => this.residueDepthFor(agentName, sessionId ?? opts.resume ?? ""),
800
+ onMessage: opts.onMessage,
801
+ onSessionId: (id) => {
802
+ sessionId = id;
803
+ },
804
+ log: (msg) =>
805
+ // eslint-disable-next-line no-console
806
+ console.log(`[resume-drain] runCommand ${agentName} (${sessionId ?? opts.resume}): ${msg}`),
807
+ });
808
+ if (consumed.sessionId)
809
+ sessionId = consumed.sessionId;
810
+ }
811
+ catch {
812
+ // Stream error — fall through and let the caller surface completion.
813
+ }
814
+ finally {
815
+ await session.close();
816
+ }
817
+ return { sessionId };
818
+ }
819
+ /**
820
+ * Cancel a running turn (Stop button → WS chat:cancel). Handles BOTH drive
821
+ * modes off the single id the client holds as `jobId`:
822
+ * - **session mode** — the id is a synthetic turn id in {@link liveSessions};
823
+ * interrupt the live `RuntimeSession` (there is no herdctl job to cancel).
824
+ * - **batch mode** — the id is a real herdctl job id; abort it via `cancelJob`
825
+ * (which kills the CLI subprocess / aborts the SDK query).
826
+ *
827
+ * Returns `true` if something was actually cancelled. Errors are logged rather
828
+ * than silently swallowed (the previous `.catch(() => undefined)` hid every
829
+ * failure, so a broken Stop looked like a no-op).
830
+ */
831
+ async cancel(jobId) {
832
+ const live = this.liveSessions.get(jobId);
833
+ if (live) {
834
+ try {
835
+ await live.interrupt();
836
+ return true;
837
+ }
838
+ catch (err) {
839
+ console.warn(`[herdctl] session interrupt failed for ${jobId}:`, err);
840
+ return false;
841
+ }
842
+ }
843
+ try {
844
+ await this.manager.cancelJob(jobId);
845
+ return true;
846
+ }
847
+ catch (err) {
848
+ // JobNotFoundError is expected if the turn already finished; log others.
849
+ console.warn(`[herdctl] cancelJob failed for ${jobId}:`, err);
850
+ return false;
851
+ }
852
+ }
853
+ /**
854
+ * Run a project's sweeper (curator) agent with a fresh session and the given
855
+ * prompt. Used OUT OF BAND by SweepService — never from the user-chat path —
856
+ * so a sweep can never enqueue another sweep. resume:null forces a clean
857
+ * session each time (the sweep is stateless).
858
+ *
859
+ * The sweeper is tool-less and returns its result as plain assistant text
860
+ * (the two marked sections SweepService parses), so we accumulate the
861
+ * assistant text deltas via @herdctl/chat's shared translator (same pattern
862
+ * as ws.ts) and return them alongside the TriggerResult.
863
+ */
864
+ async runSweeper(slug, prompt) {
865
+ let text = "";
866
+ const translate = createSDKMessageHandler({
867
+ onText: (chunk) => {
868
+ if (chunk)
869
+ text += chunk;
870
+ },
871
+ });
872
+ const result = await this.manager.trigger(sweeperAgentName(slug), undefined, {
873
+ prompt,
874
+ resume: null,
875
+ triggerType: "manual",
876
+ onMessage: async (m) => {
877
+ // core's SDKMessage types `message` as `unknown` (wider) than the
878
+ // translator's structurally-narrower SDKMessage — same runtime object,
879
+ // cast across the package boundary.
880
+ await translate(m);
881
+ },
882
+ });
883
+ return { result, text };
884
+ }
885
+ /** Recent sessions for a project's keeper agent, used to build the sweep digest. */
886
+ async recentSessions(project, limit = 10) {
887
+ return this.manager.getAgentSessions(keeperAgentName(project.slug), { limit });
888
+ }
889
+ /**
890
+ * List a project's chats across ALL of its VISIBLE agents (Epic G / G3, GG-5):
891
+ * the keeper PLUS every declared event-hook agent (`hook-<slug>-<name>`), so a
892
+ * hook's chats show up in the sidebar alongside the keeper's. The sweeper is
893
+ * deliberately excluded — it's the `hideChats` case (its curation chats stay
894
+ * hidden, unchanged). See
895
+ * {@link visibleProjectAgentNames}.
896
+ *
897
+ * Sessions are keyed by working directory in core's discovery, and every one of
898
+ * a project's agents shares the project cwd, so `getAgentSessions` attributes each
899
+ * session to the specific agent that owns it (keeper vs. a hook). We query each
900
+ * visible agent and merge — deduping by session id defensively (attribution is
901
+ * per-agent, so overlap shouldn't happen) — then re-sort mtime-descending to
902
+ * restore the interleaved recency order a single listing would have had. Each
903
+ * per-agent query is fault-isolated: a hook whose agent failed to register (or was
904
+ * just removed) yields `[]` instead of failing the whole list.
905
+ *
906
+ * A **hook-less project** (the overwhelmingly common case) has exactly one visible
907
+ * agent — its keeper — so we short-circuit to the single un-merged listing: same
908
+ * one directory scan (and no dedup/sort work) the pre-G3 keeper-only path did, i.e.
909
+ * zero added cost unless the project actually declares hooks. The extra per-hook
910
+ * scans only kick in for a project that has hook chats to show.
911
+ */
912
+ async listSessions(project) {
913
+ const agentNames = visibleProjectAgentNames(project);
914
+ if (agentNames.length === 1)
915
+ return this.manager.getAgentSessions(agentNames[0]);
916
+ const perAgent = await Promise.all(agentNames.map((name) => this.manager.getAgentSessions(name).catch(() => [])));
917
+ const seen = new Set();
918
+ const merged = [];
919
+ for (const list of perAgent) {
920
+ for (const s of list) {
921
+ if (seen.has(s.sessionId))
922
+ continue;
923
+ seen.add(s.sessionId);
924
+ merged.push(s);
925
+ }
926
+ }
927
+ // ISO-8601 mtimes sort lexicographically in chronological order → descending.
928
+ merged.sort((a, b) => (a.mtime < b.mtime ? 1 : a.mtime > b.mtime ? -1 : 0));
929
+ return merged;
930
+ }
931
+ /**
932
+ * The on-disk job-record reads (run history + the unread badge) live in
933
+ * `./herdctl-jobs.js` as pure functions over `<stateDir>/jobs` (issue #403);
934
+ * these thin wrappers thread `this.cfg.stateDir` (or, for the two unread-badge
935
+ * reads, this service's {@link jobsIndex}). See there for the full semantics of
936
+ * each (unread signal, per-project grouping, run history).
937
+ */
938
+ async lastTurnCompletedAt() {
939
+ return jobs.lastTurnCompletedAt(this.jobsIndex);
940
+ }
941
+ async lastTurnCompletedAtByProject() {
942
+ return jobs.lastTurnCompletedAtByProject(this.jobsIndex);
943
+ }
944
+ async listProjectRuns(project, limit = 100) {
945
+ return jobs.listProjectRuns(this.cfg.stateDir, project, limit);
946
+ }
947
+ async listRunsForAgents(agents, limit = 200) {
948
+ return jobs.listRunsForAgents(this.cfg.stateDir, agents, limit);
949
+ }
950
+ /**
951
+ * Promote a chat into a NEW project: re-home its transcript into that
952
+ * project's `.chats/` (rewriting the embedded `cwd` so the transcript reports
953
+ * the new project dir) and re-point the session's herdctl job records at the
954
+ * new keeper. After this + the cache invalidations below the chat lists and
955
+ * resumes under the new project with NO restart — doing the same writes from
956
+ * outside the process would need one, to drop the attribution-index cache.
957
+ *
958
+ * Moves one chat from one keeper's store to another's. The root is a workspace
959
+ * like any other, so root chats carry the promote action too.
960
+ *
961
+ * The caller MUST have already created `to` and registered its keeper
962
+ * (ensureProjectAgent), so its `.chats/` + transcript symlink exist. Throws if
963
+ * the source transcript can't be read (e.g. unknown session id).
964
+ */
965
+ async promoteSession(sessionId, from, to) {
966
+ if (!/^[A-Za-z0-9._-]+$/.test(sessionId)) {
967
+ throw new Error(`Invalid session id: ${sessionId}`);
968
+ }
969
+ const fromFile = path.join(projectChatsDir(from.dir), `${sessionId}.jsonl`);
970
+ const toFile = path.join(projectChatsDir(to.dir), `${sessionId}.jsonl`);
971
+ // Read the source transcript (throws ENOENT for an unknown/absent session).
972
+ const raw = await fs.readFile(fromFile, "utf8");
973
+ // Rewrite ONLY the embedded `cwd` token. This relies on Claude Code writing
974
+ // compact JSON (`"cwd":"/abs/path"` — no spaces, no escaping for a plain abs
975
+ // path).
976
+ // Rewrite to the destination's KEEPER cwd. For a repo-backed project that's
977
+ // the nested checkout (workingDir), not the metadata dir, so a promoted chat
978
+ // resumes in the right place (issue #187).
979
+ //
980
+ // Resume does not actually DEPEND on this: #516 Phase 6 established
981
+ // empirically that Claude Code keys resume on the transcript's location, not
982
+ // its recorded `cwd`. It is kept because the recorded value is what the
983
+ // transcript claims about itself, and a stale one is confusing to read.
984
+ const rewritten = raw.split(`"cwd":"${from.workingDir}"`).join(`"cwd":"${to.workingDir}"`);
985
+ await fs.mkdir(projectChatsDir(to.dir), { recursive: true });
986
+ await fs.writeFile(toFile, rewritten, "utf8");
987
+ // Preserve the real last-activity time on the moved file.
988
+ const st = await fs.stat(fromFile).catch(() => null);
989
+ if (st)
990
+ await fs.utimes(toFile, st.atime, st.mtime).catch(() => undefined);
991
+ // Drop the source copy AND evict the SOURCE agent's in-process tracking of
992
+ // this session. The latter is essential for same-process resume: the agent
993
+ // that CREATED the session still "owns" the session id in herdctl's live
994
+ // session state, so resuming under the new keeper without evicting it forks
995
+ // a fresh session instead of continuing (a process restart clears the same
996
+ // state, which is why it "worked after restart"). deleteSession removes the
997
+ // source transcript (already moved → no-op on content) and clears that state.
998
+ const fromAgent = keeperAgentName(from.slug);
999
+ await this.manager.deleteSession(fromAgent, sessionId).catch(() => undefined);
1000
+ await fs.rm(fromFile, { force: true });
1001
+ // Re-attribute the session to the new keeper, then drop the discovery +
1002
+ // attribution caches so the move shows immediately.
1003
+ await jobs.reattributeSession(this.cfg.stateDir, sessionId, to, st ? st.mtime : new Date());
1004
+ this.jobsIndexOrNull?.invalidate();
1005
+ this.invalidateSessions(keeperAgentName(to.slug));
1006
+ this.invalidateSessions(fromAgent);
1007
+ }
1008
+ /**
1009
+ * Fork a project chat: eagerly duplicate `sourceSessionId`'s transcript into a
1010
+ * brand-new session in the SAME project, so the fork exists immediately — a
1011
+ * real, resumable chat with the full parent history visible — rather than being
1012
+ * materialized only when the user sends a first message. The source is left
1013
+ * untouched (this is a copy, not a move).
1014
+ *
1015
+ * Same mechanics as {@link promoteSession} (copy the JSONL, keep it
1016
+ * discoverable + attributed), with two differences: a NEW session id is minted
1017
+ * and rewritten onto every transcript line (so the copy is internally
1018
+ * consistent with its new filename — Claude Code stamps appended lines with the
1019
+ * file's id, and a mismatch is version-fragile), and the source file is kept.
1020
+ * `cwd` is unchanged (the fork stays in the same project). Returns the new id.
1021
+ */
1022
+ /**
1023
+ * Whether a chat transcript exists for `sessionId` in `project`. Used by the
1024
+ * self-management MCP write tools (#214) to validate a caller-supplied target
1025
+ * before forking / messaging it, so a bad id yields a clean "not found" instead
1026
+ * of a raw ENOENT (fork) or a false-positive success (send_message). Rejects a
1027
+ * malformed id (path-traversal guard) as non-existent.
1028
+ */
1029
+ async sessionExists(project, sessionId) {
1030
+ if (!/^[A-Za-z0-9._-]+$/.test(sessionId))
1031
+ return false;
1032
+ try {
1033
+ await fs.access(path.join(projectChatsDir(project.dir), `${sessionId}.jsonl`));
1034
+ return true;
1035
+ }
1036
+ catch {
1037
+ return false;
1038
+ }
1039
+ }
1040
+ async forkSession(project, sourceSessionId, name, fromUuid) {
1041
+ if (!/^[A-Za-z0-9._-]+$/.test(sourceSessionId)) {
1042
+ throw new Error(`Invalid session id: ${sourceSessionId}`);
1043
+ }
1044
+ const dir = projectChatsDir(project.dir);
1045
+ // Read the source transcript (throws ENOENT for an unknown/absent session).
1046
+ let raw = await fs.readFile(path.join(dir, `${sourceSessionId}.jsonl`), "utf8");
1047
+ // Fork-from-here (issue #451): when a message uuid is given, copy only the
1048
+ // transcript PREFIX up to and including that message's turn, so the new chat
1049
+ // branches at the chosen point instead of inheriting the whole history. The
1050
+ // tail (later turns) is left out of the copy; the source is untouched.
1051
+ if (fromUuid) {
1052
+ const sliced = sliceTranscriptAtUuid(raw, fromUuid);
1053
+ if (sliced == null) {
1054
+ throw new Error(`Message ${fromUuid} not found in session ${sourceSessionId}`);
1055
+ }
1056
+ raw = sliced;
1057
+ }
1058
+ const newId = randomUUID();
1059
+ // Rewrite the embedded session id on every line. Same compact-JSON
1060
+ // assumption `promoteSession` makes for `cwd` (`"sessionId":"<id>"` /
1061
+ // `"session_id":"<id>"` — no spaces).
1062
+ const rewritten = raw
1063
+ .split(`"sessionId":"${sourceSessionId}"`)
1064
+ .join(`"sessionId":"${newId}"`)
1065
+ .split(`"session_id":"${sourceSessionId}"`)
1066
+ .join(`"session_id":"${newId}"`);
1067
+ await fs.writeFile(path.join(dir, `${newId}.jsonl`), rewritten, "utf8");
1068
+ // Name it (e.g. "Fork of <parent>") and make it discoverable + attributed to
1069
+ // the keeper immediately (a fresh transcript with no job records otherwise
1070
+ // relies on cwd attribution alone).
1071
+ const keeper = keeperAgentName(project.slug);
1072
+ if (name)
1073
+ await this.manager.setSessionName(keeper, newId, name).catch(() => undefined);
1074
+ await jobs.writeAdoptionJob(this.cfg.stateDir, newId, project, new Date());
1075
+ this.jobsIndexOrNull?.invalidate();
1076
+ this.invalidateSessions(keeper);
1077
+ return newId;
1078
+ }
1079
+ /**
1080
+ * Revert a chat back to an earlier message (issue #451): truncate the session's
1081
+ * transcript at `toUuid`, in place, keeping the SAME session id — so the chat's
1082
+ * identity/URL is preserved and the next turn continues as if the later
1083
+ * messages never happened. The dropped tail is backed up (recoverable) to a
1084
+ * `.reverts/` sidecar that is deliberately kept out of the discoverable
1085
+ * `<id>.jsonl` namespace so it never lists as a chat.
1086
+ *
1087
+ * NOTE: this rolls back the CONVERSATION only — real-world side-effects of the
1088
+ * reverted turns (files written, PRs opened, messages sent) are NOT undone. The
1089
+ * caller's UI is responsible for warning about that. Returns the number of
1090
+ * transcript records dropped.
1091
+ */
1092
+ async revertSession(project, sessionId, toUuid) {
1093
+ if (!/^[A-Za-z0-9._-]+$/.test(sessionId)) {
1094
+ throw new Error(`Invalid session id: ${sessionId}`);
1095
+ }
1096
+ const dir = projectChatsDir(project.dir);
1097
+ const file = path.join(dir, `${sessionId}.jsonl`);
1098
+ const raw = await fs.readFile(file, "utf8");
1099
+ // endOnCompletedAssistant: revert lands on a completed AI turn (reverting to
1100
+ // one of your own prompts rewinds to the reply before it) so resume doesn't
1101
+ // replay a dangling prompt as a phantom turn (#451).
1102
+ const sliced = sliceTranscriptAtUuid(raw, toUuid, true);
1103
+ if (sliced == null) {
1104
+ throw new Error(`Message ${toUuid} not found in session ${sessionId}`);
1105
+ }
1106
+ const countLines = (s) => s.split("\n").filter((l) => l.trim()).length;
1107
+ const removed = countLines(raw) - countLines(sliced);
1108
+ // Back up the full transcript before truncating (recoverable revert). The
1109
+ // `.reverts/` dir is not the `<id>.jsonl` session namespace, so it is never
1110
+ // discovered/listed as a chat.
1111
+ const backupsDir = path.join(dir, ".reverts");
1112
+ await fs.mkdir(backupsDir, { recursive: true });
1113
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
1114
+ await fs
1115
+ .copyFile(file, path.join(backupsDir, `${sessionId}-${stamp}.jsonl`))
1116
+ .catch(() => undefined);
1117
+ await fs.writeFile(file, sliced, "utf8");
1118
+ // The truncated file's shrunk mtime invalidates the usage/context mtime
1119
+ // caches automatically; drop the discovery cache so the shorter transcript
1120
+ // (new preview/last-turn) lists immediately.
1121
+ this.invalidateSessions(keeperAgentName(project.slug));
1122
+ return { removed };
1123
+ }
1124
+ /**
1125
+ * Attribute an *in-flight* session to its agent the moment its id is known —
1126
+ * mid first turn — so a brand-new chat lists in the sidebar immediately
1127
+ * instead of only after the first turn finishes (issue #100).
1128
+ *
1129
+ * The core attribution index is built from herdctl job records, and herdctl
1130
+ * writes the resolved `session_id` into a run's own job record only on
1131
+ * completion. While the first turn runs, that record has `session_id: null`,
1132
+ * so the session is unattributed and {@link SessionDiscoveryService.getAgentSessions}
1133
+ * filters it out. We close that window with the SAME synthetic-job-record
1134
+ * trick used for fork/promote: write an adoption record keyed to the session
1135
+ * id, then drop the discovery + attribution caches so the next list call
1136
+ * surfaces it. Idempotent — a stable per-session job id means a repeat call
1137
+ * just overwrites the same file, and when the real run later finalizes its own
1138
+ * record (same session id, same agent) the attribution is unchanged.
1139
+ *
1140
+ * @param sessionId - The freshly-resolved session id of the running turn
1141
+ * @param agentName - The qualified agent the session belongs to
1142
+ */
1143
+ async attributeRunningSession(sessionId, agentName) {
1144
+ if (!/^[A-Za-z0-9._-]+$/.test(sessionId))
1145
+ return;
1146
+ await jobs.writeAgentAdoptionJob(this.cfg.stateDir, sessionId, agentName, new Date());
1147
+ this.jobsIndexOrNull?.invalidate();
1148
+ this.invalidateSessions(agentName);
1149
+ }
1150
+ /** Read the parsed messages of a session, by agent name. */
1151
+ async sessionMessages(agentName, sessionId) {
1152
+ // Injected/synthetic (`isMeta:true`) user lines — a skill's SKILL.md,
1153
+ // command output — are dropped by @herdctl/core's parser (>=5.13.2), so a
1154
+ // skill body no longer renders as a giant user bubble (issue #31).
1155
+ return this.manager.getAgentSessionMessages(agentName, sessionId);
1156
+ }
1157
+ // Per-session token usage (last-turn context fill AND cumulative totals) is
1158
+ // read directly from the transcript in ./usage.ts (readSessionTokenUsage) —
1159
+ // paddock owns the `.chats/` layout, and core's SessionUsage only exposes the
1160
+ // last-turn fill, so the cumulative extractor supersedes the old
1161
+ // sessionUsage/sessionUsageCached wrappers that used to live here (issue #152).
1162
+ /**
1163
+ * Slash commands available to an agent, memoized per agent name. The set is
1164
+ * stable per project (built-ins + the project's `.claude/commands` + any
1165
+ * MCP-provided commands) and each underlying `listAgentCommands` call spawns a
1166
+ * short-lived `claude` streaming subprocess (open → query → close), so we
1167
+ * cache aggressively. The cache is process-lifetime: it fills on first use and
1168
+ * only clears on server restart — the same boot-only invalidation the fleet's
1169
+ * agent registration already relies on. A concurrent first call is
1170
+ * deduplicated by caching the in-flight promise, so a burst of composer fetches
1171
+ * spawns exactly one subprocess.
1172
+ */
1173
+ commandsCache = new Map();
1174
+ async listCommands(agentName) {
1175
+ const hit = this.commandsCache.get(agentName);
1176
+ if (hit)
1177
+ return hit;
1178
+ // Cache the promise (not the resolved value) so concurrent callers share one
1179
+ // subprocess; drop it on rejection so a transient failure can be retried.
1180
+ const pending = this.manager.listAgentCommands(agentName).catch((err) => {
1181
+ this.commandsCache.delete(agentName);
1182
+ throw err;
1183
+ });
1184
+ this.commandsCache.set(agentName, pending);
1185
+ return pending;
1186
+ }
1187
+ // --- agent configs -----------------------------------------------------
1188
+ //
1189
+ // Thin instance wrappers over the pure builders in `./herdctl-agent-config.js`
1190
+ // (issue #403): each threads `this.cfg` so the extracted functions stay pure
1191
+ // (config in via params, no `this`). The private names are unchanged so the
1192
+ // existing unit-test seams (which reach `sweeperAgentConfig`/`ensureConfigFile`
1193
+ // via a cast) and internal callers keep working.
1194
+ keeperAgentConfig(project, modelOverride) {
1195
+ return buildAgentConfig(this.cfg, project, modelOverride);
1196
+ }
1197
+ sweeperAgentConfig(project) {
1198
+ return buildSweeperConfig(this.cfg, project);
1199
+ }
1200
+ /**
1201
+ * Create the sweeper's own working directory (+ symlink its encoded transcript
1202
+ * path at a `.chats/` inside it), so the tool-less curator never shares a CLI
1203
+ * session directory with the project's keeper (issue #548). Reuses
1204
+ * `ensureProjectChats` with the sweeper dir as both cwd and chats host, which
1205
+ * also mkdir's the dir itself. Never throws — the helper swallows its own
1206
+ * errors, and a missing symlink only means Claude keeps its default location.
1207
+ */
1208
+ async ensureSweeperHome(project) {
1209
+ const dir = sweeperWorkingDir(this.cfg, project.slug);
1210
+ await ensureProjectChats(dir, dir);
1211
+ }
1212
+ triggerAgentConfig(project, triggerName, trigger) {
1213
+ return buildTriggerConfig(this.cfg, project, triggerName, trigger);
1214
+ }
1215
+ async ensureConfigFile() {
1216
+ await writeBootConfigFile(this.cfg);
1217
+ }
1218
+ }