@causyne/agent 1.20.121 → 1.20.124

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 (640) hide show
  1. package/README.md +3 -3
  2. package/bin/causyne.js +38 -15
  3. package/docs/SECURITY_REVIEW.md +42 -6
  4. package/package.json +5 -5
  5. package/src/acp/agentCatalog.js +141 -62
  6. package/src/acp/agentCatalog.ts +142 -65
  7. package/src/acp/client.js +489 -109
  8. package/src/acp/client.ts +465 -108
  9. package/src/acp/peerProfiles.js +55 -22
  10. package/src/acp/peerProfiles.ts +51 -22
  11. package/src/acp/protocol.js +181 -8
  12. package/src/acp/protocol.ts +189 -8
  13. package/src/acp/server.js +250 -53
  14. package/src/acp/server.ts +234 -53
  15. package/src/agent/errorClassifier.js +48 -8
  16. package/src/agent/errorClassifier.ts +50 -7
  17. package/src/agent/providerFailure.js +1 -1
  18. package/src/agent/providerFailure.ts +7 -1
  19. package/src/agent/toolArgValidator.js +38 -4
  20. package/src/agent/toolArgValidator.ts +39 -4
  21. package/src/agent/toolTurnIntegrity.js +28 -7
  22. package/src/agent/toolTurnIntegrity.ts +25 -6
  23. package/src/agent/workspaceBoundary.js +30 -4
  24. package/src/agent/workspaceBoundary.ts +32 -4
  25. package/src/agentLoop.js +609 -222
  26. package/src/agentLoop.ts +632 -220
  27. package/src/approvalGrants.js +19 -7
  28. package/src/approvalGrants.ts +20 -7
  29. package/src/approvalPolicy.js +76 -16
  30. package/src/approvalPolicy.ts +74 -16
  31. package/src/auditLog.js +641 -48
  32. package/src/auditLog.ts +661 -0
  33. package/src/autoUpdate.js +37 -7
  34. package/src/autoUpdate.ts +32 -7
  35. package/src/backgroundTasks.js +328 -0
  36. package/src/backgroundTasks.ts +339 -0
  37. package/src/benchmarks/codingEval.js +558 -0
  38. package/src/benchmarks/codingEval.ts +628 -0
  39. package/src/benchmarks/planCache.js +115 -134
  40. package/src/benchmarks/planCache.ts +163 -0
  41. package/src/browser/browserRuntime.js +52 -0
  42. package/src/browser/browserRuntime.ts +55 -0
  43. package/src/browser/causyneBrowser.js +887 -12
  44. package/src/browser/causyneBrowser.ts +1045 -34
  45. package/src/browser/searchProviders.js +95 -7
  46. package/src/browser/searchProviders.ts +90 -7
  47. package/src/browser/urlPolicy.js +8 -1
  48. package/src/browser/urlPolicy.ts +7 -1
  49. package/src/browser/workspacePathSafety.js +6 -4
  50. package/src/browser/workspacePathSafety.ts +7 -4
  51. package/src/capabilities.js +18 -17
  52. package/src/capabilities.ts +38 -0
  53. package/src/checkpoints.js +1241 -1127
  54. package/src/checkpoints.ts +1377 -0
  55. package/src/cliMode.js +707 -755
  56. package/src/cliMode.ts +780 -0
  57. package/src/codebase/repoMap.js +656 -0
  58. package/src/codebase/repoMap.ts +664 -0
  59. package/src/commands.js +3651 -2514
  60. package/src/commands.ts +3985 -0
  61. package/src/compiledSkills.js +8052 -8054
  62. package/src/compiledSkills.ts +8078 -0
  63. package/src/config.js +389 -250
  64. package/src/config.ts +451 -0
  65. package/src/configVault.js +113 -19
  66. package/src/configVault.ts +103 -19
  67. package/src/contextManager.js +473 -557
  68. package/src/contextManager.ts +599 -0
  69. package/src/continuum/adapters/antigravity.js +8 -3
  70. package/src/continuum/adapters/antigravity.ts +8 -3
  71. package/src/continuum/compactor.js +2 -1
  72. package/src/continuum/compactor.ts +2 -1
  73. package/src/continuum/sanitizer.js +33 -4
  74. package/src/continuum/sanitizer.ts +32 -4
  75. package/src/continuum/ui/continuumPicker.js +0 -2
  76. package/src/continuum/ui/continuumPicker.ts +0 -2
  77. package/src/continuum/ui/continuumPickerView.js +3 -4
  78. package/src/continuum/ui/continuumPickerView.ts +7 -22
  79. package/src/core/contextCompactor.js +88 -7
  80. package/src/core/contextCompactor.ts +87 -8
  81. package/src/cortex/vectorDb.js +26 -15
  82. package/src/cortex/vectorDb.ts +26 -16
  83. package/src/creative/liveBridge.js +10 -7
  84. package/src/creative/liveBridge.ts +11 -7
  85. package/src/creative/studioScripts.js +17 -6
  86. package/src/creative/studioScripts.ts +15 -6
  87. package/src/decideTools.js +7 -2
  88. package/src/decideTools.ts +7 -2
  89. package/src/decisionPolicy.js +26 -6
  90. package/src/decisionPolicy.ts +24 -6
  91. package/src/designPalettes.js +72 -84
  92. package/src/designPalettes.ts +111 -0
  93. package/src/devMode.js +2 -2
  94. package/src/devMode.ts +6 -0
  95. package/src/diffReview.js +370 -0
  96. package/src/diffReview.ts +407 -0
  97. package/src/documentEngine/antiSlopAuditor.js +10 -5
  98. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  99. package/src/documentEngine/documentForge.js +47 -15
  100. package/src/documentEngine/documentForge.ts +43 -14
  101. package/src/dynamicCatalogue.js +311 -11
  102. package/src/dynamicCatalogue.ts +331 -11
  103. package/src/embodimentSession.js +143 -154
  104. package/src/embodimentSession.ts +173 -0
  105. package/src/engines/design.js +2 -1
  106. package/src/engines/design.ts +2 -1
  107. package/src/engines/film.js +4 -4
  108. package/src/engines/film.ts +2 -2
  109. package/src/engines/installer.js +60 -29
  110. package/src/engines/installer.ts +73 -22
  111. package/src/engines/light.js +2 -1
  112. package/src/engines/light.ts +2 -1
  113. package/src/engines/registry.js +1 -1
  114. package/src/engines/registry.ts +1 -1
  115. package/src/engines/reverseHarness.js +4 -3
  116. package/src/engines/reverseHarness.ts +4 -3
  117. package/src/enterprisePolicy.js +660 -0
  118. package/src/enterprisePolicy.ts +728 -0
  119. package/src/entrypoint.js +514 -268
  120. package/src/entrypoint.ts +607 -0
  121. package/src/gitSnapshot.js +417 -312
  122. package/src/gitSnapshot.ts +500 -0
  123. package/src/headlessCli.js +326 -14
  124. package/src/headlessCli.ts +323 -13
  125. package/src/historyPruner.js +3 -2
  126. package/src/historyPruner.ts +3 -2
  127. package/src/hooks.js +250 -26
  128. package/src/hooks.ts +239 -26
  129. package/src/ignoreRules.js +297 -0
  130. package/src/ignoreRules.ts +308 -0
  131. package/src/implementationPlan.js +28 -17
  132. package/src/implementationPlan.ts +29 -17
  133. package/src/infra/atomicWriter.js +96 -20
  134. package/src/infra/atomicWriter.ts +112 -20
  135. package/src/launchIntent.js +14 -3
  136. package/src/launchIntent.ts +14 -3
  137. package/src/licensing/entitlements.js +553 -237
  138. package/src/licensing/entitlements.ts +590 -0
  139. package/src/licensing/policy.js +17 -1
  140. package/src/licensing/policy.ts +31 -0
  141. package/src/lsp/lspCatalog.js +398 -0
  142. package/src/lsp/lspCatalog.ts +452 -0
  143. package/src/lsp/lspClient.js +699 -0
  144. package/src/lsp/lspClient.ts +799 -0
  145. package/src/lsp/lspProtocol.js +121 -0
  146. package/src/lsp/lspProtocol.ts +140 -0
  147. package/src/mcp/mcpClient.js +69 -8
  148. package/src/mcp/mcpClient.ts +66 -9
  149. package/src/mcp/mcpRegistry.js +180 -7
  150. package/src/mcp/mcpRegistry.ts +171 -7
  151. package/src/mcp/mcpSecurity.js +6 -7
  152. package/src/mcp/mcpSecurity.ts +7 -6
  153. package/src/memory/episodicStore.js +2 -5
  154. package/src/memory/episodicStore.ts +2 -5
  155. package/src/memory/scopedFacts.js +1 -1
  156. package/src/memory/scopedFacts.ts +1 -1
  157. package/src/memory/symbolFolder.js +1 -1
  158. package/src/memory/symbolFolder.ts +1 -1
  159. package/src/memory.js +80 -32
  160. package/src/memory.ts +111 -0
  161. package/src/memoryManager.js +151 -143
  162. package/src/memoryManager.ts +182 -0
  163. package/src/modelCatalogue.js +172 -195
  164. package/src/modelCatalogue.ts +201 -0
  165. package/src/modelIds.js +8 -27
  166. package/src/modelIds.ts +33 -0
  167. package/src/modelRouter.js +1 -1
  168. package/src/modelRouter.ts +1 -1
  169. package/src/modelVariants.js +600 -0
  170. package/src/modelVariants.ts +663 -0
  171. package/src/observer/evidence.js +15 -5
  172. package/src/observer/evidence.ts +15 -5
  173. package/src/osKeychain.js +79 -17
  174. package/src/osKeychain.ts +64 -17
  175. package/src/outputStore.js +210 -156
  176. package/src/outputStore.ts +321 -0
  177. package/src/perception.js +3 -2
  178. package/src/perception.ts +3 -2
  179. package/src/planCache.js +5 -8
  180. package/src/planCache.ts +5 -8
  181. package/src/plugins/pluginManager.js +689 -461
  182. package/src/plugins/pluginManager.ts +807 -0
  183. package/src/plugins/pluginRunner.js +82 -37
  184. package/src/plugins/pluginRunner.ts +98 -0
  185. package/src/plugins/pluginSkills.js +47 -9
  186. package/src/plugins/pluginSkills.ts +46 -8
  187. package/src/pluginsFactory/discovery.js +0 -1
  188. package/src/pluginsFactory/discovery.ts +0 -1
  189. package/src/pluginsFactory/pluginsFactory.js +19 -11
  190. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  191. package/src/pluginsFactory/templates.js +17 -4
  192. package/src/pluginsFactory/templates.ts +17 -4
  193. package/src/prWorkflow.js +337 -0
  194. package/src/prWorkflow.ts +376 -0
  195. package/src/procSignal.js +1 -2
  196. package/src/procSignal.ts +1 -3
  197. package/src/projectInstructions.js +319 -0
  198. package/src/projectInstructions.ts +361 -0
  199. package/src/promptMentions.js +2 -2
  200. package/src/promptMentions.ts +2 -2
  201. package/src/providers/acp.js +235 -50
  202. package/src/providers/acp.ts +241 -51
  203. package/src/providers/anthropic.js +431 -400
  204. package/src/providers/anthropic.ts +493 -0
  205. package/src/providers/antigravity.js +575 -358
  206. package/src/providers/antigravity.ts +565 -359
  207. package/src/providers/base.js +229 -320
  208. package/src/providers/base.ts +348 -0
  209. package/src/providers/byokHttp.js +183 -30
  210. package/src/providers/byokHttp.ts +232 -32
  211. package/src/providers/byokStream.js +287 -70
  212. package/src/providers/byokStream.ts +282 -71
  213. package/src/providers/dashscope-byok.js +123 -89
  214. package/src/providers/dashscope-byok.ts +142 -0
  215. package/src/providers/deepseek.js +82 -72
  216. package/src/providers/deepseek.ts +108 -0
  217. package/src/providers/factory.js +76 -28
  218. package/src/providers/factory.ts +82 -0
  219. package/src/providers/gemini.js +279 -278
  220. package/src/providers/gemini.ts +313 -0
  221. package/src/providers/loopGuard.js +9 -5
  222. package/src/providers/loopGuard.ts +10 -5
  223. package/src/providers/moonshot.js +103 -72
  224. package/src/providers/moonshot.ts +122 -0
  225. package/src/providers/muse.js +82 -152
  226. package/src/providers/muse.ts +122 -0
  227. package/src/providers/ollama.js +360 -106
  228. package/src/providers/ollama.ts +408 -0
  229. package/src/providers/openai-compatible.js +168 -95
  230. package/src/providers/openai-compatible.ts +200 -0
  231. package/src/providers/openai.js +45 -15
  232. package/src/providers/openai.ts +52 -0
  233. package/src/providers/openrouter.js +342 -113
  234. package/src/providers/openrouter.ts +333 -116
  235. package/src/providers/pi.js +6 -0
  236. package/src/providers/pi.ts +6 -0
  237. package/src/providers/qwen-byok.js +122 -87
  238. package/src/providers/qwen-byok.ts +141 -0
  239. package/src/providers/toolContracts.js +40 -14
  240. package/src/providers/toolContracts.ts +35 -14
  241. package/src/providers/wireNormalizer.js +144 -11
  242. package/src/providers/wireNormalizer.ts +132 -12
  243. package/src/providers/xai.js +80 -72
  244. package/src/providers/xai.ts +103 -0
  245. package/src/provisioning/capabilityConsent.js +29 -11
  246. package/src/provisioning/capabilityConsent.ts +42 -0
  247. package/src/provisioning/capabilityProvisioner.js +309 -197
  248. package/src/provisioning/capabilityProvisioner.ts +413 -0
  249. package/src/provisioning/capabilityTools.js +31 -17
  250. package/src/provisioning/capabilityTools.ts +43 -0
  251. package/src/provisioning/npmInstall.js +33 -5
  252. package/src/provisioning/npmInstall.ts +33 -5
  253. package/src/reliability/assetEvidence.js +4 -2
  254. package/src/reliability/assetEvidence.ts +4 -2
  255. package/src/reporting.js +328 -326
  256. package/src/reporting.ts +482 -0
  257. package/src/sandbox.js +526 -554
  258. package/src/sandbox.ts +590 -0
  259. package/src/sandboxPolicy.js +95 -16
  260. package/src/sandboxPolicy.ts +97 -16
  261. package/src/sessionJournal.js +32 -6
  262. package/src/sessionJournal.ts +27 -6
  263. package/src/sessionStore.js +1 -2
  264. package/src/sessionStore.ts +2 -0
  265. package/src/skills/skillResourceSafety.js +19 -8
  266. package/src/skills/skillResourceSafety.ts +16 -7
  267. package/src/skillsManager.js +3 -3
  268. package/src/skillsManager.ts +3 -3
  269. package/src/slopDetector.js +202 -265
  270. package/src/slopDetector.ts +279 -0
  271. package/src/smartToolsUse.js +38 -8
  272. package/src/smartToolsUse.ts +39 -11
  273. package/src/stallGuard.js +53 -23
  274. package/src/stallGuard.ts +53 -23
  275. package/src/subagentJournal.js +6 -4
  276. package/src/subagentJournal.ts +6 -4
  277. package/src/taskBuffer.js +91 -40
  278. package/src/taskBuffer.ts +94 -0
  279. package/src/textDiff.js +6 -1
  280. package/src/textDiff.ts +6 -1
  281. package/src/timeMachine.js +7 -1
  282. package/src/timeMachine.ts +7 -1
  283. package/src/tokenTracker.js +120 -38
  284. package/src/tokenTracker.ts +110 -38
  285. package/src/toolPacks.js +8 -1
  286. package/src/toolPacks.ts +8 -1
  287. package/src/tools/applyPatch.js +610 -0
  288. package/src/tools/applyPatch.ts +661 -0
  289. package/src/tools/archive.js +372 -48
  290. package/src/tools/archive.ts +372 -48
  291. package/src/tools/astryxOracle.js +77 -72
  292. package/src/tools/astryxOracle.ts +95 -0
  293. package/src/tools/axSnapshot.js +127 -147
  294. package/src/tools/axSnapshot.ts +174 -0
  295. package/src/tools/backgroundTask.js +86 -0
  296. package/src/tools/backgroundTask.ts +121 -0
  297. package/src/tools/blenderAutomator.js +434 -390
  298. package/src/tools/blenderAutomator.ts +623 -0
  299. package/src/tools/checkSystemSpecs.js +54 -61
  300. package/src/tools/checkSystemSpecs.ts +73 -0
  301. package/src/tools/clipboard.js +42 -31
  302. package/src/tools/clipboard.ts +61 -0
  303. package/src/tools/codeSearchAst.js +359 -91
  304. package/src/tools/codeSearchAst.ts +399 -0
  305. package/src/tools/codeSearcher.js +179 -37
  306. package/src/tools/codeSearcher.ts +188 -33
  307. package/src/tools/codeTools.js +208 -245
  308. package/src/tools/codeTools.ts +271 -0
  309. package/src/tools/codebaseSearch.js +5 -0
  310. package/src/tools/codebaseSearch.ts +5 -0
  311. package/src/tools/computerUse.js +7 -3
  312. package/src/tools/computerUse.ts +7 -3
  313. package/src/tools/creativeApps.js +13 -8
  314. package/src/tools/creativeApps.ts +22 -9
  315. package/src/tools/deferredMcpSearch.js +26 -14
  316. package/src/tools/deferredMcpSearch.ts +26 -14
  317. package/src/tools/desktopAct.js +185 -197
  318. package/src/tools/desktopAct.ts +257 -0
  319. package/src/tools/desktopOpen.js +69 -10
  320. package/src/tools/desktopOpen.ts +70 -11
  321. package/src/tools/documentForge.js +167 -82
  322. package/src/tools/documentForge.ts +169 -84
  323. package/src/tools/dynamicLoader.js +4 -40
  324. package/src/tools/dynamicLoader.ts +13 -0
  325. package/src/tools/executeProceduralMedia.js +117 -86
  326. package/src/tools/executeProceduralMedia.ts +135 -0
  327. package/src/tools/fileTracker.js +74 -0
  328. package/src/tools/fileTracker.ts +94 -0
  329. package/src/tools/fsDelete.js +57 -47
  330. package/src/tools/fsDelete.ts +80 -0
  331. package/src/tools/fsEdit.js +250 -61
  332. package/src/tools/fsEdit.ts +265 -63
  333. package/src/tools/fsFind.js +8 -5
  334. package/src/tools/fsFind.ts +7 -4
  335. package/src/tools/fsMove.js +79 -52
  336. package/src/tools/fsMove.ts +108 -0
  337. package/src/tools/fsRead.js +163 -18
  338. package/src/tools/fsRead.ts +169 -18
  339. package/src/tools/fsSearch.js +5 -0
  340. package/src/tools/fsSearch.ts +5 -0
  341. package/src/tools/fsWrite.js +31 -11
  342. package/src/tools/fsWrite.ts +31 -13
  343. package/src/tools/gameAiBehaviorTree.js +74 -91
  344. package/src/tools/gameAiBehaviorTree.ts +219 -0
  345. package/src/tools/gameAnimationRig.js +128 -147
  346. package/src/tools/gameAnimationRig.ts +215 -0
  347. package/src/tools/gameAssetFetcher.js +403 -441
  348. package/src/tools/gameAssetFetcher.ts +477 -0
  349. package/src/tools/gameAssetHarvester.js +171 -200
  350. package/src/tools/gameAssetHarvester.ts +261 -0
  351. package/src/tools/gameAudioSynth.js +223 -259
  352. package/src/tools/gameAudioSynth.ts +255 -0
  353. package/src/tools/gameBuilder.js +100 -91
  354. package/src/tools/gameBuilder.ts +913 -0
  355. package/src/tools/gameCanvasAudit.js +138 -96
  356. package/src/tools/gameCanvasAudit.ts +157 -0
  357. package/src/tools/gameCinematicSequencer.js +93 -111
  358. package/src/tools/gameCinematicSequencer.ts +165 -0
  359. package/src/tools/gameDataForge.js +115 -118
  360. package/src/tools/gameDataForge.ts +151 -0
  361. package/src/tools/gameDialogueTreeGen.js +125 -156
  362. package/src/tools/gameDialogueTreeGen.ts +159 -0
  363. package/src/tools/gameEconomyBalancer.js +150 -153
  364. package/src/tools/gameEconomyBalancer.ts +186 -0
  365. package/src/tools/gameEntitySpawner.js +91 -108
  366. package/src/tools/gameEntitySpawner.ts +209 -0
  367. package/src/tools/gameLoreForge.js +125 -147
  368. package/src/tools/gameLoreForge.ts +162 -0
  369. package/src/tools/gameQuestArcBuilder.js +105 -144
  370. package/src/tools/gameQuestArcBuilder.ts +147 -0
  371. package/src/tools/gameSceneBuilder.js +143 -149
  372. package/src/tools/gameSceneBuilder.ts +196 -0
  373. package/src/tools/gameShaderForge.js +83 -101
  374. package/src/tools/gameShaderForge.ts +181 -0
  375. package/src/tools/gameTilemapGenerator.js +99 -129
  376. package/src/tools/gameTilemapGenerator.ts +158 -0
  377. package/src/tools/gameUiHudBuilder.js +109 -129
  378. package/src/tools/gameUiHudBuilder.ts +300 -0
  379. package/src/tools/gameVfxEmitterGen.js +86 -89
  380. package/src/tools/gameVfxEmitterGen.ts +133 -0
  381. package/src/tools/gameWebRuntimeInspector.js +153 -86
  382. package/src/tools/gameWebRuntimeInspector.ts +167 -0
  383. package/src/tools/generateMediaViaApi.js +126 -22
  384. package/src/tools/generateMediaViaApi.ts +123 -22
  385. package/src/tools/gitExec.js +133 -86
  386. package/src/tools/gitExec.ts +146 -0
  387. package/src/tools/gitWorktree.js +115 -0
  388. package/src/tools/gitWorktree.ts +150 -0
  389. package/src/tools/godotAutomator.js +417 -394
  390. package/src/tools/godotAutomator.ts +530 -0
  391. package/src/tools/lspCodeIntel.js +217 -0
  392. package/src/tools/lspCodeIntel.ts +260 -0
  393. package/src/tools/manageLocalAiDependencies.js +242 -206
  394. package/src/tools/manageLocalAiDependencies.ts +288 -0
  395. package/src/tools/memoryRecall.js +62 -11
  396. package/src/tools/memoryRecall.ts +70 -13
  397. package/src/tools/memoryWrite.js +27 -14
  398. package/src/tools/memoryWrite.ts +30 -14
  399. package/src/tools/multiEdit.js +73 -63
  400. package/src/tools/multiEdit.ts +80 -65
  401. package/src/tools/nativeEngine.js +33 -18
  402. package/src/tools/nativeEngine.ts +31 -18
  403. package/src/tools/openSourceToolProvisioner.js +49 -14
  404. package/src/tools/openSourceToolProvisioner.ts +54 -15
  405. package/src/tools/osSandbox.js +202 -25
  406. package/src/tools/osSandbox.ts +192 -25
  407. package/src/tools/palmierAutomator.js +147 -95
  408. package/src/tools/palmierAutomator.ts +171 -0
  409. package/src/tools/payloadSanitizer.js +40 -8
  410. package/src/tools/payloadSanitizer.ts +39 -8
  411. package/src/tools/pdfReader.js +95 -104
  412. package/src/tools/pdfReader.ts +125 -0
  413. package/src/tools/peerAgent.js +96 -34
  414. package/src/tools/peerAgent.ts +114 -37
  415. package/src/tools/persistentShell.js +267 -144
  416. package/src/tools/persistentShell.ts +314 -0
  417. package/src/tools/pluginManager.js +84 -72
  418. package/src/tools/pluginManager.ts +109 -0
  419. package/src/tools/pluginsFactory.js +38 -6
  420. package/src/tools/pluginsFactory.ts +42 -6
  421. package/src/tools/printer.js +278 -296
  422. package/src/tools/printer.ts +326 -0
  423. package/src/tools/procTerm.js +96 -83
  424. package/src/tools/procTerm.ts +127 -0
  425. package/src/tools/processList.js +45 -48
  426. package/src/tools/processList.ts +73 -0
  427. package/src/tools/readNativeSkill.js +10 -8
  428. package/src/tools/readNativeSkill.ts +10 -8
  429. package/src/tools/registry.js +298 -286
  430. package/src/tools/registry.ts +486 -0
  431. package/src/tools/repoMap.js +46 -0
  432. package/src/tools/repoMap.ts +66 -0
  433. package/src/tools/requestDecision.js +10 -3
  434. package/src/tools/requestDecision.ts +10 -3
  435. package/src/tools/resolveAutomator.js +91 -17
  436. package/src/tools/resolveAutomator.ts +102 -17
  437. package/src/tools/reverseEngineering.js +168 -41
  438. package/src/tools/reverseEngineering.ts +161 -41
  439. package/src/tools/subagentOrchestrator.js +404 -348
  440. package/src/tools/subagentOrchestrator.ts +457 -0
  441. package/src/tools/sysRun.js +148 -51
  442. package/src/tools/sysRun.ts +142 -46
  443. package/src/tools/toolDispatch.js +24 -1
  444. package/src/tools/toolDispatch.ts +21 -1
  445. package/src/tools/toolForge.js +84 -67
  446. package/src/tools/toolForge.ts +102 -0
  447. package/src/tools/toolOutputStore.js +62 -23
  448. package/src/tools/toolOutputStore.ts +56 -23
  449. package/src/tools/toolPathSafety.js +262 -0
  450. package/src/tools/toolPathSafety.ts +308 -0
  451. package/src/tools/toolScanner.js +41 -10
  452. package/src/tools/toolScanner.ts +42 -10
  453. package/src/tools/toolSelfRepair.js +115 -34
  454. package/src/tools/toolSelfRepair.ts +122 -34
  455. package/src/tools/uiForge.js +71 -6
  456. package/src/tools/uiForge.ts +74 -6
  457. package/src/tools/viewImage.js +62 -17
  458. package/src/tools/viewImage.ts +57 -12
  459. package/src/tools/visionInspector.js +15 -3
  460. package/src/tools/visionInspector.ts +15 -3
  461. package/src/tools/walkerSafety.js +2 -0
  462. package/src/tools/walkerSafety.ts +2 -0
  463. package/src/tools/webFetch.js +110 -12
  464. package/src/tools/webFetch.ts +110 -13
  465. package/src/toolsList.js +5 -0
  466. package/src/toolsList.ts +5 -0
  467. package/src/tui/ask.js +159 -168
  468. package/src/tui/ask.ts +259 -0
  469. package/src/tui/banner.js +3 -2
  470. package/src/tui/banner.ts +3 -2
  471. package/src/tui/block.js +0 -1
  472. package/src/tui/block.ts +0 -1
  473. package/src/tui/chatRenderer.js +1193 -1441
  474. package/src/tui/chatRenderer.ts +1336 -0
  475. package/src/tui/clipboardImage.js +36 -12
  476. package/src/tui/clipboardImage.ts +39 -13
  477. package/src/tui/clipboardSync.js +34 -9
  478. package/src/tui/clipboardSync.ts +38 -9
  479. package/src/tui/codeProgress.js +0 -1
  480. package/src/tui/codeProgress.ts +0 -1
  481. package/src/tui/completion.js +395 -371
  482. package/src/tui/completion.ts +574 -0
  483. package/src/tui/composerControls.js +113 -19
  484. package/src/tui/composerControls.ts +124 -19
  485. package/src/tui/consoleGuard.js +39 -11
  486. package/src/tui/consoleGuard.ts +38 -11
  487. package/src/tui/dialogs.js +864 -717
  488. package/src/tui/dialogs.ts +984 -0
  489. package/src/tui/diff.js +205 -195
  490. package/src/tui/diff.ts +336 -0
  491. package/src/tui/history.js +143 -108
  492. package/src/tui/history.ts +167 -0
  493. package/src/tui/home.js +165 -161
  494. package/src/tui/home.ts +251 -0
  495. package/src/tui/invocation.js +58 -65
  496. package/src/tui/invocation.ts +117 -0
  497. package/src/tui/keys.js +437 -420
  498. package/src/tui/keys.ts +597 -0
  499. package/src/tui/lineEditor.js +477 -432
  500. package/src/tui/lineEditor.ts +542 -0
  501. package/src/tui/messageActionPlacement.js +0 -1
  502. package/src/tui/messageActionPlacement.ts +0 -1
  503. package/src/tui/messageInteraction.js +2 -5
  504. package/src/tui/messageInteraction.ts +2 -5
  505. package/src/tui/modelPicker.js +1 -3
  506. package/src/tui/modelPicker.ts +4 -6
  507. package/src/tui/observerPicker.js +0 -2
  508. package/src/tui/observerPicker.ts +0 -2
  509. package/src/tui/overlay.js +3 -2
  510. package/src/tui/overlay.ts +3 -2
  511. package/src/tui/prompt.js +1816 -2151
  512. package/src/tui/prompt.ts +1870 -0
  513. package/src/tui/runningLight.js +0 -1
  514. package/src/tui/runningLight.ts +0 -1
  515. package/src/tui/selectList.js +365 -337
  516. package/src/tui/selectList.ts +441 -0
  517. package/src/tui/sessionPicker.js +3 -3
  518. package/src/tui/sessionPicker.ts +3 -3
  519. package/src/tui/sessionPickerView.js +7 -3
  520. package/src/tui/sessionPickerView.ts +10 -22
  521. package/src/tui/sessionSidebar.js +3 -1
  522. package/src/tui/sessionSidebar.ts +4 -1
  523. package/src/tui/setup.js +17 -5
  524. package/src/tui/setup.ts +19 -5
  525. package/src/tui/skillAuthoring.js +0 -2
  526. package/src/tui/skillAuthoring.ts +0 -3
  527. package/src/tui/stageSurface.js +829 -909
  528. package/src/tui/stageSurface.ts +1003 -0
  529. package/src/tui/statusLine.js +7 -4
  530. package/src/tui/statusLine.ts +7 -3
  531. package/src/tui/terminalInputFramer.js +82 -69
  532. package/src/tui/terminalInputFramer.ts +116 -0
  533. package/src/tui/text.js +25 -10
  534. package/src/tui/text.ts +24 -10
  535. package/src/tui/textLayout.js +0 -1
  536. package/src/tui/textLayout.ts +0 -1
  537. package/src/tui/theme.js +245 -250
  538. package/src/tui/theme.ts +441 -0
  539. package/src/tui/thinkingBox.js +0 -1
  540. package/src/tui/thinkingBox.ts +0 -1
  541. package/src/tui/toolOutputNormalizer.js +2 -3
  542. package/src/tui/toolOutputNormalizer.ts +4 -3
  543. package/src/tui/transcript.js +239 -216
  544. package/src/tui/transcript.ts +324 -0
  545. package/src/tui/turnRail.js +53 -54
  546. package/src/tui/turnRail.ts +51 -49
  547. package/src/tui/usageCard.js +0 -2
  548. package/src/tui/usageCard.ts +0 -2
  549. package/src/tui/viewport.js +4 -4
  550. package/src/tui/viewport.ts +5 -5
  551. package/src/tui/workspaceIdentity.js +2 -1
  552. package/src/tui/workspaceIdentity.ts +2 -1
  553. package/src/tui/workspaceSwitch.js +4 -2
  554. package/src/tui/workspaceSwitch.ts +5 -2
  555. package/src/types/contracts.ts +4 -1
  556. package/src/uncertainty.js +8 -3
  557. package/src/uncertainty.ts +8 -3
  558. package/src/utils/browserOpen.js +107 -0
  559. package/src/utils/browserOpen.ts +129 -0
  560. package/src/utils/cli_ui.js +0 -0
  561. package/src/utils/cli_ui.ts +158 -0
  562. package/src/utils/paths.js +8 -5
  563. package/src/utils/paths.ts +9 -7
  564. package/src/utils/winSpawn.js +248 -0
  565. package/src/utils/winSpawn.ts +275 -0
  566. package/src/verification/boundedExplorer.js +138 -107
  567. package/src/verification/boundedExplorer.ts +154 -0
  568. package/src/verification/byokSmokeProbe.js +193 -0
  569. package/src/verification/byokSmokeProbe.ts +234 -0
  570. package/src/verification/cliProbe.js +144 -110
  571. package/src/verification/cliProbe.ts +170 -0
  572. package/src/verification/featureMap.js +105 -75
  573. package/src/verification/featureMap.ts +124 -0
  574. package/src/verification/interactivePty.js +195 -100
  575. package/src/verification/interactivePty.ts +333 -0
  576. package/src/verification/propertyProbe.js +109 -101
  577. package/src/verification/propertyProbe.ts +159 -0
  578. package/src/verification/ptyProbe.js +168 -73
  579. package/src/verification/ptyProbe.ts +254 -0
  580. package/src/verification/skillCatalog.js +25 -25
  581. package/src/verification/skillCatalog.ts +66 -0
  582. package/src/verification/statechart.js +140 -127
  583. package/src/verification/statechart.ts +196 -0
  584. package/src/verification/uiRuntime.js +80 -49
  585. package/src/verification/uiRuntime.ts +88 -0
  586. package/src/version.js +37 -32
  587. package/src/version.ts +45 -0
  588. package/src/vfeTracker.js +9 -3
  589. package/src/vfeTracker.ts +9 -3
  590. package/src/web/guiLauncher.js +89 -0
  591. package/src/web/guiLauncher.ts +119 -0
  592. package/src/web/skybridgeBrowserBridge.js +256 -0
  593. package/src/web/skybridgeBrowserBridge.ts +285 -0
  594. package/src/web/skybridgeBrowserMcp.js +730 -0
  595. package/src/web/skybridgeBrowserMcp.ts +813 -0
  596. package/src/web/skybridgeClientScript.js +3951 -0
  597. package/src/web/skybridgeClientScript.ts +3952 -0
  598. package/src/web/skybridgeServer.js +2622 -0
  599. package/src/web/skybridgeServer.ts +2787 -0
  600. package/src/web/skybridgeStyles.js +827 -0
  601. package/src/web/skybridgeStyles.ts +828 -0
  602. package/src/web/skybridgeUi.js +472 -0
  603. package/src/web/skybridgeUi.ts +485 -0
  604. package/src/worktreeManager.js +511 -0
  605. package/src/worktreeManager.ts +546 -0
  606. package/src/zeroCostFailover.js +168 -0
  607. package/src/zeroCostFailover.ts +198 -0
  608. package/src/zeroCostRouting.js +391 -0
  609. package/src/zeroCostRouting.ts +437 -0
  610. package/src/agentLoop.d.ts +0 -65
  611. package/src/auditLog.d.ts +0 -3
  612. package/src/checkpoints.d.ts +0 -4
  613. package/src/compiledSkills.d.ts +0 -5
  614. package/src/config.d.ts +0 -2
  615. package/src/contextManager.d.ts +0 -14
  616. package/src/designPalettes.d.ts +0 -2
  617. package/src/devMode.d.ts +0 -1
  618. package/src/embodimentSession.d.ts +0 -2
  619. package/src/licensing/entitlements.d.ts +0 -14
  620. package/src/memory.d.ts +0 -13
  621. package/src/memoryManager.d.ts +0 -1
  622. package/src/modelCatalogue.d.ts +0 -6
  623. package/src/modelIds.d.ts +0 -2
  624. package/src/outputStore.d.ts +0 -4
  625. package/src/plugins/pluginManager.d.ts +0 -7
  626. package/src/providers/antigravity.d.ts +0 -19
  627. package/src/providers/base.d.ts +0 -94
  628. package/src/providers/factory.d.ts +0 -1
  629. package/src/provisioning/capabilityProvisioner.d.ts +0 -12
  630. package/src/sandbox.d.ts +0 -1
  631. package/src/slopDetector.d.ts +0 -3
  632. package/src/taskBuffer.d.ts +0 -1
  633. package/src/tools/desktopAct.d.ts +0 -10
  634. package/src/tools/registry.d.ts +0 -5
  635. package/src/tui/chatRenderer.d.ts +0 -27
  636. package/src/tui/diff.d.ts +0 -3
  637. package/src/utils/cli_ui.d.ts +0 -19
  638. package/src/utils/paths.d.ts +0 -3
  639. package/src/verification/skillCatalog.d.ts +0 -1
  640. package/src/version.d.ts +0 -1
@@ -1,1230 +1,1344 @@
1
-
2
-
3
- import fs from 'fs';
4
- import path from 'path';
5
- import os from 'os';
6
- import crypto from 'crypto';
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import crypto from 'node:crypto';
7
5
  import * as gitBackend from './gitSnapshot.js';
8
6
  import { unifiedDiff, looksBinary } from './textDiff.js';
9
7
  import { causyneHome } from './utils/paths.js';
10
- import {
11
- getActiveSessionId,
12
- restoreSessionFromSnapshot,
13
- sessionTranscriptFile,
14
- SESSION_DIR
15
- } from './sessionStore.js';
16
-
17
- /**
18
- * Diagnostics, off by default.
19
- *
20
- * These were console.warn, which writes to a terminal the chat prompt is
21
- * repainting a live region into — an uncontrolled second writer that leaves the
22
- * prompt's row accounting describing a block that has moved. Housekeeping that
23
- * skipped is not news to the person using Causyne; it is news to whoever is
24
- * debugging it.
25
- */
8
+ import { isProtectedPhysicalPath, isWithinPhysicalPath, physicalPath } from './agent/workspaceBoundary.js';
9
+ import { extractPatchTargetPaths } from './tools/applyPatch.js';
10
+ import { isBlockedWorkspaceRoot } from './sandboxPolicy.js';
11
+ import { getActiveSessionId, restoreSessionFromSnapshot, sessionTranscriptFile } from './sessionStore.js';
12
+ import { loadWorkspaceIgnoreMatcher } from './ignoreRules.js';
13
+ import { atomicRenameSync } from './infra/atomicWriter.js';
26
14
  function debugLog(message) {
27
- if (process.env.CAUSYNE_DEBUG !== '1') return;
28
- process.stderr.write(`[causyne] ${message}\n`);
15
+ if (process.env.CAUSYNE_DEBUG !== '1')
16
+ return;
17
+ process.stderr.write(`[causyne] ${message}\n`);
29
18
  }
30
-
31
-
32
- const STORE_DIR = path.join(causyneHome(), 'checkpoints');
33
- const OBJECTS_DIR = path.join(STORE_DIR, 'objects');
34
- const JOURNAL_FILE = path.join(STORE_DIR, 'index.jsonl');
35
- const STAT_CACHE_FILE = path.join(STORE_DIR, 'stat-cache.json');
36
-
37
- // The LEGACY single global conversation. Kept only so a journal entry written
38
- // before sessions existed can still be restored.
39
- const HISTORY_FILE = path.join(causyneHome(), 'memory', 'chat_history.json');
40
-
41
- /**
42
- * The conversation file undo must snapshot and restore.
43
- *
44
- * THE REGRESSION THIS FIXES. Undo is session-level BY DESIGN: restoring files
45
- * while the conversation still claims the edits happened leaves the model
46
- * reasoning about a disk state that no longer exists. That is the whole reason
47
- * the history is captured at all.
48
- *
49
- * Chat history then moved out of one global `memory/chat_history.json` into per
50
- * session files under `sessions/`, and `migrateLegacyHistory()` RENAMES the old
51
- * file to `.migrated`. This module was never told. So `fs.existsSync(
52
- * HISTORY_FILE)` became permanently false, `history` was recorded as null, and
53
- * **the conversation rewind silently stopped happening** — undo restored the
54
- * files and left the agent believing in edits that were gone.
55
- *
56
- * It survived the test suite because tests/checkpoints.test.js builds this path
57
- * itself and writes the file before asserting. A test that creates the world it
58
- * measures proves nothing about production.
59
- */
60
- function activeHistoryFile() {
61
- try {
62
- const id = getActiveSessionId();
63
- if (id) {
64
- const safe = String(id).replace(/[^a-zA-Z0-9_-]/g, '');
65
- if (safe) return sessionTranscriptFile(safe);
66
- }
67
- } catch (e) { /* fall through to the legacy file */ }
68
- return HISTORY_FILE;
19
+ function storeDir() {
20
+ return path.join(causyneHome(), 'checkpoints');
21
+ }
22
+ function objectsDir() {
23
+ return path.join(storeDir(), 'objects');
24
+ }
25
+ function journalFile() {
26
+ return path.join(storeDir(), 'index.jsonl');
27
+ }
28
+ function statCacheFile() {
29
+ return path.join(storeDir(), 'stat-cache.json');
30
+ }
31
+ function legacyHistoryFile() {
32
+ return path.join(causyneHome(), 'memory', 'chat_history.json');
33
+ }
34
+ function activeHistoryFile(explicitSessionId) {
35
+ try {
36
+ const id = (typeof explicitSessionId === 'string' && explicitSessionId.trim())
37
+ ? explicitSessionId.trim()
38
+ : getActiveSessionId();
39
+ if (id) {
40
+ const safe = String(id).replace(/[^a-zA-Z0-9_-]/g, '');
41
+ if (safe)
42
+ return sessionTranscriptFile(safe);
43
+ }
44
+ }
45
+ catch {
46
+ // fall through to the legacy file
47
+ }
48
+ return legacyHistoryFile();
69
49
  }
70
-
71
- // Retention. Generous enough that yesterday's mistake is still undoable, bounded
72
- // enough that the store cannot grow without limit.
73
50
  const RETENTION_MS = 14 * 24 * 60 * 60 * 1000;
74
51
  const MAX_STORE_BYTES = 512 * 1024 * 1024;
75
52
  const MAX_JOURNAL_ENTRIES = 4000;
76
-
77
- // A single file above this is recorded but not stored: snapshotting a 200 MB
78
- // asset on every write would turn the safety net into a disk problem.
79
53
  const MAX_FILE_BYTES = 16 * 1024 * 1024;
80
-
81
- // Whole-workspace snapshot budgets. Exceeding either records an honest "skipped"
82
- // rather than half a snapshot that would restore into an inconsistent tree.
83
54
  const MAX_TREE_FILES = 5000;
84
55
  const MAX_TREE_BYTES = 64 * 1024 * 1024;
85
56
  const MAX_TREE_FILE_BYTES = 2 * 1024 * 1024;
86
-
87
- // Directories never worth snapshotting: regenerable, and they dwarf the source.
57
+ const MAX_OBJECT_BYTES = 32 * 1024 * 1024;
88
58
  const IGNORED_DIRECTORIES = new Set([
89
- '.git', 'node_modules', 'dist', 'build', 'out', 'target',
90
- '.next', '.nuxt', '.svelte-kit', '.turbo', '.cache', '.parcel-cache',
91
- 'venv', '.venv', '__pycache__', '.pytest_cache', '.mypy_cache',
92
- 'vendor', 'Pods', '.gradle', '.idea', '.vscode', 'coverage',
93
- '.causyne'
59
+ '.git', 'node_modules', 'dist', 'build', 'out', 'target',
60
+ '.next', '.nuxt', '.svelte-kit', '.turbo', '.cache', '.parcel-cache',
61
+ 'venv', '.venv', '__pycache__', '.pytest_cache', '.mypy_cache',
62
+ 'vendor', 'Pods', '.gradle', '.idea', '.vscode', 'coverage',
63
+ '.causyne'
94
64
  ]);
95
-
96
- /** Which argument of each mutating tool names the file it is about to change. */
97
65
  const MUTATING_TOOL_PATHS = {
98
- fs_write: ['path'],
99
- fs_edit: ['path'],
100
- MultiEdit: ['file_path'],
101
- fs_delete: ['path'],
102
- // An overwrite move clobbers the destination, so both ends need a snapshot.
103
- fs_move: ['source', 'destination']
66
+ fs_write: ['path'],
67
+ fs_edit: ['path'],
68
+ MultiEdit: ['file_path'],
69
+ fs_delete: ['path'],
70
+ fs_move: ['source', 'destination']
104
71
  };
105
-
106
72
  export function isCheckpointingEnabled() {
107
- return process.env.CAUSYNE_CHECKPOINTS !== '0';
73
+ return process.env.CAUSYNE_CHECKPOINTS !== '0';
108
74
  }
109
-
110
75
  function ensureStore() {
111
- if (!fs.existsSync(OBJECTS_DIR)) {
112
- fs.mkdirSync(OBJECTS_DIR, { recursive: true, mode: 0o700 });
113
- }
76
+ const base = storeDir();
77
+ const objs = objectsDir();
78
+ for (const dir of [base, objs]) {
79
+ if (!fs.existsSync(dir)) {
80
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
81
+ }
82
+ else {
83
+ const stat = fs.lstatSync(dir);
84
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
85
+ throw new Error(`refusing symlink or non-directory checkpoint store: ${dir}`);
86
+ }
87
+ }
88
+ }
89
+ }
90
+ const SHA256_HEX_RE = /^[0-9a-f]{64}$/;
91
+ function isValidSha256(hash) {
92
+ return typeof hash === 'string' && SHA256_HEX_RE.test(hash);
114
93
  }
115
-
116
94
  function sha256(buffer) {
117
- return crypto.createHash('sha256').update(buffer).digest('hex');
95
+ return crypto.createHash('sha256').update(buffer).digest('hex');
118
96
  }
119
-
120
97
  function objectPath(hash) {
121
- return path.join(OBJECTS_DIR, hash.slice(0, 2), hash);
98
+ if (!isValidSha256(hash)) {
99
+ throw new Error('refusing invalid checkpoint object hash');
100
+ }
101
+ return path.join(objectsDir(), hash.slice(0, 2), hash);
122
102
  }
123
-
124
- /**
125
- * Store bytes under their own hash. Identical content is stored once, so a file
126
- * edited ten times across three distinct states costs three blobs.
127
- */
128
103
  function writeObject(buffer) {
129
- const hash = sha256(buffer);
130
- const target = objectPath(hash);
131
- if (fs.existsSync(target)) return hash; // already have it
132
-
133
- fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
134
- // Write-then-rename: a crash mid-write must never leave a truncated blob
135
- // sitting under a hash that claims to describe the full content.
136
- const temp = `${target}.tmp_${process.pid}_${Date.now()}`;
137
- fs.writeFileSync(temp, buffer, { mode: 0o600 });
138
- fs.renameSync(temp, target);
139
- return hash;
104
+ const hash = sha256(buffer);
105
+ const target = objectPath(hash);
106
+ try {
107
+ const existing = fs.lstatSync(target);
108
+ if (existing.isSymbolicLink() || !existing.isFile()) {
109
+ throw new Error('refusing symlink or non-regular checkpoint object');
110
+ }
111
+ return hash;
112
+ }
113
+ catch (err) {
114
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
115
+ if (code !== 'ENOENT')
116
+ throw err;
117
+ }
118
+ const shardDir = path.dirname(target);
119
+ if (!fs.existsSync(shardDir)) {
120
+ fs.mkdirSync(shardDir, { recursive: true, mode: 0o700 });
121
+ }
122
+ else {
123
+ const shardStat = fs.lstatSync(shardDir);
124
+ if (shardStat.isSymbolicLink() || !shardStat.isDirectory()) {
125
+ throw new Error('refusing symlink or non-directory checkpoint shard');
126
+ }
127
+ }
128
+ const temp = `${target}.tmp_${process.pid}_${crypto.randomBytes(6).toString('hex')}`;
129
+ try {
130
+ const fd = fs.openSync(temp, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
131
+ try {
132
+ fs.writeSync(fd, buffer, 0, buffer.length);
133
+ fs.fsyncSync(fd);
134
+ }
135
+ finally {
136
+ fs.closeSync(fd);
137
+ }
138
+ atomicRenameSync(temp, target);
139
+ }
140
+ catch (err) {
141
+ try {
142
+ if (fs.existsSync(temp))
143
+ fs.unlinkSync(temp);
144
+ }
145
+ catch { /* ignore */ }
146
+ throw err;
147
+ }
148
+ return hash;
140
149
  }
141
-
142
150
  function readObject(hash) {
143
- return fs.readFileSync(objectPath(hash));
151
+ const target = objectPath(hash);
152
+ const stat = fs.lstatSync(target);
153
+ if (stat.isSymbolicLink() || !stat.isFile()) {
154
+ throw new Error('refusing to read symlink or non-regular checkpoint object');
155
+ }
156
+ if (stat.size > MAX_OBJECT_BYTES) {
157
+ throw new Error('refusing oversized checkpoint object');
158
+ }
159
+ const buf = fs.readFileSync(target);
160
+ if (sha256(buf) !== hash) {
161
+ throw new Error('checkpoint object integrity mismatch');
162
+ }
163
+ return buf;
144
164
  }
145
-
146
- /** Expand `~` exactly the way every fs tool does, then resolve. */
147
165
  export function resolveToolPath(value) {
148
- if (typeof value !== 'string' || value.length === 0) return null;
149
- const expanded = value.replace(/^~\//, os.homedir() + '/');
150
- return path.resolve(expanded);
166
+ if (typeof value !== 'string' || value.length === 0 || value.includes('\0'))
167
+ return null;
168
+ const trimmed = value.trim();
169
+ if (!trimmed)
170
+ return null;
171
+ let expanded = trimmed;
172
+ if (trimmed === '~') {
173
+ expanded = os.homedir();
174
+ }
175
+ else if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
176
+ expanded = path.join(os.homedir(), trimmed.slice(2));
177
+ }
178
+ return path.resolve(expanded);
151
179
  }
152
-
153
180
  function appendJournal(entry) {
154
- fs.appendFileSync(JOURNAL_FILE, JSON.stringify(entry) + '\n', { mode: 0o600 });
181
+ const jf = journalFile();
182
+ try {
183
+ const stat = fs.lstatSync(jf);
184
+ if (stat.isSymbolicLink() || !stat.isFile()) {
185
+ throw new Error('refusing symlink or non-regular checkpoint journal');
186
+ }
187
+ }
188
+ catch (err) {
189
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
190
+ if (code !== 'ENOENT')
191
+ throw err;
192
+ }
193
+ fs.appendFileSync(jf, JSON.stringify(entry) + '\n', { encoding: 'utf8', mode: 0o600 });
155
194
  }
156
-
157
195
  export function readJournal() {
158
- if (!fs.existsSync(JOURNAL_FILE)) return [];
159
- const raw = fs.readFileSync(JOURNAL_FILE, 'utf8');
160
- const entries = [];
161
- for (const line of raw.split('\n')) {
162
- if (!line.trim()) continue;
163
- try { entries.push(JSON.parse(line)); } catch (e) { /* skip a torn line */ }
164
- }
165
- return entries;
196
+ const jf = journalFile();
197
+ let stat;
198
+ try {
199
+ stat = fs.lstatSync(jf);
200
+ }
201
+ catch {
202
+ return [];
203
+ }
204
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size === 0 || stat.size > MAX_OBJECT_BYTES)
205
+ return [];
206
+ const raw = fs.readFileSync(jf, 'utf8');
207
+ const entries = [];
208
+ for (const line of raw.split('\n')) {
209
+ if (!line.trim())
210
+ continue;
211
+ try {
212
+ const parsed = JSON.parse(line);
213
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)
214
+ && typeof parsed.type === 'string'
215
+ && typeof parsed.taskId === 'string') {
216
+ entries.push(parsed);
217
+ }
218
+ }
219
+ catch {
220
+ /* skip a torn line */
221
+ }
222
+ }
223
+ return entries;
166
224
  }
167
-
168
225
  function rewriteJournal(entries) {
169
- const temp = `${JOURNAL_FILE}.tmp_${process.pid}`;
170
- fs.writeFileSync(temp, entries.map(e => JSON.stringify(e)).join('\n') + (entries.length ? '\n' : ''), { mode: 0o600 });
171
- fs.renameSync(temp, JOURNAL_FILE);
226
+ const jf = journalFile();
227
+ try {
228
+ const stat = fs.lstatSync(jf);
229
+ if (stat.isSymbolicLink() || !stat.isFile()) {
230
+ throw new Error('refusing symlink or non-regular checkpoint journal');
231
+ }
232
+ }
233
+ catch (err) {
234
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
235
+ if (code !== 'ENOENT')
236
+ throw err;
237
+ }
238
+ const temp = `${jf}.tmp_${process.pid}_${crypto.randomBytes(6).toString('hex')}`;
239
+ const payload = Buffer.from(entries.map(e => JSON.stringify(e)).join('\n') + (entries.length ? '\n' : ''), 'utf8');
240
+ try {
241
+ const fd = fs.openSync(temp, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
242
+ try {
243
+ fs.writeSync(fd, payload, 0, payload.length);
244
+ fs.fsyncSync(fd);
245
+ }
246
+ finally {
247
+ fs.closeSync(fd);
248
+ }
249
+ atomicRenameSync(temp, jf);
250
+ }
251
+ catch (err) {
252
+ try {
253
+ if (fs.existsSync(temp))
254
+ fs.unlinkSync(temp);
255
+ }
256
+ catch { /* ignore */ }
257
+ throw err;
258
+ }
172
259
  }
173
-
174
260
  function newId() {
175
- return `ck_${Date.now().toString(36)}_${crypto.randomBytes(4).toString('hex')}`;
261
+ return `ck_${Date.now().toString(36)}_${crypto.randomBytes(4).toString('hex')}`;
176
262
  }
177
-
178
- // ---------------------------------------------------------------------------
179
- // Snapshotting
180
- // ---------------------------------------------------------------------------
181
-
182
- /**
183
- * Snapshot one file's current state.
184
- * @returns {object|null} the `before` record, or null when the file is absent
185
- * (which is itself meaningful: undo of a create means delete).
186
- */
187
263
  function snapshotFile(absolutePath) {
188
- let stats;
189
- try {
190
- stats = fs.lstatSync(absolutePath);
191
- } catch (e) {
192
- return null; // does not exist yet
193
- }
194
-
195
- // A symlink is snapshotted as a link, never followed: following it would
196
- // capture (and later overwrite) a file somewhere else entirely.
197
- if (stats.isSymbolicLink()) {
198
- return { kind: 'symlink', target: fs.readlinkSync(absolutePath), mode: stats.mode & 0o777 };
199
- }
200
- if (stats.isDirectory()) {
201
- return { kind: 'directory', mode: stats.mode & 0o777 };
202
- }
203
- if (!stats.isFile()) {
204
- return { kind: 'special' };
205
- }
206
- if (stats.size > MAX_FILE_BYTES) {
207
- return { kind: 'file', skipped: 'too_large', size: stats.size, mode: stats.mode & 0o777 };
208
- }
209
-
210
- const buffer = fs.readFileSync(absolutePath);
211
- return {
212
- kind: 'file',
213
- hash: writeObject(buffer),
214
- size: stats.size,
215
- mode: stats.mode & 0o777
216
- };
264
+ let stats;
265
+ try {
266
+ stats = fs.lstatSync(absolutePath);
267
+ }
268
+ catch {
269
+ return null;
270
+ }
271
+ if (stats.isSymbolicLink()) {
272
+ return { kind: 'symlink', target: fs.readlinkSync(absolutePath), mode: stats.mode & 0o777 };
273
+ }
274
+ if (stats.isDirectory()) {
275
+ return { kind: 'directory', mode: stats.mode & 0o777 };
276
+ }
277
+ if (!stats.isFile()) {
278
+ return { kind: 'special' };
279
+ }
280
+ if (stats.size > MAX_FILE_BYTES) {
281
+ return { kind: 'file', skipped: 'too_large', size: stats.size, mode: stats.mode & 0o777 };
282
+ }
283
+ const buffer = fs.readFileSync(absolutePath);
284
+ return {
285
+ kind: 'file',
286
+ hash: writeObject(buffer),
287
+ size: stats.size,
288
+ mode: stats.mode & 0o777
289
+ };
217
290
  }
218
-
219
- /**
220
- * Capture the state of every file a mutating tool is about to touch.
221
- *
222
- * FAIL-OPEN BY CONTRACT: never throws, never blocks the tool call. A read-only
223
- * or full disk degrades the safety net; it does not fail the task.
224
- *
225
- * @returns {string[]} ids of the entries written
226
- */
227
- export function captureBeforeMutation(toolName, args, meta = {}) {
228
- if (!isCheckpointingEnabled()) return [];
229
- const fields = MUTATING_TOOL_PATHS[toolName];
230
- if (!fields || !args) return [];
231
-
232
- const ids = [];
233
- try {
234
- ensureStore();
235
- for (const field of fields) {
236
- const absolutePath = resolveToolPath(args[field]);
237
- if (!absolutePath) continue;
238
-
239
- const before = snapshotFile(absolutePath);
240
- const entry = {
241
- id: newId(),
242
- ts: Date.now(),
243
- type: 'file',
244
- taskId: meta.taskId || 'unknown',
245
- step: meta.step == null ? null : meta.step,
246
- tool: toolName,
247
- path: absolutePath,
248
- before
249
- };
250
- appendJournal(entry);
251
- ids.push(entry.id);
252
- }
253
- } catch (e) {
254
- debugLog(`checkpoint snapshot skipped: ${e.message}`);
255
- }
256
- return ids;
291
+ export function captureBeforeMutation(toolName, args, meta) {
292
+ if (!isCheckpointingEnabled())
293
+ return [];
294
+ if (typeof toolName !== 'string' || !args || typeof args !== 'object')
295
+ return [];
296
+ const canonicalTool = toolName.replace(/\./g, '_');
297
+ const fields = Object.hasOwn(MUTATING_TOOL_PATHS, canonicalTool)
298
+ ? MUTATING_TOOL_PATHS[canonicalTool]
299
+ : undefined;
300
+ const rawTargets = [];
301
+ if (fields) {
302
+ for (const field of fields)
303
+ rawTargets.push(args[field]);
304
+ }
305
+ else if (canonicalTool === 'apply_patch' && typeof args.patch === 'string') {
306
+ for (const target of extractPatchTargetPaths(args.patch).paths) {
307
+ rawTargets.push(target);
308
+ }
309
+ }
310
+ else {
311
+ return [];
312
+ }
313
+ const safeMeta = meta && typeof meta === 'object' ? meta : {};
314
+ const taskId = typeof safeMeta.taskId === 'string' && safeMeta.taskId && !safeMeta.taskId.includes('\0')
315
+ ? safeMeta.taskId
316
+ : 'unknown';
317
+ const ids = [];
318
+ try {
319
+ ensureStore();
320
+ for (const rawTarget of rawTargets) {
321
+ const absolutePath = resolveToolPath(rawTarget);
322
+ if (!absolutePath)
323
+ continue;
324
+ const before = snapshotFile(absolutePath);
325
+ const entry = {
326
+ id: newId(),
327
+ ts: Date.now(),
328
+ type: 'file',
329
+ taskId,
330
+ step: safeMeta.step == null ? null : safeMeta.step,
331
+ tool: toolName,
332
+ path: absolutePath,
333
+ before
334
+ };
335
+ appendJournal(entry);
336
+ ids.push(entry.id);
337
+ }
338
+ }
339
+ catch (e) {
340
+ debugLog(`checkpoint snapshot skipped: ${e instanceof Error ? e.message : String(e)}`);
341
+ }
342
+ return ids;
257
343
  }
258
-
259
- // ---------------------------------------------------------------------------
260
- // Workspace tree snapshot — covers changes a per-file hook cannot see
261
- // ---------------------------------------------------------------------------
262
-
263
344
  function loadStatCache() {
264
- try {
265
- return JSON.parse(fs.readFileSync(STAT_CACHE_FILE, 'utf8'));
266
- } catch (e) {
267
- return {};
268
- }
345
+ try {
346
+ const cf = statCacheFile();
347
+ const stat = fs.lstatSync(cf);
348
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 16 * 1024 * 1024)
349
+ return {};
350
+ const parsed = JSON.parse(fs.readFileSync(cf, 'utf8'));
351
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
352
+ return {};
353
+ const clean = Object.create(null);
354
+ for (const [key, rec] of Object.entries(parsed)) {
355
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype')
356
+ continue;
357
+ if (rec && typeof rec === 'object' && !Array.isArray(rec)
358
+ && typeof rec.mtimeMs === 'number'
359
+ && typeof rec.size === 'number'
360
+ && isValidSha256(rec.hash)) {
361
+ clean[key] = rec;
362
+ }
363
+ }
364
+ return clean;
365
+ }
366
+ catch {
367
+ return {};
368
+ }
269
369
  }
270
-
271
370
  function saveStatCache(cache) {
272
- try {
273
- const temp = `${STAT_CACHE_FILE}.tmp_${process.pid}`;
274
- fs.writeFileSync(temp, JSON.stringify(cache), { mode: 0o600 });
275
- fs.renameSync(temp, STAT_CACHE_FILE);
276
- } catch (e) { /* the cache is an optimisation; losing it costs time, not correctness */ }
371
+ const cf = statCacheFile();
372
+ const temp = `${cf}.tmp_${process.pid}_${crypto.randomBytes(6).toString('hex')}`;
373
+ try {
374
+ try {
375
+ const existing = fs.lstatSync(cf);
376
+ if (existing.isSymbolicLink() || !existing.isFile())
377
+ return;
378
+ }
379
+ catch (err) {
380
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
381
+ if (code !== 'ENOENT')
382
+ return;
383
+ }
384
+ const payload = Buffer.from(JSON.stringify(cache), 'utf8');
385
+ const fd = fs.openSync(temp, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
386
+ try {
387
+ fs.writeSync(fd, payload, 0, payload.length);
388
+ fs.fsyncSync(fd);
389
+ }
390
+ finally {
391
+ fs.closeSync(fd);
392
+ }
393
+ atomicRenameSync(temp, cf);
394
+ }
395
+ catch {
396
+ try {
397
+ if (fs.existsSync(temp))
398
+ fs.unlinkSync(temp);
399
+ }
400
+ catch { /* ignore */ }
401
+ }
277
402
  }
278
-
279
- /**
280
- * Walk a workspace root and record every file's content hash.
281
- *
282
- * The stat cache is what makes this affordable to repeat: a file whose mtime and
283
- * size are unchanged since the last walk keeps its known hash and is never read
284
- * again. That is git's own trick, and it is the difference between a snapshot
285
- * that costs milliseconds and one that re-reads the whole tree every task.
286
- *
287
- * @returns {{manifest: object|null, skipped: string|null}}
288
- */
289
403
  function snapshotTree(root) {
290
- const cache = loadStatCache();
291
- const files = {};
292
- let fileCount = 0;
293
- let totalBytes = 0;
294
- const stack = [root];
295
-
296
- while (stack.length > 0) {
297
- const dir = stack.pop();
298
- let entries;
299
- try {
300
- entries = fs.readdirSync(dir, { withFileTypes: true });
301
- } catch (e) {
302
- continue; // unreadable directory: skip rather than abort the snapshot
404
+ const cache = loadStatCache();
405
+ const causyneIgnore = loadWorkspaceIgnoreMatcher(root, { includeGitIgnore: false });
406
+ const files = {};
407
+ let fileCount = 0;
408
+ let totalBytes = 0;
409
+ const stack = [root];
410
+ while (stack.length > 0) {
411
+ const dir = stack.pop();
412
+ let entries;
413
+ try {
414
+ entries = fs.readdirSync(dir, { withFileTypes: true });
415
+ }
416
+ catch {
417
+ continue;
418
+ }
419
+ for (const entry of entries) {
420
+ const full = path.join(dir, entry.name);
421
+ if (entry.isDirectory()) {
422
+ if (IGNORED_DIRECTORIES.has(entry.name) || causyneIgnore.isIgnored(full, true))
423
+ continue;
424
+ stack.push(full);
425
+ continue;
426
+ }
427
+ if (causyneIgnore.isIgnored(full, false))
428
+ continue;
429
+ if (entry.isSymbolicLink()) {
430
+ try {
431
+ files[full] = { kind: 'symlink', target: fs.readlinkSync(full) };
432
+ }
433
+ catch { /* ignore */ }
434
+ continue;
435
+ }
436
+ if (!entry.isFile())
437
+ continue;
438
+ let stats;
439
+ try {
440
+ stats = fs.lstatSync(full);
441
+ }
442
+ catch {
443
+ continue;
444
+ }
445
+ if (stats.isSymbolicLink() || !stats.isFile())
446
+ continue;
447
+ if (stats.size > MAX_TREE_FILE_BYTES)
448
+ continue;
449
+ fileCount++;
450
+ totalBytes += stats.size;
451
+ if (fileCount > MAX_TREE_FILES)
452
+ return { manifest: null, skipped: 'too_many_files' };
453
+ if (totalBytes > MAX_TREE_BYTES)
454
+ return { manifest: null, skipped: 'workspace_too_large' };
455
+ const cached = Object.hasOwn(cache, full) ? cache[full] : undefined;
456
+ if (cached && isValidSha256(cached.hash) && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size
457
+ && fs.existsSync(objectPath(cached.hash))) {
458
+ files[full] = { kind: 'file', hash: cached.hash, size: stats.size, mode: stats.mode & 0o777 };
459
+ continue;
460
+ }
461
+ try {
462
+ const hash = writeObject(fs.readFileSync(full));
463
+ files[full] = { kind: 'file', hash, size: stats.size, mode: stats.mode & 0o777 };
464
+ cache[full] = { mtimeMs: stats.mtimeMs, size: stats.size, hash };
465
+ }
466
+ catch {
467
+ // vanished mid-walk
468
+ }
469
+ }
303
470
  }
304
-
305
- for (const entry of entries) {
306
- const full = path.join(dir, entry.name);
307
-
308
- if (entry.isDirectory()) {
309
- if (IGNORED_DIRECTORIES.has(entry.name)) continue;
310
- stack.push(full);
311
- continue;
312
- }
313
- // Symlinks are recorded by target, never followed — following them can
314
- // walk out of the workspace entirely, or loop.
315
- if (entry.isSymbolicLink()) {
316
- try { files[full] = { kind: 'symlink', target: fs.readlinkSync(full) }; } catch (e) {}
317
- continue;
318
- }
319
- if (!entry.isFile()) continue;
320
-
321
- let stats;
322
- try { stats = fs.statSync(full); } catch (e) { continue; }
323
- if (stats.size > MAX_TREE_FILE_BYTES) continue;
324
-
325
- fileCount++;
326
- totalBytes += stats.size;
327
- if (fileCount > MAX_TREE_FILES) return { manifest: null, skipped: 'too_many_files' };
328
- if (totalBytes > MAX_TREE_BYTES) return { manifest: null, skipped: 'workspace_too_large' };
329
-
330
- const cached = cache[full];
331
- if (cached && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size
332
- && fs.existsSync(objectPath(cached.hash))) {
333
- files[full] = { kind: 'file', hash: cached.hash, size: stats.size, mode: stats.mode & 0o777 };
334
- continue;
335
- }
336
-
337
- try {
338
- const hash = writeObject(fs.readFileSync(full));
339
- files[full] = { kind: 'file', hash, size: stats.size, mode: stats.mode & 0o777 };
340
- cache[full] = { mtimeMs: stats.mtimeMs, size: stats.size, hash };
341
- } catch (e) { /* a file that vanished mid-walk is simply not in the snapshot */ }
342
- }
343
- }
344
-
345
- saveStatCache(cache);
346
- return { manifest: { root, files, fileCount, totalBytes }, skipped: null };
471
+ saveStatCache(cache);
472
+ return { manifest: { root, files, fileCount, totalBytes }, skipped: null };
347
473
  }
348
-
349
- /**
350
- * Open a checkpoint group for a task: snapshot the conversation, and optionally
351
- * the workspace tree. Called once per task, fail-open.
352
- *
353
- * @returns {string|null} the task id the group is filed under
354
- */
355
- /**
356
- * Files that mark a directory as a PROJECT rather than a place.
357
- *
358
- * Ordered by how strongly each implies "this is the thing being worked on".
359
- */
360
474
  const PROJECT_MARKERS = [
361
- '.git', 'package.json', 'pyproject.toml', 'go.mod', 'Cargo.toml',
362
- 'pom.xml', 'build.gradle', 'build.gradle.kts', 'Gemfile', 'composer.json',
363
- 'requirements.txt', 'CMakeLists.txt', 'Makefile'
475
+ '.git', 'package.json', 'pyproject.toml', 'go.mod', 'Cargo.toml',
476
+ 'pom.xml', 'build.gradle', 'build.gradle.kts', 'Gemfile', 'composer.json',
477
+ 'requirements.txt', 'CMakeLists.txt', 'Makefile'
364
478
  ];
365
-
366
-
367
479
  function isSnapshotableRoot(dir) {
368
- if (!dir) return false;
369
- let resolved;
370
- try {
371
- resolved = path.resolve(dir);
372
- } catch (e) {
373
- return false;
374
- }
375
-
376
- const home = os.homedir();
377
- const parsed = path.parse(resolved);
378
-
379
- // The filesystem root, and the user's home itself.
380
- if (resolved === parsed.root) return false;
381
- if (home && path.resolve(home) === resolved) return false;
382
-
383
-
384
- // lands in one of these is not in a project, it is lost.
385
- const forbidden = ['/Users', '/home', '/Users/Shared', '/var', '/tmp', '/etc', '/opt', '/usr'];
386
- if (forbidden.includes(resolved)) return false;
387
-
388
- // Directly inside a system root with no project marker is not a workspace.
389
- return true;
480
+ if (typeof dir !== 'string' || !dir.trim() || dir.includes('\0'))
481
+ return false;
482
+ let resolved;
483
+ try {
484
+ resolved = path.resolve(dir);
485
+ }
486
+ catch {
487
+ return false;
488
+ }
489
+ const home = os.homedir();
490
+ const parsed = path.parse(resolved);
491
+ if (resolved === parsed.root)
492
+ return false;
493
+ if (home && path.resolve(home) === resolved)
494
+ return false;
495
+ const forbidden = ['/Users', '/home', '/Users/Shared', '/var', '/tmp', '/private/tmp', '/etc', '/opt', '/usr'];
496
+ if (forbidden.includes(resolved))
497
+ return false;
498
+ if (isBlockedWorkspaceRoot(resolved))
499
+ return false;
500
+ return true;
390
501
  }
391
-
392
- /**
393
- * The project `startDir` belongs to, or null when it belongs to none.
394
- *
395
- * Walks upward for a project marker, stopping at the home directory — a marker
396
- * found above home would mean snapshotting somebody's whole account.
397
- */
398
502
  export function resolveProjectRoot(startDir) {
399
- let current;
400
- try {
401
- current = path.resolve(startDir || process.cwd());
402
- } catch (e) {
403
- return null;
404
- }
405
-
406
- const home = os.homedir() ? path.resolve(os.homedir()) : null;
407
- const stop = path.parse(current).root;
408
-
409
- const start = current;
410
- let nearestMarker = null;
411
-
412
- for (let depth = 0; depth < 40; depth++) {
413
- if (!isSnapshotableRoot(current)) break;
414
-
415
- // A repository root wins outright, even from further up.
416
- //
417
- // Stopping at the FIRST marker found sounds right and is not: this project
418
- // has package.json in causyne-agent/ and .git one level above it, so the
419
- // nearest marker would scope the checkpoint to causyne-agent — which the git
420
- // backend then declines, because its root is not the repository root. The
421
- // native store would take it instead and immediately hit MAX_TREE_FILES on
422
- // node_modules. The repository root is both the true project boundary AND
423
- // the only root where git can apply the user's own .gitignore, which is what
424
- // keeps a snapshot to the files that actually matter.
503
+ let current;
425
504
  try {
426
- if (fs.existsSync(path.join(current, '.git'))) return current;
427
- } catch (e) {}
428
-
429
- if (!nearestMarker) {
430
- for (const marker of PROJECT_MARKERS) {
431
- if (marker === '.git') continue;
505
+ current = path.resolve(startDir || process.cwd());
506
+ }
507
+ catch {
508
+ return null;
509
+ }
510
+ const home = os.homedir() ? path.resolve(os.homedir()) : null;
511
+ const stop = path.parse(current).root;
512
+ let nearestMarker = null;
513
+ for (let depth = 0; depth < 40; depth++) {
514
+ if (!isSnapshotableRoot(current))
515
+ break;
432
516
  try {
433
- if (fs.existsSync(path.join(current, marker))) { nearestMarker = current; break; }
434
- } catch (e) {}
435
- }
436
- }
437
-
438
- const parent = path.dirname(current);
439
- if (parent === current || current === stop) break;
440
- if (home && parent === home) break;
441
- current = parent;
442
- }
443
-
444
- // No repository anywhere above: fall back to the nearest ordinary project.
445
- return nearestMarker && isSnapshotableRoot(nearestMarker) ? nearestMarker : null;
517
+ if (fs.existsSync(path.join(current, '.git')))
518
+ return current;
519
+ }
520
+ catch { /* ignore */ }
521
+ if (!nearestMarker) {
522
+ for (const marker of PROJECT_MARKERS) {
523
+ if (marker === '.git')
524
+ continue;
525
+ try {
526
+ if (fs.existsSync(path.join(current, marker))) {
527
+ nearestMarker = current;
528
+ break;
529
+ }
530
+ }
531
+ catch { /* ignore */ }
532
+ }
533
+ }
534
+ const parent = path.dirname(current);
535
+ if (parent === current || current === stop)
536
+ break;
537
+ if (home && parent === home)
538
+ break;
539
+ current = parent;
540
+ }
541
+ return nearestMarker && isSnapshotableRoot(nearestMarker) ? nearestMarker : null;
446
542
  }
447
-
448
- /**
449
- * Capture `root` with the git backend, or return null to use the native store.
450
- *
451
- * Every failure path returns null rather than throwing: a checkpoint is
452
- * best-effort and must never be the reason a task fails to start.
453
- */
454
543
  function gitRootFor(root) {
455
- try {
456
- if (!gitBackend.isGitAvailable()) return null;
457
- const worktree = gitBackend.resolveWorktree(root);
458
- // Only capture when the root IS the repository root. A subdirectory would
459
- // snapshot its whole parent project, which is not what the caller asked to
460
- // protect and could be enormous.
461
- if (!worktree || path.resolve(worktree) !== path.resolve(root)) return null;
462
- return worktree;
463
- } catch (e) {
464
- debugLog(`git checkpoint unavailable for ${root}: ${e.message}`);
465
- return null;
466
- }
544
+ try {
545
+ if (!gitBackend.isGitAvailable())
546
+ return null;
547
+ const worktree = gitBackend.resolveWorktree(root);
548
+ if (!worktree || path.resolve(worktree) !== path.resolve(root))
549
+ return null;
550
+ return worktree;
551
+ }
552
+ catch (e) {
553
+ debugLog(`git checkpoint unavailable for ${root}: ${e instanceof Error ? e.message : String(e)}`);
554
+ return null;
555
+ }
467
556
  }
468
-
469
- /**
470
- * What a git-backed tree would restore, and — when asked — restoring it.
471
- *
472
- * Returns null on any git failure so the caller falls back to the native path;
473
- * reporting "nothing changed" because git errored would be a lie with a
474
- * rollback button attached to it.
475
- */
476
- function gitTreeChanges(tree, undoTaskId, dryRun, applyFull) {
477
- try {
478
- const changes = gitBackend.previewRestore(tree.root, tree.gitTree);
479
- const driftFiles = changes.map((c) => c.path);
480
-
481
- if (!applyFull || dryRun) {
482
- return {
483
- driftFiles,
484
- results: changes.map((c) => ({
485
- path: path.join(tree.root, c.path),
486
- action: c.status === 'deleted' ? 'removed' : 'restored',
487
- ok: true
488
- }))
489
- };
490
- }
491
-
492
- gitBackend.restoreTree(tree.root, tree.gitTree);
493
- return {
494
- driftFiles,
495
- results: changes.map((c) => ({
496
- path: path.join(tree.root, c.path),
497
- action: c.status === 'deleted' ? 'removed' : 'restored',
498
- ok: true
499
- }))
500
- };
501
- } catch (e) {
502
- debugLog(`git restore unavailable for ${tree.root}: ${e.message}`);
503
- return null;
504
- }
557
+ function gitTreeChanges(tree, _undoTaskId, dryRun, applyFull) {
558
+ if (!tree.root || !tree.gitTree)
559
+ return null;
560
+ try {
561
+ const changes = gitBackend.previewRestore(tree.root, tree.gitTree);
562
+ const driftFiles = changes.map((c) => c.path);
563
+ if (!applyFull || dryRun) {
564
+ return {
565
+ driftFiles,
566
+ results: changes.map((c) => ({
567
+ path: path.join(tree.root, c.path),
568
+ action: c.status === 'deleted' ? 'removed' : 'restored',
569
+ ok: true
570
+ }))
571
+ };
572
+ }
573
+ gitBackend.restoreTree(tree.root, tree.gitTree);
574
+ return {
575
+ driftFiles,
576
+ results: changes.map((c) => ({
577
+ path: path.join(tree.root, c.path),
578
+ action: c.status === 'deleted' ? 'removed' : 'restored',
579
+ ok: true
580
+ }))
581
+ };
582
+ }
583
+ catch (e) {
584
+ debugLog(`git restore unavailable for ${tree.root}: ${e instanceof Error ? e.message : String(e)}`);
585
+ return null;
586
+ }
505
587
  }
506
-
507
588
  export async function beginTask(meta = {}) {
508
- if (!isCheckpointingEnabled()) return null;
509
- const taskId = meta.taskId || 'unknown';
510
-
511
- try {
512
- ensureStore();
513
-
514
- // The conversation. Snapshotting the FILE rather than a message index,
515
- // because boundHistory() trims chat_history.json to its newest 120 messages
516
- // on every save — an index into that array does not survive the trimming.
517
- let history = null;
518
- const historyFile = activeHistoryFile();
519
- if (fs.existsSync(historyFile)) {
520
- const buffer = fs.readFileSync(historyFile);
521
- // The PATH is recorded, not just the bytes. The active session can change
522
- // between the task and the undo, and restoring a snapshot into whichever
523
- // conversation happens to be current would corrupt a different one.
524
- history = { hash: writeObject(buffer), size: buffer.length, file: historyFile };
525
- }
526
-
527
- appendJournal({
528
- id: newId(),
529
- ts: Date.now(),
530
- type: 'task_start',
531
- taskId,
532
- prompt: typeof meta.prompt === 'string' ? meta.prompt.slice(0, 200) : null,
533
- history
534
- });
535
-
536
- // The workspace tree, which also covers files changed by sysRun and by any
537
- // other tool that does not announce its paths.
538
- //
539
- // De-duplicated before the slice: only three roots are snapshotted, so a
540
- // repeated path spends one of those three slots twice and doubles the
541
- // storage for a directory already covered. The caller's list is a
542
- // concatenation of the working directory and the permitted scope, which
543
- // overlap whenever the user is working inside their own workspace — that is
544
- // to say, normally.
545
- // A root that is not a project is not worth snapshotting, and trying is
546
- // what made undo useless: $HOME blew past MAX_TREE_FILES and the fallbacks
547
- // captured directories nobody edits. Filtered HERE as well as at the caller,
548
- // because a checkpoint store that quietly fills with junk is worse than one
549
- // that honestly captures nothing.
550
- const roots = (meta.workspaceRoots || [])
551
- .filter((root, index, all) => root && all.indexOf(root) === index)
552
- .filter((root) => isSnapshotableRoot(root))
553
- .slice(0, 3);
554
-
555
- for (const root of roots) {
556
- if (!fs.existsSync(root)) continue;
557
-
558
- // Prefer git where the root is a repository and git is installed.
559
- //
560
- // The file-copy path below copies bytes, so it has to cap what it will
561
- // look at — MAX_TREE_FILES is 5000, and a real home directory exceeds it
562
- // and is recorded as `too_many_files`, covered by no rollback at all. Git
563
- // has no such ceiling: it reuses the project's own object database, so a
564
- // checkpoint is one `write-tree` rather than a walk-and-hash of every
565
- // file. The shadow repository lives in ~/.causyne and the user's own .git
566
- // is never written to.
567
- //
568
- // Fail-open in both directions: no git binary, or a root that is not a
569
- // repository, or any git error at all, and this silently uses the native
570
- // store exactly as before.
571
- // The decision is made SYNCHRONOUSLY, and only a real git capture awaits.
572
- //
573
- // Awaiting unconditionally deferred the native path too: an `async`
574
- // function runs synchronously only until its first await, so every caller
575
- // that does not itself await — which is most of them — stopped seeing the
576
- // journal entries this function had always written before returning.
577
- const gitWorktree = gitRootFor(root);
578
- let gitTree = null;
579
- if (gitWorktree) {
580
- // Async here and nowhere else: this runs at the start of every task,
581
- // and a synchronous capture can stall the foreground agent loop.
582
- try {
583
- gitTree = await gitBackend.captureTreeAsync(gitWorktree);
584
- } catch (e) {
585
- debugLog(`git capture failed for ${root}: ${e.message}`);
589
+ if (!isCheckpointingEnabled())
590
+ return null;
591
+ const taskId = meta.taskId || 'unknown';
592
+ try {
593
+ ensureStore();
594
+ let history = null;
595
+ const historyFile = activeHistoryFile(meta.sessionId);
596
+ if (fs.existsSync(historyFile)) {
597
+ const buffer = fs.readFileSync(historyFile);
598
+ history = { hash: writeObject(buffer), size: buffer.length, file: historyFile };
586
599
  }
587
- }
588
- if (gitTree) {
589
600
  appendJournal({
590
- id: newId(),
591
- ts: Date.now(),
592
- type: 'tree',
593
- taskId,
594
- root,
595
- skipped: null,
596
- backend: 'git',
597
- gitTree,
598
- manifestHash: null,
599
- fileCount: 0,
600
- totalBytes: 0
601
+ id: newId(),
602
+ ts: Date.now(),
603
+ type: 'task_start',
604
+ taskId,
605
+ prompt: typeof meta.prompt === 'string' ? meta.prompt.slice(0, 200) : null,
606
+ history
601
607
  });
602
- continue;
603
- }
604
-
605
- const { manifest, skipped } = snapshotTree(root);
606
- appendJournal({
607
- id: newId(),
608
- ts: Date.now(),
609
- type: 'tree',
610
- taskId,
611
- root,
612
- skipped,
613
- manifestHash: manifest ? writeObject(Buffer.from(JSON.stringify(manifest), 'utf8')) : null,
614
- fileCount: manifest ? manifest.fileCount : 0,
615
- totalBytes: manifest ? manifest.totalBytes : 0
616
- });
617
- }
618
-
619
- return taskId;
620
- } catch (e) {
621
- debugLog(`checkpoint task snapshot skipped: ${e.message}`);
622
- return null;
623
- }
608
+ const roots = (meta.workspaceRoots || [])
609
+ .filter((root) => typeof root === 'string' && root.length > 0)
610
+ .filter((root, index, all) => all.indexOf(root) === index)
611
+ .filter((root) => isSnapshotableRoot(root))
612
+ .slice(0, 3);
613
+ for (const root of roots) {
614
+ if (!fs.existsSync(root))
615
+ continue;
616
+ const gitWorktree = gitRootFor(root);
617
+ let gitTree = null;
618
+ if (gitWorktree) {
619
+ try {
620
+ gitTree = await gitBackend.captureTreeAsync(gitWorktree);
621
+ }
622
+ catch (e) {
623
+ debugLog(`git capture failed for ${root}: ${e instanceof Error ? e.message : String(e)}`);
624
+ }
625
+ }
626
+ if (gitTree) {
627
+ appendJournal({
628
+ id: newId(),
629
+ ts: Date.now(),
630
+ type: 'tree',
631
+ taskId,
632
+ root,
633
+ skipped: null,
634
+ backend: 'git',
635
+ gitTree,
636
+ manifestHash: null,
637
+ fileCount: 0,
638
+ totalBytes: 0
639
+ });
640
+ continue;
641
+ }
642
+ const { manifest, skipped } = snapshotTree(root);
643
+ appendJournal({
644
+ id: newId(),
645
+ ts: Date.now(),
646
+ type: 'tree',
647
+ taskId,
648
+ root,
649
+ skipped,
650
+ manifestHash: manifest ? writeObject(Buffer.from(JSON.stringify(manifest), 'utf8')) : null,
651
+ fileCount: manifest ? manifest.fileCount : 0,
652
+ totalBytes: manifest ? manifest.totalBytes : 0
653
+ });
654
+ }
655
+ return taskId;
656
+ }
657
+ catch (e) {
658
+ debugLog(`checkpoint task snapshot skipped: ${e instanceof Error ? e.message : String(e)}`);
659
+ return null;
660
+ }
624
661
  }
625
-
626
- // ---------------------------------------------------------------------------
627
- // Restore
628
- // ---------------------------------------------------------------------------
629
-
630
- /**
631
- * Refuse to write through anything that is not a plain file.
632
- *
633
- * A restore writes attacker-influenced paths. If the target has been replaced by
634
- * a symlink between snapshot and restore, following it writes wherever the link
635
- * points; a hardlink means the write lands in a second visible location too.
636
- * Both are refused rather than followed.
637
- */
638
662
  function assertSafeTarget(absolutePath) {
639
- if (!path.isAbsolute(absolutePath)) {
640
- throw new Error(`refusing a non-absolute path: ${absolutePath}`);
641
- }
642
- if (absolutePath !== path.resolve(absolutePath)) {
643
- throw new Error(`refusing an unnormalised path: ${absolutePath}`);
644
- }
645
-
646
- let stats;
647
- try {
648
- stats = fs.lstatSync(absolutePath);
649
- } catch (e) {
650
- return; // absent: nothing to be tricked by
651
- }
652
- if (stats.isSymbolicLink()) {
653
- throw new Error(`refusing to write through a symlink: ${absolutePath}`);
654
- }
655
- if (stats.isFile() && stats.nlink > 1) {
656
- throw new Error(`refusing to write through a hardlink (${stats.nlink} links): ${absolutePath}`);
657
- }
663
+ if (typeof absolutePath !== 'string' || !absolutePath || absolutePath.includes('\0')) {
664
+ throw new Error('refusing an invalid checkpoint target path');
665
+ }
666
+ if (!path.isAbsolute(absolutePath)) {
667
+ throw new Error(`refusing a non-absolute path: ${absolutePath}`);
668
+ }
669
+ if (absolutePath !== path.resolve(absolutePath)) {
670
+ throw new Error(`refusing an unnormalised path: ${absolutePath}`);
671
+ }
672
+ try {
673
+ const stats = fs.lstatSync(absolutePath);
674
+ if (stats.isSymbolicLink()) {
675
+ throw new Error(`refusing to write through a symlink: ${absolutePath}`);
676
+ }
677
+ if (stats.isFile() && stats.nlink > 1) {
678
+ throw new Error(`refusing to write through a hardlink (${stats.nlink} links): ${absolutePath}`);
679
+ }
680
+ }
681
+ catch (err) {
682
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
683
+ if (code !== 'ENOENT')
684
+ throw err;
685
+ }
686
+ // Walk existing ancestors to refuse symlinked parent directories (allowing only
687
+ // canonical macOS OS-level /var and /tmp symlinks into /private).
688
+ let ancestor = path.dirname(absolutePath);
689
+ for (let depth = 0; depth < 128; depth++) {
690
+ const parent = path.dirname(ancestor);
691
+ if (parent === ancestor)
692
+ break;
693
+ try {
694
+ const aStat = fs.lstatSync(ancestor);
695
+ if (aStat.isSymbolicLink()) {
696
+ const isDarwinOsLink = process.platform === 'darwin' && (ancestor === '/var' || ancestor === '/tmp');
697
+ if (!isDarwinOsLink) {
698
+ throw new Error(`refusing to write through a symlink ancestor: ${ancestor}`);
699
+ }
700
+ }
701
+ }
702
+ catch (err) {
703
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
704
+ if (code !== 'ENOENT')
705
+ throw err;
706
+ }
707
+ ancestor = parent;
708
+ }
709
+ const realTarget = physicalPath(absolutePath);
710
+ if (!realTarget) {
711
+ throw new Error(`refusing to write through a symlink or unresolvable path: ${absolutePath}`);
712
+ }
713
+ if (isProtectedPhysicalPath(absolutePath) || isProtectedPhysicalPath(realTarget)) {
714
+ throw new Error(`refusing to write into a protected system path: ${absolutePath}`);
715
+ }
658
716
  }
659
-
660
717
  function restoreFileState(absolutePath, before) {
661
- assertSafeTarget(absolutePath);
662
-
663
- // The file did not exist when we snapshotted, so undoing means removing it.
664
- if (before === null) {
665
- if (fs.existsSync(absolutePath)) fs.rmSync(absolutePath, { recursive: true, force: true });
666
- return 'removed';
667
- }
668
- if (before.kind === 'symlink') {
669
- // lstat, not exists(): a dangling symlink fails existsSync but still
670
- // occupies the name and would make symlinkSync throw EEXIST.
671
- try { fs.lstatSync(absolutePath); fs.unlinkSync(absolutePath); } catch (e) { /* nothing there */ }
672
- fs.symlinkSync(before.target, absolutePath);
673
- return 'restored symlink';
674
- }
675
- if (before.kind === 'directory') {
676
- fs.mkdirSync(absolutePath, { recursive: true });
677
- return 'restored directory';
678
- }
679
- if (before.kind !== 'file') return 'skipped (not a regular file)';
680
- if (before.skipped) return `skipped (${before.skipped})`;
681
-
682
- const buffer = readObject(before.hash);
683
- fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
684
- // Atomic swap, matching how fs_write itself lands content.
685
- const temp = `${absolutePath}.causyne_restore_${process.pid}_${Date.now()}`;
686
- fs.writeFileSync(temp, buffer, { mode: before.mode || 0o644 });
687
- fs.renameSync(temp, absolutePath);
688
- return 'restored';
718
+ assertSafeTarget(absolutePath);
719
+ if (before === null || before === undefined) {
720
+ if (fs.existsSync(absolutePath))
721
+ fs.rmSync(absolutePath, { recursive: true, force: true });
722
+ return 'removed';
723
+ }
724
+ if (before.kind === 'symlink') {
725
+ if (typeof before.target !== 'string' || !before.target || before.target.includes('\0')) {
726
+ throw new Error('refusing to restore symlink with invalid target');
727
+ }
728
+ try {
729
+ fs.lstatSync(absolutePath);
730
+ fs.unlinkSync(absolutePath);
731
+ }
732
+ catch { /* nothing there */ }
733
+ fs.symlinkSync(before.target, absolutePath);
734
+ return 'restored symlink';
735
+ }
736
+ if (before.kind === 'directory') {
737
+ fs.mkdirSync(absolutePath, { recursive: true });
738
+ return 'restored directory';
739
+ }
740
+ if (before.kind !== 'file')
741
+ return 'skipped (not a regular file)';
742
+ if (before.skipped || !before.hash || !isValidSha256(before.hash)) {
743
+ return `skipped (${before.skipped || 'missing_hash'})`;
744
+ }
745
+ const buffer = readObject(before.hash);
746
+ fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
747
+ const temp = `${absolutePath}.causyne_restore_${process.pid}_${crypto.randomBytes(6).toString('hex')}`;
748
+ try {
749
+ const fd = fs.openSync(temp, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, before.mode || 0o644);
750
+ try {
751
+ fs.writeSync(fd, buffer, 0, buffer.length);
752
+ fs.fsyncSync(fd);
753
+ }
754
+ finally {
755
+ fs.closeSync(fd);
756
+ }
757
+ atomicRenameSync(temp, absolutePath);
758
+ }
759
+ catch (err) {
760
+ try {
761
+ if (fs.existsSync(temp))
762
+ fs.unlinkSync(temp);
763
+ }
764
+ catch { /* ignore */ }
765
+ throw err;
766
+ }
767
+ return 'restored';
689
768
  }
690
-
691
- /**
692
- * Compare the workspace as it is NOW against the manifest taken at task start.
693
- *
694
- * This is what covers files changed by `sysRun` and friends: a shell command
695
- * announces no paths, so the per-file hook cannot see it, but the tree snapshot
696
- * did record the before-state of everything under the workspace root.
697
- *
698
- * @returns {{modified: string[], created: string[], deleted: string[]}|null}
699
- */
700
769
  export function diffTree(treeEntry) {
701
- if (!treeEntry || !treeEntry.manifestHash || treeEntry.skipped) return null;
702
-
703
- let manifest;
704
- try {
705
- manifest = JSON.parse(readObject(treeEntry.manifestHash).toString('utf8'));
706
- } catch (e) {
707
- return null;
708
- }
709
-
710
- const modified = [];
711
- const deleted = [];
712
- const known = new Set(Object.keys(manifest.files || {}));
713
-
714
- for (const [absolutePath, record] of Object.entries(manifest.files || {})) {
715
- if (record.kind !== 'file') continue;
716
- let stats;
770
+ if (!treeEntry || !treeEntry.manifestHash || treeEntry.skipped)
771
+ return null;
772
+ let manifest;
717
773
  try {
718
- stats = fs.lstatSync(absolutePath);
719
- } catch (e) {
720
- deleted.push(absolutePath);
721
- continue;
774
+ manifest = JSON.parse(readObject(treeEntry.manifestHash).toString('utf8'));
722
775
  }
723
- if (stats.isSymbolicLink() || !stats.isFile()) continue;
724
- if (stats.size !== record.size) { modified.push(absolutePath); continue; }
725
- try {
726
- if (sha256(fs.readFileSync(absolutePath)) !== record.hash) modified.push(absolutePath);
727
- } catch (e) { /* unreadable now: leave it alone rather than guess */ }
728
- }
729
-
730
- // Files that exist now but were not in the snapshot were created during the task.
731
- const created = [];
732
- const { manifest: current } = snapshotTree(manifest.root);
733
- if (current) {
734
- for (const absolutePath of Object.keys(current.files)) {
735
- if (!known.has(absolutePath)) created.push(absolutePath);
736
- }
737
- }
738
-
739
- return { modified, created, deleted, manifest };
776
+ catch {
777
+ return null;
778
+ }
779
+ const modified = [];
780
+ const deleted = [];
781
+ const known = new Set(Object.keys(manifest.files || {}));
782
+ for (const [absolutePath, record] of Object.entries(manifest.files || {})) {
783
+ if (record.kind !== 'file' || record.skipped)
784
+ continue;
785
+ let stats;
786
+ try {
787
+ stats = fs.lstatSync(absolutePath);
788
+ }
789
+ catch {
790
+ deleted.push(absolutePath);
791
+ continue;
792
+ }
793
+ if (stats.isSymbolicLink() || !stats.isFile())
794
+ continue;
795
+ if (stats.size !== record.size) {
796
+ modified.push(absolutePath);
797
+ continue;
798
+ }
799
+ try {
800
+ if (sha256(fs.readFileSync(absolutePath)) !== record.hash)
801
+ modified.push(absolutePath);
802
+ }
803
+ catch {
804
+ // unreadable now: leave it alone rather than guess
805
+ }
806
+ }
807
+ const created = [];
808
+ const { manifest: current } = snapshotTree(manifest.root);
809
+ if (current) {
810
+ for (const absolutePath of Object.keys(current.files)) {
811
+ if (!known.has(absolutePath))
812
+ created.push(absolutePath);
813
+ }
814
+ }
815
+ return { modified, created, deleted, manifest };
740
816
  }
741
-
742
- /**
743
- * Restore every file the tree snapshot covers that has drifted since task start.
744
- * Deliberately NOT the default: it reverts changes the agent did not make too
745
- * (anything you edited yourself in another window while the task ran), so it is
746
- * only reached through an explicit `--full`.
747
- */
748
817
  function restoreFromTree(treeEntry, undoTaskId, dryRun) {
749
- const diff = diffTree(treeEntry);
750
- if (!diff) return [];
751
-
752
- const results = [];
753
- const apply = (absolutePath, before, label) => {
754
- if (dryRun) {
755
- results.push({ path: absolutePath, action: `would ${label}` });
756
- return;
818
+ const diff = diffTree(treeEntry);
819
+ if (!diff)
820
+ return [];
821
+ const results = [];
822
+ const apply = (absolutePath, before, label) => {
823
+ if (dryRun) {
824
+ results.push({ path: absolutePath, action: `would ${label}` });
825
+ return;
826
+ }
827
+ try {
828
+ const current = snapshotFile(absolutePath);
829
+ appendJournal({
830
+ id: newId(), ts: Date.now(), type: 'file', taskId: undoTaskId,
831
+ step: null, tool: 'undo-tree', path: absolutePath, before: current
832
+ });
833
+ results.push({ path: absolutePath, action: restoreFileState(absolutePath, before) });
834
+ }
835
+ catch (e) {
836
+ results.push({ path: absolutePath, action: `FAILED: ${e instanceof Error ? e.message : String(e)}` });
837
+ }
838
+ };
839
+ for (const absolutePath of [...diff.modified, ...diff.deleted]) {
840
+ apply(absolutePath, diff.manifest.files[absolutePath], 'restore');
757
841
  }
758
- try {
759
- const current = snapshotFile(absolutePath);
760
- appendJournal({
761
- id: newId(), ts: Date.now(), type: 'file', taskId: undoTaskId,
762
- step: null, tool: 'undo-tree', path: absolutePath, before: current
763
- });
764
- results.push({ path: absolutePath, action: restoreFileState(absolutePath, before) });
765
- } catch (e) {
766
- results.push({ path: absolutePath, action: `FAILED: ${e.message}` });
767
- }
768
- };
769
-
770
- for (const absolutePath of [...diff.modified, ...diff.deleted]) {
771
- apply(absolutePath, diff.manifest.files[absolutePath], 'restore');
772
- }
773
- for (const absolutePath of diff.created) {
774
- apply(absolutePath, null, 'remove');
775
- }
776
- return results;
842
+ for (const absolutePath of diff.created) {
843
+ apply(absolutePath, null, 'remove');
844
+ }
845
+ return results;
777
846
  }
778
-
779
-
780
847
  export function isUndoable(group) {
781
- if (!group) return false;
782
- return group.fileEntries.length > 0 || group.trees.some((tree) => !tree.skipped);
848
+ if (!group)
849
+ return false;
850
+ return group.fileEntries.length > 0 || group.trees.some((tree) => !tree.skipped);
783
851
  }
784
-
785
- /** Group the journal into per-task groups, newest first. */
786
852
  export function listGroups(limit = 20) {
787
- const entries = readJournal();
788
- const byTask = new Map();
789
-
790
- for (const entry of entries) {
791
- if (!byTask.has(entry.taskId)) {
792
- byTask.set(entry.taskId, { taskId: entry.taskId, ts: entry.ts, entries: [], prompt: null });
793
- }
794
- const group = byTask.get(entry.taskId);
795
- group.ts = Math.max(group.ts, entry.ts);
796
- if (entry.type === 'task_start' && entry.prompt) group.prompt = entry.prompt;
797
- group.entries.push(entry);
798
- }
799
-
800
- return [...byTask.values()]
801
- .sort((a, b) => b.ts - a.ts)
802
- .slice(0, limit)
803
- .map(group => ({
804
- ...group,
805
- fileEntries: group.entries.filter(e => e.type === 'file'),
806
- hasHistory: group.entries.some(e => e.type === 'task_start' && e.history),
807
- trees: group.entries.filter(e => e.type === 'tree')
853
+ const safeLimit = typeof limit === 'number' && Number.isFinite(limit)
854
+ ? Math.max(1, Math.min(10_000, Math.floor(limit)))
855
+ : 20;
856
+ const entries = readJournal();
857
+ const byTask = new Map();
858
+ for (const entry of entries) {
859
+ const entryTs = typeof entry.ts === 'number' && Number.isFinite(entry.ts) ? entry.ts : 0;
860
+ if (!byTask.has(entry.taskId)) {
861
+ byTask.set(entry.taskId, { taskId: entry.taskId, ts: entryTs, entries: [], prompt: null });
862
+ }
863
+ const group = byTask.get(entry.taskId);
864
+ group.ts = Math.max(group.ts, entryTs);
865
+ if (entry.type === 'task_start' && entry.prompt)
866
+ group.prompt = entry.prompt;
867
+ group.entries.push(entry);
868
+ }
869
+ return [...byTask.values()]
870
+ .sort((a, b) => b.ts - a.ts)
871
+ .slice(0, safeLimit)
872
+ .map(group => ({
873
+ ...group,
874
+ fileEntries: group.entries.filter(e => e.type === 'file'),
875
+ hasHistory: group.entries.some(e => e.type === 'task_start' && Boolean(e.history)),
876
+ trees: group.entries.filter(e => e.type === 'tree')
808
877
  }));
809
878
  }
810
-
811
- /**
812
- * Roll a task back: its files AND the conversation, together.
813
- *
814
- * The restore itself is checkpointed first, under a fresh `undo_<ts>` task, so
815
- * an undo can itself be undone.
816
- */
817
879
  export function undoTask(taskId, options = {}) {
818
- // Fail SAFE, not dangerous.
819
- //
820
- // This was `=== true`, so an options object that simply lacked the flag —
821
- // a malformed frame, a truncated payload, a new caller that forgot it —
822
- // performed a REAL rollback over the user's files. The default for an
823
- // operation that overwrites work must be the one that writes nothing; a
824
- // caller that means to write now has to say so.
825
- const dryRun = options.dryRun !== false;
826
- const groups = listGroups(1000);
827
- const group = groups.find(g => g.taskId === taskId);
828
- if (!group) return { ok: false, error: `no checkpoint group for task "${taskId}"` };
829
-
830
- const results = [];
831
- const undoTaskId = `undo_${Date.now().toString(36)}`;
832
-
833
- // A file touched three times in one task must end up back at the state it had
834
- // before the FIRST of those writes — so for each path keep the OLDEST
835
- // snapshot, walking the group oldest-first.
836
- const earliest = new Map();
837
- for (const entry of [...group.fileEntries].sort((a, b) => a.ts - b.ts)) {
838
- if (!earliest.has(entry.path)) earliest.set(entry.path, entry);
839
- }
840
-
841
- const wantsFiles = options.scope !== 'conversation';
842
- const wantsHistory = options.scope !== 'code';
843
-
844
- for (const entry of (wantsFiles ? earliest.values() : [])) {
880
+ const dryRun = options.dryRun !== false;
881
+ const groups = listGroups(1000);
882
+ const group = groups.find(g => g.taskId === taskId);
883
+ if (!group)
884
+ return { ok: false, error: `no checkpoint group for task "${taskId}"` };
885
+ const results = [];
886
+ const undoTaskId = `undo_${Date.now().toString(36)}`;
887
+ const earliest = new Map();
888
+ for (const entry of [...group.fileEntries].sort((a, b) => a.ts - b.ts)) {
889
+ if (entry.path && !earliest.has(entry.path))
890
+ earliest.set(entry.path, entry);
891
+ }
892
+ const wantsFiles = options.scope !== 'conversation';
893
+ const wantsHistory = options.scope !== 'code';
894
+ for (const entry of (wantsFiles ? earliest.values() : [])) {
895
+ if (!entry.path)
896
+ continue;
897
+ if (dryRun) {
898
+ results.push({ path: entry.path, action: entry.before === null ? 'would remove' : 'would restore' });
899
+ continue;
900
+ }
901
+ try {
902
+ const current = snapshotFile(entry.path);
903
+ appendJournal({
904
+ id: newId(), ts: Date.now(), type: 'file', taskId: undoTaskId,
905
+ step: null, tool: 'undo', path: entry.path, before: current
906
+ });
907
+ const action = restoreFileState(entry.path, entry.before);
908
+ results.push({ path: entry.path, action });
909
+ }
910
+ catch (e) {
911
+ results.push({ path: entry.path, action: `FAILED: ${e instanceof Error ? e.message : String(e)}` });
912
+ }
913
+ }
914
+ let historyRestored = false;
915
+ const start = group.entries.find(e => e.type === 'task_start' && e.history);
916
+ if (start && start.history && !dryRun && wantsHistory) {
917
+ const target = start.history.file || legacyHistoryFile();
918
+ try {
919
+ const root = causyneHome();
920
+ const resolved = path.resolve(target);
921
+ const realRoot = physicalPath(root);
922
+ const realTarget = physicalPath(resolved);
923
+ if (!realRoot || !realTarget || !isWithinPhysicalPath(realTarget, realRoot)) {
924
+ throw new Error('conversation snapshot points outside the Causyne state directory');
925
+ }
926
+ if (fs.existsSync(resolved)) {
927
+ const curStat = fs.lstatSync(resolved);
928
+ if (!curStat.isSymbolicLink() && curStat.isFile()) {
929
+ const buffer = fs.readFileSync(resolved);
930
+ appendJournal({
931
+ id: newId(), ts: Date.now(), type: 'task_start', taskId: undoTaskId,
932
+ prompt: 'undo restore point',
933
+ history: { hash: writeObject(buffer), size: buffer.length, file: resolved }
934
+ });
935
+ }
936
+ }
937
+ const snapshot = readObject(start.history.hash);
938
+ if (path.extname(resolved) === '.jsonl') {
939
+ historyRestored = restoreSessionFromSnapshot(resolved, snapshot);
940
+ if (!historyRestored)
941
+ throw new Error('conversation journal snapshot could not be projected');
942
+ }
943
+ else {
944
+ assertSafeTarget(resolved);
945
+ fs.mkdirSync(path.dirname(resolved), { recursive: true, mode: 0o700 });
946
+ const temp = `${resolved}.tmp_${process.pid}_${crypto.randomBytes(6).toString('hex')}`;
947
+ try {
948
+ const fd = fs.openSync(temp, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
949
+ try {
950
+ fs.writeSync(fd, snapshot, 0, snapshot.length);
951
+ fs.fsyncSync(fd);
952
+ }
953
+ finally {
954
+ fs.closeSync(fd);
955
+ }
956
+ atomicRenameSync(temp, resolved);
957
+ }
958
+ catch (writeErr) {
959
+ try {
960
+ if (fs.existsSync(temp))
961
+ fs.unlinkSync(temp);
962
+ }
963
+ catch { /* ignore */ }
964
+ throw writeErr;
965
+ }
966
+ historyRestored = true;
967
+ }
968
+ }
969
+ catch (e) {
970
+ results.push({ path: target, action: `FAILED: ${e instanceof Error ? e.message : String(e)}` });
971
+ }
972
+ }
973
+ const drift = [];
974
+ const treeResults = [];
975
+ for (const tree of (wantsFiles ? group.trees : [])) {
976
+ if (tree.skipped || !tree.root)
977
+ continue;
978
+ if (tree.backend === 'git' && tree.gitTree) {
979
+ const gitChanges = gitTreeChanges(tree, undoTaskId, dryRun, options.full === true);
980
+ if (gitChanges) {
981
+ if (options.full)
982
+ treeResults.push(...gitChanges.results);
983
+ else if (gitChanges.driftFiles.length > 0) {
984
+ drift.push({ root: tree.root, files: gitChanges.driftFiles });
985
+ }
986
+ continue;
987
+ }
988
+ }
989
+ if (options.full) {
990
+ treeResults.push(...restoreFromTree(tree, undoTaskId, dryRun));
991
+ continue;
992
+ }
993
+ const diff = diffTree(tree);
994
+ if (!diff)
995
+ continue;
996
+ const untracked = [...diff.modified, ...diff.created, ...diff.deleted]
997
+ .filter(p => !earliest.has(p));
998
+ if (untracked.length > 0)
999
+ drift.push({ root: tree.root, files: untracked });
1000
+ }
1001
+ if (!dryRun) {
1002
+ try {
1003
+ appendJournal({
1004
+ id: newId(),
1005
+ ts: Date.now(),
1006
+ type: 'undo_marker',
1007
+ taskId: undoTaskId,
1008
+ targetTaskId: taskId,
1009
+ undoTaskId
1010
+ });
1011
+ }
1012
+ catch { /* best-effort marker */ }
1013
+ }
1014
+ return {
1015
+ ok: true,
1016
+ taskId,
1017
+ undoTaskId: dryRun ? null : undoTaskId,
1018
+ dryRun,
1019
+ full: options.full === true,
1020
+ results: [...results, ...treeResults],
1021
+ historyRestored,
1022
+ historyAvailable: Boolean(start),
1023
+ scope: options.scope || 'both',
1024
+ drift,
1025
+ skippedTrees: group.trees.filter(t => t.skipped).map(t => ({ root: t.root, reason: t.skipped }))
1026
+ };
1027
+ }
1028
+ function collectUndoneTaskIds() {
1029
+ const undone = new Set();
1030
+ const redoStack = [];
1031
+ for (const entry of readJournal()) {
1032
+ if (entry.type === 'undo_marker' && entry.targetTaskId && entry.undoTaskId) {
1033
+ undone.add(entry.targetTaskId);
1034
+ redoStack.push({ targetTaskId: entry.targetTaskId, undoTaskId: entry.undoTaskId });
1035
+ }
1036
+ else if (entry.type === 'redo_marker' && entry.targetTaskId) {
1037
+ undone.delete(entry.targetTaskId);
1038
+ const idx = redoStack.findLastIndex((item) => item.targetTaskId === entry.targetTaskId);
1039
+ if (idx !== -1)
1040
+ redoStack.splice(idx, 1);
1041
+ }
1042
+ }
1043
+ return { undone, redoStack };
1044
+ }
1045
+ export function redoLast(options) {
1046
+ const safeOptions = options && typeof options === 'object' ? options : {};
1047
+ const dryRun = safeOptions.dryRun !== false;
1048
+ const { redoStack } = collectUndoneTaskIds();
1049
+ const top = redoStack.at(-1);
1050
+ if (!top) {
1051
+ return { ok: false, error: 'nothing to redo — no undone checkpoint is pending' };
1052
+ }
1053
+ const applied = undoTask(top.undoTaskId, { ...safeOptions, dryRun });
1054
+ if (applied.ok && !dryRun) {
1055
+ try {
1056
+ appendJournal({
1057
+ id: newId(),
1058
+ ts: Date.now(),
1059
+ type: 'redo_marker',
1060
+ taskId: `redo_${Date.now().toString(36)}`,
1061
+ targetTaskId: top.targetTaskId,
1062
+ undoTaskId: top.undoTaskId
1063
+ });
1064
+ }
1065
+ catch { /* best-effort marker */ }
1066
+ }
1067
+ return { ...applied, redoneTaskId: top.targetTaskId };
1068
+ }
1069
+ export function undoLast(options) {
1070
+ const safeOptions = options && typeof options === 'object' ? options : {};
1071
+ const hasExplicitWorkspace = typeof safeOptions.workspaceRoot === 'string' && safeOptions.workspaceRoot.trim().length > 0;
1072
+ const ws = hasExplicitWorkspace ? path.resolve(safeOptions.workspaceRoot) : path.resolve(process.cwd());
1073
+ const { undone } = collectUndoneTaskIds();
1074
+ const allCandidates = listGroups(200).filter((group) => !group.taskId.startsWith('undo_')
1075
+ && !group.taskId.startsWith('redo_')
1076
+ && !undone.has(group.taskId)
1077
+ && isUndoable(group));
1078
+ const validCandidates = allCandidates.filter((group) => {
1079
+ const allPaths = [
1080
+ ...group.trees.map((t) => t.root).filter((p) => Boolean(p)),
1081
+ ...group.fileEntries.map((e) => e.path).filter((p) => Boolean(p))
1082
+ ];
1083
+ if (allPaths.length > 0 && allPaths.every((p) => (p.startsWith('/var/folders/') || p.startsWith('/tmp/')) && !fs.existsSync(p))) {
1084
+ return false;
1085
+ }
1086
+ return true;
1087
+ });
1088
+ const workspaceCandidates = validCandidates.filter((group) => {
1089
+ const matchesTree = group.trees.some((t) => t.root && (t.root === ws || ws.startsWith(t.root + path.sep) || t.root.startsWith(ws + path.sep)));
1090
+ const matchesFile = group.fileEntries.some((e) => e.path && (e.path.startsWith(ws + path.sep) || e.path === ws));
1091
+ return matchesTree || matchesFile;
1092
+ });
1093
+ const candidates = hasExplicitWorkspace
1094
+ ? workspaceCandidates
1095
+ : (workspaceCandidates.length > 0 ? workspaceCandidates : validCandidates);
1096
+ if (candidates.length === 0) {
1097
+ return { ok: false, error: 'nothing has been checkpointed yet — no task has run in this workspace' };
1098
+ }
1099
+ return undoTask(candidates[0].taskId, safeOptions);
1100
+ }
1101
+ export function undoStep(options) {
1102
+ const safeOptions = options && typeof options === 'object' ? options : {};
1103
+ const dryRun = safeOptions.dryRun !== false;
1104
+ const hasExplicitWorkspace = typeof safeOptions.workspaceRoot === 'string' && safeOptions.workspaceRoot.trim().length > 0;
1105
+ const ws = hasExplicitWorkspace ? path.resolve(safeOptions.workspaceRoot) : null;
1106
+ const entries = readJournal().filter(e => {
1107
+ if (e.type !== 'file' || e.tool === 'undo' || !e.path)
1108
+ return false;
1109
+ if (ws && e.path !== ws && !e.path.startsWith(ws + path.sep))
1110
+ return false;
1111
+ return true;
1112
+ });
1113
+ if (entries.length === 0)
1114
+ return { ok: false, error: 'no file mutation has been checkpointed yet' };
1115
+ const entry = entries[entries.length - 1];
1116
+ const targetPath = entry.path;
845
1117
  if (dryRun) {
846
- results.push({ path: entry.path, action: entry.before === null ? 'would remove' : 'would restore' });
847
- continue;
1118
+ return { ok: true, dryRun, results: [{ path: targetPath, action: entry.before === null ? 'would remove' : 'would restore' }] };
848
1119
  }
849
1120
  try {
850
- // Checkpoint the CURRENT state before overwriting it, so this is reversible.
851
- const current = snapshotFile(entry.path);
852
- appendJournal({
853
- id: newId(), ts: Date.now(), type: 'file', taskId: undoTaskId,
854
- step: null, tool: 'undo', path: entry.path, before: current
855
- });
856
-
857
- const action = restoreFileState(entry.path, entry.before);
858
- results.push({ path: entry.path, action });
859
- } catch (e) {
860
- results.push({ path: entry.path, action: `FAILED: ${e.message}` });
861
- }
862
- }
863
-
864
- // The conversation, rewound to the state it had when the task began.
865
- let historyRestored = false;
866
- const start = group.entries.find(e => e.type === 'task_start' && e.history);
867
-
868
- // The two halves of a rewind are independently selectable.
869
- //
870
- // undoTask has always restored files AND rewound the conversation together,
871
- // and the split existed internally without ever reaching the user. A rewind
872
- // that only rewinds the chat is genuinely useful — it is how you re-ask a
873
- // question without throwing away work the agent got right — and one that only
874
- // touches files keeps the reasoning while discarding the edits. An absent
875
- // scope means BOTH, so every existing caller is unchanged.
876
- if (start && !dryRun && wantsHistory) {
877
- // Restore into the file the snapshot was TAKEN from. Entries written before
878
- // sessions existed carry no path and mean the legacy global history.
879
- const target = start.history.file || HISTORY_FILE;
880
- try {
881
- // A journal is local and 0600, but it is still data deciding a write
882
- // target. Confine the restore to Causyne's own state root so a tampered or
883
- // hand-edited entry cannot direct it anywhere else.
884
- const root = causyneHome();
885
- const resolved = path.resolve(target);
886
- if (resolved !== root && !resolved.startsWith(root + path.sep)) {
887
- throw new Error('conversation snapshot points outside the Causyne state directory');
888
- }
889
-
890
- if (fs.existsSync(resolved)) {
891
- const buffer = fs.readFileSync(resolved);
1121
+ const current = snapshotFile(targetPath);
892
1122
  appendJournal({
893
- id: newId(), ts: Date.now(), type: 'task_start', taskId: undoTaskId,
894
- prompt: 'undo restore point',
895
- history: { hash: writeObject(buffer), size: buffer.length, file: resolved }
1123
+ id: newId(), ts: Date.now(), type: 'file', taskId: `undo_${Date.now().toString(36)}`,
1124
+ step: null, tool: 'undo', path: targetPath, before: current
896
1125
  });
897
- }
898
- const snapshot = readObject(start.history.hash);
899
- if (path.extname(resolved) === '.jsonl') {
900
- historyRestored = restoreSessionFromSnapshot(resolved, snapshot);
901
- if (!historyRestored) throw new Error('conversation journal snapshot could not be projected');
902
- } else {
903
- // Older checkpoints still point at the legacy JSON snapshot. Keep that
904
- // recovery path while new sessions remain append-only.
905
- assertSafeTarget(resolved);
906
- fs.mkdirSync(path.dirname(resolved), { recursive: true });
907
- fs.writeFileSync(resolved, snapshot, { mode: 0o600 });
908
- historyRestored = true;
909
- }
910
- } catch (e) {
911
- results.push({ path: target, action: `FAILED: ${e.message}` });
912
- }
913
- }
914
-
915
- // Workspace drift the per-file hook could not see — a shell command announces
916
- // no paths. Reported by default, restored only when explicitly asked, because
917
- // it also covers edits the user made by hand while the task ran.
918
- const drift = [];
919
- const treeResults = [];
920
- for (const tree of (wantsFiles ? group.trees : [])) {
921
- if (tree.skipped) continue;
922
-
923
- // A git-backed tree answers both questions from the same pair of SHAs, so
924
- // the preview and the restore can never disagree about what would happen.
925
- if (tree.backend === 'git' && tree.gitTree) {
926
- const gitChanges = gitTreeChanges(tree, undoTaskId, dryRun, options.full === true);
927
- if (gitChanges) {
928
- if (options.full) treeResults.push(...gitChanges.results);
929
- else if (gitChanges.driftFiles.length > 0) {
930
- drift.push({ root: tree.root, files: gitChanges.driftFiles });
931
- }
932
- continue;
933
- }
934
- // Any git failure falls through to the native path below rather than
935
- // silently reporting that nothing changed.
936
- }
937
-
938
- if (options.full) {
939
- treeResults.push(...restoreFromTree(tree, undoTaskId, dryRun));
940
- continue;
941
- }
942
- const diff = diffTree(tree);
943
- if (!diff) continue;
944
- const untracked = [...diff.modified, ...diff.created, ...diff.deleted]
945
- .filter(p => !earliest.has(p));
946
- if (untracked.length > 0) drift.push({ root: tree.root, files: untracked });
947
- }
948
-
949
- return {
950
- ok: true,
951
- taskId,
952
- dryRun,
953
- full: options.full === true,
954
- results: [...results, ...treeResults],
955
- historyRestored,
956
- historyAvailable: Boolean(start),
957
- scope: options.scope || 'both',
958
- drift,
959
- skippedTrees: group.trees.filter(t => t.skipped).map(t => ({ root: t.root, reason: t.skipped }))
960
- };
961
- }
962
-
963
- /** Undo the most recent task that actually changed a file. */
964
- export function undoLast(options = {}) {
965
- // A task is undoable if it captured file entries OR a workspace tree.
966
- //
967
- // This used to require `fileEntries.length > 0`, which quietly discarded the
968
- // entire tree mechanism. The per-file hook only fires for the fs_* tools;
969
- // a task that did its work through the shell — `npm install`, `git checkout`,
970
- // a build script, `mv`, `rm` — announces no paths and produces ZERO file
971
- // entries. beginTask() snapshots the whole workspace tree precisely to cover
972
- // that case, and undoTask() already knows how to diff and restore it.
973
- const ws = options.workspaceRoot ? path.resolve(options.workspaceRoot) : path.resolve(process.cwd());
974
- const allCandidates = listGroups(200).filter((group) =>
975
- !group.taskId.startsWith('undo_') && isUndoable(group));
976
-
977
- // Filter out dead temporary test directories
978
- const validCandidates = allCandidates.filter((group) => {
979
- const allPaths = [
980
- ...group.trees.map((t) => t.root),
981
- ...group.fileEntries.map((e) => e.path)
982
- ];
983
- if (allPaths.length > 0 && allPaths.every((p) => (p.startsWith('/var/folders/') || p.startsWith('/tmp/')) && !fs.existsSync(p))) {
984
- return false;
1126
+ const action = restoreFileState(targetPath, entry.before);
1127
+ return { ok: true, dryRun: false, results: [{ path: targetPath, action }] };
1128
+ }
1129
+ catch (e) {
1130
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
985
1131
  }
986
- return true;
987
- });
988
-
989
- // Prefer candidates belonging to the current workspace root
990
- const workspaceCandidates = validCandidates.filter((group) => {
991
- const matchesTree = group.trees.some((t) => t.root && (t.root === ws || ws.startsWith(t.root + path.sep) || t.root.startsWith(ws + path.sep)));
992
- const matchesFile = group.fileEntries.some((e) => e.path && (e.path.startsWith(ws + path.sep) || e.path === ws));
993
- return matchesTree || matchesFile;
994
- });
995
-
996
- const candidates = workspaceCandidates.length > 0 ? workspaceCandidates : validCandidates;
997
-
998
- if (candidates.length === 0) {
999
- return { ok: false, error: 'nothing has been checkpointed yet — no task has run in this workspace' };
1000
- }
1001
- return undoTask(candidates[0].taskId, options);
1002
- }
1003
-
1004
- /** Undo just the single most recent file mutation. */
1005
- export function undoStep(options = {}) {
1006
- // Fail SAFE, not dangerous.
1007
- //
1008
- // This was `=== true`, so an options object that simply lacked the flag —
1009
- // a malformed frame, a truncated payload, a new caller that forgot it —
1010
- // performed a REAL rollback over the user's files. The default for an
1011
- // operation that overwrites work must be the one that writes nothing; a
1012
- // caller that means to write now has to say so.
1013
- const dryRun = options.dryRun !== false;
1014
- const entries = readJournal().filter(e => e.type === 'file' && e.tool !== 'undo');
1015
- if (entries.length === 0) return { ok: false, error: 'no file mutation has been checkpointed yet' };
1016
-
1017
- const entry = entries[entries.length - 1];
1018
- if (dryRun) {
1019
- return { ok: true, dryRun, results: [{ path: entry.path, action: entry.before === null ? 'would remove' : 'would restore' }] };
1020
- }
1021
-
1022
- try {
1023
- const current = snapshotFile(entry.path);
1024
- appendJournal({
1025
- id: newId(), ts: Date.now(), type: 'file', taskId: `undo_${Date.now().toString(36)}`,
1026
- step: null, tool: 'undo', path: entry.path, before: current
1027
- });
1028
- const action = restoreFileState(entry.path, entry.before);
1029
- return { ok: true, dryRun: false, results: [{ path: entry.path, action }] };
1030
- } catch (e) {
1031
- return { ok: false, error: e.message };
1032
- }
1033
1132
  }
1034
-
1035
- // ---------------------------------------------------------------------------
1036
- // Retention
1037
- // ---------------------------------------------------------------------------
1038
-
1039
1133
  function directorySize(dir) {
1040
- let total = 0;
1041
- const stack = [dir];
1042
- while (stack.length > 0) {
1043
- const current = stack.pop();
1044
- let entries;
1045
- try { entries = fs.readdirSync(current, { withFileTypes: true }); } catch (e) { continue; }
1046
- for (const entry of entries) {
1047
- const full = path.join(current, entry.name);
1048
- if (entry.isDirectory()) { stack.push(full); continue; }
1049
- try { total += fs.statSync(full).size; } catch (e) {}
1134
+ let total = 0;
1135
+ const stack = [dir];
1136
+ while (stack.length > 0) {
1137
+ const current = stack.pop();
1138
+ let entries;
1139
+ try {
1140
+ entries = fs.readdirSync(current, { withFileTypes: true });
1141
+ }
1142
+ catch {
1143
+ continue;
1144
+ }
1145
+ for (const entry of entries) {
1146
+ if (entry.isSymbolicLink())
1147
+ continue;
1148
+ const full = path.join(current, entry.name);
1149
+ if (entry.isDirectory()) {
1150
+ stack.push(full);
1151
+ continue;
1152
+ }
1153
+ try {
1154
+ const stat = fs.lstatSync(full);
1155
+ if (!stat.isSymbolicLink() && stat.isFile())
1156
+ total += stat.size;
1157
+ }
1158
+ catch {
1159
+ /* ignore */
1160
+ }
1161
+ }
1050
1162
  }
1051
- }
1052
- return total;
1163
+ return total;
1053
1164
  }
1054
-
1055
- /**
1056
- * Drop journal entries past the retention window (or past the entry ceiling),
1057
- * then delete every blob no surviving entry still references.
1058
- */
1059
1165
  export function pruneStore() {
1060
- try {
1061
- if (!fs.existsSync(JOURNAL_FILE)) return { removedEntries: 0, removedObjects: 0 };
1062
-
1063
- let entries = readJournal();
1064
- const before = entries.length;
1065
- const cutoff = Date.now() - RETENTION_MS;
1066
- const overSize = directorySize(OBJECTS_DIR) > MAX_STORE_BYTES;
1067
-
1068
- entries = entries.filter(e => e.ts >= cutoff);
1069
- if (entries.length > MAX_JOURNAL_ENTRIES || overSize) {
1070
- const keep = overSize ? Math.floor(MAX_JOURNAL_ENTRIES / 2) : MAX_JOURNAL_ENTRIES;
1071
- entries = entries.slice(-keep);
1072
- }
1073
- if (entries.length !== before) rewriteJournal(entries);
1074
-
1075
- // Mark and sweep: anything no surviving entry references is unreachable.
1076
- const live = new Set();
1077
- for (const entry of entries) {
1078
- if (entry.before && entry.before.hash) live.add(entry.before.hash);
1079
- if (entry.history && entry.history.hash) live.add(entry.history.hash);
1080
- if (entry.manifestHash) {
1081
- live.add(entry.manifestHash);
1166
+ try {
1167
+ const jf = journalFile();
1168
+ const objs = objectsDir();
1169
+ if (!fs.existsSync(jf))
1170
+ return { removedEntries: 0, removedObjects: 0 };
1171
+ let entries = readJournal();
1172
+ const before = entries.length;
1173
+ const cutoff = Date.now() - RETENTION_MS;
1174
+ const overSize = directorySize(objs) > MAX_STORE_BYTES;
1175
+ entries = entries.filter(e => e.ts >= cutoff);
1176
+ if (entries.length > MAX_JOURNAL_ENTRIES || overSize) {
1177
+ const keep = overSize ? Math.floor(MAX_JOURNAL_ENTRIES / 2) : MAX_JOURNAL_ENTRIES;
1178
+ entries = entries.slice(-keep);
1179
+ }
1180
+ if (entries.length !== before)
1181
+ rewriteJournal(entries);
1182
+ const live = new Set();
1183
+ for (const entry of entries) {
1184
+ if (entry.before && entry.before.kind === 'file' && entry.before.hash)
1185
+ live.add(entry.before.hash);
1186
+ if (entry.history && entry.history.hash)
1187
+ live.add(entry.history.hash);
1188
+ if (entry.manifestHash) {
1189
+ live.add(entry.manifestHash);
1190
+ try {
1191
+ const manifest = JSON.parse(readObject(entry.manifestHash).toString('utf8'));
1192
+ for (const record of Object.values(manifest.files || {})) {
1193
+ if (record && record.kind === 'file' && record.hash)
1194
+ live.add(record.hash);
1195
+ }
1196
+ }
1197
+ catch {
1198
+ // an unreadable manifest keeps only itself alive
1199
+ }
1200
+ }
1201
+ }
1202
+ let removedObjects = 0;
1203
+ let shards;
1082
1204
  try {
1083
- const manifest = JSON.parse(readObject(entry.manifestHash).toString('utf8'));
1084
- for (const record of Object.values(manifest.files || {})) {
1085
- if (record && record.hash) live.add(record.hash);
1086
- }
1087
- } catch (e) { /* an unreadable manifest keeps only itself alive */ }
1088
- }
1089
- }
1090
-
1091
- let removedObjects = 0;
1092
- let shards;
1093
- try { shards = fs.readdirSync(OBJECTS_DIR); } catch (e) { shards = []; }
1094
- for (const shard of shards) {
1095
- const shardDir = path.join(OBJECTS_DIR, shard);
1096
- let objects;
1097
- try { objects = fs.readdirSync(shardDir); } catch (e) { continue; }
1098
- for (const name of objects) {
1099
- if (live.has(name)) continue;
1100
- try { fs.unlinkSync(path.join(shardDir, name)); removedObjects++; } catch (e) {}
1101
- }
1102
- try { if (fs.readdirSync(shardDir).length === 0) fs.rmdirSync(shardDir); } catch (e) {}
1103
- }
1104
-
1105
- return { removedEntries: before - entries.length, removedObjects };
1106
- } catch (e) {
1107
- debugLog(`checkpoint prune skipped: ${e.message}`);
1108
- return { removedEntries: 0, removedObjects: 0 };
1109
- }
1205
+ shards = fs.readdirSync(objs);
1206
+ }
1207
+ catch {
1208
+ shards = [];
1209
+ }
1210
+ for (const shard of shards) {
1211
+ const shardDir = path.join(objs, shard);
1212
+ try {
1213
+ const sStat = fs.lstatSync(shardDir);
1214
+ if (sStat.isSymbolicLink() || !sStat.isDirectory())
1215
+ continue;
1216
+ }
1217
+ catch {
1218
+ continue;
1219
+ }
1220
+ let objects;
1221
+ try {
1222
+ objects = fs.readdirSync(shardDir);
1223
+ }
1224
+ catch {
1225
+ continue;
1226
+ }
1227
+ for (const name of objects) {
1228
+ if (live.has(name))
1229
+ continue;
1230
+ const objFile = path.join(shardDir, name);
1231
+ try {
1232
+ const oStat = fs.lstatSync(objFile);
1233
+ if (oStat.isSymbolicLink() || !oStat.isFile())
1234
+ continue;
1235
+ fs.unlinkSync(objFile);
1236
+ removedObjects++;
1237
+ }
1238
+ catch { /* ignore */ }
1239
+ }
1240
+ try {
1241
+ if (fs.readdirSync(shardDir).length === 0)
1242
+ fs.rmdirSync(shardDir);
1243
+ }
1244
+ catch { /* ignore */ }
1245
+ }
1246
+ return { removedEntries: before - entries.length, removedObjects };
1247
+ }
1248
+ catch (e) {
1249
+ debugLog(`checkpoint prune skipped: ${e instanceof Error ? e.message : String(e)}`);
1250
+ return { removedEntries: 0, removedObjects: 0 };
1251
+ }
1110
1252
  }
1111
-
1112
1253
  export function getStoreDir() {
1113
- return STORE_DIR;
1254
+ return storeDir();
1114
1255
  }
1115
-
1116
1256
  export function getStoreStats() {
1117
- return {
1118
- dir: STORE_DIR,
1119
- entries: readJournal().length,
1120
- bytes: fs.existsSync(OBJECTS_DIR) ? directorySize(OBJECTS_DIR) : 0
1121
- };
1257
+ const objs = objectsDir();
1258
+ return {
1259
+ dir: storeDir(),
1260
+ entries: readJournal().length,
1261
+ bytes: fs.existsSync(objs) ? directorySize(objs) : 0
1262
+ };
1122
1263
  }
1123
-
1124
- // ---------------------------------------------------------------------------
1125
- // Task diff — what REVIEW shows
1126
- // ---------------------------------------------------------------------------
1127
-
1128
- /**
1129
- * The per-file changes a task made, as a real diff.
1130
- *
1131
- * This is what REVIEW opens. Before it existed, REVIEW raised the ROLLBACK
1132
- * confirmation dialog — so "let me see what happened" and "undo this" were the
1133
- * same button, and the only way to find out what an agent had done was to be
1134
- * asked whether you wanted to destroy it. Read-only, and it never restores.
1135
- *
1136
- * Both backends answer: git supplies patches directly, and the native store
1137
- * reconstructs them from the `before` blob it already holds, so the feature
1138
- * degrades in fidelity rather than disappearing on a machine without git.
1139
- */
1140
1264
  export function buildTaskDiff(taskId) {
1141
- const group = listGroups(1000).find((g) => g.taskId === taskId);
1142
- if (!group) {
1143
- return { ok: false, taskId: taskId || null, error: 'no checkpoint for that task', files: [] };
1144
- }
1145
-
1146
- const files = [];
1147
-
1148
- // 1. Git-backed trees: git computes the patch against the checkpoint tree.
1149
- for (const tree of group.trees || []) {
1150
- if (tree.backend !== 'git' || !tree.gitTree) continue;
1151
- try {
1152
- for (const change of gitBackend.previewRestore(tree.root, tree.gitTree)) {
1265
+ const group = listGroups(1000).find((g) => g.taskId === taskId);
1266
+ if (!group) {
1267
+ return { ok: false, taskId: taskId || null, error: 'no checkpoint for that task', files: [] };
1268
+ }
1269
+ const files = [];
1270
+ for (const tree of group.trees || []) {
1271
+ if (tree.backend !== 'git' || !tree.gitTree || !tree.root)
1272
+ continue;
1273
+ try {
1274
+ for (const change of gitBackend.previewForwardDiff(tree.root, tree.gitTree)) {
1275
+ files.push({
1276
+ path: change.path,
1277
+ status: change.status === 'added' ? 'created' : change.status,
1278
+ additions: change.additions,
1279
+ deletions: change.deletions,
1280
+ patch: change.patch || '',
1281
+ truncated: false
1282
+ });
1283
+ }
1284
+ }
1285
+ catch (e) {
1286
+ debugLog(`task diff unavailable for ${tree.root}: ${e instanceof Error ? e.message : String(e)}`);
1287
+ }
1288
+ }
1289
+ const seen = new Set(files.map((f) => f.path));
1290
+ for (const entry of group.fileEntries || []) {
1291
+ if (!entry.path)
1292
+ continue;
1293
+ const fromCwd = path.relative(process.cwd(), entry.path);
1294
+ const relative = (!fromCwd || fromCwd.startsWith('..'))
1295
+ ? path.basename(entry.path)
1296
+ : fromCwd;
1297
+ if (seen.has(relative))
1298
+ continue;
1299
+ seen.add(relative);
1300
+ let beforeBuffer = null;
1301
+ if (entry.before && entry.before.kind === 'file' && entry.before.hash && isValidSha256(entry.before.hash)) {
1302
+ try {
1303
+ beforeBuffer = readObject(entry.before.hash);
1304
+ }
1305
+ catch {
1306
+ beforeBuffer = null;
1307
+ }
1308
+ }
1309
+ let afterBuffer = null;
1310
+ try {
1311
+ const afterStat = fs.lstatSync(entry.path);
1312
+ if (!afterStat.isSymbolicLink() && afterStat.isFile() && afterStat.size <= MAX_FILE_BYTES) {
1313
+ afterBuffer = fs.readFileSync(entry.path);
1314
+ }
1315
+ }
1316
+ catch { /* ignore */ }
1317
+ const status = !beforeBuffer ? 'created' : !afterBuffer ? 'deleted' : 'modified';
1318
+ if (looksBinary(beforeBuffer) || looksBinary(afterBuffer)) {
1319
+ files.push({
1320
+ path: relative, status, additions: 0, deletions: 0, patch: '', truncated: true
1321
+ });
1322
+ continue;
1323
+ }
1324
+ const diff = unifiedDiff(beforeBuffer ? beforeBuffer.toString('utf8') : '', afterBuffer ? afterBuffer.toString('utf8') : '', relative);
1153
1325
  files.push({
1154
- path: change.path,
1155
- // The preview describes the RESTORE, which runs backwards. Invert it
1156
- // so the user reads what the TASK did, which is what they asked.
1157
- status: change.status === 'deleted' ? 'created'
1158
- : change.status === 'added' ? 'deleted'
1159
- : change.status,
1160
- additions: change.deletions,
1161
- deletions: change.additions,
1162
- patch: change.patch || '',
1163
- truncated: false
1326
+ path: relative,
1327
+ status,
1328
+ additions: diff.additions,
1329
+ deletions: diff.deletions,
1330
+ patch: diff.patch,
1331
+ truncated: diff.truncated
1164
1332
  });
1165
- }
1166
- } catch (e) {
1167
- debugLog(`task diff unavailable for ${tree.root}: ${e.message}`);
1168
- }
1169
- }
1170
-
1171
- // 2. Native file entries, for anything git did not already describe.
1172
- const seen = new Set(files.map((f) => f.path));
1173
- for (const entry of group.fileEntries || []) {
1174
- // The journal stores absolute paths; a diff header showing
1175
-
1176
- // the working directory where that makes sense, basename otherwise.
1177
- const fromCwd = path.relative(process.cwd(), entry.path);
1178
- const relative = (!fromCwd || fromCwd.startsWith('..'))
1179
- ? path.basename(entry.path)
1180
- : fromCwd;
1181
- if (seen.has(relative)) continue;
1182
- seen.add(relative);
1183
-
1184
- const beforeBuffer = entry.before ? readObject(entry.before.hash) : null;
1185
- let afterBuffer = null;
1186
- try {
1187
- if (fs.existsSync(entry.path)) afterBuffer = fs.readFileSync(entry.path);
1188
- } catch (e) {}
1189
-
1190
- const status = !beforeBuffer ? 'created' : !afterBuffer ? 'deleted' : 'modified';
1191
-
1192
- if (looksBinary(beforeBuffer) || looksBinary(afterBuffer)) {
1193
- files.push({
1194
- path: relative, status, additions: 0, deletions: 0, patch: '', truncated: true
1195
- });
1196
- continue;
1197
- }
1198
-
1199
- const diff = unifiedDiff(
1200
- beforeBuffer ? beforeBuffer.toString('utf8') : '',
1201
- afterBuffer ? afterBuffer.toString('utf8') : '',
1202
- relative
1203
- );
1204
- files.push({
1205
- path: relative,
1206
- status,
1207
- additions: diff.additions,
1208
- deletions: diff.deletions,
1209
- patch: diff.patch,
1210
- truncated: diff.truncated
1211
- });
1212
- }
1213
-
1214
- const totals = files.reduce(
1215
- (acc, f) => ({ additions: acc.additions + f.additions, deletions: acc.deletions + f.deletions }),
1216
- { additions: 0, deletions: 0 }
1217
- );
1218
-
1219
- return {
1220
- ok: true,
1221
- taskId: group.taskId,
1222
- prompt: group.prompt || null,
1223
- fileCount: files.length,
1224
- additions: totals.additions,
1225
- deletions: totals.deletions,
1226
- // Capped: a refactor can touch hundreds of files and this frame crosses a
1227
-
1228
- files: files.slice(0, 50)
1229
- };
1333
+ }
1334
+ const totals = files.reduce((acc, f) => ({ additions: acc.additions + f.additions, deletions: acc.deletions + f.deletions }), { additions: 0, deletions: 0 });
1335
+ return {
1336
+ ok: true,
1337
+ taskId: group.taskId,
1338
+ prompt: group.prompt || null,
1339
+ fileCount: files.length,
1340
+ additions: totals.additions,
1341
+ deletions: totals.deletions,
1342
+ files: files.slice(0, 50)
1343
+ };
1230
1344
  }