@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
@@ -0,0 +1,1377 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import crypto from 'node:crypto';
5
+ import * as gitBackend from './gitSnapshot.js';
6
+ import { unifiedDiff, looksBinary } from './textDiff.js';
7
+ import { causyneHome } from './utils/paths.js';
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';
14
+
15
+ export type SnapshotRecord =
16
+ | { kind: 'symlink'; target: string; mode?: number | undefined }
17
+ | { kind: 'directory'; mode?: number | undefined }
18
+ | { kind: 'special' }
19
+ | { kind: 'file'; skipped: string; size: number; mode?: number | undefined; hash?: undefined }
20
+ | { kind: 'file'; hash: string; size: number; mode?: number | undefined; skipped?: undefined };
21
+
22
+ export interface HistorySnapshot {
23
+ hash: string;
24
+ size: number;
25
+ file?: string | undefined;
26
+ }
27
+
28
+ export interface CheckpointJournalEntry {
29
+ id: string;
30
+ ts: number;
31
+ type: 'file' | 'task_start' | 'tree' | 'undo_marker' | 'redo_marker';
32
+ taskId: string;
33
+ targetTaskId?: string | undefined;
34
+ undoTaskId?: string | undefined;
35
+ step?: number | null | undefined;
36
+ tool?: string | undefined;
37
+ path?: string | undefined;
38
+ before?: SnapshotRecord | null | undefined;
39
+ prompt?: string | null | undefined;
40
+ history?: HistorySnapshot | null | undefined;
41
+ root?: string | undefined;
42
+ skipped?: string | null | undefined;
43
+ backend?: string | undefined;
44
+ gitTree?: string | null | undefined;
45
+ manifestHash?: string | null | undefined;
46
+ fileCount?: number | undefined;
47
+ totalBytes?: number | undefined;
48
+ }
49
+
50
+ export interface TreeManifest {
51
+ root: string;
52
+ files: Record<string, SnapshotRecord>;
53
+ fileCount: number;
54
+ totalBytes: number;
55
+ }
56
+
57
+ export interface CheckpointGroup {
58
+ taskId: string;
59
+ ts: number;
60
+ entries: CheckpointJournalEntry[];
61
+ prompt: string | null;
62
+ fileEntries: CheckpointJournalEntry[];
63
+ hasHistory: boolean;
64
+ trees: CheckpointJournalEntry[];
65
+ }
66
+
67
+ export interface UndoOptions {
68
+ dryRun?: boolean | undefined;
69
+ full?: boolean | undefined;
70
+ scope?: 'code' | 'conversation' | 'both' | string | undefined;
71
+ workspaceRoot?: string | undefined;
72
+ }
73
+
74
+ function debugLog(message: string): void {
75
+ if (process.env.CAUSYNE_DEBUG !== '1') return;
76
+ process.stderr.write(`[causyne] ${message}\n`);
77
+ }
78
+
79
+ function storeDir(): string {
80
+ return path.join(causyneHome(), 'checkpoints');
81
+ }
82
+ function objectsDir(): string {
83
+ return path.join(storeDir(), 'objects');
84
+ }
85
+ function journalFile(): string {
86
+ return path.join(storeDir(), 'index.jsonl');
87
+ }
88
+ function statCacheFile(): string {
89
+ return path.join(storeDir(), 'stat-cache.json');
90
+ }
91
+ function legacyHistoryFile(): string {
92
+ return path.join(causyneHome(), 'memory', 'chat_history.json');
93
+ }
94
+
95
+ function activeHistoryFile(explicitSessionId?: string | null): string {
96
+ try {
97
+ const id = (typeof explicitSessionId === 'string' && explicitSessionId.trim())
98
+ ? explicitSessionId.trim()
99
+ : getActiveSessionId();
100
+ if (id) {
101
+ const safe = String(id).replace(/[^a-zA-Z0-9_-]/g, '');
102
+ if (safe) return sessionTranscriptFile(safe);
103
+ }
104
+ } catch {
105
+ // fall through to the legacy file
106
+ }
107
+ return legacyHistoryFile();
108
+ }
109
+
110
+ const RETENTION_MS = 14 * 24 * 60 * 60 * 1000;
111
+ const MAX_STORE_BYTES = 512 * 1024 * 1024;
112
+ const MAX_JOURNAL_ENTRIES = 4000;
113
+ const MAX_FILE_BYTES = 16 * 1024 * 1024;
114
+ const MAX_TREE_FILES = 5000;
115
+ const MAX_TREE_BYTES = 64 * 1024 * 1024;
116
+ const MAX_TREE_FILE_BYTES = 2 * 1024 * 1024;
117
+ const MAX_OBJECT_BYTES = 32 * 1024 * 1024;
118
+
119
+ const IGNORED_DIRECTORIES = new Set([
120
+ '.git', 'node_modules', 'dist', 'build', 'out', 'target',
121
+ '.next', '.nuxt', '.svelte-kit', '.turbo', '.cache', '.parcel-cache',
122
+ 'venv', '.venv', '__pycache__', '.pytest_cache', '.mypy_cache',
123
+ 'vendor', 'Pods', '.gradle', '.idea', '.vscode', 'coverage',
124
+ '.causyne'
125
+ ]);
126
+
127
+ const MUTATING_TOOL_PATHS: Record<string, readonly string[]> = {
128
+ fs_write: ['path'],
129
+ fs_edit: ['path'],
130
+ MultiEdit: ['file_path'],
131
+ fs_delete: ['path'],
132
+ fs_move: ['source', 'destination']
133
+ };
134
+
135
+ export function isCheckpointingEnabled(): boolean {
136
+ return process.env.CAUSYNE_CHECKPOINTS !== '0';
137
+ }
138
+
139
+ function ensureStore(): void {
140
+ const base = storeDir();
141
+ const objs = objectsDir();
142
+ for (const dir of [base, objs]) {
143
+ if (!fs.existsSync(dir)) {
144
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
145
+ } else {
146
+ const stat = fs.lstatSync(dir);
147
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
148
+ throw new Error(`refusing symlink or non-directory checkpoint store: ${dir}`);
149
+ }
150
+ }
151
+ }
152
+ }
153
+
154
+ const SHA256_HEX_RE = /^[0-9a-f]{64}$/;
155
+
156
+ function isValidSha256(hash: unknown): hash is string {
157
+ return typeof hash === 'string' && SHA256_HEX_RE.test(hash);
158
+ }
159
+
160
+ function sha256(buffer: Buffer): string {
161
+ return crypto.createHash('sha256').update(buffer).digest('hex');
162
+ }
163
+
164
+ function objectPath(hash: string): string {
165
+ if (!isValidSha256(hash)) {
166
+ throw new Error('refusing invalid checkpoint object hash');
167
+ }
168
+ return path.join(objectsDir(), hash.slice(0, 2), hash);
169
+ }
170
+
171
+ function writeObject(buffer: Buffer): string {
172
+ const hash = sha256(buffer);
173
+ const target = objectPath(hash);
174
+ try {
175
+ const existing = fs.lstatSync(target);
176
+ if (existing.isSymbolicLink() || !existing.isFile()) {
177
+ throw new Error('refusing symlink or non-regular checkpoint object');
178
+ }
179
+ return hash;
180
+ } catch (err: unknown) {
181
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
182
+ if (code !== 'ENOENT') throw err;
183
+ }
184
+
185
+ const shardDir = path.dirname(target);
186
+ if (!fs.existsSync(shardDir)) {
187
+ fs.mkdirSync(shardDir, { recursive: true, mode: 0o700 });
188
+ } else {
189
+ const shardStat = fs.lstatSync(shardDir);
190
+ if (shardStat.isSymbolicLink() || !shardStat.isDirectory()) {
191
+ throw new Error('refusing symlink or non-directory checkpoint shard');
192
+ }
193
+ }
194
+
195
+ const temp = `${target}.tmp_${process.pid}_${crypto.randomBytes(6).toString('hex')}`;
196
+ try {
197
+ const fd = fs.openSync(temp, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
198
+ try {
199
+ fs.writeSync(fd, buffer, 0, buffer.length);
200
+ fs.fsyncSync(fd);
201
+ } finally {
202
+ fs.closeSync(fd);
203
+ }
204
+ atomicRenameSync(temp, target);
205
+ } catch (err: unknown) {
206
+ try { if (fs.existsSync(temp)) fs.unlinkSync(temp); } catch { /* ignore */ }
207
+ throw err;
208
+ }
209
+ return hash;
210
+ }
211
+
212
+ function readObject(hash: string): Buffer {
213
+ const target = objectPath(hash);
214
+ const stat = fs.lstatSync(target);
215
+ if (stat.isSymbolicLink() || !stat.isFile()) {
216
+ throw new Error('refusing to read symlink or non-regular checkpoint object');
217
+ }
218
+ if (stat.size > MAX_OBJECT_BYTES) {
219
+ throw new Error('refusing oversized checkpoint object');
220
+ }
221
+ const buf = fs.readFileSync(target);
222
+ if (sha256(buf) !== hash) {
223
+ throw new Error('checkpoint object integrity mismatch');
224
+ }
225
+ return buf;
226
+ }
227
+
228
+ export function resolveToolPath(value: unknown): string | null {
229
+ if (typeof value !== 'string' || value.length === 0 || value.includes('\0')) return null;
230
+ const trimmed = value.trim();
231
+ if (!trimmed) return null;
232
+ let expanded = trimmed;
233
+ if (trimmed === '~') {
234
+ expanded = os.homedir();
235
+ } else if (trimmed.startsWith('~/') || trimmed.startsWith('~\\')) {
236
+ expanded = path.join(os.homedir(), trimmed.slice(2));
237
+ }
238
+ return path.resolve(expanded);
239
+ }
240
+
241
+ function appendJournal(entry: CheckpointJournalEntry): void {
242
+ const jf = journalFile();
243
+ try {
244
+ const stat = fs.lstatSync(jf);
245
+ if (stat.isSymbolicLink() || !stat.isFile()) {
246
+ throw new Error('refusing symlink or non-regular checkpoint journal');
247
+ }
248
+ } catch (err: unknown) {
249
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
250
+ if (code !== 'ENOENT') throw err;
251
+ }
252
+ fs.appendFileSync(jf, JSON.stringify(entry) + '\n', { encoding: 'utf8', mode: 0o600 });
253
+ }
254
+
255
+ export function readJournal(): CheckpointJournalEntry[] {
256
+ const jf = journalFile();
257
+ let stat: fs.Stats;
258
+ try {
259
+ stat = fs.lstatSync(jf);
260
+ } catch {
261
+ return [];
262
+ }
263
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size === 0 || stat.size > MAX_OBJECT_BYTES) return [];
264
+ const raw = fs.readFileSync(jf, 'utf8');
265
+ const entries: CheckpointJournalEntry[] = [];
266
+ for (const line of raw.split('\n')) {
267
+ if (!line.trim()) continue;
268
+ try {
269
+ const parsed = JSON.parse(line) as unknown;
270
+ if (
271
+ parsed && typeof parsed === 'object' && !Array.isArray(parsed)
272
+ && typeof (parsed as Record<string, unknown>).type === 'string'
273
+ && typeof (parsed as Record<string, unknown>).taskId === 'string'
274
+ ) {
275
+ entries.push(parsed as CheckpointJournalEntry);
276
+ }
277
+ } catch {
278
+ /* skip a torn line */
279
+ }
280
+ }
281
+ return entries;
282
+ }
283
+
284
+ function rewriteJournal(entries: CheckpointJournalEntry[]): void {
285
+ const jf = journalFile();
286
+ try {
287
+ const stat = fs.lstatSync(jf);
288
+ if (stat.isSymbolicLink() || !stat.isFile()) {
289
+ throw new Error('refusing symlink or non-regular checkpoint journal');
290
+ }
291
+ } catch (err: unknown) {
292
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
293
+ if (code !== 'ENOENT') throw err;
294
+ }
295
+ const temp = `${jf}.tmp_${process.pid}_${crypto.randomBytes(6).toString('hex')}`;
296
+ const payload = Buffer.from(entries.map(e => JSON.stringify(e)).join('\n') + (entries.length ? '\n' : ''), 'utf8');
297
+ try {
298
+ const fd = fs.openSync(temp, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
299
+ try {
300
+ fs.writeSync(fd, payload, 0, payload.length);
301
+ fs.fsyncSync(fd);
302
+ } finally {
303
+ fs.closeSync(fd);
304
+ }
305
+ atomicRenameSync(temp, jf);
306
+ } catch (err: unknown) {
307
+ try { if (fs.existsSync(temp)) fs.unlinkSync(temp); } catch { /* ignore */ }
308
+ throw err;
309
+ }
310
+ }
311
+
312
+ function newId(): string {
313
+ return `ck_${Date.now().toString(36)}_${crypto.randomBytes(4).toString('hex')}`;
314
+ }
315
+
316
+ function snapshotFile(absolutePath: string): SnapshotRecord | null {
317
+ let stats: fs.Stats;
318
+ try {
319
+ stats = fs.lstatSync(absolutePath);
320
+ } catch {
321
+ return null;
322
+ }
323
+
324
+ if (stats.isSymbolicLink()) {
325
+ return { kind: 'symlink', target: fs.readlinkSync(absolutePath), mode: stats.mode & 0o777 };
326
+ }
327
+ if (stats.isDirectory()) {
328
+ return { kind: 'directory', mode: stats.mode & 0o777 };
329
+ }
330
+ if (!stats.isFile()) {
331
+ return { kind: 'special' };
332
+ }
333
+ if (stats.size > MAX_FILE_BYTES) {
334
+ return { kind: 'file', skipped: 'too_large', size: stats.size, mode: stats.mode & 0o777 };
335
+ }
336
+
337
+ const buffer = fs.readFileSync(absolutePath);
338
+ return {
339
+ kind: 'file',
340
+ hash: writeObject(buffer),
341
+ size: stats.size,
342
+ mode: stats.mode & 0o777
343
+ };
344
+ }
345
+
346
+ export function captureBeforeMutation(
347
+ toolName: unknown,
348
+ args: Record<string, unknown> | null | undefined,
349
+ meta?: { taskId?: string | undefined; step?: number | null | undefined } | null
350
+ ): string[] {
351
+ if (!isCheckpointingEnabled()) return [];
352
+ if (typeof toolName !== 'string' || !args || typeof args !== 'object') return [];
353
+ const canonicalTool = toolName.replace(/\./g, '_');
354
+ const fields = Object.hasOwn(MUTATING_TOOL_PATHS, canonicalTool)
355
+ ? MUTATING_TOOL_PATHS[canonicalTool]
356
+ : undefined;
357
+ const rawTargets: unknown[] = [];
358
+ if (fields) {
359
+ for (const field of fields) rawTargets.push(args[field]);
360
+ } else if (canonicalTool === 'apply_patch' && typeof args.patch === 'string') {
361
+ for (const target of extractPatchTargetPaths(args.patch).paths) {
362
+ rawTargets.push(target);
363
+ }
364
+ } else {
365
+ return [];
366
+ }
367
+
368
+ const safeMeta = meta && typeof meta === 'object' ? meta : {};
369
+ const taskId = typeof safeMeta.taskId === 'string' && safeMeta.taskId && !safeMeta.taskId.includes('\0')
370
+ ? safeMeta.taskId
371
+ : 'unknown';
372
+ const ids: string[] = [];
373
+ try {
374
+ ensureStore();
375
+ for (const rawTarget of rawTargets) {
376
+ const absolutePath = resolveToolPath(rawTarget);
377
+ if (!absolutePath) continue;
378
+
379
+ const before = snapshotFile(absolutePath);
380
+ const entry: CheckpointJournalEntry = {
381
+ id: newId(),
382
+ ts: Date.now(),
383
+ type: 'file',
384
+ taskId,
385
+ step: safeMeta.step == null ? null : safeMeta.step,
386
+ tool: toolName,
387
+ path: absolutePath,
388
+ before
389
+ };
390
+ appendJournal(entry);
391
+ ids.push(entry.id);
392
+ }
393
+ } catch (e: unknown) {
394
+ debugLog(`checkpoint snapshot skipped: ${e instanceof Error ? e.message : String(e)}`);
395
+ }
396
+ return ids;
397
+ }
398
+
399
+ interface StatCacheRecord {
400
+ mtimeMs: number;
401
+ size: number;
402
+ hash: string;
403
+ }
404
+
405
+ function loadStatCache(): Record<string, StatCacheRecord> {
406
+ try {
407
+ const cf = statCacheFile();
408
+ const stat = fs.lstatSync(cf);
409
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > 16 * 1024 * 1024) return {};
410
+ const parsed = JSON.parse(fs.readFileSync(cf, 'utf8')) as unknown;
411
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return {};
412
+ const clean: Record<string, StatCacheRecord> = Object.create(null);
413
+ for (const [key, rec] of Object.entries(parsed as Record<string, unknown>)) {
414
+ if (key === '__proto__' || key === 'constructor' || key === 'prototype') continue;
415
+ if (
416
+ rec && typeof rec === 'object' && !Array.isArray(rec)
417
+ && typeof (rec as Record<string, unknown>).mtimeMs === 'number'
418
+ && typeof (rec as Record<string, unknown>).size === 'number'
419
+ && isValidSha256((rec as Record<string, unknown>).hash)
420
+ ) {
421
+ clean[key] = rec as StatCacheRecord;
422
+ }
423
+ }
424
+ return clean;
425
+ } catch {
426
+ return {};
427
+ }
428
+ }
429
+
430
+ function saveStatCache(cache: Record<string, StatCacheRecord>): void {
431
+ const cf = statCacheFile();
432
+ const temp = `${cf}.tmp_${process.pid}_${crypto.randomBytes(6).toString('hex')}`;
433
+ try {
434
+ try {
435
+ const existing = fs.lstatSync(cf);
436
+ if (existing.isSymbolicLink() || !existing.isFile()) return;
437
+ } catch (err: unknown) {
438
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
439
+ if (code !== 'ENOENT') return;
440
+ }
441
+ const payload = Buffer.from(JSON.stringify(cache), 'utf8');
442
+ const fd = fs.openSync(temp, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
443
+ try {
444
+ fs.writeSync(fd, payload, 0, payload.length);
445
+ fs.fsyncSync(fd);
446
+ } finally {
447
+ fs.closeSync(fd);
448
+ }
449
+ atomicRenameSync(temp, cf);
450
+ } catch {
451
+ try { if (fs.existsSync(temp)) fs.unlinkSync(temp); } catch { /* ignore */ }
452
+ }
453
+ }
454
+
455
+ function snapshotTree(root: string): { manifest: TreeManifest | null; skipped: string | null } {
456
+ const cache = loadStatCache();
457
+ const causyneIgnore = loadWorkspaceIgnoreMatcher(root, { includeGitIgnore: false });
458
+ const files: Record<string, SnapshotRecord> = {};
459
+ let fileCount = 0;
460
+ let totalBytes = 0;
461
+ const stack: string[] = [root];
462
+
463
+ while (stack.length > 0) {
464
+ const dir = stack.pop()!;
465
+ let entries: fs.Dirent[];
466
+ try {
467
+ entries = fs.readdirSync(dir, { withFileTypes: true });
468
+ } catch {
469
+ continue;
470
+ }
471
+
472
+ for (const entry of entries) {
473
+ const full = path.join(dir, entry.name);
474
+
475
+ if (entry.isDirectory()) {
476
+ if (IGNORED_DIRECTORIES.has(entry.name) || causyneIgnore.isIgnored(full, true)) continue;
477
+ stack.push(full);
478
+ continue;
479
+ }
480
+ if (causyneIgnore.isIgnored(full, false)) continue;
481
+ if (entry.isSymbolicLink()) {
482
+ try { files[full] = { kind: 'symlink', target: fs.readlinkSync(full) }; } catch { /* ignore */ }
483
+ continue;
484
+ }
485
+ if (!entry.isFile()) continue;
486
+
487
+ let stats: fs.Stats;
488
+ try { stats = fs.lstatSync(full); } catch { continue; }
489
+ if (stats.isSymbolicLink() || !stats.isFile()) continue;
490
+ if (stats.size > MAX_TREE_FILE_BYTES) continue;
491
+
492
+ fileCount++;
493
+ totalBytes += stats.size;
494
+ if (fileCount > MAX_TREE_FILES) return { manifest: null, skipped: 'too_many_files' };
495
+ if (totalBytes > MAX_TREE_BYTES) return { manifest: null, skipped: 'workspace_too_large' };
496
+
497
+ const cached = Object.hasOwn(cache, full) ? cache[full] : undefined;
498
+ if (cached && isValidSha256(cached.hash) && cached.mtimeMs === stats.mtimeMs && cached.size === stats.size
499
+ && fs.existsSync(objectPath(cached.hash))) {
500
+ files[full] = { kind: 'file', hash: cached.hash, size: stats.size, mode: stats.mode & 0o777 };
501
+ continue;
502
+ }
503
+
504
+ try {
505
+ const hash = writeObject(fs.readFileSync(full));
506
+ files[full] = { kind: 'file', hash, size: stats.size, mode: stats.mode & 0o777 };
507
+ cache[full] = { mtimeMs: stats.mtimeMs, size: stats.size, hash };
508
+ } catch {
509
+ // vanished mid-walk
510
+ }
511
+ }
512
+ }
513
+
514
+ saveStatCache(cache);
515
+ return { manifest: { root, files, fileCount, totalBytes }, skipped: null };
516
+ }
517
+
518
+ const PROJECT_MARKERS = [
519
+ '.git', 'package.json', 'pyproject.toml', 'go.mod', 'Cargo.toml',
520
+ 'pom.xml', 'build.gradle', 'build.gradle.kts', 'Gemfile', 'composer.json',
521
+ 'requirements.txt', 'CMakeLists.txt', 'Makefile'
522
+ ];
523
+
524
+ function isSnapshotableRoot(dir: unknown): boolean {
525
+ if (typeof dir !== 'string' || !dir.trim() || dir.includes('\0')) return false;
526
+ let resolved: string;
527
+ try {
528
+ resolved = path.resolve(dir);
529
+ } catch {
530
+ return false;
531
+ }
532
+
533
+ const home = os.homedir();
534
+ const parsed = path.parse(resolved);
535
+
536
+ if (resolved === parsed.root) return false;
537
+ if (home && path.resolve(home) === resolved) return false;
538
+
539
+ const forbidden = ['/Users', '/home', '/Users/Shared', '/var', '/tmp', '/private/tmp', '/etc', '/opt', '/usr'];
540
+ if (forbidden.includes(resolved)) return false;
541
+ if (isBlockedWorkspaceRoot(resolved)) return false;
542
+
543
+ return true;
544
+ }
545
+
546
+ export function resolveProjectRoot(startDir?: string): string | null {
547
+ let current: string;
548
+ try {
549
+ current = path.resolve(startDir || process.cwd());
550
+ } catch {
551
+ return null;
552
+ }
553
+
554
+ const home = os.homedir() ? path.resolve(os.homedir()) : null;
555
+ const stop = path.parse(current).root;
556
+
557
+ let nearestMarker: string | null = null;
558
+
559
+ for (let depth = 0; depth < 40; depth++) {
560
+ if (!isSnapshotableRoot(current)) break;
561
+
562
+ try {
563
+ if (fs.existsSync(path.join(current, '.git'))) return current;
564
+ } catch { /* ignore */ }
565
+
566
+ if (!nearestMarker) {
567
+ for (const marker of PROJECT_MARKERS) {
568
+ if (marker === '.git') continue;
569
+ try {
570
+ if (fs.existsSync(path.join(current, marker))) { nearestMarker = current; break; }
571
+ } catch { /* ignore */ }
572
+ }
573
+ }
574
+
575
+ const parent = path.dirname(current);
576
+ if (parent === current || current === stop) break;
577
+ if (home && parent === home) break;
578
+ current = parent;
579
+ }
580
+
581
+ return nearestMarker && isSnapshotableRoot(nearestMarker) ? nearestMarker : null;
582
+ }
583
+
584
+ function gitRootFor(root: string): string | null {
585
+ try {
586
+ if (!gitBackend.isGitAvailable()) return null;
587
+ const worktree = gitBackend.resolveWorktree(root);
588
+ if (!worktree || path.resolve(worktree) !== path.resolve(root)) return null;
589
+ return worktree;
590
+ } catch (e: unknown) {
591
+ debugLog(`git checkpoint unavailable for ${root}: ${e instanceof Error ? e.message : String(e)}`);
592
+ return null;
593
+ }
594
+ }
595
+
596
+ function gitTreeChanges(
597
+ tree: CheckpointJournalEntry,
598
+ _undoTaskId: string,
599
+ dryRun: boolean,
600
+ applyFull: boolean
601
+ ): { driftFiles: string[]; results: Array<{ path: string; action: string; ok: boolean }> } | null {
602
+ if (!tree.root || !tree.gitTree) return null;
603
+ try {
604
+ const changes = gitBackend.previewRestore(tree.root, tree.gitTree);
605
+ const driftFiles = changes.map((c) => c.path);
606
+
607
+ if (!applyFull || dryRun) {
608
+ return {
609
+ driftFiles,
610
+ results: changes.map((c) => ({
611
+ path: path.join(tree.root!, c.path),
612
+ action: c.status === 'deleted' ? 'removed' : 'restored',
613
+ ok: true
614
+ }))
615
+ };
616
+ }
617
+
618
+ gitBackend.restoreTree(tree.root, tree.gitTree);
619
+ return {
620
+ driftFiles,
621
+ results: changes.map((c) => ({
622
+ path: path.join(tree.root!, c.path),
623
+ action: c.status === 'deleted' ? 'removed' : 'restored',
624
+ ok: true
625
+ }))
626
+ };
627
+ } catch (e: unknown) {
628
+ debugLog(`git restore unavailable for ${tree.root}: ${e instanceof Error ? e.message : String(e)}`);
629
+ return null;
630
+ }
631
+ }
632
+
633
+ export async function beginTask(
634
+ meta: { taskId?: string | undefined; prompt?: unknown; sessionId?: string | null | undefined; workspaceRoots?: unknown[] | undefined } = {}
635
+ ): Promise<string | null> {
636
+ if (!isCheckpointingEnabled()) return null;
637
+ const taskId = meta.taskId || 'unknown';
638
+
639
+ try {
640
+ ensureStore();
641
+
642
+ let history: HistorySnapshot | null = null;
643
+ const historyFile = activeHistoryFile(meta.sessionId);
644
+ if (fs.existsSync(historyFile)) {
645
+ const buffer = fs.readFileSync(historyFile);
646
+ history = { hash: writeObject(buffer), size: buffer.length, file: historyFile };
647
+ }
648
+
649
+ appendJournal({
650
+ id: newId(),
651
+ ts: Date.now(),
652
+ type: 'task_start',
653
+ taskId,
654
+ prompt: typeof meta.prompt === 'string' ? meta.prompt.slice(0, 200) : null,
655
+ history
656
+ });
657
+
658
+ const roots = (meta.workspaceRoots || [])
659
+ .filter((root): root is string => typeof root === 'string' && root.length > 0)
660
+ .filter((root, index, all) => all.indexOf(root) === index)
661
+ .filter((root) => isSnapshotableRoot(root))
662
+ .slice(0, 3);
663
+
664
+ for (const root of roots) {
665
+ if (!fs.existsSync(root)) continue;
666
+
667
+ const gitWorktree = gitRootFor(root);
668
+ let gitTree: string | null = null;
669
+ if (gitWorktree) {
670
+ try {
671
+ gitTree = await gitBackend.captureTreeAsync(gitWorktree);
672
+ } catch (e: unknown) {
673
+ debugLog(`git capture failed for ${root}: ${e instanceof Error ? e.message : String(e)}`);
674
+ }
675
+ }
676
+ if (gitTree) {
677
+ appendJournal({
678
+ id: newId(),
679
+ ts: Date.now(),
680
+ type: 'tree',
681
+ taskId,
682
+ root,
683
+ skipped: null,
684
+ backend: 'git',
685
+ gitTree,
686
+ manifestHash: null,
687
+ fileCount: 0,
688
+ totalBytes: 0
689
+ });
690
+ continue;
691
+ }
692
+
693
+ const { manifest, skipped } = snapshotTree(root);
694
+ appendJournal({
695
+ id: newId(),
696
+ ts: Date.now(),
697
+ type: 'tree',
698
+ taskId,
699
+ root,
700
+ skipped,
701
+ manifestHash: manifest ? writeObject(Buffer.from(JSON.stringify(manifest), 'utf8')) : null,
702
+ fileCount: manifest ? manifest.fileCount : 0,
703
+ totalBytes: manifest ? manifest.totalBytes : 0
704
+ });
705
+ }
706
+
707
+ return taskId;
708
+ } catch (e: unknown) {
709
+ debugLog(`checkpoint task snapshot skipped: ${e instanceof Error ? e.message : String(e)}`);
710
+ return null;
711
+ }
712
+ }
713
+
714
+ function assertSafeTarget(absolutePath: string): void {
715
+ if (typeof absolutePath !== 'string' || !absolutePath || absolutePath.includes('\0')) {
716
+ throw new Error('refusing an invalid checkpoint target path');
717
+ }
718
+ if (!path.isAbsolute(absolutePath)) {
719
+ throw new Error(`refusing a non-absolute path: ${absolutePath}`);
720
+ }
721
+ if (absolutePath !== path.resolve(absolutePath)) {
722
+ throw new Error(`refusing an unnormalised path: ${absolutePath}`);
723
+ }
724
+
725
+ try {
726
+ const stats = fs.lstatSync(absolutePath);
727
+ if (stats.isSymbolicLink()) {
728
+ throw new Error(`refusing to write through a symlink: ${absolutePath}`);
729
+ }
730
+ if (stats.isFile() && stats.nlink > 1) {
731
+ throw new Error(`refusing to write through a hardlink (${stats.nlink} links): ${absolutePath}`);
732
+ }
733
+ } catch (err: unknown) {
734
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
735
+ if (code !== 'ENOENT') throw err;
736
+ }
737
+
738
+ // Walk existing ancestors to refuse symlinked parent directories (allowing only
739
+ // canonical macOS OS-level /var and /tmp symlinks into /private).
740
+ let ancestor = path.dirname(absolutePath);
741
+ for (let depth = 0; depth < 128; depth++) {
742
+ const parent = path.dirname(ancestor);
743
+ if (parent === ancestor) break;
744
+ try {
745
+ const aStat = fs.lstatSync(ancestor);
746
+ if (aStat.isSymbolicLink()) {
747
+ const isDarwinOsLink = process.platform === 'darwin' && (ancestor === '/var' || ancestor === '/tmp');
748
+ if (!isDarwinOsLink) {
749
+ throw new Error(`refusing to write through a symlink ancestor: ${ancestor}`);
750
+ }
751
+ }
752
+ } catch (err: unknown) {
753
+ const code = typeof err === 'object' && err !== null && 'code' in err ? String(err.code) : '';
754
+ if (code !== 'ENOENT') throw err;
755
+ }
756
+ ancestor = parent;
757
+ }
758
+
759
+ const realTarget = physicalPath(absolutePath);
760
+ if (!realTarget) {
761
+ throw new Error(`refusing to write through a symlink or unresolvable path: ${absolutePath}`);
762
+ }
763
+ if (isProtectedPhysicalPath(absolutePath) || isProtectedPhysicalPath(realTarget)) {
764
+ throw new Error(`refusing to write into a protected system path: ${absolutePath}`);
765
+ }
766
+ }
767
+
768
+ function restoreFileState(absolutePath: string, before: SnapshotRecord | null | undefined): string {
769
+ assertSafeTarget(absolutePath);
770
+
771
+ if (before === null || before === undefined) {
772
+ if (fs.existsSync(absolutePath)) fs.rmSync(absolutePath, { recursive: true, force: true });
773
+ return 'removed';
774
+ }
775
+ if (before.kind === 'symlink') {
776
+ if (typeof before.target !== 'string' || !before.target || before.target.includes('\0')) {
777
+ throw new Error('refusing to restore symlink with invalid target');
778
+ }
779
+ try { fs.lstatSync(absolutePath); fs.unlinkSync(absolutePath); } catch { /* nothing there */ }
780
+ fs.symlinkSync(before.target, absolutePath);
781
+ return 'restored symlink';
782
+ }
783
+ if (before.kind === 'directory') {
784
+ fs.mkdirSync(absolutePath, { recursive: true });
785
+ return 'restored directory';
786
+ }
787
+ if (before.kind !== 'file') return 'skipped (not a regular file)';
788
+ if (before.skipped || !before.hash || !isValidSha256(before.hash)) {
789
+ return `skipped (${before.skipped || 'missing_hash'})`;
790
+ }
791
+
792
+ const buffer = readObject(before.hash);
793
+ fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
794
+ const temp = `${absolutePath}.causyne_restore_${process.pid}_${crypto.randomBytes(6).toString('hex')}`;
795
+ try {
796
+ const fd = fs.openSync(temp, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, before.mode || 0o644);
797
+ try {
798
+ fs.writeSync(fd, buffer, 0, buffer.length);
799
+ fs.fsyncSync(fd);
800
+ } finally {
801
+ fs.closeSync(fd);
802
+ }
803
+ atomicRenameSync(temp, absolutePath);
804
+ } catch (err: unknown) {
805
+ try { if (fs.existsSync(temp)) fs.unlinkSync(temp); } catch { /* ignore */ }
806
+ throw err;
807
+ }
808
+ return 'restored';
809
+ }
810
+
811
+ export function diffTree(
812
+ treeEntry: CheckpointJournalEntry | null | undefined
813
+ ): { modified: string[]; created: string[]; deleted: string[]; manifest: TreeManifest } | null {
814
+ if (!treeEntry || !treeEntry.manifestHash || treeEntry.skipped) return null;
815
+
816
+ let manifest: TreeManifest;
817
+ try {
818
+ manifest = JSON.parse(readObject(treeEntry.manifestHash).toString('utf8')) as TreeManifest;
819
+ } catch {
820
+ return null;
821
+ }
822
+
823
+ const modified: string[] = [];
824
+ const deleted: string[] = [];
825
+ const known = new Set(Object.keys(manifest.files || {}));
826
+
827
+ for (const [absolutePath, record] of Object.entries(manifest.files || {})) {
828
+ if (record.kind !== 'file' || record.skipped) continue;
829
+ let stats: fs.Stats;
830
+ try {
831
+ stats = fs.lstatSync(absolutePath);
832
+ } catch {
833
+ deleted.push(absolutePath);
834
+ continue;
835
+ }
836
+ if (stats.isSymbolicLink() || !stats.isFile()) continue;
837
+ if (stats.size !== record.size) { modified.push(absolutePath); continue; }
838
+ try {
839
+ if (sha256(fs.readFileSync(absolutePath)) !== record.hash) modified.push(absolutePath);
840
+ } catch {
841
+ // unreadable now: leave it alone rather than guess
842
+ }
843
+ }
844
+
845
+ const created: string[] = [];
846
+ const { manifest: current } = snapshotTree(manifest.root);
847
+ if (current) {
848
+ for (const absolutePath of Object.keys(current.files)) {
849
+ if (!known.has(absolutePath)) created.push(absolutePath);
850
+ }
851
+ }
852
+
853
+ return { modified, created, deleted, manifest };
854
+ }
855
+
856
+ function restoreFromTree(
857
+ treeEntry: CheckpointJournalEntry,
858
+ undoTaskId: string,
859
+ dryRun: boolean
860
+ ): Array<{ path: string; action: string }> {
861
+ const diff = diffTree(treeEntry);
862
+ if (!diff) return [];
863
+
864
+ const results: Array<{ path: string; action: string }> = [];
865
+ const apply = (absolutePath: string, before: SnapshotRecord | null | undefined, label: string): void => {
866
+ if (dryRun) {
867
+ results.push({ path: absolutePath, action: `would ${label}` });
868
+ return;
869
+ }
870
+ try {
871
+ const current = snapshotFile(absolutePath);
872
+ appendJournal({
873
+ id: newId(), ts: Date.now(), type: 'file', taskId: undoTaskId,
874
+ step: null, tool: 'undo-tree', path: absolutePath, before: current
875
+ });
876
+ results.push({ path: absolutePath, action: restoreFileState(absolutePath, before) });
877
+ } catch (e: unknown) {
878
+ results.push({ path: absolutePath, action: `FAILED: ${e instanceof Error ? e.message : String(e)}` });
879
+ }
880
+ };
881
+
882
+ for (const absolutePath of [...diff.modified, ...diff.deleted]) {
883
+ apply(absolutePath, diff.manifest.files[absolutePath], 'restore');
884
+ }
885
+ for (const absolutePath of diff.created) {
886
+ apply(absolutePath, null, 'remove');
887
+ }
888
+ return results;
889
+ }
890
+
891
+ export function isUndoable(group: CheckpointGroup | null | undefined): boolean {
892
+ if (!group) return false;
893
+ return group.fileEntries.length > 0 || group.trees.some((tree) => !tree.skipped);
894
+ }
895
+
896
+ export function listGroups(limit = 20): CheckpointGroup[] {
897
+ const safeLimit = typeof limit === 'number' && Number.isFinite(limit)
898
+ ? Math.max(1, Math.min(10_000, Math.floor(limit)))
899
+ : 20;
900
+ const entries = readJournal();
901
+ const byTask = new Map<string, { taskId: string; ts: number; entries: CheckpointJournalEntry[]; prompt: string | null }>();
902
+
903
+ for (const entry of entries) {
904
+ const entryTs = typeof entry.ts === 'number' && Number.isFinite(entry.ts) ? entry.ts : 0;
905
+ if (!byTask.has(entry.taskId)) {
906
+ byTask.set(entry.taskId, { taskId: entry.taskId, ts: entryTs, entries: [], prompt: null });
907
+ }
908
+ const group = byTask.get(entry.taskId)!;
909
+ group.ts = Math.max(group.ts, entryTs);
910
+ if (entry.type === 'task_start' && entry.prompt) group.prompt = entry.prompt;
911
+ group.entries.push(entry);
912
+ }
913
+
914
+ return [...byTask.values()]
915
+ .sort((a, b) => b.ts - a.ts)
916
+ .slice(0, safeLimit)
917
+ .map(group => ({
918
+ ...group,
919
+ fileEntries: group.entries.filter(e => e.type === 'file'),
920
+ hasHistory: group.entries.some(e => e.type === 'task_start' && Boolean(e.history)),
921
+ trees: group.entries.filter(e => e.type === 'tree')
922
+ }));
923
+ }
924
+
925
+ export function undoTask(taskId: string, options: UndoOptions = {}): any {
926
+ const dryRun = options.dryRun !== false;
927
+ const groups = listGroups(1000);
928
+ const group = groups.find(g => g.taskId === taskId);
929
+ if (!group) return { ok: false, error: `no checkpoint group for task "${taskId}"` };
930
+
931
+ const results: Array<{ path: string; action: string; ok?: boolean }> = [];
932
+ const undoTaskId = `undo_${Date.now().toString(36)}`;
933
+
934
+ const earliest = new Map<string, CheckpointJournalEntry>();
935
+ for (const entry of [...group.fileEntries].sort((a, b) => a.ts - b.ts)) {
936
+ if (entry.path && !earliest.has(entry.path)) earliest.set(entry.path, entry);
937
+ }
938
+
939
+ const wantsFiles = options.scope !== 'conversation';
940
+ const wantsHistory = options.scope !== 'code';
941
+
942
+ for (const entry of (wantsFiles ? earliest.values() : [])) {
943
+ if (!entry.path) continue;
944
+ if (dryRun) {
945
+ results.push({ path: entry.path, action: entry.before === null ? 'would remove' : 'would restore' });
946
+ continue;
947
+ }
948
+ try {
949
+ const current = snapshotFile(entry.path);
950
+ appendJournal({
951
+ id: newId(), ts: Date.now(), type: 'file', taskId: undoTaskId,
952
+ step: null, tool: 'undo', path: entry.path, before: current
953
+ });
954
+
955
+ const action = restoreFileState(entry.path, entry.before);
956
+ results.push({ path: entry.path, action });
957
+ } catch (e: unknown) {
958
+ results.push({ path: entry.path, action: `FAILED: ${e instanceof Error ? e.message : String(e)}` });
959
+ }
960
+ }
961
+
962
+ let historyRestored = false;
963
+ const start = group.entries.find(e => e.type === 'task_start' && e.history);
964
+
965
+ if (start && start.history && !dryRun && wantsHistory) {
966
+ const target = start.history.file || legacyHistoryFile();
967
+ try {
968
+ const root = causyneHome();
969
+ const resolved = path.resolve(target);
970
+ const realRoot = physicalPath(root);
971
+ const realTarget = physicalPath(resolved);
972
+ if (!realRoot || !realTarget || !isWithinPhysicalPath(realTarget, realRoot)) {
973
+ throw new Error('conversation snapshot points outside the Causyne state directory');
974
+ }
975
+
976
+ if (fs.existsSync(resolved)) {
977
+ const curStat = fs.lstatSync(resolved);
978
+ if (!curStat.isSymbolicLink() && curStat.isFile()) {
979
+ const buffer = fs.readFileSync(resolved);
980
+ appendJournal({
981
+ id: newId(), ts: Date.now(), type: 'task_start', taskId: undoTaskId,
982
+ prompt: 'undo restore point',
983
+ history: { hash: writeObject(buffer), size: buffer.length, file: resolved }
984
+ });
985
+ }
986
+ }
987
+ const snapshot = readObject(start.history.hash);
988
+ if (path.extname(resolved) === '.jsonl') {
989
+ historyRestored = restoreSessionFromSnapshot(resolved, snapshot);
990
+ if (!historyRestored) throw new Error('conversation journal snapshot could not be projected');
991
+ } else {
992
+ assertSafeTarget(resolved);
993
+ fs.mkdirSync(path.dirname(resolved), { recursive: true, mode: 0o700 });
994
+ const temp = `${resolved}.tmp_${process.pid}_${crypto.randomBytes(6).toString('hex')}`;
995
+ try {
996
+ const fd = fs.openSync(temp, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600);
997
+ try {
998
+ fs.writeSync(fd, snapshot, 0, snapshot.length);
999
+ fs.fsyncSync(fd);
1000
+ } finally {
1001
+ fs.closeSync(fd);
1002
+ }
1003
+ atomicRenameSync(temp, resolved);
1004
+ } catch (writeErr: unknown) {
1005
+ try { if (fs.existsSync(temp)) fs.unlinkSync(temp); } catch { /* ignore */ }
1006
+ throw writeErr;
1007
+ }
1008
+ historyRestored = true;
1009
+ }
1010
+ } catch (e: unknown) {
1011
+ results.push({ path: target, action: `FAILED: ${e instanceof Error ? e.message : String(e)}` });
1012
+ }
1013
+ }
1014
+
1015
+ const drift: Array<{ root: string; files: string[] }> = [];
1016
+ const treeResults: Array<{ path: string; action: string; ok?: boolean }> = [];
1017
+ for (const tree of (wantsFiles ? group.trees : [])) {
1018
+ if (tree.skipped || !tree.root) continue;
1019
+
1020
+ if (tree.backend === 'git' && tree.gitTree) {
1021
+ const gitChanges = gitTreeChanges(tree, undoTaskId, dryRun, options.full === true);
1022
+ if (gitChanges) {
1023
+ if (options.full) treeResults.push(...gitChanges.results);
1024
+ else if (gitChanges.driftFiles.length > 0) {
1025
+ drift.push({ root: tree.root, files: gitChanges.driftFiles });
1026
+ }
1027
+ continue;
1028
+ }
1029
+ }
1030
+
1031
+ if (options.full) {
1032
+ treeResults.push(...restoreFromTree(tree, undoTaskId, dryRun));
1033
+ continue;
1034
+ }
1035
+ const diff = diffTree(tree);
1036
+ if (!diff) continue;
1037
+ const untracked = [...diff.modified, ...diff.created, ...diff.deleted]
1038
+ .filter(p => !earliest.has(p));
1039
+ if (untracked.length > 0) drift.push({ root: tree.root, files: untracked });
1040
+ }
1041
+
1042
+ if (!dryRun) {
1043
+ try {
1044
+ appendJournal({
1045
+ id: newId(),
1046
+ ts: Date.now(),
1047
+ type: 'undo_marker',
1048
+ taskId: undoTaskId,
1049
+ targetTaskId: taskId,
1050
+ undoTaskId
1051
+ });
1052
+ } catch { /* best-effort marker */ }
1053
+ }
1054
+
1055
+ return {
1056
+ ok: true,
1057
+ taskId,
1058
+ undoTaskId: dryRun ? null : undoTaskId,
1059
+ dryRun,
1060
+ full: options.full === true,
1061
+ results: [...results, ...treeResults],
1062
+ historyRestored,
1063
+ historyAvailable: Boolean(start),
1064
+ scope: options.scope || 'both',
1065
+ drift,
1066
+ skippedTrees: group.trees.filter(t => t.skipped).map(t => ({ root: t.root, reason: t.skipped }))
1067
+ };
1068
+ }
1069
+
1070
+ function collectUndoneTaskIds(): { undone: Set<string>; redoStack: Array<{ targetTaskId: string; undoTaskId: string }> } {
1071
+ const undone = new Set<string>();
1072
+ const redoStack: Array<{ targetTaskId: string; undoTaskId: string }> = [];
1073
+ for (const entry of readJournal()) {
1074
+ if (entry.type === 'undo_marker' && entry.targetTaskId && entry.undoTaskId) {
1075
+ undone.add(entry.targetTaskId);
1076
+ redoStack.push({ targetTaskId: entry.targetTaskId, undoTaskId: entry.undoTaskId });
1077
+ } else if (entry.type === 'redo_marker' && entry.targetTaskId) {
1078
+ undone.delete(entry.targetTaskId);
1079
+ const idx = redoStack.findLastIndex((item) => item.targetTaskId === entry.targetTaskId);
1080
+ if (idx !== -1) redoStack.splice(idx, 1);
1081
+ }
1082
+ }
1083
+ return { undone, redoStack };
1084
+ }
1085
+
1086
+ export function redoLast(options?: UndoOptions | null): any {
1087
+ const safeOptions: UndoOptions = options && typeof options === 'object' ? options : {};
1088
+ const dryRun = safeOptions.dryRun !== false;
1089
+ const { redoStack } = collectUndoneTaskIds();
1090
+ const top = redoStack.at(-1);
1091
+ if (!top) {
1092
+ return { ok: false, error: 'nothing to redo — no undone checkpoint is pending' };
1093
+ }
1094
+ const applied = undoTask(top.undoTaskId, { ...safeOptions, dryRun });
1095
+ if (applied.ok && !dryRun) {
1096
+ try {
1097
+ appendJournal({
1098
+ id: newId(),
1099
+ ts: Date.now(),
1100
+ type: 'redo_marker',
1101
+ taskId: `redo_${Date.now().toString(36)}`,
1102
+ targetTaskId: top.targetTaskId,
1103
+ undoTaskId: top.undoTaskId
1104
+ });
1105
+ } catch { /* best-effort marker */ }
1106
+ }
1107
+ return { ...applied, redoneTaskId: top.targetTaskId };
1108
+ }
1109
+
1110
+ export function undoLast(options?: UndoOptions | null): any {
1111
+ const safeOptions: UndoOptions = options && typeof options === 'object' ? options : {};
1112
+ const hasExplicitWorkspace = typeof safeOptions.workspaceRoot === 'string' && safeOptions.workspaceRoot.trim().length > 0;
1113
+ const ws = hasExplicitWorkspace ? path.resolve(safeOptions.workspaceRoot!) : path.resolve(process.cwd());
1114
+ const { undone } = collectUndoneTaskIds();
1115
+ const allCandidates = listGroups(200).filter((group) =>
1116
+ !group.taskId.startsWith('undo_')
1117
+ && !group.taskId.startsWith('redo_')
1118
+ && !undone.has(group.taskId)
1119
+ && isUndoable(group));
1120
+
1121
+ const validCandidates = allCandidates.filter((group) => {
1122
+ const allPaths = [
1123
+ ...group.trees.map((t) => t.root).filter((p): p is string => Boolean(p)),
1124
+ ...group.fileEntries.map((e) => e.path).filter((p): p is string => Boolean(p))
1125
+ ];
1126
+ if (allPaths.length > 0 && allPaths.every((p) => (p.startsWith('/var/folders/') || p.startsWith('/tmp/')) && !fs.existsSync(p))) {
1127
+ return false;
1128
+ }
1129
+ return true;
1130
+ });
1131
+
1132
+ const workspaceCandidates = validCandidates.filter((group) => {
1133
+ const matchesTree = group.trees.some((t) => t.root && (t.root === ws || ws.startsWith(t.root + path.sep) || t.root.startsWith(ws + path.sep)));
1134
+ const matchesFile = group.fileEntries.some((e) => e.path && (e.path.startsWith(ws + path.sep) || e.path === ws));
1135
+ return matchesTree || matchesFile;
1136
+ });
1137
+
1138
+ const candidates = hasExplicitWorkspace
1139
+ ? workspaceCandidates
1140
+ : (workspaceCandidates.length > 0 ? workspaceCandidates : validCandidates);
1141
+
1142
+ if (candidates.length === 0) {
1143
+ return { ok: false, error: 'nothing has been checkpointed yet — no task has run in this workspace' };
1144
+ }
1145
+ return undoTask(candidates[0]!.taskId, safeOptions);
1146
+ }
1147
+
1148
+ export function undoStep(options?: UndoOptions | null): any {
1149
+ const safeOptions: UndoOptions = options && typeof options === 'object' ? options : {};
1150
+ const dryRun = safeOptions.dryRun !== false;
1151
+ const hasExplicitWorkspace = typeof safeOptions.workspaceRoot === 'string' && safeOptions.workspaceRoot.trim().length > 0;
1152
+ const ws = hasExplicitWorkspace ? path.resolve(safeOptions.workspaceRoot!) : null;
1153
+ const entries = readJournal().filter(e => {
1154
+ if (e.type !== 'file' || e.tool === 'undo' || !e.path) return false;
1155
+ if (ws && e.path !== ws && !e.path.startsWith(ws + path.sep)) return false;
1156
+ return true;
1157
+ });
1158
+ if (entries.length === 0) return { ok: false, error: 'no file mutation has been checkpointed yet' };
1159
+
1160
+ const entry = entries[entries.length - 1]!;
1161
+ const targetPath = entry.path!;
1162
+ if (dryRun) {
1163
+ return { ok: true, dryRun, results: [{ path: targetPath, action: entry.before === null ? 'would remove' : 'would restore' }] };
1164
+ }
1165
+
1166
+ try {
1167
+ const current = snapshotFile(targetPath);
1168
+ appendJournal({
1169
+ id: newId(), ts: Date.now(), type: 'file', taskId: `undo_${Date.now().toString(36)}`,
1170
+ step: null, tool: 'undo', path: targetPath, before: current
1171
+ });
1172
+ const action = restoreFileState(targetPath, entry.before);
1173
+ return { ok: true, dryRun: false, results: [{ path: targetPath, action }] };
1174
+ } catch (e: unknown) {
1175
+ return { ok: false, error: e instanceof Error ? e.message : String(e) };
1176
+ }
1177
+ }
1178
+
1179
+ function directorySize(dir: string): number {
1180
+ let total = 0;
1181
+ const stack: string[] = [dir];
1182
+ while (stack.length > 0) {
1183
+ const current = stack.pop()!;
1184
+ let entries: fs.Dirent[];
1185
+ try { entries = fs.readdirSync(current, { withFileTypes: true }); } catch { continue; }
1186
+ for (const entry of entries) {
1187
+ if (entry.isSymbolicLink()) continue;
1188
+ const full = path.join(current, entry.name);
1189
+ if (entry.isDirectory()) { stack.push(full); continue; }
1190
+ try {
1191
+ const stat = fs.lstatSync(full);
1192
+ if (!stat.isSymbolicLink() && stat.isFile()) total += stat.size;
1193
+ } catch {
1194
+ /* ignore */
1195
+ }
1196
+ }
1197
+ }
1198
+ return total;
1199
+ }
1200
+
1201
+ export function pruneStore(): { removedEntries: number; removedObjects: number } {
1202
+ try {
1203
+ const jf = journalFile();
1204
+ const objs = objectsDir();
1205
+ if (!fs.existsSync(jf)) return { removedEntries: 0, removedObjects: 0 };
1206
+
1207
+ let entries = readJournal();
1208
+ const before = entries.length;
1209
+ const cutoff = Date.now() - RETENTION_MS;
1210
+ const overSize = directorySize(objs) > MAX_STORE_BYTES;
1211
+
1212
+ entries = entries.filter(e => e.ts >= cutoff);
1213
+ if (entries.length > MAX_JOURNAL_ENTRIES || overSize) {
1214
+ const keep = overSize ? Math.floor(MAX_JOURNAL_ENTRIES / 2) : MAX_JOURNAL_ENTRIES;
1215
+ entries = entries.slice(-keep);
1216
+ }
1217
+ if (entries.length !== before) rewriteJournal(entries);
1218
+
1219
+ const live = new Set<string>();
1220
+ for (const entry of entries) {
1221
+ if (entry.before && entry.before.kind === 'file' && entry.before.hash) live.add(entry.before.hash);
1222
+ if (entry.history && entry.history.hash) live.add(entry.history.hash);
1223
+ if (entry.manifestHash) {
1224
+ live.add(entry.manifestHash);
1225
+ try {
1226
+ const manifest = JSON.parse(readObject(entry.manifestHash).toString('utf8')) as TreeManifest;
1227
+ for (const record of Object.values(manifest.files || {})) {
1228
+ if (record && record.kind === 'file' && record.hash) live.add(record.hash);
1229
+ }
1230
+ } catch {
1231
+ // an unreadable manifest keeps only itself alive
1232
+ }
1233
+ }
1234
+ }
1235
+
1236
+ let removedObjects = 0;
1237
+ let shards: string[];
1238
+ try { shards = fs.readdirSync(objs); } catch { shards = []; }
1239
+ for (const shard of shards) {
1240
+ const shardDir = path.join(objs, shard);
1241
+ try {
1242
+ const sStat = fs.lstatSync(shardDir);
1243
+ if (sStat.isSymbolicLink() || !sStat.isDirectory()) continue;
1244
+ } catch { continue; }
1245
+ let objects: string[];
1246
+ try { objects = fs.readdirSync(shardDir); } catch { continue; }
1247
+ for (const name of objects) {
1248
+ if (live.has(name)) continue;
1249
+ const objFile = path.join(shardDir, name);
1250
+ try {
1251
+ const oStat = fs.lstatSync(objFile);
1252
+ if (oStat.isSymbolicLink() || !oStat.isFile()) continue;
1253
+ fs.unlinkSync(objFile);
1254
+ removedObjects++;
1255
+ } catch { /* ignore */ }
1256
+ }
1257
+ try { if (fs.readdirSync(shardDir).length === 0) fs.rmdirSync(shardDir); } catch { /* ignore */ }
1258
+ }
1259
+
1260
+ return { removedEntries: before - entries.length, removedObjects };
1261
+ } catch (e: unknown) {
1262
+ debugLog(`checkpoint prune skipped: ${e instanceof Error ? e.message : String(e)}`);
1263
+ return { removedEntries: 0, removedObjects: 0 };
1264
+ }
1265
+ }
1266
+
1267
+ export function getStoreDir(): string {
1268
+ return storeDir();
1269
+ }
1270
+
1271
+ export function getStoreStats(): { dir: string; entries: number; bytes: number } {
1272
+ const objs = objectsDir();
1273
+ return {
1274
+ dir: storeDir(),
1275
+ entries: readJournal().length,
1276
+ bytes: fs.existsSync(objs) ? directorySize(objs) : 0
1277
+ };
1278
+ }
1279
+
1280
+ export function buildTaskDiff(taskId: string): any {
1281
+ const group = listGroups(1000).find((g) => g.taskId === taskId);
1282
+ if (!group) {
1283
+ return { ok: false, taskId: taskId || null, error: 'no checkpoint for that task', files: [] };
1284
+ }
1285
+
1286
+ const files: Array<{
1287
+ path: string;
1288
+ status: string;
1289
+ additions: number;
1290
+ deletions: number;
1291
+ patch: string;
1292
+ truncated: boolean;
1293
+ }> = [];
1294
+
1295
+ for (const tree of group.trees || []) {
1296
+ if (tree.backend !== 'git' || !tree.gitTree || !tree.root) continue;
1297
+ try {
1298
+ for (const change of gitBackend.previewForwardDiff(tree.root, tree.gitTree)) {
1299
+ files.push({
1300
+ path: change.path,
1301
+ status: change.status === 'added' ? 'created' : change.status,
1302
+ additions: change.additions,
1303
+ deletions: change.deletions,
1304
+ patch: change.patch || '',
1305
+ truncated: false
1306
+ });
1307
+ }
1308
+ } catch (e: unknown) {
1309
+ debugLog(`task diff unavailable for ${tree.root}: ${e instanceof Error ? e.message : String(e)}`);
1310
+ }
1311
+ }
1312
+
1313
+ const seen = new Set(files.map((f) => f.path));
1314
+ for (const entry of group.fileEntries || []) {
1315
+ if (!entry.path) continue;
1316
+ const fromCwd = path.relative(process.cwd(), entry.path);
1317
+ const relative = (!fromCwd || fromCwd.startsWith('..'))
1318
+ ? path.basename(entry.path)
1319
+ : fromCwd;
1320
+ if (seen.has(relative)) continue;
1321
+ seen.add(relative);
1322
+
1323
+ let beforeBuffer: Buffer | null = null;
1324
+ if (entry.before && entry.before.kind === 'file' && entry.before.hash && isValidSha256(entry.before.hash)) {
1325
+ try {
1326
+ beforeBuffer = readObject(entry.before.hash);
1327
+ } catch {
1328
+ beforeBuffer = null;
1329
+ }
1330
+ }
1331
+ let afterBuffer: Buffer | null = null;
1332
+ try {
1333
+ const afterStat = fs.lstatSync(entry.path);
1334
+ if (!afterStat.isSymbolicLink() && afterStat.isFile() && afterStat.size <= MAX_FILE_BYTES) {
1335
+ afterBuffer = fs.readFileSync(entry.path);
1336
+ }
1337
+ } catch { /* ignore */ }
1338
+
1339
+ const status = !beforeBuffer ? 'created' : !afterBuffer ? 'deleted' : 'modified';
1340
+
1341
+ if (looksBinary(beforeBuffer) || looksBinary(afterBuffer)) {
1342
+ files.push({
1343
+ path: relative, status, additions: 0, deletions: 0, patch: '', truncated: true
1344
+ });
1345
+ continue;
1346
+ }
1347
+
1348
+ const diff = unifiedDiff(
1349
+ beforeBuffer ? beforeBuffer.toString('utf8') : '',
1350
+ afterBuffer ? afterBuffer.toString('utf8') : '',
1351
+ relative
1352
+ );
1353
+ files.push({
1354
+ path: relative,
1355
+ status,
1356
+ additions: diff.additions,
1357
+ deletions: diff.deletions,
1358
+ patch: diff.patch,
1359
+ truncated: diff.truncated
1360
+ });
1361
+ }
1362
+
1363
+ const totals = files.reduce(
1364
+ (acc, f) => ({ additions: acc.additions + f.additions, deletions: acc.deletions + f.deletions }),
1365
+ { additions: 0, deletions: 0 }
1366
+ );
1367
+
1368
+ return {
1369
+ ok: true,
1370
+ taskId: group.taskId,
1371
+ prompt: group.prompt || null,
1372
+ fileCount: files.length,
1373
+ additions: totals.additions,
1374
+ deletions: totals.deletions,
1375
+ files: files.slice(0, 50)
1376
+ };
1377
+ }