@draht/coding-agent 2026.7.13 → 2026.9.5-1

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 (614) hide show
  1. package/CHANGELOG.md +241 -0
  2. package/README.md +47 -2
  3. package/agents/debugger.md +12 -1
  4. package/agents/git-committer.md +1 -0
  5. package/agents/implementer.md +20 -0
  6. package/agents/investigator.md +75 -0
  7. package/agents/reviewer.md +7 -0
  8. package/agents/spec-reviewer.md +66 -0
  9. package/agents/verifier.md +4 -3
  10. package/bin/draht-tools.cjs +472 -41
  11. package/dist/agents/debugger.md +12 -1
  12. package/dist/agents/git-committer.md +1 -0
  13. package/dist/agents/implementer.md +20 -0
  14. package/dist/agents/investigator.md +75 -0
  15. package/dist/agents/reviewer.md +7 -0
  16. package/dist/agents/spec-reviewer.md +66 -0
  17. package/dist/agents/verifier.md +4 -3
  18. package/dist/bun/cli.js +2 -0
  19. package/dist/bun/cli.js.map +1 -1
  20. package/dist/cli/args.d.ts +10 -0
  21. package/dist/cli/args.d.ts.map +1 -1
  22. package/dist/cli/args.js +80 -3
  23. package/dist/cli/args.js.map +1 -1
  24. package/dist/cli/attach-mode.d.ts +61 -0
  25. package/dist/cli/attach-mode.d.ts.map +1 -1
  26. package/dist/cli/attach-mode.js +243 -5
  27. package/dist/cli/attach-mode.js.map +1 -1
  28. package/dist/cli/config-selector.js +1 -1
  29. package/dist/cli/config-selector.js.map +1 -1
  30. package/dist/cli/credential-print.d.ts +23 -0
  31. package/dist/cli/credential-print.d.ts.map +1 -0
  32. package/dist/cli/credential-print.js +117 -0
  33. package/dist/cli/credential-print.js.map +1 -0
  34. package/dist/cli/list-models.d.ts +2 -2
  35. package/dist/cli/list-models.d.ts.map +1 -1
  36. package/dist/cli/list-models.js +3 -3
  37. package/dist/cli/list-models.js.map +1 -1
  38. package/dist/cli/startup-ui.js +1 -1
  39. package/dist/cli/startup-ui.js.map +1 -1
  40. package/dist/config.d.ts +9 -0
  41. package/dist/config.d.ts.map +1 -1
  42. package/dist/config.js +31 -4
  43. package/dist/config.js.map +1 -1
  44. package/dist/core/agent-session-runtime.d.ts +17 -1
  45. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  46. package/dist/core/agent-session-runtime.js +90 -30
  47. package/dist/core/agent-session-runtime.js.map +1 -1
  48. package/dist/core/agent-session-services.d.ts +4 -7
  49. package/dist/core/agent-session-services.d.ts.map +1 -1
  50. package/dist/core/agent-session-services.js +24 -9
  51. package/dist/core/agent-session-services.js.map +1 -1
  52. package/dist/core/agent-session.d.ts +87 -27
  53. package/dist/core/agent-session.d.ts.map +1 -1
  54. package/dist/core/agent-session.js +337 -154
  55. package/dist/core/agent-session.js.map +1 -1
  56. package/dist/core/auth-storage.d.ts +20 -104
  57. package/dist/core/auth-storage.d.ts.map +1 -1
  58. package/dist/core/auth-storage.js +104 -260
  59. package/dist/core/auth-storage.js.map +1 -1
  60. package/dist/core/builtins/checkpoints.d.ts +20 -0
  61. package/dist/core/builtins/checkpoints.d.ts.map +1 -0
  62. package/dist/core/builtins/checkpoints.js +161 -0
  63. package/dist/core/builtins/checkpoints.js.map +1 -0
  64. package/dist/core/builtins/duet.d.ts +26 -0
  65. package/dist/core/builtins/duet.d.ts.map +1 -0
  66. package/dist/core/builtins/duet.js +660 -0
  67. package/dist/core/builtins/duet.js.map +1 -0
  68. package/dist/core/builtins/index.d.ts.map +1 -1
  69. package/dist/core/builtins/index.js +7 -1
  70. package/dist/core/builtins/index.js.map +1 -1
  71. package/dist/core/builtins/subagent.d.ts +24 -4
  72. package/dist/core/builtins/subagent.d.ts.map +1 -1
  73. package/dist/core/builtins/subagent.js +278 -35
  74. package/dist/core/builtins/subagent.js.map +1 -1
  75. package/dist/core/cache-stats.d.ts +2 -2
  76. package/dist/core/cache-stats.d.ts.map +1 -1
  77. package/dist/core/cache-stats.js +1 -1
  78. package/dist/core/cache-stats.js.map +1 -1
  79. package/dist/core/checkpoints/checkpoint-cli.d.ts +17 -0
  80. package/dist/core/checkpoints/checkpoint-cli.d.ts.map +1 -0
  81. package/dist/core/checkpoints/checkpoint-cli.js +78 -0
  82. package/dist/core/checkpoints/checkpoint-cli.js.map +1 -0
  83. package/dist/core/checkpoints/checkpoint-manager.d.ts +294 -0
  84. package/dist/core/checkpoints/checkpoint-manager.d.ts.map +1 -0
  85. package/dist/core/checkpoints/checkpoint-manager.js +865 -0
  86. package/dist/core/checkpoints/checkpoint-manager.js.map +1 -0
  87. package/dist/core/checkpoints/rewind.d.ts +141 -0
  88. package/dist/core/checkpoints/rewind.d.ts.map +1 -0
  89. package/dist/core/checkpoints/rewind.js +246 -0
  90. package/dist/core/checkpoints/rewind.js.map +1 -0
  91. package/dist/core/compaction/branch-summarization.d.ts +9 -3
  92. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  93. package/dist/core/compaction/branch-summarization.js +16 -14
  94. package/dist/core/compaction/branch-summarization.js.map +1 -1
  95. package/dist/core/compaction/compaction.d.ts +24 -3
  96. package/dist/core/compaction/compaction.d.ts.map +1 -1
  97. package/dist/core/compaction/compaction.js +96 -30
  98. package/dist/core/compaction/compaction.js.map +1 -1
  99. package/dist/core/compaction/utils.d.ts +1 -1
  100. package/dist/core/compaction/utils.d.ts.map +1 -1
  101. package/dist/core/compaction/utils.js +6 -17
  102. package/dist/core/compaction/utils.js.map +1 -1
  103. package/dist/core/context-windows.d.ts +7 -0
  104. package/dist/core/context-windows.d.ts.map +1 -0
  105. package/dist/core/context-windows.js +35 -0
  106. package/dist/core/context-windows.js.map +1 -0
  107. package/dist/core/extensions/index.d.ts +1 -1
  108. package/dist/core/extensions/index.d.ts.map +1 -1
  109. package/dist/core/extensions/index.js.map +1 -1
  110. package/dist/core/extensions/loader.d.ts.map +1 -1
  111. package/dist/core/extensions/loader.js +101 -23
  112. package/dist/core/extensions/loader.js.map +1 -1
  113. package/dist/core/extensions/runner.d.ts +19 -3
  114. package/dist/core/extensions/runner.d.ts.map +1 -1
  115. package/dist/core/extensions/runner.js +117 -2
  116. package/dist/core/extensions/runner.js.map +1 -1
  117. package/dist/core/extensions/types.d.ts +236 -9
  118. package/dist/core/extensions/types.d.ts.map +1 -1
  119. package/dist/core/extensions/types.js.map +1 -1
  120. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  121. package/dist/core/extensions/wrapper.js +22 -3
  122. package/dist/core/extensions/wrapper.js.map +1 -1
  123. package/dist/core/footer-data-provider.d.ts +10 -0
  124. package/dist/core/footer-data-provider.d.ts.map +1 -1
  125. package/dist/core/footer-data-provider.js +1 -1
  126. package/dist/core/footer-data-provider.js.map +1 -1
  127. package/dist/core/http-dispatcher.d.ts.map +1 -1
  128. package/dist/core/http-dispatcher.js +7 -0
  129. package/dist/core/http-dispatcher.js.map +1 -1
  130. package/dist/core/index.d.ts +1 -1
  131. package/dist/core/index.d.ts.map +1 -1
  132. package/dist/core/index.js.map +1 -1
  133. package/dist/core/keybindings.d.ts +18 -3
  134. package/dist/core/keybindings.d.ts.map +1 -1
  135. package/dist/core/keybindings.js +12 -3
  136. package/dist/core/keybindings.js.map +1 -1
  137. package/dist/core/model-config.d.ts +542 -0
  138. package/dist/core/model-config.d.ts.map +1 -0
  139. package/dist/core/model-config.js +247 -0
  140. package/dist/core/model-config.js.map +1 -0
  141. package/dist/core/model-registry.d.ts +19 -124
  142. package/dist/core/model-registry.d.ts.map +1 -1
  143. package/dist/core/model-registry.js +56 -727
  144. package/dist/core/model-registry.js.map +1 -1
  145. package/dist/core/model-resolver.d.ts +7 -6
  146. package/dist/core/model-resolver.d.ts.map +1 -1
  147. package/dist/core/model-resolver.js +74 -27
  148. package/dist/core/model-resolver.js.map +1 -1
  149. package/dist/core/model-runtime.d.ts +89 -0
  150. package/dist/core/model-runtime.d.ts.map +1 -0
  151. package/dist/core/model-runtime.js +451 -0
  152. package/dist/core/model-runtime.js.map +1 -0
  153. package/dist/core/models-store.d.ts +17 -0
  154. package/dist/core/models-store.d.ts.map +1 -0
  155. package/dist/core/models-store.js +46 -0
  156. package/dist/core/models-store.js.map +1 -0
  157. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  158. package/dist/core/multi-agent/permission-gate.js +4 -3
  159. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  160. package/dist/core/multi-agent/worktree.d.ts +2 -0
  161. package/dist/core/multi-agent/worktree.d.ts.map +1 -1
  162. package/dist/core/multi-agent/worktree.js +2 -2
  163. package/dist/core/multi-agent/worktree.js.map +1 -1
  164. package/dist/core/package-manager.d.ts +7 -1
  165. package/dist/core/package-manager.d.ts.map +1 -1
  166. package/dist/core/package-manager.js +41 -45
  167. package/dist/core/package-manager.js.map +1 -1
  168. package/dist/core/permission-relay/index.d.ts +19 -0
  169. package/dist/core/permission-relay/index.d.ts.map +1 -0
  170. package/dist/core/permission-relay/index.js +49 -0
  171. package/dist/core/permission-relay/index.js.map +1 -0
  172. package/dist/core/permission-relay/relay-ui-context.d.ts +39 -0
  173. package/dist/core/permission-relay/relay-ui-context.d.ts.map +1 -0
  174. package/dist/core/permission-relay/relay-ui-context.js +788 -0
  175. package/dist/core/permission-relay/relay-ui-context.js.map +1 -0
  176. package/dist/core/permission-relay/types.d.ts +222 -0
  177. package/dist/core/permission-relay/types.d.ts.map +1 -0
  178. package/dist/core/permission-relay/types.js +15 -0
  179. package/dist/core/permission-relay/types.js.map +1 -0
  180. package/dist/core/pi-manifest.d.ts +14 -0
  181. package/dist/core/pi-manifest.d.ts.map +1 -0
  182. package/dist/core/pi-manifest.js +35 -0
  183. package/dist/core/pi-manifest.js.map +1 -0
  184. package/dist/core/project-trust.js +2 -2
  185. package/dist/core/project-trust.js.map +1 -1
  186. package/dist/core/prompt-templates.d.ts +1 -0
  187. package/dist/core/prompt-templates.d.ts.map +1 -1
  188. package/dist/core/prompt-templates.js +4 -4
  189. package/dist/core/prompt-templates.js.map +1 -1
  190. package/dist/core/provider-composer.d.ts +55 -0
  191. package/dist/core/provider-composer.d.ts.map +1 -0
  192. package/dist/core/provider-composer.js +375 -0
  193. package/dist/core/provider-composer.js.map +1 -0
  194. package/dist/core/radius.d.ts +2 -0
  195. package/dist/core/radius.d.ts.map +1 -0
  196. package/dist/core/radius.js +2 -0
  197. package/dist/core/radius.js.map +1 -0
  198. package/dist/core/remote-catalog-provider.d.ts +5 -0
  199. package/dist/core/remote-catalog-provider.d.ts.map +1 -0
  200. package/dist/core/remote-catalog-provider.js +115 -0
  201. package/dist/core/remote-catalog-provider.js.map +1 -0
  202. package/dist/core/resource-loader.d.ts +36 -0
  203. package/dist/core/resource-loader.d.ts.map +1 -1
  204. package/dist/core/resource-loader.js +159 -27
  205. package/dist/core/resource-loader.js.map +1 -1
  206. package/dist/core/runtime-credentials.d.ts +15 -0
  207. package/dist/core/runtime-credentials.d.ts.map +1 -0
  208. package/dist/core/runtime-credentials.js +35 -0
  209. package/dist/core/runtime-credentials.js.map +1 -0
  210. package/dist/core/sandbox/bash-operations.d.ts +149 -0
  211. package/dist/core/sandbox/bash-operations.d.ts.map +1 -0
  212. package/dist/core/sandbox/bash-operations.js +163 -0
  213. package/dist/core/sandbox/bash-operations.js.map +1 -0
  214. package/dist/core/sandbox/env.d.ts +83 -0
  215. package/dist/core/sandbox/env.d.ts.map +1 -0
  216. package/dist/core/sandbox/env.js +123 -0
  217. package/dist/core/sandbox/env.js.map +1 -0
  218. package/dist/core/sandbox/executor.d.ts +104 -0
  219. package/dist/core/sandbox/executor.d.ts.map +1 -0
  220. package/dist/core/sandbox/executor.js +92 -0
  221. package/dist/core/sandbox/executor.js.map +1 -0
  222. package/dist/core/sandbox/index.d.ts +36 -0
  223. package/dist/core/sandbox/index.d.ts.map +1 -0
  224. package/dist/core/sandbox/index.js +36 -0
  225. package/dist/core/sandbox/index.js.map +1 -0
  226. package/dist/core/sandbox/linux.d.ts +121 -0
  227. package/dist/core/sandbox/linux.d.ts.map +1 -0
  228. package/dist/core/sandbox/linux.js +260 -0
  229. package/dist/core/sandbox/linux.js.map +1 -0
  230. package/dist/core/sandbox/policy.d.ts +142 -0
  231. package/dist/core/sandbox/policy.d.ts.map +1 -0
  232. package/dist/core/sandbox/policy.js +297 -0
  233. package/dist/core/sandbox/policy.js.map +1 -0
  234. package/dist/core/sandbox/real-path.d.ts +112 -0
  235. package/dist/core/sandbox/real-path.d.ts.map +1 -0
  236. package/dist/core/sandbox/real-path.js +158 -0
  237. package/dist/core/sandbox/real-path.js.map +1 -0
  238. package/dist/core/sandbox/seatbelt-profile.d.ts +95 -0
  239. package/dist/core/sandbox/seatbelt-profile.d.ts.map +1 -0
  240. package/dist/core/sandbox/seatbelt-profile.js +239 -0
  241. package/dist/core/sandbox/seatbelt-profile.js.map +1 -0
  242. package/dist/core/sandbox/seatbelt.d.ts +95 -0
  243. package/dist/core/sandbox/seatbelt.d.ts.map +1 -0
  244. package/dist/core/sandbox/seatbelt.js +154 -0
  245. package/dist/core/sandbox/seatbelt.js.map +1 -0
  246. package/dist/core/sandbox/self-test.d.ts +109 -0
  247. package/dist/core/sandbox/self-test.d.ts.map +1 -0
  248. package/dist/core/sandbox/self-test.js +369 -0
  249. package/dist/core/sandbox/self-test.js.map +1 -0
  250. package/dist/core/sandbox/spawn.d.ts +33 -0
  251. package/dist/core/sandbox/spawn.d.ts.map +1 -0
  252. package/dist/core/sandbox/spawn.js +87 -0
  253. package/dist/core/sandbox/spawn.js.map +1 -0
  254. package/dist/core/sdk.d.ts +3 -6
  255. package/dist/core/sdk.d.ts.map +1 -1
  256. package/dist/core/sdk.js +25 -22
  257. package/dist/core/sdk.js.map +1 -1
  258. package/dist/core/session-manager.d.ts +74 -7
  259. package/dist/core/session-manager.d.ts.map +1 -1
  260. package/dist/core/session-manager.js +169 -34
  261. package/dist/core/session-manager.js.map +1 -1
  262. package/dist/core/settings-manager.d.ts +22 -1
  263. package/dist/core/settings-manager.d.ts.map +1 -1
  264. package/dist/core/settings-manager.js +36 -16
  265. package/dist/core/settings-manager.js.map +1 -1
  266. package/dist/core/skills.d.ts +3 -1
  267. package/dist/core/skills.d.ts.map +1 -1
  268. package/dist/core/skills.js +19 -6
  269. package/dist/core/skills.js.map +1 -1
  270. package/dist/core/slash-commands.d.ts.map +1 -1
  271. package/dist/core/slash-commands.js +1 -0
  272. package/dist/core/slash-commands.js.map +1 -1
  273. package/dist/core/soak/soak-log.d.ts +298 -0
  274. package/dist/core/soak/soak-log.d.ts.map +1 -0
  275. package/dist/core/soak/soak-log.js +660 -0
  276. package/dist/core/soak/soak-log.js.map +1 -0
  277. package/dist/core/soak/soak-reader.d.ts +60 -0
  278. package/dist/core/soak/soak-reader.d.ts.map +1 -0
  279. package/dist/core/soak/soak-reader.js +106 -0
  280. package/dist/core/soak/soak-reader.js.map +1 -0
  281. package/dist/core/socket-server/discovery.d.ts +78 -1
  282. package/dist/core/socket-server/discovery.d.ts.map +1 -1
  283. package/dist/core/socket-server/discovery.js +356 -37
  284. package/dist/core/socket-server/discovery.js.map +1 -1
  285. package/dist/core/socket-server/index.d.ts +10 -4
  286. package/dist/core/socket-server/index.d.ts.map +1 -1
  287. package/dist/core/socket-server/index.js +6 -3
  288. package/dist/core/socket-server/index.js.map +1 -1
  289. package/dist/core/socket-server/permission-delivery.d.ts +125 -0
  290. package/dist/core/socket-server/permission-delivery.d.ts.map +1 -0
  291. package/dist/core/socket-server/permission-delivery.js +152 -0
  292. package/dist/core/socket-server/permission-delivery.js.map +1 -0
  293. package/dist/core/socket-server/permission-registry.d.ts +301 -0
  294. package/dist/core/socket-server/permission-registry.d.ts.map +1 -0
  295. package/dist/core/socket-server/permission-registry.js +410 -0
  296. package/dist/core/socket-server/permission-registry.js.map +1 -0
  297. package/dist/core/socket-server/permission-relay.d.ts +81 -0
  298. package/dist/core/socket-server/permission-relay.d.ts.map +1 -0
  299. package/dist/core/socket-server/permission-relay.js +528 -0
  300. package/dist/core/socket-server/permission-relay.js.map +1 -0
  301. package/dist/core/socket-server/safe-text.d.ts +83 -0
  302. package/dist/core/socket-server/safe-text.d.ts.map +1 -0
  303. package/dist/core/socket-server/safe-text.js +277 -0
  304. package/dist/core/socket-server/safe-text.js.map +1 -0
  305. package/dist/core/socket-server/session-integration.d.ts +65 -2
  306. package/dist/core/socket-server/session-integration.d.ts.map +1 -1
  307. package/dist/core/socket-server/session-integration.js +434 -32
  308. package/dist/core/socket-server/session-integration.js.map +1 -1
  309. package/dist/core/socket-server/socket-client.d.ts +21 -2
  310. package/dist/core/socket-server/socket-client.d.ts.map +1 -1
  311. package/dist/core/socket-server/socket-client.js +52 -1
  312. package/dist/core/socket-server/socket-client.js.map +1 -1
  313. package/dist/core/socket-server/socket-server.d.ts +152 -1
  314. package/dist/core/socket-server/socket-server.d.ts.map +1 -1
  315. package/dist/core/socket-server/socket-server.js +775 -26
  316. package/dist/core/socket-server/socket-server.js.map +1 -1
  317. package/dist/core/socket-server/types.d.ts +106 -2
  318. package/dist/core/socket-server/types.d.ts.map +1 -1
  319. package/dist/core/socket-server/types.js +13 -1
  320. package/dist/core/socket-server/types.js.map +1 -1
  321. package/dist/core/system-prompt.d.ts.map +1 -1
  322. package/dist/core/system-prompt.js +10 -21
  323. package/dist/core/system-prompt.js.map +1 -1
  324. package/dist/core/tools/bash.d.ts +3 -1
  325. package/dist/core/tools/bash.d.ts.map +1 -1
  326. package/dist/core/tools/bash.js +39 -7
  327. package/dist/core/tools/bash.js.map +1 -1
  328. package/dist/core/tools/edit.d.ts.map +1 -1
  329. package/dist/core/tools/edit.js +17 -2
  330. package/dist/core/tools/edit.js.map +1 -1
  331. package/dist/core/tools/find.d.ts +3 -0
  332. package/dist/core/tools/find.d.ts.map +1 -1
  333. package/dist/core/tools/find.js +11 -18
  334. package/dist/core/tools/find.js.map +1 -1
  335. package/dist/core/tools/read.js +1 -1
  336. package/dist/core/tools/read.js.map +1 -1
  337. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  338. package/dist/core/tools/tool-definition-wrapper.js +3 -1
  339. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  340. package/dist/core/trust-manager.d.ts +6 -4
  341. package/dist/core/trust-manager.d.ts.map +1 -1
  342. package/dist/core/trust-manager.js +55 -21
  343. package/dist/core/trust-manager.js.map +1 -1
  344. package/dist/core/usage-totals.d.ts +19 -0
  345. package/dist/core/usage-totals.d.ts.map +1 -0
  346. package/dist/core/usage-totals.js +52 -0
  347. package/dist/core/usage-totals.js.map +1 -0
  348. package/dist/extensions/index.d.ts +3 -0
  349. package/dist/extensions/index.d.ts.map +1 -0
  350. package/dist/extensions/index.js +7 -0
  351. package/dist/extensions/index.js.map +1 -0
  352. package/dist/extensions/llama/client.d.ts +61 -0
  353. package/dist/extensions/llama/client.d.ts.map +1 -0
  354. package/dist/extensions/llama/client.js +300 -0
  355. package/dist/extensions/llama/client.js.map +1 -0
  356. package/dist/extensions/llama/huggingface.d.ts +23 -0
  357. package/dist/extensions/llama/huggingface.d.ts.map +1 -0
  358. package/dist/extensions/llama/huggingface.js +139 -0
  359. package/dist/extensions/llama/huggingface.js.map +1 -0
  360. package/dist/extensions/llama/index.d.ts +3 -0
  361. package/dist/extensions/llama/index.d.ts.map +1 -0
  362. package/dist/extensions/llama/index.js +208 -0
  363. package/dist/extensions/llama/index.js.map +1 -0
  364. package/dist/extensions/llama/provider.d.ts +10 -0
  365. package/dist/extensions/llama/provider.d.ts.map +1 -0
  366. package/dist/extensions/llama/provider.js +111 -0
  367. package/dist/extensions/llama/provider.js.map +1 -0
  368. package/dist/extensions/llama/ui.d.ts +42 -0
  369. package/dist/extensions/llama/ui.d.ts.map +1 -0
  370. package/dist/extensions/llama/ui.js +400 -0
  371. package/dist/extensions/llama/ui.js.map +1 -0
  372. package/dist/extensions/stub-provider/index.d.ts +9 -0
  373. package/dist/extensions/stub-provider/index.d.ts.map +1 -0
  374. package/dist/extensions/stub-provider/index.js +13 -0
  375. package/dist/extensions/stub-provider/index.js.map +1 -0
  376. package/dist/extensions/stub-provider/provider.d.ts +77 -0
  377. package/dist/extensions/stub-provider/provider.d.ts.map +1 -0
  378. package/dist/extensions/stub-provider/provider.js +193 -0
  379. package/dist/extensions/stub-provider/provider.js.map +1 -0
  380. package/dist/hooks/gsd/draht-quality-gate.js +3 -3
  381. package/dist/index.d.ts +4 -3
  382. package/dist/index.d.ts.map +1 -1
  383. package/dist/index.js +3 -3
  384. package/dist/index.js.map +1 -1
  385. package/dist/main.d.ts.map +1 -1
  386. package/dist/main.js +305 -61
  387. package/dist/main.js.map +1 -1
  388. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  389. package/dist/modes/interactive/components/assistant-message.js +22 -10
  390. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  391. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  392. package/dist/modes/interactive/components/config-selector.js +3 -2
  393. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  394. package/dist/modes/interactive/components/custom-editor.js +1 -1
  395. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  396. package/dist/modes/interactive/components/custom-message.d.ts +3 -1
  397. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  398. package/dist/modes/interactive/components/custom-message.js +9 -2
  399. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  400. package/dist/modes/interactive/components/extension-editor.d.ts +1 -2
  401. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  402. package/dist/modes/interactive/components/extension-editor.js +16 -46
  403. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  404. package/dist/modes/interactive/components/extension-selector.d.ts +49 -0
  405. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  406. package/dist/modes/interactive/components/extension-selector.js +202 -5
  407. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  408. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  409. package/dist/modes/interactive/components/footer.js +24 -23
  410. package/dist/modes/interactive/components/footer.js.map +1 -1
  411. package/dist/modes/interactive/components/login-dialog.d.ts +5 -5
  412. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  413. package/dist/modes/interactive/components/login-dialog.js +17 -8
  414. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  415. package/dist/modes/interactive/components/model-selector.d.ts +11 -4
  416. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  417. package/dist/modes/interactive/components/model-selector.js +74 -41
  418. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  419. package/dist/modes/interactive/components/oauth-selector.d.ts +4 -4
  420. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  421. package/dist/modes/interactive/components/oauth-selector.js +14 -25
  422. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  423. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  424. package/dist/modes/interactive/components/scoped-models-selector.js +22 -13
  425. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  426. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  427. package/dist/modes/interactive/components/session-selector.js +10 -2
  428. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  429. package/dist/modes/interactive/components/settings-selector.d.ts +2 -0
  430. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  431. package/dist/modes/interactive/components/settings-selector.js +10 -0
  432. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  433. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  434. package/dist/modes/interactive/components/tool-execution.js +10 -1
  435. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  436. package/dist/modes/interactive/components/tree-selector.d.ts +25 -2
  437. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  438. package/dist/modes/interactive/components/tree-selector.js +68 -17
  439. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  440. package/dist/modes/interactive/external-editor.d.ts +12 -0
  441. package/dist/modes/interactive/external-editor.d.ts.map +1 -0
  442. package/dist/modes/interactive/external-editor.js +37 -0
  443. package/dist/modes/interactive/external-editor.js.map +1 -0
  444. package/dist/modes/interactive/interactive-mode.d.ts +107 -10
  445. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  446. package/dist/modes/interactive/interactive-mode.js +763 -285
  447. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  448. package/dist/modes/rpc/rpc-client.d.ts +4 -0
  449. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  450. package/dist/modes/rpc/rpc-client.js +7 -0
  451. package/dist/modes/rpc/rpc-client.js.map +1 -1
  452. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  453. package/dist/modes/rpc/rpc-mode.js +185 -9
  454. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  455. package/dist/modes/rpc/rpc-types.d.ts +79 -1
  456. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  457. package/dist/modes/rpc/rpc-types.js.map +1 -1
  458. package/dist/package-manager-cli.d.ts.map +1 -1
  459. package/dist/package-manager-cli.js +67 -5
  460. package/dist/package-manager-cli.js.map +1 -1
  461. package/dist/prompts/commands/atomic-commit.md +1 -12
  462. package/dist/prompts/commands/brainstorm.md +12 -15
  463. package/dist/prompts/commands/create-verification-skill.md +108 -0
  464. package/dist/prompts/commands/discuss-phase.md +3 -14
  465. package/dist/prompts/commands/execute-phase.md +3 -11
  466. package/dist/prompts/commands/fix.md +41 -18
  467. package/dist/prompts/commands/grill.md +66 -0
  468. package/dist/prompts/commands/init-project.md +5 -15
  469. package/dist/prompts/commands/map-codebase.md +1 -13
  470. package/dist/prompts/commands/new-project.md +5 -15
  471. package/dist/prompts/commands/next-milestone.md +1 -13
  472. package/dist/prompts/commands/orchestrate.md +1 -1
  473. package/dist/prompts/commands/pause-work.md +1 -13
  474. package/dist/prompts/commands/plan-phase.md +2 -11
  475. package/dist/prompts/commands/progress.md +0 -13
  476. package/dist/prompts/commands/quick.md +3 -11
  477. package/dist/prompts/commands/resolve-conflicts.md +71 -0
  478. package/dist/prompts/commands/resume-work.md +0 -13
  479. package/dist/prompts/commands/review.md +4 -13
  480. package/dist/prompts/commands/triage.md +159 -0
  481. package/dist/prompts/commands/verify-work.md +4 -14
  482. package/dist/prompts/commands/why.md +135 -0
  483. package/dist/skills/atomic-reasoning/SKILL.md +115 -0
  484. package/dist/skills/blast-radius/SKILL.md +55 -0
  485. package/dist/skills/epistemics/SKILL.md +99 -0
  486. package/dist/skills/hexagon-animation/SKILL.md +49 -0
  487. package/dist/skills/hexagon-animation/generate.mjs +81 -0
  488. package/dist/skills/hexagon-animation/template.html +361 -0
  489. package/dist/skills/typescript-discipline/SKILL.md +50 -0
  490. package/dist/skills/typescript-discipline/references/patterns.md +294 -0
  491. package/dist/skills/unslop/SKILL.md +101 -0
  492. package/dist/utils/canonical-path.d.ts +28 -0
  493. package/dist/utils/canonical-path.d.ts.map +1 -0
  494. package/dist/utils/canonical-path.js +90 -0
  495. package/dist/utils/canonical-path.js.map +1 -0
  496. package/dist/utils/child-process.d.ts +12 -1
  497. package/dist/utils/child-process.d.ts.map +1 -1
  498. package/dist/utils/child-process.js +25 -8
  499. package/dist/utils/child-process.js.map +1 -1
  500. package/dist/utils/clipboard-native.d.ts +1 -0
  501. package/dist/utils/clipboard-native.d.ts.map +1 -1
  502. package/dist/utils/clipboard-native.js.map +1 -1
  503. package/dist/utils/clipboard.d.ts +2 -0
  504. package/dist/utils/clipboard.d.ts.map +1 -1
  505. package/dist/utils/clipboard.js +53 -9
  506. package/dist/utils/clipboard.js.map +1 -1
  507. package/dist/utils/exif-orientation.d.ts.map +1 -1
  508. package/dist/utils/exif-orientation.js +2 -3
  509. package/dist/utils/exif-orientation.js.map +1 -1
  510. package/dist/utils/paths.d.ts +2 -7
  511. package/dist/utils/paths.d.ts.map +1 -1
  512. package/dist/utils/paths.js +13 -15
  513. package/dist/utils/paths.js.map +1 -1
  514. package/dist/utils/shell.d.ts.map +1 -1
  515. package/dist/utils/shell.js +6 -4
  516. package/dist/utils/shell.js.map +1 -1
  517. package/dist/utils/tools-manager.d.ts.map +1 -1
  518. package/dist/utils/tools-manager.js +3 -5
  519. package/dist/utils/tools-manager.js.map +1 -1
  520. package/dist/utils/version-check.d.ts.map +1 -1
  521. package/dist/utils/version-check.js +3 -1
  522. package/dist/utils/version-check.js.map +1 -1
  523. package/docs/attachable-sessions.md +79 -0
  524. package/docs/compaction.md +29 -24
  525. package/docs/containerization.md +23 -23
  526. package/docs/custom-provider.md +66 -32
  527. package/docs/development.md +9 -9
  528. package/docs/docs.json +6 -2
  529. package/docs/duet.md +42 -0
  530. package/docs/environment-variables.md +88 -0
  531. package/docs/extensions.md +278 -65
  532. package/docs/index.md +12 -10
  533. package/docs/json.md +12 -8
  534. package/docs/keybindings.md +8 -5
  535. package/docs/llama-cpp.md +99 -0
  536. package/docs/models.md +19 -8
  537. package/docs/packages.md +43 -42
  538. package/docs/prompt-templates.md +5 -4
  539. package/docs/providers.md +45 -11
  540. package/docs/quickstart.md +33 -33
  541. package/docs/rpc.md +190 -19
  542. package/docs/sdk.md +18 -15
  543. package/docs/security.md +18 -18
  544. package/docs/session-format.md +53 -15
  545. package/docs/sessions.md +17 -14
  546. package/docs/settings.md +26 -19
  547. package/docs/shell-aliases.md +2 -2
  548. package/docs/skills.md +12 -11
  549. package/docs/terminal-setup.md +12 -12
  550. package/docs/termux.md +6 -6
  551. package/docs/themes.md +11 -11
  552. package/docs/tmux.md +4 -4
  553. package/docs/tui.md +46 -31
  554. package/docs/usage.md +53 -63
  555. package/docs/windows.md +2 -2
  556. package/examples/extensions/custom-compaction.ts +4 -0
  557. package/examples/extensions/custom-provider-anthropic/index.ts +9 -3
  558. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  559. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  560. package/examples/extensions/custom-provider-qwen-cli/package.json +1 -1
  561. package/examples/extensions/gondolin/package.json +2 -2
  562. package/examples/extensions/handoff.ts +9 -1
  563. package/examples/extensions/kimi-deferred-tools.ts +61 -0
  564. package/examples/extensions/message-renderer.ts +2 -2
  565. package/examples/extensions/overlay-qa-tests.ts +3 -3
  566. package/examples/extensions/sandbox/package.json +1 -1
  567. package/examples/extensions/summarize.ts +3 -0
  568. package/examples/extensions/with-deps/package.json +1 -1
  569. package/examples/sdk/02-custom-model.ts +5 -8
  570. package/examples/sdk/09-api-keys-and-oauth.ts +15 -31
  571. package/examples/sdk/12-full-control.ts +9 -12
  572. package/hooks/gsd/draht-quality-gate.js +3 -3
  573. package/package.json +14 -11
  574. package/prompts/commands/atomic-commit.md +1 -12
  575. package/prompts/commands/brainstorm.md +12 -15
  576. package/prompts/commands/create-verification-skill.md +108 -0
  577. package/prompts/commands/discuss-phase.md +3 -14
  578. package/prompts/commands/execute-phase.md +3 -11
  579. package/prompts/commands/fix.md +41 -18
  580. package/prompts/commands/grill.md +66 -0
  581. package/prompts/commands/init-project.md +5 -15
  582. package/prompts/commands/map-codebase.md +1 -13
  583. package/prompts/commands/new-project.md +5 -15
  584. package/prompts/commands/next-milestone.md +1 -13
  585. package/prompts/commands/orchestrate.md +1 -1
  586. package/prompts/commands/pause-work.md +1 -13
  587. package/prompts/commands/plan-phase.md +2 -11
  588. package/prompts/commands/progress.md +0 -13
  589. package/prompts/commands/quick.md +3 -11
  590. package/prompts/commands/resolve-conflicts.md +71 -0
  591. package/prompts/commands/resume-work.md +0 -13
  592. package/prompts/commands/review.md +4 -13
  593. package/prompts/commands/triage.md +159 -0
  594. package/prompts/commands/verify-work.md +4 -14
  595. package/prompts/commands/why.md +135 -0
  596. package/skills/atomic-reasoning/SKILL.md +115 -0
  597. package/skills/blast-radius/SKILL.md +55 -0
  598. package/skills/epistemics/SKILL.md +99 -0
  599. package/skills/hexagon-animation/SKILL.md +49 -0
  600. package/skills/hexagon-animation/generate.mjs +81 -0
  601. package/skills/hexagon-animation/template.html +361 -0
  602. package/skills/typescript-discipline/SKILL.md +50 -0
  603. package/skills/typescript-discipline/references/patterns.md +294 -0
  604. package/skills/unslop/SKILL.md +101 -0
  605. package/dist/core/provider-display-names.d.ts +0 -2
  606. package/dist/core/provider-display-names.d.ts.map +0 -1
  607. package/dist/core/provider-display-names.js +0 -36
  608. package/dist/core/provider-display-names.js.map +0 -1
  609. package/dist/prompts/agents/build.md +0 -86
  610. package/dist/prompts/agents/plan.md +0 -79
  611. package/dist/prompts/agents/verify.md +0 -69
  612. package/prompts/agents/build.md +0 -86
  613. package/prompts/agents/plan.md +0 -79
  614. package/prompts/agents/verify.md +0 -69
@@ -0,0 +1,865 @@
1
+ /**
2
+ * CheckpointManager — working-tree snapshot capture and durable storage (Phase 41).
3
+ *
4
+ * Captures git snapshots of the working tree via a temporary index
5
+ * (`GIT_INDEX_FILE` + `add -A` + `write-tree` + `commit-tree`) and anchors
6
+ * them at `refs/draht/checkpoints/<session-id>/<entry-id>` so they are
7
+ * GC-proof and invisible to the user's git workflow: the user's index,
8
+ * `HEAD`, stash, and reflog are never touched, and `git stash` is never used.
9
+ *
10
+ * Metadata lives in a sidecar JSONL next to the session file
11
+ * (`<session-file>.checkpoints.jsonl`).
12
+ */
13
+ import { execFile } from "node:child_process";
14
+ import { randomUUID } from "node:crypto";
15
+ import { appendFileSync, copyFileSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmdirSync, rmSync, statSync, utimesSync, writeFileSync, } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { basename, dirname, join, resolve, sep } from "node:path";
18
+ import { promisify } from "node:util";
19
+ const execFileAsync = promisify(execFile);
20
+ /** Ref namespace for checkpoint snapshots: `refs/draht/checkpoints/<session-id>/<entry-id>`. */
21
+ export const CHECKPOINT_REF_PREFIX = "refs/draht/checkpoints";
22
+ /**
23
+ * Ref-name segment marking a pre-rewind safety snapshot. Keeps safety refs out
24
+ * of the plain `<session-id>/<entry-id>` name space so capturing one can never
25
+ * overwrite the checkpoint already anchored for that entry.
26
+ */
27
+ export const SAFETY_REF_SEGMENT = "pre-rewind";
28
+ const MILLISECONDS_PER_DAY = 86_400_000;
29
+ /**
30
+ * Identity for snapshot commits. Passed explicitly so capture works in
31
+ * repositories (and environments) with no configured git identity — the user's
32
+ * own config is never read for this and never written.
33
+ */
34
+ const CHECKPOINT_IDENTITY = {
35
+ GIT_AUTHOR_NAME: "draht",
36
+ GIT_AUTHOR_EMAIL: "checkpoints@draht.local",
37
+ GIT_COMMITTER_NAME: "draht",
38
+ GIT_COMMITTER_EMAIL: "checkpoints@draht.local",
39
+ };
40
+ /** Raw stdout, untrimmed — required for `-z` output whose records end in NUL. */
41
+ async function gitRaw(cwd, args, extraEnv) {
42
+ const { stdout } = await execFileAsync("git", args, {
43
+ cwd,
44
+ env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
45
+ maxBuffer: 64 * 1024 * 1024,
46
+ });
47
+ return stdout;
48
+ }
49
+ async function git(cwd, args, extraEnv) {
50
+ return (await gitRaw(cwd, args, extraEnv)).trim();
51
+ }
52
+ function describeError(error) {
53
+ return error instanceof Error ? error.message : String(error);
54
+ }
55
+ async function isGitRepository(cwd) {
56
+ try {
57
+ return (await git(cwd, ["rev-parse", "--is-inside-work-tree"])) === "true";
58
+ }
59
+ catch {
60
+ return false;
61
+ }
62
+ }
63
+ /**
64
+ * Make one path component safe to use inside a git ref name. Session ids and
65
+ * entry ids are opaque to us, so anything `git check-ref-format` would reject
66
+ * (`..`, control/special characters, leading or trailing punctuation, a
67
+ * `.lock` suffix) is folded to `-`.
68
+ */
69
+ /**
70
+ * A fresh id for one snapshot: sortable-ish prefix, random suffix, and safe to
71
+ * paste straight into a ref name (`sanitizeRefComponent` leaves it untouched).
72
+ */
73
+ function newRecoveryId() {
74
+ return `${Date.now().toString(36)}-${randomUUID().slice(0, 8)}`;
75
+ }
76
+ function sanitizeRefComponent(value) {
77
+ let out = value.replace(/[^A-Za-z0-9._-]/g, "-").replace(/\.{2,}/g, "-");
78
+ out = out.replace(/^[.-]+/, "").replace(/[.-]+$/, "");
79
+ if (out.endsWith(".lock"))
80
+ out = `${out.slice(0, -".lock".length)}-lock`;
81
+ return out.length > 0 ? out : "checkpoint";
82
+ }
83
+ /**
84
+ * Diff two snapshot trees into the paths a restore has to write and the paths
85
+ * it has to delete. `--no-renames` keeps every record a plain status/path pair;
86
+ * `-z` keeps paths literal so filenames with spaces or newlines survive.
87
+ */
88
+ async function diffTrees(top, fromTree, toTree) {
89
+ const raw = await gitRaw(top, ["diff-tree", "-r", "-z", "--no-renames", "--name-status", fromTree, toTree]);
90
+ const tokens = raw.split("\0");
91
+ const diff = { writes: [], deletes: [], added: [] };
92
+ for (let i = 0; i + 1 < tokens.length; i += 2) {
93
+ const status = tokens[i];
94
+ const path = tokens[i + 1];
95
+ if (status.length === 0 || path.length === 0)
96
+ continue;
97
+ // D = present in `fromTree`, absent in `toTree`. Everything else
98
+ // (A/M/T) exists in `toTree` and has to be written out of it.
99
+ if (status.startsWith("D")) {
100
+ diff.deletes.push(path);
101
+ continue;
102
+ }
103
+ diff.writes.push(path);
104
+ if (status.startsWith("A"))
105
+ diff.added.push(path);
106
+ }
107
+ return diff;
108
+ }
109
+ /** Path arguments per git invocation, so a huge diff cannot overflow ARG_MAX. */
110
+ const GIT_PATH_BATCH = 200;
111
+ /** Ignore-rule file that can live inside a snapshot tree. */
112
+ const IGNORE_RULE_FILE = ".gitignore";
113
+ /** Directory entries, or none when the directory cannot be read. */
114
+ function readDirEntries(dir) {
115
+ try {
116
+ return readdirSync(dir, { withFileTypes: true });
117
+ }
118
+ catch {
119
+ return [];
120
+ }
121
+ }
122
+ /** `lstat`-based existence: a dangling symlink exists for our purposes. */
123
+ function pathExists(full) {
124
+ try {
125
+ lstatSync(full);
126
+ return true;
127
+ }
128
+ catch {
129
+ return false;
130
+ }
131
+ }
132
+ /** Quote at most five paths for a refusal message. */
133
+ function formatPathList(paths) {
134
+ const shown = paths.slice(0, 5).map((path) => `"${path}"`);
135
+ const rest = paths.length - shown.length;
136
+ return rest > 0 ? `${shown.join(", ")} and ${rest} more` : shown.join(", ");
137
+ }
138
+ /**
139
+ * Object type (`blob`, `tree`, `commit`) of each given path in a tree; paths
140
+ * absent from the tree are absent from the map. `ls-tree` resolves exact paths
141
+ * without `-r`, so the cost tracks the paths asked about, not the tree size.
142
+ */
143
+ async function treeEntryTypes(top, tree, paths) {
144
+ const types = new Map();
145
+ for (let i = 0; i < paths.length; i += GIT_PATH_BATCH) {
146
+ // Literal pathspecs: a path containing `*` or `[` is a filename here,
147
+ // never a glob.
148
+ const raw = await gitRaw(top, ["ls-tree", "-z", tree, "--", ...paths.slice(i, i + GIT_PATH_BATCH)], {
149
+ GIT_LITERAL_PATHSPECS: "1",
150
+ });
151
+ for (const record of raw.split("\0")) {
152
+ // "<mode> SP <type> SP <object> TAB <path>"
153
+ const tab = record.indexOf("\t");
154
+ if (tab < 0)
155
+ continue;
156
+ const type = record.slice(0, tab).split(" ")[1];
157
+ if (type)
158
+ types.set(record.slice(tab + 1), type);
159
+ }
160
+ }
161
+ return types;
162
+ }
163
+ /**
164
+ * The shallowest directory at or under `full` that is a git repository, or
165
+ * undefined when there is none. `.git` is a directory in a clone and a file in
166
+ * a linked worktree, so both shapes count.
167
+ */
168
+ function findGitRepositoryUnder(full) {
169
+ let stat;
170
+ try {
171
+ stat = lstatSync(full);
172
+ }
173
+ catch {
174
+ return undefined;
175
+ }
176
+ if (!stat.isDirectory())
177
+ return undefined;
178
+ // Breadth-first, so the reported path is the shallowest repository found.
179
+ const queue = [full];
180
+ while (queue.length > 0) {
181
+ const dir = queue.shift();
182
+ const entries = readDirEntries(dir);
183
+ if (entries.some((entry) => entry.name === ".git"))
184
+ return dir;
185
+ // Symlinked directories are not descended: git never snapshotted
186
+ // through them, so a restore cannot have scheduled anything inside.
187
+ for (const entry of entries)
188
+ if (entry.isDirectory())
189
+ queue.push(join(dir, entry.name));
190
+ }
191
+ return undefined;
192
+ }
193
+ /**
194
+ * Paths scheduled for deletion that are — or contain — a nested git repository.
195
+ *
196
+ * `git add -A` collapses an embedded clone or a `git worktree add` checkout
197
+ * into a single gitlink entry, so deleting OR overwriting that one path takes the nested
198
+ * repository's `.git` with it: its committed history and any uncommitted work
199
+ * are destroyed, and no snapshot holds either (a gitlink records only a commit
200
+ * id). There is no safe way to put that back, so a restore that would do it is
201
+ * refused rather than attempted.
202
+ */
203
+ async function findNestedRepositories(top, fromTree, paths) {
204
+ if (paths.length === 0)
205
+ return [];
206
+ const root = resolve(top);
207
+ const types = await treeEntryTypes(top, fromTree, paths);
208
+ const found = [];
209
+ for (const path of paths) {
210
+ // A gitlink ("commit") entry is a nested repository by definition.
211
+ if (types.get(path) === "commit" || findGitRepositoryUnder(join(root, path)) !== undefined)
212
+ found.push(path);
213
+ }
214
+ return found;
215
+ }
216
+ /**
217
+ * Paths the restore would create that already exist on disk while being absent
218
+ * from the pre-rewind snapshot.
219
+ *
220
+ * The safety snapshot images everything git can see, so an existing path it
221
+ * does not contain is content no snapshot holds — an ignored file, most often,
222
+ * which is precisely what happens when `.gitignore` changed between capture
223
+ * and restore. Overwriting it is unrecoverable, so the restore is refused.
224
+ */
225
+ function findUncapturedWrites(top, added) {
226
+ const root = resolve(top);
227
+ return added.filter((path) => pathExists(join(root, path)));
228
+ }
229
+ /**
230
+ * Ignore-rule files that differ between the two snapshots. The "ignored files
231
+ * are never in a snapshot, never in the diff, never touched" invariant only
232
+ * holds while the rules are the same at capture and at restore; when they
233
+ * drift, a path can be tracked in one snapshot and ignored in the other and so
234
+ * be deleted although the user believes it is ignored. Detected, not guessed
235
+ * at: a drifting rule set with deletions pending is refused.
236
+ */
237
+ function findIgnoreRuleDrift(diff) {
238
+ return [...diff.writes, ...diff.deletes].filter((path) => basename(path) === IGNORE_RULE_FILE);
239
+ }
240
+ /**
241
+ * Pre-flight refusal check, run after the safety snapshot and before the first
242
+ * mutation. Returns the refusal message, or undefined when the restore is safe
243
+ * to apply. Fails closed by design: every case here is one where proceeding
244
+ * could destroy content no snapshot can bring back.
245
+ */
246
+ async function findRestoreHazard(top, fromTree, diff) {
247
+ // Every mutated path, not just deletes: a nested repository sitting where the
248
+ // target tree holds a blob diffs as a typechange and lands in `writes`, where
249
+ // `git checkout-index -f` destroys it exactly as a delete would.
250
+ const nested = await findNestedRepositories(top, fromTree, [...diff.deletes, ...diff.writes]);
251
+ if (nested.length > 0) {
252
+ return `refusing to restore: ${formatPathList(nested)} would be removed or overwritten, and that is a nested git repository (or a directory holding one) — doing so would take its history and any uncommitted work with it, and no snapshot holds either. Move or remove it yourself, then rewind again.`;
253
+ }
254
+ const uncaptured = findUncapturedWrites(top, diff.added);
255
+ if (uncaptured.length > 0) {
256
+ return `refusing to restore: ${formatPathList(uncaptured)} exists in the working tree but is in no snapshot (ignored, or otherwise invisible to git), so restoring would overwrite content nothing can bring back. Move it aside, or stop ignoring it so it gets snapshotted, then rewind again.`;
257
+ }
258
+ const drift = findIgnoreRuleDrift(diff);
259
+ if (drift.length > 0 && diff.deletes.length > 0) {
260
+ return `refusing to restore: the ignore rules in ${formatPathList(drift)} differ between this checkpoint and the working tree, so a file that is ignored in one snapshot and tracked in the other could be deleted. Undo the ignore-rule change first, or rewind with "Conversation only".`;
261
+ }
262
+ return undefined;
263
+ }
264
+ /** Remove a worktree path and any directories the removal left empty. */
265
+ function deleteWorktreePath(top, path) {
266
+ // `git rev-parse --show-toplevel` reports forward slashes even on Windows;
267
+ // resolve so the prune loop compares like-for-like separators.
268
+ const root = resolve(top);
269
+ const full = join(root, path);
270
+ // Last line of defence for the one call that recursively deletes: a nested
271
+ // git repository must never be removed, because nothing snapshots it. The
272
+ // restore refuses long before this (`findNestedRepositories`); reaching
273
+ // here means the tree changed under us, so abort and let the caller roll
274
+ // back rather than delete a repository.
275
+ const nested = findGitRepositoryUnder(full);
276
+ if (nested !== undefined) {
277
+ throw new Error(`refusing to delete "${path}": ${nested} is a git repository and no snapshot holds it`);
278
+ }
279
+ rmSync(full, { force: true, recursive: true });
280
+ // Prune the directories the removal emptied, the way git's own checkout does.
281
+ for (let dir = dirname(full); dir !== root && dir.startsWith(root + sep); dir = dirname(dir)) {
282
+ try {
283
+ if (readdirSync(dir).length > 0)
284
+ break;
285
+ rmdirSync(dir);
286
+ }
287
+ catch {
288
+ break;
289
+ }
290
+ }
291
+ }
292
+ /**
293
+ * Apply a tree diff to the working tree, writing the `writes` paths out of
294
+ * `sourceTree` through a throwaway index. Deletions run first: a path can be a
295
+ * file in one tree and a directory in the other, and clearing the old shape
296
+ * first keeps the checkout from colliding with it.
297
+ */
298
+ async function applyTreeDiff(top, sourceTree, diff, onPathRestored) {
299
+ for (const path of diff.deletes) {
300
+ deleteWorktreePath(top, path);
301
+ await onPathRestored?.(path);
302
+ }
303
+ if (diff.writes.length === 0)
304
+ return;
305
+ const indexDir = mkdtempSync(join(tmpdir(), "draht-checkpoint-restore-"));
306
+ try {
307
+ const indexEnv = { ...CHECKPOINT_IDENTITY, GIT_INDEX_FILE: join(indexDir, "index") };
308
+ await git(top, ["read-tree", sourceTree], indexEnv);
309
+ for (const path of diff.writes) {
310
+ // `-f` overwrites an existing file and creates missing parent
311
+ // directories; the user's own index is untouched throughout.
312
+ await git(top, ["checkout-index", "-f", "-u", "--", path], indexEnv);
313
+ await onPathRestored?.(path);
314
+ }
315
+ }
316
+ finally {
317
+ rmSync(indexDir, { recursive: true, force: true });
318
+ }
319
+ }
320
+ /** Path of the checkpoint metadata sidecar for a session file. */
321
+ export function checkpointSidecarPath(sessionFile) {
322
+ return `${sessionFile}.checkpoints.jsonl`;
323
+ }
324
+ /**
325
+ * Name of the in-progress marker, written inside the repository's git
326
+ * directory (per worktree, like the rest of git's own state) so it is found
327
+ * again from any session that opens the same tree.
328
+ */
329
+ export const RESTORE_MARKER_FILE = "draht-restore-in-progress.json";
330
+ function stringOrUndefined(value) {
331
+ return typeof value === "string" && value.length > 0 ? value : undefined;
332
+ }
333
+ /**
334
+ * Read the marker, if there is one. A marker that exists but cannot be parsed
335
+ * still reports an interrupted restore — its presence is the signal; its
336
+ * contents are only the detail — so corruption can never downgrade to "fine".
337
+ */
338
+ function readRestoreMarker(markerPath) {
339
+ if (!existsSync(markerPath))
340
+ return undefined;
341
+ try {
342
+ const parsed = JSON.parse(readFileSync(markerPath, "utf8"));
343
+ return {
344
+ markerPath,
345
+ safetyRef: stringOrUndefined(parsed.safetyRef) ?? "",
346
+ safetyRecoveryId: stringOrUndefined(parsed.safetyRecoveryId),
347
+ targetRef: stringOrUndefined(parsed.targetRef),
348
+ targetEntryId: stringOrUndefined(parsed.targetEntryId),
349
+ currentEntryId: stringOrUndefined(parsed.currentEntryId),
350
+ startedAt: stringOrUndefined(parsed.startedAt),
351
+ };
352
+ }
353
+ catch {
354
+ return { markerPath, safetyRef: "" };
355
+ }
356
+ }
357
+ function writeRestoreMarker(markerPath, marker) {
358
+ mkdirSync(dirname(markerPath), { recursive: true });
359
+ writeFileSync(markerPath, `${JSON.stringify(marker, null, "\t")}\n`);
360
+ }
361
+ function clearRestoreMarker(markerPath) {
362
+ rmSync(markerPath, { force: true });
363
+ }
364
+ /** The message shown when a previous restore is found to have been interrupted. */
365
+ export function describeInterruptedRestore(marker) {
366
+ const recovery = marker.safetyRef.length > 0
367
+ ? `Your pre-rewind files are snapshotted at ${marker.safetyRef} — recover them with \`git checkout ${marker.safetyRef} -- .\``
368
+ : "The marker could not be read, so the safety ref is unknown — look for one under refs/draht/checkpoints/";
369
+ const started = marker.startedAt ? ` (started ${marker.startedAt})` : "";
370
+ return `refusing to restore: a previous restore was interrupted${started} and the working tree may be between two snapshots. ${recovery}. Delete ${marker.markerPath} once the tree is the way you want it.`;
371
+ }
372
+ function toCheckpointRecord(value) {
373
+ if (typeof value !== "object" || value === null)
374
+ return undefined;
375
+ const candidate = value;
376
+ if (typeof candidate.entryId !== "string" ||
377
+ typeof candidate.ref !== "string" ||
378
+ typeof candidate.treeHash !== "string" ||
379
+ typeof candidate.timestamp !== "string" ||
380
+ typeof candidate.dirtyFileCount !== "number") {
381
+ return undefined;
382
+ }
383
+ const record = {
384
+ entryId: candidate.entryId,
385
+ ref: candidate.ref,
386
+ treeHash: candidate.treeHash,
387
+ timestamp: candidate.timestamp,
388
+ dirtyFileCount: candidate.dirtyFileCount,
389
+ };
390
+ // Optional: sidecars written before recovery ids existed stay readable.
391
+ if (typeof candidate.recoveryId === "string")
392
+ record.recoveryId = candidate.recoveryId;
393
+ if (candidate.kind === "safety" || candidate.kind === "checkpoint")
394
+ record.kind = candidate.kind;
395
+ return record;
396
+ }
397
+ /** Read all valid records from a sidecar file. Malformed lines are skipped. */
398
+ export function readCheckpointSidecar(sidecarPath) {
399
+ if (!existsSync(sidecarPath))
400
+ return [];
401
+ let content;
402
+ try {
403
+ content = readFileSync(sidecarPath, "utf8");
404
+ }
405
+ catch {
406
+ return [];
407
+ }
408
+ const records = [];
409
+ for (const line of content.split("\n")) {
410
+ const trimmed = line.trim();
411
+ if (trimmed.length === 0)
412
+ continue;
413
+ let parsed;
414
+ try {
415
+ parsed = JSON.parse(trimmed);
416
+ }
417
+ catch {
418
+ continue;
419
+ }
420
+ const record = toCheckpointRecord(parsed);
421
+ if (record)
422
+ records.push(record);
423
+ }
424
+ return records;
425
+ }
426
+ function appendCheckpointRecord(sidecarPath, record) {
427
+ mkdirSync(dirname(sidecarPath), { recursive: true });
428
+ appendFileSync(sidecarPath, `${JSON.stringify(record)}\n`);
429
+ }
430
+ /**
431
+ * Copy sidecar records for preserved entry ids from one session file's
432
+ * sidecar to another's (used by /fork and /clone). Returns the number of
433
+ * records copied. Refs are copied verbatim — they keep pointing at the
434
+ * source session's namespace, which stays anchored in the repository.
435
+ */
436
+ export function propagateCheckpointSidecar(sourceSessionFile, targetSessionFile, preservedEntryIds) {
437
+ const source = readCheckpointSidecar(checkpointSidecarPath(sourceSessionFile));
438
+ const kept = source.filter((record) => preservedEntryIds.has(record.entryId));
439
+ if (kept.length === 0)
440
+ return 0;
441
+ const target = checkpointSidecarPath(targetSessionFile);
442
+ mkdirSync(dirname(target), { recursive: true });
443
+ writeFileSync(target, `${kept.map((record) => JSON.stringify(record)).join("\n")}\n`);
444
+ return kept.length;
445
+ }
446
+ export class CheckpointManager {
447
+ constructor(options) {
448
+ this.cwd = options.cwd;
449
+ this.sessionId = options.sessionId;
450
+ this.sidecarPath = checkpointSidecarPath(options.sessionFile);
451
+ this.onCaptured = options.onCaptured;
452
+ }
453
+ /**
454
+ * Capture a snapshot of the working tree keyed to the given session entry
455
+ * id, unless the tree hash equals the previous checkpoint's (dedup).
456
+ * Never throws for expected conditions: non-git cwds report "disabled",
457
+ * git failures report "failed".
458
+ */
459
+ async captureIfChanged(entryId) {
460
+ if (!(await isGitRepository(this.cwd))) {
461
+ return { status: "disabled", reason: `${this.cwd} is not inside a git repository` };
462
+ }
463
+ try {
464
+ const treeHash = await this.writeTreeSnapshot();
465
+ const previous = this.list().at(-1);
466
+ if (previous?.treeHash === treeHash)
467
+ return { status: "deduplicated" };
468
+ const recoveryId = newRecoveryId();
469
+ const base = `${CHECKPOINT_REF_PREFIX}/${sanitizeRefComponent(this.sessionId)}/${sanitizeRefComponent(entryId)}`;
470
+ // A second capture for the same entry id (a retried or re-entered
471
+ // turn) must not overwrite the first: `update-ref` would drop the
472
+ // only anchor of a tree the user can still rewind to. Suffix
473
+ // instead, and let the sidecar order decide which one `get` returns.
474
+ const ref = (await this.refExists(base)) ? `${base}-${recoveryId}` : base;
475
+ await this.anchorTree(treeHash, ref, `draht checkpoint ${entryId}`);
476
+ const record = await this.recordSnapshot(entryId, ref, treeHash, recoveryId, "checkpoint");
477
+ try {
478
+ await this.onCaptured?.(record);
479
+ }
480
+ catch {
481
+ // A listener failure never turns a captured checkpoint into a failed one.
482
+ }
483
+ return { status: "created", record };
484
+ }
485
+ catch (error) {
486
+ return { status: "failed", reason: describeError(error) };
487
+ }
488
+ }
489
+ /**
490
+ * Snapshot the working tree into a throwaway index and return its tree
491
+ * hash. A private index keeps `add -A` off the user's real index entirely,
492
+ * and `add -A` honours `.gitignore` for *untracked* files, so ignored files
493
+ * never enter a snapshot — and therefore can never be restored or deleted
494
+ * by a rewind.
495
+ *
496
+ * The throwaway index is seeded from the user's real one first. Ignore
497
+ * rules never apply to a path git already tracks, so seeding is what keeps
498
+ * a tracked-but-ignored file (`git add -f secret.env` with `secret.env` in
499
+ * `.gitignore`) inside the snapshot: from an empty index every path looks
500
+ * untracked, and such files silently fell out of every snapshot while
501
+ * restores still reported success.
502
+ */
503
+ async writeTreeSnapshot() {
504
+ const indexDir = mkdtempSync(join(tmpdir(), "draht-checkpoint-index-"));
505
+ try {
506
+ const indexFile = join(indexDir, "index");
507
+ const indexEnv = { ...CHECKPOINT_IDENTITY, GIT_INDEX_FILE: indexFile };
508
+ await this.seedSnapshotIndex(indexFile, indexEnv);
509
+ await git(this.cwd, ["add", "-A"], indexEnv);
510
+ return await git(this.cwd, ["write-tree"], indexEnv);
511
+ }
512
+ finally {
513
+ rmSync(indexDir, { recursive: true, force: true });
514
+ }
515
+ }
516
+ /**
517
+ * Copy the user's index into the throwaway one so its tracked set carries
518
+ * over. Read-only with respect to the real index — it is copied, never
519
+ * written back, and `git rev-parse --git-path index` resolves the effective
520
+ * index (split-index links resolve against the git dir, so a copy still
521
+ * reads). Falls back to `read-tree HEAD`, whose tracked set is the next
522
+ * best answer, and to an empty index when HEAD is unborn — where nothing is
523
+ * tracked and empty is the correct answer.
524
+ */
525
+ async seedSnapshotIndex(indexFile, indexEnv) {
526
+ try {
527
+ const realIndex = resolve(this.cwd, await git(this.cwd, ["rev-parse", "--git-path", "index"]));
528
+ if (existsSync(realIndex)) {
529
+ // Stat before copying: a copy of an index rewritten mid-stat then
530
+ // carries a too-old timestamp, which only widens the re-check below.
531
+ const stat = statSync(realIndex);
532
+ copyFileSync(realIndex, indexFile);
533
+ // The copy must not look newer than the index it was taken from.
534
+ // Git re-checks the content of any entry whose cached mtime is not
535
+ // older than the index file's own mtime (its racy-timestamp
536
+ // protection); a fresh-mtimed copy silences that for every entry,
537
+ // so a file rewritten with the same size within the stat
538
+ // granularity of its cached entry kept its stale blob and the
539
+ // stale content leaked into snapshots (and out of restores).
540
+ utimesSync(indexFile, stat.atime, stat.mtime);
541
+ return;
542
+ }
543
+ }
544
+ catch {
545
+ // Fall through to the HEAD-based seed.
546
+ }
547
+ try {
548
+ await git(this.cwd, ["read-tree", "HEAD"], indexEnv);
549
+ }
550
+ catch {
551
+ // Unborn HEAD: nothing is tracked, so the empty index is correct.
552
+ }
553
+ }
554
+ /** Whether a ref already exists, without throwing for the common "it does not" case. */
555
+ async refExists(ref) {
556
+ try {
557
+ await git(this.cwd, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`]);
558
+ return true;
559
+ }
560
+ catch {
561
+ return false;
562
+ }
563
+ }
564
+ /** Absolute path of this repository's in-progress restore marker. */
565
+ async restoreMarkerPath() {
566
+ return join(resolve(this.cwd, await git(this.cwd, ["rev-parse", "--git-dir"])), RESTORE_MARKER_FILE);
567
+ }
568
+ /** Anchor a tree behind a commit at `ref` so it survives GC. */
569
+ async anchorTree(treeHash, ref, message) {
570
+ const commit = await git(this.cwd, ["commit-tree", treeHash, "-m", message], CHECKPOINT_IDENTITY);
571
+ await git(this.cwd, ["update-ref", ref, commit], CHECKPOINT_IDENTITY);
572
+ }
573
+ /** Append the sidecar record for an anchored snapshot. */
574
+ async recordSnapshot(entryId, ref, treeHash, recoveryId, kind) {
575
+ const record = {
576
+ entryId,
577
+ ref,
578
+ treeHash,
579
+ timestamp: new Date().toISOString(),
580
+ dirtyFileCount: await this.countDirtyFiles(treeHash),
581
+ recoveryId,
582
+ kind,
583
+ };
584
+ appendCheckpointRecord(this.sidecarPath, record);
585
+ return record;
586
+ }
587
+ /**
588
+ * Capture the pre-rewind safety snapshot (R42-RWD.3). Unlike
589
+ * `captureIfChanged` this never dedups — the rewind must always have an
590
+ * anchored ref to roll back to — and it never reuses the plain checkpoint
591
+ * ref name, so an existing checkpoint for the same entry id is preserved.
592
+ * The record is keyed to the current leaf so that rewinding back to it is
593
+ * a redo of the abandoned state.
594
+ */
595
+ async captureSafetySnapshot(entryId) {
596
+ const treeHash = await this.writeTreeSnapshot();
597
+ const recoveryId = newRecoveryId();
598
+ const ref = `${CHECKPOINT_REF_PREFIX}/${sanitizeRefComponent(this.sessionId)}/${SAFETY_REF_SEGMENT}-${sanitizeRefComponent(entryId)}-${recoveryId}`;
599
+ await this.anchorTree(treeHash, ref, `draht pre-rewind snapshot ${entryId}`);
600
+ return await this.recordSnapshot(entryId, ref, treeHash, recoveryId, "safety");
601
+ }
602
+ /**
603
+ * Restore the working tree to the checkpoint recorded for `targetEntryId`
604
+ * (R42-RWD.3, R42-RWD.4).
605
+ *
606
+ * Ordering is fixed: a safety snapshot of the current tree is captured and
607
+ * anchored *before* anything is mutated, then the two snapshot trees are
608
+ * diffed and only the differing paths are touched — differing paths are
609
+ * checked out of the target snapshot, paths absent from it are deleted.
610
+ * Deliberately not `git stash apply` and not `git checkout -- .`: both
611
+ * clobber untracked and ignored state. Ignored files are never in a
612
+ * snapshot, so they are never in the diff and never touched.
613
+ *
614
+ * Before the first mutation the diff is checked for the cases where that
615
+ * reasoning does not hold, and the whole restore is refused (`failed`,
616
+ * nothing touched) rather than applied part-way:
617
+ * - a path to delete that is, or contains, a nested git repository;
618
+ * - a path to create that already exists on disk yet is in no snapshot;
619
+ * - ignore rules that differ between the snapshots while deletions pend.
620
+ * A refusal is recoverable, a deletion is not.
621
+ *
622
+ * Any failure after the first mutation rolls the tree back to the safety
623
+ * snapshot; if that rollback also fails, both refs are reported on the
624
+ * result rather than left implicit. An in-progress marker in the git dir
625
+ * names the safety ref for as long as the tree is being mutated, so an
626
+ * interrupted restore is never silent. Never throws.
627
+ */
628
+ async restore(options) {
629
+ const untouched = { restored: [], deleted: [] };
630
+ if (!(await isGitRepository(this.cwd))) {
631
+ return { status: "disabled", ...untouched, reason: `${this.cwd} is not inside a git repository` };
632
+ }
633
+ // Resolved before the safety snapshot is recorded, so the lookup cannot
634
+ // pick up the safety record this call is about to append. A recovery id
635
+ // addresses one specific snapshot, which is the only way to reach a
636
+ // safety snapshot that a later rewind from the same leaf shadows.
637
+ const target = this.get(options.targetEntryId) ?? this.getRecoveryPoint(options.targetEntryId);
638
+ if (!target) {
639
+ return { status: "failed", ...untouched, reason: `no checkpoint recorded for entry ${options.targetEntryId}` };
640
+ }
641
+ let top;
642
+ let markerPath;
643
+ let targetTree;
644
+ let safety;
645
+ try {
646
+ // Plumbing below addresses index paths, which are relative to the
647
+ // repository root rather than to this manager's cwd.
648
+ top = await git(this.cwd, ["rev-parse", "--show-toplevel"]);
649
+ markerPath = await this.restoreMarkerPath();
650
+ // A marker still on disk means a previous restore never finished, so
651
+ // the tree is somewhere between two snapshots and diffing against a
652
+ // fresh snapshot of it would bake that half-state in. Refuse, and
653
+ // name the ref that recovers the tree.
654
+ const interrupted = readRestoreMarker(markerPath);
655
+ if (interrupted) {
656
+ return { status: "failed", ...untouched, target, reason: describeInterruptedRestore(interrupted) };
657
+ }
658
+ // Resolve through the ref so a pruned or corrupt snapshot fails here,
659
+ // before the safety snapshot and before any mutation.
660
+ targetTree = await git(top, ["rev-parse", "--verify", `${target.ref}^{tree}`]);
661
+ safety = await this.captureSafetySnapshot(options.currentEntryId);
662
+ }
663
+ catch (error) {
664
+ return { status: "failed", ...untouched, target, reason: describeError(error) };
665
+ }
666
+ if (targetTree === safety.treeHash) {
667
+ return { status: "unchanged", ...untouched, safety, target };
668
+ }
669
+ let diff;
670
+ let hazard;
671
+ try {
672
+ diff = await diffTrees(top, safety.treeHash, targetTree);
673
+ // Every hazard here is content the snapshots cannot bring back, so
674
+ // the restore is refused whole rather than applied part-way. Nothing
675
+ // has been mutated at this point.
676
+ hazard = await findRestoreHazard(top, safety.treeHash, diff);
677
+ }
678
+ catch (error) {
679
+ return { status: "failed", ...untouched, safety, target, reason: describeError(error) };
680
+ }
681
+ if (hazard) {
682
+ return { status: "failed", ...untouched, safety, target, reason: hazard };
683
+ }
684
+ try {
685
+ // Written before the first mutation so an interrupted restore — a
686
+ // SIGINT, a crash, a pulled plug — leaves behind the name of the ref
687
+ // that recovers the tree. Cancellation itself is out of scope; this
688
+ // only guarantees the interruption is never silent.
689
+ writeRestoreMarker(markerPath, {
690
+ safetyRef: safety.ref,
691
+ safetyRecoveryId: safety.recoveryId,
692
+ targetRef: target.ref,
693
+ targetEntryId: options.targetEntryId,
694
+ currentEntryId: options.currentEntryId,
695
+ startedAt: new Date().toISOString(),
696
+ });
697
+ }
698
+ catch (error) {
699
+ return {
700
+ status: "failed",
701
+ ...untouched,
702
+ safety,
703
+ target,
704
+ reason: `could not write the restore marker at ${markerPath}: ${describeError(error)}`,
705
+ };
706
+ }
707
+ try {
708
+ await applyTreeDiff(top, targetTree, diff, options.onPathRestored);
709
+ clearRestoreMarker(markerPath);
710
+ return { status: "restored", restored: diff.writes, deleted: diff.deletes, safety, target };
711
+ }
712
+ catch (error) {
713
+ const reason = describeError(error);
714
+ try {
715
+ // The inverse diff covers exactly the paths the forward pass could
716
+ // have touched, and re-applying it is idempotent for the ones it
717
+ // never reached.
718
+ const inverse = await diffTrees(top, targetTree, safety.treeHash);
719
+ await applyTreeDiff(top, safety.treeHash, inverse);
720
+ clearRestoreMarker(markerPath);
721
+ return { status: "rolled-back", ...untouched, safety, target, reason };
722
+ }
723
+ catch (rollbackError) {
724
+ // Marker deliberately left in place: the tree really is between
725
+ // two snapshots, and the next restore has to say so.
726
+ return {
727
+ status: "unrecoverable",
728
+ ...untouched,
729
+ safety,
730
+ target,
731
+ reason,
732
+ rollbackReason: describeError(rollbackError),
733
+ };
734
+ }
735
+ }
736
+ }
737
+ /**
738
+ * Restore files and then move the conversation leaf, in that order
739
+ * (R42-RWD.5). `navigate` runs only once the file restore has succeeded,
740
+ * so a caller cannot move the leaf ahead of the working tree. Never throws.
741
+ */
742
+ async rewind(options) {
743
+ const { navigate, ...restoreOptions } = options;
744
+ const restore = await this.restore(restoreOptions);
745
+ if (restore.status !== "restored" && restore.status !== "unchanged") {
746
+ return { restore, navigated: false };
747
+ }
748
+ try {
749
+ await navigate();
750
+ return { restore, navigated: true };
751
+ }
752
+ catch (error) {
753
+ return { restore, navigated: false, navigateReason: describeError(error) };
754
+ }
755
+ }
756
+ /** Files in the snapshot that differ from HEAD; the whole tree when HEAD is unborn. */
757
+ async countDirtyFiles(treeHash) {
758
+ try {
759
+ const headTree = await git(this.cwd, ["rev-parse", "--verify", "HEAD^{tree}"]);
760
+ const diff = await git(this.cwd, ["diff", "--name-only", headTree, treeHash]);
761
+ return diff.length === 0 ? 0 : diff.split("\n").length;
762
+ }
763
+ catch {
764
+ const files = await git(this.cwd, ["ls-tree", "-r", "--name-only", treeHash]);
765
+ return files.length === 0 ? 0 : files.split("\n").length;
766
+ }
767
+ }
768
+ /** All sidecar records for this session, in capture order. */
769
+ list() {
770
+ return readCheckpointSidecar(this.sidecarPath);
771
+ }
772
+ /** Latest record for an entry id, if any. */
773
+ get(entryId) {
774
+ const records = this.list();
775
+ for (let i = records.length - 1; i >= 0; i--) {
776
+ if (records[i].entryId === entryId)
777
+ return records[i];
778
+ }
779
+ return undefined;
780
+ }
781
+ /**
782
+ * The one snapshot with this recovery id. `get` answers "the newest
783
+ * snapshot for this entry", which by design shadows older ones — two
784
+ * rewinds from the same leaf record two safety snapshots under the same
785
+ * entry id. This addresses a single snapshot, so no recovery point is ever
786
+ * unreachable, and `restore` accepts a recovery id wherever it accepts an
787
+ * entry id.
788
+ */
789
+ getRecoveryPoint(recoveryId) {
790
+ return this.list().find((record) => record.recoveryId === recoveryId);
791
+ }
792
+ /** Every pre-rewind safety snapshot, oldest first — the undo history of `/rewind`. */
793
+ listSafetySnapshots() {
794
+ return this.list().filter((record) => record.kind === "safety");
795
+ }
796
+ /**
797
+ * The marker left behind by a restore that never finished, if there is one
798
+ * (D5). Call it at startup to tell the user which ref recovers their tree;
799
+ * `restore` refuses while it is present. Clearing it is the user's decision
800
+ * (`clearInterruptedRestore`), because only they know whether the tree is
801
+ * the way they want it.
802
+ */
803
+ static async findInterruptedRestore(cwd) {
804
+ if (!(await isGitRepository(cwd)))
805
+ return undefined;
806
+ try {
807
+ return readRestoreMarker(join(resolve(cwd, await git(cwd, ["rev-parse", "--git-dir"])), RESTORE_MARKER_FILE));
808
+ }
809
+ catch {
810
+ return undefined;
811
+ }
812
+ }
813
+ /** Acknowledge an interrupted restore, re-enabling `restore`. Returns whether a marker was cleared. */
814
+ static async clearInterruptedRestore(cwd) {
815
+ const marker = await CheckpointManager.findInterruptedRestore(cwd);
816
+ if (!marker)
817
+ return false;
818
+ clearRestoreMarker(marker.markerPath);
819
+ return true;
820
+ }
821
+ /** Delete checkpoint refs per the retention policy. Repo-wide, all sessions. */
822
+ static async pruneRepository(cwd, options = {}) {
823
+ if (!(await isGitRepository(cwd)))
824
+ return { examined: 0, deleted: [] };
825
+ const listing = await git(cwd, [
826
+ "for-each-ref",
827
+ "--format=%(refname)%09%(committerdate:iso-strict)",
828
+ CHECKPOINT_REF_PREFIX,
829
+ ]);
830
+ const refs = (listing.length === 0 ? [] : listing.split("\n")).flatMap((line) => {
831
+ const [refname, committedAt] = line.split("\t");
832
+ if (!refname || !committedAt)
833
+ return [];
834
+ const at = new Date(committedAt).getTime();
835
+ return Number.isNaN(at) ? [] : [{ refname, at }];
836
+ });
837
+ const doomed = new Set();
838
+ const cutoff = (options.now ?? new Date()).getTime() - (options.retentionDays ?? 30) * MILLISECONDS_PER_DAY;
839
+ for (const ref of refs) {
840
+ if (ref.at < cutoff)
841
+ doomed.add(ref.refname);
842
+ }
843
+ if (options.maxPerSession !== undefined) {
844
+ const bySession = new Map();
845
+ for (const ref of refs) {
846
+ const session = ref.refname.slice(CHECKPOINT_REF_PREFIX.length + 1).split("/")[0] ?? "";
847
+ const group = bySession.get(session) ?? [];
848
+ group.push(ref);
849
+ bySession.set(session, group);
850
+ }
851
+ for (const group of bySession.values()) {
852
+ const newestFirst = [...group].sort((a, b) => b.at - a.at);
853
+ for (const surplus of newestFirst.slice(options.maxPerSession))
854
+ doomed.add(surplus.refname);
855
+ }
856
+ }
857
+ const deleted = [...doomed].sort();
858
+ if (!options.dryRun) {
859
+ for (const ref of deleted)
860
+ await git(cwd, ["update-ref", "-d", ref]);
861
+ }
862
+ return { examined: refs.length, deleted };
863
+ }
864
+ }
865
+ //# sourceMappingURL=checkpoint-manager.js.map