@narumitw/pi-sync 0.61.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (250) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/README.md +24 -17
  3. package/dist/chunks/{chunk-EMVZL4PH.ts → chunk-3E3TR3JE.ts} +4 -4
  4. package/dist/chunks/{chunk-JVFCVPPD.ts → chunk-6PFZUEUG.ts} +41 -18
  5. package/dist/chunks/chunk-6PFZUEUG.ts.map +7 -0
  6. package/dist/chunks/{chunk-ZIL6PW5L.ts → chunk-6YKOHBSC.ts} +2 -2
  7. package/dist/chunks/{chunk-OA4NZLSL.ts → chunk-APZVJAEW.ts} +4 -3
  8. package/dist/chunks/{chunk-4SR3ZYHA.ts → chunk-GELYN4UC.ts} +2 -2
  9. package/dist/chunks/{chunk-S7F4FOAS.ts → chunk-GSCZ4VXV.ts} +5 -5
  10. package/dist/chunks/{chunk-YQSFJLJ3.ts → chunk-IBXEM35O.ts} +4 -3
  11. package/dist/chunks/{chunk-E3YLRLJM.ts → chunk-INECVQNR.ts} +10 -10
  12. package/dist/chunks/{chunk-2JHAN3ZO.ts → chunk-JREGWM2B.ts} +3 -3
  13. package/dist/chunks/{chunk-277VHM2P.ts → chunk-MNYRU5U5.ts} +5 -2
  14. package/dist/chunks/{chunk-277VHM2P.ts.map → chunk-MNYRU5U5.ts.map} +2 -2
  15. package/dist/chunks/{chunk-2ZGV5KNC.ts → chunk-NHFGAZEC.ts} +11 -8
  16. package/dist/chunks/chunk-NHFGAZEC.ts.map +7 -0
  17. package/dist/chunks/{chunk-EMRFVLZM.ts → chunk-NXWHPVXR.ts} +2 -2
  18. package/dist/chunks/{chunk-SMVKMYLK.ts → chunk-P4GI7LTT.ts} +2 -2
  19. package/dist/chunks/{chunk-PJMM75W5.ts → chunk-PWESMTH6.ts} +6 -6
  20. package/dist/chunks/{chunk-ZVGRZD4C.ts → chunk-R3SAMXB6.ts} +2 -2
  21. package/dist/chunks/{chunk-RNIEVDTR.ts → chunk-T3LABNHF.ts} +2 -2
  22. package/dist/chunks/{chunk-S3R3W3KF.ts → chunk-UMPA5S7X.ts} +2 -2
  23. package/dist/chunks/{chunk-WP2M67XZ.ts → chunk-WBIOSK76.ts} +2 -2
  24. package/dist/chunks/{chunk-4KTJLJSJ.ts → chunk-ZB3GNX3P.ts} +11 -11
  25. package/dist/chunks/{chunk-HEB6YT64.ts → chunk-ZO52JM4H.ts} +2 -2
  26. package/dist/chunks/{command-handler-K4XJOGYC.ts → command-handler-6ATREPG7.ts} +16 -16
  27. package/dist/chunks/command-handler-6ATREPG7.ts.map +7 -0
  28. package/dist/chunks/{conflict-review-IGKY2TOJ.ts → conflict-review-MAOGTIAI.ts} +4 -4
  29. package/dist/chunks/{continuous-record-3XDXDOMV.ts → continuous-record-3SKJ6I3V.ts} +2 -2
  30. package/dist/chunks/{continuous-storage-HLKCHF6Z.ts → continuous-storage-3EU6I7Z3.ts} +2 -2
  31. package/dist/chunks/{file-selection-MGGVOKM7.ts → file-selection-QR2KZVGD.ts} +10 -10
  32. package/dist/chunks/manager-result-dispatcher-MC6EQOQY.ts +19 -0
  33. package/dist/chunks/{manager-ui-KYQ5AZJS.ts → manager-ui-AOFUNXAJ.ts} +547 -135
  34. package/dist/chunks/manager-ui-AOFUNXAJ.ts.map +7 -0
  35. package/dist/chunks/remote-selection-ui-4BTP2OJR.ts +18 -0
  36. package/dist/chunks/{setup-switch-D6K6PBPC.ts → setup-switch-Y6AMFFNK.ts} +7 -7
  37. package/dist/chunks/{setup-wizard-4DYUDHJR.ts → setup-wizard-5G426MOZ.ts} +10 -10
  38. package/dist/chunks/{snapshot-5HY3M2NL.ts → snapshot-ZUJJZCFW.ts} +2 -2
  39. package/dist/chunks/{snapshot-transaction-directory-OU2D7R7A.ts → snapshot-transaction-directory-F46JWRAU.ts} +2 -2
  40. package/dist/chunks/{state-directory-XXHU73Z3.ts → state-directory-CMAIF34J.ts} +2 -2
  41. package/dist/chunks/{sync-inspection-J3CRBORL.ts → sync-inspection-ITZ6Z4DE.ts} +5 -5
  42. package/dist/chunks/{sync-operations-BVWYYKH3.ts → sync-operations-NMVKF7SE.ts} +13 -9
  43. package/dist/chunks/sync-operations-NMVKF7SE.ts.map +7 -0
  44. package/dist/chunks/{sync-state-2LMIXJ2C.ts → sync-state-QIT64TKV.ts} +2 -2
  45. package/dist/daemon/LICENSE +21 -0
  46. package/dist/daemon/dist/build-version.js +8 -0
  47. package/dist/daemon/dist/child-sdk.mjs +17 -0
  48. package/dist/daemon/dist/cli.js +169 -0
  49. package/dist/daemon/dist/client.js +909 -0
  50. package/dist/daemon/dist/consent.js +265 -0
  51. package/dist/daemon/dist/document.js +6 -0
  52. package/dist/daemon/dist/endpoint.js +91 -0
  53. package/dist/daemon/dist/engine/backends/backend-factory.js +16 -0
  54. package/dist/daemon/dist/engine/backends/backend-identity.js +38 -0
  55. package/dist/daemon/dist/engine/backends/backend-types.js +1 -0
  56. package/dist/daemon/dist/engine/backends/git/git-backend.js +715 -0
  57. package/dist/daemon/dist/engine/backends/git/git-config.js +118 -0
  58. package/dist/daemon/dist/engine/backends/git/git-runner.js +232 -0
  59. package/dist/daemon/dist/engine/backends/git/git-storage.js +252 -0
  60. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +444 -0
  61. package/dist/daemon/dist/engine/backends/s3/s3-client.js +352 -0
  62. package/dist/daemon/dist/engine/backends/s3/s3-conditions.js +66 -0
  63. package/dist/daemon/dist/engine/backends/snapshot-pointer.js +22 -0
  64. package/dist/daemon/dist/engine/backends/sync-backend.js +23 -0
  65. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +542 -0
  66. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +326 -0
  67. package/dist/daemon/dist/engine/backends/webdav/webdav-config.js +73 -0
  68. package/dist/daemon/dist/engine/commands/command-types.js +1 -0
  69. package/dist/daemon/dist/engine/host.js +16 -0
  70. package/dist/daemon/dist/engine/ignore/effective-ignore-policy.js +33 -0
  71. package/dist/daemon/dist/engine/ignore/ignore-edit.js +102 -0
  72. package/dist/daemon/dist/engine/ignore/ignore-initialization.js +186 -0
  73. package/dist/daemon/dist/engine/ignore/ignore-migration-prompt.js +139 -0
  74. package/dist/daemon/dist/engine/ignore/ignore-settings.js +322 -0
  75. package/dist/daemon/dist/engine/ignore/ignore-source.js +250 -0
  76. package/dist/daemon/dist/engine/paths.js +71 -0
  77. package/dist/daemon/dist/engine/settings/config-errors.js +4 -0
  78. package/dist/daemon/dist/engine/settings/config-file.js +736 -0
  79. package/dist/daemon/dist/engine/settings/config.js +301 -0
  80. package/dist/daemon/dist/engine/settings/settings-management.js +193 -0
  81. package/dist/daemon/dist/engine/settings/settings-store.js +41 -0
  82. package/dist/daemon/dist/engine/settings/settings-types.js +1 -0
  83. package/dist/daemon/dist/engine/settings/settings-validation.js +384 -0
  84. package/dist/daemon/dist/engine/snapshot/session-paths.js +160 -0
  85. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +348 -0
  86. package/dist/daemon/dist/engine/snapshot/snapshot-bounds.js +20 -0
  87. package/dist/daemon/dist/engine/snapshot/snapshot-case-replacement.js +82 -0
  88. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +61 -0
  89. package/dist/daemon/dist/engine/snapshot/snapshot-entry-projection.js +78 -0
  90. package/dist/daemon/dist/engine/snapshot/snapshot-exclude-safety.js +262 -0
  91. package/dist/daemon/dist/engine/snapshot/snapshot-mutation-queues.js +133 -0
  92. package/dist/daemon/dist/engine/snapshot/snapshot-paths.js +11 -0
  93. package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +10 -0
  94. package/dist/daemon/dist/engine/snapshot/snapshot-reviewed-preimages.js +60 -0
  95. package/dist/daemon/dist/engine/snapshot/snapshot-root-transition.js +138 -0
  96. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-directory.js +16 -0
  97. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +387 -0
  98. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-plan.js +68 -0
  99. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-policy.js +276 -0
  100. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-stage.js +303 -0
  101. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-verification.js +78 -0
  102. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +813 -0
  103. package/dist/daemon/dist/engine/snapshot/snapshot-types.js +9 -0
  104. package/dist/daemon/dist/engine/snapshot/snapshot.js +678 -0
  105. package/dist/daemon/dist/engine/state/json-file.js +49 -0
  106. package/dist/daemon/dist/engine/state/lock-policy.js +2 -0
  107. package/dist/daemon/dist/engine/state/lock.js +259 -0
  108. package/dist/daemon/dist/engine/state/lockfile-fs.js +13 -0
  109. package/dist/daemon/dist/engine/state/merge-baseline-store.js +198 -0
  110. package/dist/daemon/dist/engine/state/mutation-directory-sync.js +34 -0
  111. package/dist/daemon/dist/engine/state/operation-availability.js +40 -0
  112. package/dist/daemon/dist/engine/state/state-directory.js +227 -0
  113. package/dist/daemon/dist/engine/state/state-types.js +1 -0
  114. package/dist/daemon/dist/engine/state/sync-state-store.js +54 -0
  115. package/dist/daemon/dist/engine/sync/agent-candidate.js +207 -0
  116. package/dist/daemon/dist/engine/sync/agent-plan.js +84 -0
  117. package/dist/daemon/dist/engine/sync/agent-policy.js +10 -0
  118. package/dist/daemon/dist/engine/sync/agent-refusal-retry.js +39 -0
  119. package/dist/daemon/dist/engine/sync/agent-request.js +13 -0
  120. package/dist/daemon/dist/engine/sync/agent-runner.js +183 -0
  121. package/dist/daemon/dist/engine/sync/agent-store.js +177 -0
  122. package/dist/daemon/dist/engine/sync/agent-sync.js +132 -0
  123. package/dist/daemon/dist/engine/sync/apply-review.js +52 -0
  124. package/dist/daemon/dist/engine/sync/conflict-artifact-ownership.js +53 -0
  125. package/dist/daemon/dist/engine/sync/conflict-artifacts.js +158 -0
  126. package/dist/daemon/dist/engine/sync/conflict-groups.js +76 -0
  127. package/dist/daemon/dist/engine/sync/conflict-preview.js +53 -0
  128. package/dist/daemon/dist/engine/sync/conflict-resolution.js +53 -0
  129. package/dist/daemon/dist/engine/sync/conflict-retention.js +61 -0
  130. package/dist/daemon/dist/engine/sync/conflict-review.js +73 -0
  131. package/dist/daemon/dist/engine/sync/content-conflicts.js +70 -0
  132. package/dist/daemon/dist/engine/sync/continuous-errors.js +66 -0
  133. package/dist/daemon/dist/engine/sync/continuous-lease.js +206 -0
  134. package/dist/daemon/dist/engine/sync/continuous-record.js +199 -0
  135. package/dist/daemon/dist/engine/sync/continuous-storage.js +59 -0
  136. package/dist/daemon/dist/engine/sync/continuous-sync.js +521 -0
  137. package/dist/daemon/dist/engine/sync/continuous-watch.js +140 -0
  138. package/dist/daemon/dist/engine/sync/exclude-policy.js +86 -0
  139. package/dist/daemon/dist/engine/sync/field-migration.js +20 -0
  140. package/dist/daemon/dist/engine/sync/file-merge-planner.js +123 -0
  141. package/dist/daemon/dist/engine/sync/initialization.js +80 -0
  142. package/dist/daemon/dist/engine/sync/json-document.js +172 -0
  143. package/dist/daemon/dist/engine/sync/local-field-policy.js +26 -0
  144. package/dist/daemon/dist/engine/sync/local-fields.js +196 -0
  145. package/dist/daemon/dist/engine/sync/merge-apply.js +529 -0
  146. package/dist/daemon/dist/engine/sync/merge-journal.js +295 -0
  147. package/dist/daemon/dist/engine/sync/merge-transfer-error.js +64 -0
  148. package/dist/daemon/dist/engine/sync/merged-sync.js +674 -0
  149. package/dist/daemon/dist/engine/sync/mutation-owner.js +18 -0
  150. package/dist/daemon/dist/engine/sync/package-merge.js +82 -0
  151. package/dist/daemon/dist/engine/sync/partial-progress.js +41 -0
  152. package/dist/daemon/dist/engine/sync/remote-snapshot.js +104 -0
  153. package/dist/daemon/dist/engine/sync/resolver-stream.js +34 -0
  154. package/dist/daemon/dist/engine/sync/session-merge.js +178 -0
  155. package/dist/daemon/dist/engine/sync/session-push.js +33 -0
  156. package/dist/daemon/dist/engine/sync/settings-conflicts.js +56 -0
  157. package/dist/daemon/dist/engine/sync/settings-merge.js +93 -0
  158. package/dist/daemon/dist/engine/sync/signals.js +8 -0
  159. package/dist/daemon/dist/engine/sync/startup-timings.js +44 -0
  160. package/dist/daemon/dist/engine/sync/sync-decision.js +81 -0
  161. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +55 -0
  162. package/dist/daemon/dist/engine/sync/sync-errors.js +18 -0
  163. package/dist/daemon/dist/engine/sync/sync-inspection.js +42 -0
  164. package/dist/daemon/dist/engine/sync/sync-loaders.js +8 -0
  165. package/dist/daemon/dist/engine/sync/sync-local.js +40 -0
  166. package/dist/daemon/dist/engine/sync/sync-mutations.js +733 -0
  167. package/dist/daemon/dist/engine/sync/sync-operations.js +3 -0
  168. package/dist/daemon/dist/engine/sync/sync-policy.js +621 -0
  169. package/dist/daemon/dist/engine/sync/sync-queries.js +212 -0
  170. package/dist/daemon/dist/engine/sync/sync-state.js +129 -0
  171. package/dist/daemon/dist/engine/sync/text-merge.js +124 -0
  172. package/dist/daemon/dist/engine/types.js +2 -0
  173. package/dist/daemon/dist/engine/ui/merge-review.js +7 -0
  174. package/dist/daemon/dist/engine/ui/merged-sync-summary.js +86 -0
  175. package/dist/daemon/dist/engine/ui/sync-format.js +165 -0
  176. package/dist/daemon/dist/engine/ui/sync-status.js +30 -0
  177. package/dist/daemon/dist/engine/ui/terminal-text.js +9 -0
  178. package/dist/daemon/dist/engine/ui/transfer-changes.js +24 -0
  179. package/dist/daemon/dist/engine/ui/transfer-review.js +19 -0
  180. package/dist/daemon/dist/engine-service.js +344 -0
  181. package/dist/daemon/dist/identity.js +241 -0
  182. package/dist/daemon/dist/idle-exit.js +77 -0
  183. package/dist/daemon/dist/index.js +4 -0
  184. package/dist/daemon/dist/lifecycle-log.js +53 -0
  185. package/dist/daemon/dist/lifecycle.js +21 -0
  186. package/dist/daemon/dist/model-signature.js +7 -0
  187. package/dist/daemon/dist/monitor.js +272 -0
  188. package/dist/daemon/dist/participant-admission.js +30 -0
  189. package/dist/daemon/dist/protocol.js +104 -0
  190. package/dist/daemon/dist/resolver-host.js +78 -0
  191. package/dist/daemon/dist/server.js +953 -0
  192. package/dist/daemon/dist/service-host.js +174 -0
  193. package/dist/daemon/dist/upgrade-repair.js +55 -0
  194. package/dist/daemon/package.json +3 -0
  195. package/dist/index.ts +21 -21
  196. package/dist/package.json +6 -0
  197. package/docs/daemon-migration.md +27 -16
  198. package/package.json +9 -3
  199. package/skills/configure-pi-sync/SKILL.md +38 -13
  200. package/skills/configure-pi-sync/references/configuration.md +2 -2
  201. package/src/commands/command-execution.ts +1 -1
  202. package/src/settings/config.ts +1 -0
  203. package/src/sync/sync-operations.ts +18 -10
  204. package/src/ui/excluded-paths-ui.ts +4 -1
  205. package/src/ui/ignore-file-ui.ts +271 -0
  206. package/src/ui/ignore-migration-prompt.ts +65 -0
  207. package/src/ui/manager-state.ts +27 -13
  208. package/src/ui/manager-ui.ts +38 -19
  209. package/src/ui/remote-selection-ui.ts +41 -8
  210. package/src/ui/settings-review.ts +26 -0
  211. package/src/ui/settings-ui.ts +316 -213
  212. package/src/ui/storage-connections-ui.ts +20 -12
  213. package/src/ui/sync-setups-ui.ts +45 -27
  214. package/dist/chunks/chunk-2ZGV5KNC.ts.map +0 -7
  215. package/dist/chunks/chunk-JVFCVPPD.ts.map +0 -7
  216. package/dist/chunks/command-handler-K4XJOGYC.ts.map +0 -7
  217. package/dist/chunks/manager-result-dispatcher-4VJVDEUD.ts +0 -19
  218. package/dist/chunks/manager-ui-KYQ5AZJS.ts.map +0 -7
  219. package/dist/chunks/remote-selection-ui-W3KOZM3W.ts +0 -18
  220. package/dist/chunks/sync-operations-BVWYYKH3.ts.map +0 -7
  221. /package/dist/chunks/{chunk-EMVZL4PH.ts.map → chunk-3E3TR3JE.ts.map} +0 -0
  222. /package/dist/chunks/{chunk-ZIL6PW5L.ts.map → chunk-6YKOHBSC.ts.map} +0 -0
  223. /package/dist/chunks/{chunk-OA4NZLSL.ts.map → chunk-APZVJAEW.ts.map} +0 -0
  224. /package/dist/chunks/{chunk-4SR3ZYHA.ts.map → chunk-GELYN4UC.ts.map} +0 -0
  225. /package/dist/chunks/{chunk-S7F4FOAS.ts.map → chunk-GSCZ4VXV.ts.map} +0 -0
  226. /package/dist/chunks/{chunk-YQSFJLJ3.ts.map → chunk-IBXEM35O.ts.map} +0 -0
  227. /package/dist/chunks/{chunk-E3YLRLJM.ts.map → chunk-INECVQNR.ts.map} +0 -0
  228. /package/dist/chunks/{chunk-2JHAN3ZO.ts.map → chunk-JREGWM2B.ts.map} +0 -0
  229. /package/dist/chunks/{chunk-EMRFVLZM.ts.map → chunk-NXWHPVXR.ts.map} +0 -0
  230. /package/dist/chunks/{chunk-SMVKMYLK.ts.map → chunk-P4GI7LTT.ts.map} +0 -0
  231. /package/dist/chunks/{chunk-PJMM75W5.ts.map → chunk-PWESMTH6.ts.map} +0 -0
  232. /package/dist/chunks/{chunk-ZVGRZD4C.ts.map → chunk-R3SAMXB6.ts.map} +0 -0
  233. /package/dist/chunks/{chunk-RNIEVDTR.ts.map → chunk-T3LABNHF.ts.map} +0 -0
  234. /package/dist/chunks/{chunk-S3R3W3KF.ts.map → chunk-UMPA5S7X.ts.map} +0 -0
  235. /package/dist/chunks/{chunk-WP2M67XZ.ts.map → chunk-WBIOSK76.ts.map} +0 -0
  236. /package/dist/chunks/{chunk-4KTJLJSJ.ts.map → chunk-ZB3GNX3P.ts.map} +0 -0
  237. /package/dist/chunks/{chunk-HEB6YT64.ts.map → chunk-ZO52JM4H.ts.map} +0 -0
  238. /package/dist/chunks/{conflict-review-IGKY2TOJ.ts.map → conflict-review-MAOGTIAI.ts.map} +0 -0
  239. /package/dist/chunks/{continuous-record-3XDXDOMV.ts.map → continuous-record-3SKJ6I3V.ts.map} +0 -0
  240. /package/dist/chunks/{continuous-storage-HLKCHF6Z.ts.map → continuous-storage-3EU6I7Z3.ts.map} +0 -0
  241. /package/dist/chunks/{file-selection-MGGVOKM7.ts.map → file-selection-QR2KZVGD.ts.map} +0 -0
  242. /package/dist/chunks/{manager-result-dispatcher-4VJVDEUD.ts.map → manager-result-dispatcher-MC6EQOQY.ts.map} +0 -0
  243. /package/dist/chunks/{remote-selection-ui-W3KOZM3W.ts.map → remote-selection-ui-4BTP2OJR.ts.map} +0 -0
  244. /package/dist/chunks/{setup-switch-D6K6PBPC.ts.map → setup-switch-Y6AMFFNK.ts.map} +0 -0
  245. /package/dist/chunks/{setup-wizard-4DYUDHJR.ts.map → setup-wizard-5G426MOZ.ts.map} +0 -0
  246. /package/dist/chunks/{snapshot-5HY3M2NL.ts.map → snapshot-ZUJJZCFW.ts.map} +0 -0
  247. /package/dist/chunks/{snapshot-transaction-directory-OU2D7R7A.ts.map → snapshot-transaction-directory-F46JWRAU.ts.map} +0 -0
  248. /package/dist/chunks/{state-directory-XXHU73Z3.ts.map → state-directory-CMAIF34J.ts.map} +0 -0
  249. /package/dist/chunks/{sync-inspection-J3CRBORL.ts.map → sync-inspection-ITZ6Z4DE.ts.map} +0 -0
  250. /package/dist/chunks/{sync-state-2LMIXJ2C.ts.map → sync-state-QIT64TKV.ts.map} +0 -0
@@ -0,0 +1,813 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { syncDirectory, writeJson } from "../state/json-file.js";
5
+ import { withLock } from "../state/lock.js";
6
+ import { syncMutationParents } from "../state/mutation-directory-sync.js";
7
+ import { stateDir } from "../state/state-directory.js";
8
+ import { normalizeSyncExclude } from "../sync/exclude-policy.js";
9
+ import { mergePathIdentity } from "../sync/file-merge-planner.js";
10
+ import { includeFromSelectionConfig, selectionForSnapshot } from "../sync/sync-policy.js";
11
+ import { agentDir, configuredSessionDir } from "./session-paths.js";
12
+ import { agentDirectoryConfiguredSessionDir } from "./snapshot.js";
13
+ import { caseReplacementSpelling, coalesceCaseReplacements } from "./snapshot-case-replacement.js";
14
+ import { recheckAgentDirectoryBudget } from "./snapshot-entry-projection.js";
15
+ import { assertUnexcludedTargets } from "./snapshot-exclude-safety.js";
16
+ import { withMissingTargetQueues, withTargetQueues } from "./snapshot-mutation-queues.js";
17
+ import { sessionStorageRoot } from "./snapshot-paths.js";
18
+ import { prepareSessionRootTransition, resolveTransitionSessionRoot, stableAgentDirectorySettingsImage, } from "./snapshot-root-transition.js";
19
+ import { pendingTransactionEntries, transactionRoot } from "./snapshot-transaction-directory.js";
20
+ import { legacyImage, MAX_TRANSACTION_JOURNAL_BYTES, ownedScopedPostTree, readTransactionJournal, recheckScopedImage, removeScopedImage, scopedDescendant, scopedIdentity, scopedPathIdentity, scopedTransactionImage, stableScopedIdentity, } from "./snapshot-transaction-images.js";
21
+ import { indexTransactionPlan } from "./snapshot-transaction-plan.js";
22
+ import { AGENT_DIRECTORY_JOURNAL_VERSION, assertAllowedTarget, assertRecoveryPolicy, assertSafeParents, IGNORE_POLICY_JOURNAL_VERSION, ignorePolicyValidator, ignoreSourceBinding, isScopedJournal, isStrictlyInside, StaleIgnorePolicyError, touchesProtectedTarget, transactionHasSessionTargets, validateJournal, validateJournalPolicy, } from "./snapshot-transaction-policy.js";
23
+ import { assertNoUnclaimedLegacyStage, buildScopedRecoveryStage, cleanScopedLegacyStage, cleanScopedWorkspace, inspectScopedRecoveryStage, prepareLegacyRecoveryStage, recoveryStagePath, } from "./snapshot-transaction-stage.js";
24
+ import { verifyTarget } from "./snapshot-transaction-verification.js";
25
+ const JOURNAL_VERSION = 4;
26
+ class ScopedRemovalError extends Error {
27
+ }
28
+ export async function applySnapshotTransaction(plan, options = {}) {
29
+ options.validateMutation?.();
30
+ const root = path.resolve(agentDir());
31
+ if (options.scope === "agent-directory") {
32
+ const sessionDir = options.sessionDir ?? (await agentDirectoryConfiguredSessionDir(options.signal, root, options));
33
+ options = { ...options, sessionDir: sessionStorageRoot(root, sessionDir) };
34
+ }
35
+ const validateIgnorePolicy = ignorePolicyValidator(options);
36
+ await recoverPendingSnapshotTransactions(options);
37
+ const coalesced = await coalesceCaseReplacements(root, plan);
38
+ options.validateMutation?.();
39
+ options.signal?.throwIfAborted();
40
+ const targets = [...new Set([...coalesced.plan.deletes, ...coalesced.plan.writes.map((item) => item.target)])].sort();
41
+ if (targets.length > 16_384)
42
+ throw new Error("Snapshot transaction exceeds its target bound; review a smaller transfer.");
43
+ return withTargetQueues(targets, options, async (heldKeys) => {
44
+ if (validateIgnorePolicy)
45
+ await validateIgnorePolicy();
46
+ await assertUnexcludedTargets(root, [...targets, ...coalesced.replacements.values()], options);
47
+ options.signal?.throwIfAborted();
48
+ if (targets.some((target) => touchesProtectedTarget(target, options.protectedTargets)))
49
+ throw new Error("Snapshot transaction targets the current session; review is required.");
50
+ for (const [before, after] of coalesced.replacements) {
51
+ if ((await caseReplacementSpelling(before, after)) !== before)
52
+ throw new Error("Case replacement changed before preparation; review is required.");
53
+ options.validateMutation?.();
54
+ options.signal?.throwIfAborted();
55
+ }
56
+ const originalTargets = new Map([...coalesced.replacements].map(([before, after]) => [after, before]));
57
+ const scoped = options.scope === "agent-directory";
58
+ /** Fresh apply authorization only; recovery remains bound to durable journal images. */
59
+ const expectedPreimages = new Map([...(options.expectedPreimages ?? [])]
60
+ .filter(([target]) => !scoped || !originalTargets.has(target))
61
+ .map(([target, expected]) => [originalTargets.get(target) ?? target, expected]));
62
+ // A case-sensitive spelling replacement has two targets, unlike a coalesced physical alias.
63
+ // Bind both the source bytes and destination absence/bytes before capturing their backups.
64
+ for (const [target, expected] of scoped ? [] : (options.expectedPreimages ?? [])) {
65
+ if (originalTargets.has(target))
66
+ continue;
67
+ const variants = coalesced.plan.deletes.filter((candidate) => candidate !== target &&
68
+ path.dirname(candidate) === path.dirname(target) &&
69
+ mergePathIdentity(candidate) === mergePathIdentity(target));
70
+ if (variants.length > 1)
71
+ throw new Error("Ambiguous reviewed file preimage spellings; review required.");
72
+ const original = variants[0];
73
+ if (!original)
74
+ continue;
75
+ const destination = await legacyImage(target);
76
+ options.validateMutation?.();
77
+ options.signal?.throwIfAborted();
78
+ if (destination !== "missing" && destination !== expected)
79
+ throw new Error("Reviewed destination preimage changed before apply.");
80
+ expectedPreimages.set(original, expected);
81
+ expectedPreimages.set(target, destination);
82
+ }
83
+ if (options.scope === "agent-directory") {
84
+ const evidence = await stableAgentDirectorySettingsImage(root, plan, options);
85
+ if (evidence) {
86
+ const target = originalTargets.get(evidence.target) ?? evidence.target;
87
+ const reviewed = expectedPreimages.get(target);
88
+ if (reviewed !== undefined && reviewed !== evidence.image)
89
+ throw new Error("Reviewed Pi settings changed before apply; snapshot installation refused.");
90
+ expectedPreimages.set(target, evidence.image);
91
+ }
92
+ }
93
+ for (const [target, expected] of expectedPreimages) {
94
+ if (scoped || options.reservedIgnoreNames?.length)
95
+ await assertUnexcludedTargets(root, [target], options);
96
+ const current = scoped ? (await scopedTransactionImage(target, options)).value : await legacyImage(target);
97
+ options.validateMutation?.();
98
+ options.signal?.throwIfAborted();
99
+ if (current !== expected)
100
+ throw new Error("Reviewed file preimage changed before apply; snapshot installation refused.");
101
+ }
102
+ if (validateIgnorePolicy)
103
+ await validateIgnorePolicy();
104
+ const transaction = await prepareTransaction(coalesced.plan, targets, { ...options, expectedPreimages }, coalesced.replacements);
105
+ const entriesByTarget = new Map(transaction.journal.entries.flatMap((entry) => [
106
+ [entry.target, entry],
107
+ ...(entry.afterTarget ? [[entry.afterTarget, entry]] : []),
108
+ ]));
109
+ // A released additional key cannot authorize rollback, even for recognized raced bytes.
110
+ const changesQueueKey = transaction.journal.entries.some((entry) => !heldKeys.has(entry.target) || (entry.afterTarget && !heldKeys.has(entry.afterTarget)));
111
+ try {
112
+ if (scoped && transaction.deletes.length)
113
+ await recheckAgentDirectoryBudget(root, plan, options, stateDir(root));
114
+ for (const target of transaction.deletes.sort((a, b) => a.length - b.length)) {
115
+ options.signal?.throwIfAborted();
116
+ const entry = entriesByTarget.get(target);
117
+ if (!entry)
118
+ throw new Error("Unowned transaction target.");
119
+ await removeOwnedTarget(transaction.directory, entry, transaction.journal, options, { apply: true });
120
+ await syncDirectory(path.dirname(target));
121
+ }
122
+ await withMissingTargetQueues(transaction.journal.entries
123
+ .filter((entry) => entry.removalPending)
124
+ .flatMap((entry) => [entry.target, ...(entry.afterTarget ? [entry.afterTarget] : [])]), heldKeys, options, async () => {
125
+ if (validateIgnorePolicy)
126
+ await validateIgnorePolicy();
127
+ if (scoped && plan.writes.length)
128
+ await recheckAgentDirectoryBudget(root, { deletes: [], writes: plan.writes }, options);
129
+ if (validateIgnorePolicy)
130
+ await validateIgnorePolicy();
131
+ await retireRemovalIntent(transaction.directory, transaction.journal, transaction.journal.entries.filter((entry) => entry.removalPending && (entry.afterImage !== "missing" || (entry.postFiles?.length ?? 0) > 0)), options);
132
+ // Only this uninterrupted call knows which deleted writes have not attempted installation yet.
133
+ const uninstalledWrites = new Set(transaction.deletedWrites);
134
+ for (const item of plan.writes) {
135
+ options.signal?.throwIfAborted();
136
+ const entry = entriesByTarget.get(item.target);
137
+ if (!entry)
138
+ throw new Error("Unowned transaction target.");
139
+ const deletedByThisCall = uninstalledWrites.delete(entry.target);
140
+ if (options.scope === "agent-directory" || options.reservedIgnoreNames?.length)
141
+ await assertUnexcludedTargets(transaction.journal.root, [item.target], options);
142
+ await verifyTarget(transaction.directory, entry, transaction.journal, options, deletedByThisCall);
143
+ options.validateMutation?.();
144
+ options.signal?.throwIfAborted();
145
+ if (validateIgnorePolicy)
146
+ await validateIgnorePolicy();
147
+ await fs.mkdir(path.dirname(item.target), { recursive: true });
148
+ options.validateMutation?.();
149
+ options.signal?.throwIfAborted();
150
+ const temp = path.join(path.dirname(item.target), `.pi-sync.json.${randomUUID()}.apply`);
151
+ try {
152
+ let mode = 0o600;
153
+ try {
154
+ const stat = await fs.lstat(item.target);
155
+ if (stat.isFile())
156
+ mode = stat.mode & 0o777;
157
+ }
158
+ catch (error) {
159
+ if (error.code !== "ENOENT")
160
+ throw error;
161
+ }
162
+ const handle = await fs.open(temp, "wx", mode);
163
+ try {
164
+ await handle.writeFile(item.content);
165
+ await handle.sync();
166
+ }
167
+ finally {
168
+ await handle.close();
169
+ }
170
+ const verified = await verifyTarget(transaction.directory, entry, transaction.journal, options, deletedByThisCall);
171
+ options.signal?.throwIfAborted();
172
+ options.validateMutation?.();
173
+ if (validateIgnorePolicy && verified.scoped) {
174
+ await validateIgnorePolicy();
175
+ await recheckScopedImage(item.target, verified.scoped, options);
176
+ }
177
+ await fs.rename(temp, item.target);
178
+ await syncDirectory(path.dirname(item.target));
179
+ }
180
+ finally {
181
+ await fs.rm(temp, { force: true });
182
+ }
183
+ }
184
+ options.validateMutation?.();
185
+ options.signal?.throwIfAborted();
186
+ await syncMutationParents(targets, [transaction.journal.root, ...(transaction.journal.sessionRoot ? [transaction.journal.sessionRoot] : [])], options);
187
+ options.validateMutation?.();
188
+ options.signal?.throwIfAborted();
189
+ if (validateIgnorePolicy)
190
+ await validateIgnorePolicy();
191
+ });
192
+ if (validateIgnorePolicy)
193
+ await validateIgnorePolicy();
194
+ }
195
+ catch (error) {
196
+ // Aborted owners cannot roll back files after another session has replaced them.
197
+ if (options.signal?.aborted)
198
+ throw new Error("Snapshot apply cancelled; guarded transaction evidence retained for review.");
199
+ if (error instanceof ScopedRemovalError || error instanceof StaleIgnorePolicyError)
200
+ throw error;
201
+ // Additional queues have been released. Recovery must reserve missing keys afresh.
202
+ if (changesQueueKey)
203
+ throw new Error("Snapshot apply failed; guarded transaction evidence retained for review.", {
204
+ cause: error,
205
+ });
206
+ try {
207
+ await restoreTransaction(transaction.directory, transaction.journal, options, heldKeys);
208
+ }
209
+ catch (recoveryError) {
210
+ throw new AggregateError([error, recoveryError], "Snapshot apply failed and guarded recovery requires review. Transaction and backup retained; newer bytes were not restored over.");
211
+ }
212
+ throw error;
213
+ }
214
+ // Files are durably installed. Cleanup cannot roll back once it starts deleting evidence.
215
+ await completeTransaction(transaction.directory, transaction.journal);
216
+ });
217
+ }
218
+ export async function recoverSnapshotTransactionsOnStartup(options = {}) {
219
+ if (!(await pendingTransactionEntries()).some((entry) => entry.isDirectory()))
220
+ return;
221
+ // A pending settings.json may itself be the interrupted postimage. Read each journal
222
+ // before consulting that file, and only consult it when a session target needs it.
223
+ options.validateMutation?.();
224
+ options.signal?.throwIfAborted();
225
+ await withLock("recovery", () => recoverPendingSnapshotTransactions({ ...options, resolveConfiguredSessionDir: true }), {
226
+ reclaimStale: true,
227
+ });
228
+ }
229
+ export async function recoverPendingSnapshotTransactions(options = {}) {
230
+ for (const entry of (await pendingTransactionEntries()).sort((a, b) => a.name.localeCompare(b.name))) {
231
+ if (!entry.isDirectory())
232
+ continue;
233
+ const directory = path.join(transactionRoot(), entry.name);
234
+ let journal;
235
+ try {
236
+ const content = await readTransactionJournal(path.join(directory, "journal.json"), options);
237
+ // Unknown evidence is not disposable, including interrupted preparation directories.
238
+ if (content === undefined)
239
+ continue;
240
+ journal = JSON.parse(content);
241
+ }
242
+ catch {
243
+ options.validateMutation?.();
244
+ options.signal?.throwIfAborted();
245
+ throw new Error("Cannot recover malformed pi-sync transaction; preserve private evidence for review.");
246
+ }
247
+ validateJournalPolicy(journal);
248
+ if (!journal.completed) {
249
+ assertRecoveryPolicy(journal, options);
250
+ ignorePolicyValidator(options);
251
+ }
252
+ let sessionDir = options.sessionDir;
253
+ if (sessionDir === undefined && !journal.completed) {
254
+ if (options.scope === "agent-directory")
255
+ sessionDir = await agentDirectoryConfiguredSessionDir(options.signal, agentDir(), options);
256
+ else if (options.resolveConfiguredSessionDir && transactionHasSessionTargets(journal))
257
+ sessionDir = await configuredSessionDir(options);
258
+ }
259
+ options.validateMutation?.();
260
+ options.signal?.throwIfAborted();
261
+ if (journal.sessionRootTransition && !journal.completed) {
262
+ // Validate every path before consulting backup evidence under the recorded root.
263
+ validateJournal(directory, journal, journal.sessionRoot);
264
+ sessionDir = await resolveTransitionSessionRoot(directory, journal.root, journal.sessionRoot, journal.sessionRootTransition, journal.entries, path.resolve(sessionStorageRoot(journal.root, sessionDir)), options);
265
+ options.validateMutation?.();
266
+ options.signal?.throwIfAborted();
267
+ }
268
+ validateJournal(directory, journal, sessionDir);
269
+ if (journal.completed) {
270
+ await removeTransaction(directory);
271
+ continue;
272
+ }
273
+ await withTargetQueues(journal.entries.map((entry) => entry.target).sort(), options, (heldKeys) => restoreTransaction(directory, journal, { ...options, sessionDir }, heldKeys));
274
+ }
275
+ }
276
+ async function prepareTransaction(plan, targets, options, replacements = new Map()) {
277
+ const { sessionDir } = options;
278
+ const root = path.resolve(agentDir());
279
+ const wholeDirectory = options.scope === "agent-directory";
280
+ const ignoreSource = options.ignorePolicy ? ignoreSourceBinding(options.ignorePolicy) : undefined;
281
+ const sessionRoot = sessionDir || wholeDirectory ? path.resolve(sessionStorageRoot(root, sessionDir)) : undefined;
282
+ const indexed = indexTransactionPlan(plan, targets);
283
+ const directory = path.join(transactionRoot(), randomUUID());
284
+ const backupDirectory = path.join(directory, "before");
285
+ await fs.mkdir(backupDirectory, { recursive: true, mode: 0o700 });
286
+ const entries = [];
287
+ for (const [index, target] of targets.entries()) {
288
+ options.signal?.throwIfAborted();
289
+ options.validateMutation?.();
290
+ assertAllowedTarget(root, sessionRoot, target);
291
+ await assertSafeParents(root, sessionRoot, target);
292
+ if (wholeDirectory || options.reservedIgnoreNames?.length)
293
+ await assertUnexcludedTargets(root, [target], options);
294
+ const entry = { target, backupName: `${index}`, kind: "missing" };
295
+ if (replacements.has(target))
296
+ entry.afterTarget = replacements.get(target);
297
+ const backup = path.join(backupDirectory, entry.backupName);
298
+ if (wholeDirectory) {
299
+ const captured = await scopedTransactionImage(target, options, backup, (source) => assertUnexcludedTargets(root, [source], options, { recursive: false }));
300
+ entry.kind = captured.kind;
301
+ entry.beforeImage = captured.value;
302
+ }
303
+ else {
304
+ await captureLegacyBackup(target, backup, entry, options);
305
+ }
306
+ options.validateMutation?.();
307
+ options.signal?.throwIfAborted();
308
+ const expected = options.expectedPreimages?.get(target);
309
+ if (wholeDirectory && entry.kind === "directory" && expected === undefined)
310
+ throw new Error("Scoped directory replacement requires a reviewed preimage.");
311
+ if (expected !== undefined && entry.beforeImage !== expected)
312
+ throw new Error("Reviewed file preimage changed during backup; private preparation evidence retained.");
313
+ if (entry.afterTarget) {
314
+ if (entry.kind !== "file" || (await caseReplacementSpelling(target, entry.afterTarget)) !== target)
315
+ throw new Error("Case replacement preimage changed during backup; evidence retained for review.");
316
+ options.validateMutation?.();
317
+ options.signal?.throwIfAborted();
318
+ }
319
+ entry.afterImage = indexed.writeImages.get(target) ?? "missing";
320
+ entry.postFiles = indexed.postFiles.get(target) ?? [];
321
+ entries.push(entry);
322
+ }
323
+ // File fsync does not persist the name linking each backup into this directory.
324
+ await syncDirectory(backupDirectory);
325
+ const effectiveRoot = sessionRoot ?? path.join(root, "sessions");
326
+ const sessionRootTransition = wholeDirectory
327
+ ? undefined
328
+ : await prepareSessionRootTransition(directory, root, effectiveRoot, entries, plan, options);
329
+ const journal = {
330
+ version: ignoreSource
331
+ ? IGNORE_POLICY_JOURNAL_VERSION
332
+ : wholeDirectory
333
+ ? AGENT_DIRECTORY_JOURNAL_VERSION
334
+ : sessionRootTransition
335
+ ? 7
336
+ : replacements.size
337
+ ? 5
338
+ : JOURNAL_VERSION,
339
+ root,
340
+ ignoreSource,
341
+ ...(wholeDirectory
342
+ ? { selection: selectionForSnapshot(includeFromSelectionConfig(options), options.exclude, options) }
343
+ : options.exclude === undefined
344
+ ? {}
345
+ : { exclude: normalizeSyncExclude(options.exclude) }),
346
+ sessionRoot: sessionRootTransition ? effectiveRoot : sessionRoot,
347
+ sessionRootTransition,
348
+ entries,
349
+ };
350
+ options.signal?.throwIfAborted();
351
+ options.validateMutation?.();
352
+ await writeJson(path.join(directory, "journal.json"), journal, { maxBytes: MAX_TRANSACTION_JOURNAL_BYTES });
353
+ await syncDirectory(transactionRoot());
354
+ await syncDirectory(stateDir());
355
+ await syncDirectory(path.dirname(stateDir()));
356
+ return { directory, journal, deletes: indexed.deletes, deletedWrites: indexed.deletedWrites };
357
+ }
358
+ async function captureLegacyBackup(target, backup, entry, options) {
359
+ try {
360
+ const stat = await fs.lstat(target);
361
+ if (stat.isSymbolicLink()) {
362
+ entry.kind = "symlink";
363
+ entry.linkTarget = await fs.readlink(target);
364
+ }
365
+ else if (stat.isDirectory()) {
366
+ entry.kind = "directory";
367
+ await fs.cp(target, backup, {
368
+ recursive: true,
369
+ dereference: false,
370
+ verbatimSymlinks: true,
371
+ preserveTimestamps: true,
372
+ filter: () => {
373
+ options.signal?.throwIfAborted();
374
+ options.validateMutation?.();
375
+ return true;
376
+ },
377
+ });
378
+ }
379
+ else if (stat.isFile()) {
380
+ entry.kind = "file";
381
+ await fs.copyFile(target, backup);
382
+ await fs.chmod(backup, stat.mode);
383
+ }
384
+ else
385
+ throw new Error("Unsupported existing snapshot target.");
386
+ }
387
+ catch (error) {
388
+ const code = error.code;
389
+ if (code !== "ENOENT" && code !== "ENOTDIR")
390
+ throw error;
391
+ }
392
+ entry.beforeImage =
393
+ entry.kind === "symlink"
394
+ ? `symlink:${entry.linkTarget}`
395
+ : entry.kind === "missing"
396
+ ? "missing"
397
+ : await legacyImage(backup, true);
398
+ }
399
+ async function restoreTransaction(directory, journal, options, heldKeys) {
400
+ validateJournal(directory, journal, options.sessionDir);
401
+ const missingSpellings = [];
402
+ for (const entry of journal.entries) {
403
+ if (!entry.afterTarget)
404
+ continue;
405
+ options.validateMutation?.();
406
+ options.signal?.throwIfAborted();
407
+ const spelling = await caseReplacementSpelling(entry.target, entry.afterTarget);
408
+ options.validateMutation?.();
409
+ options.signal?.throwIfAborted();
410
+ if (spelling === undefined)
411
+ missingSpellings.push(entry.target, entry.afterTarget);
412
+ }
413
+ // Reserve an interrupted removal's other spelling before staging or image checks:
414
+ // recognizable bytes installed by a writer in that gap are not our postimage.
415
+ return withMissingTargetQueues(missingSpellings, heldKeys, options, (reservedKeys) => restoreQueuedTransaction(directory, journal, options, reservedKeys));
416
+ }
417
+ async function restoreQueuedTransaction(directory, journal, options, heldKeys) {
418
+ validateJournal(directory, journal, options.sessionDir);
419
+ const scoped = isScopedJournal(journal);
420
+ const validateIgnorePolicy = ignorePolicyValidator(options);
421
+ options.validateMutation?.();
422
+ options.signal?.throwIfAborted();
423
+ if (validateIgnorePolicy) {
424
+ assertRecoveryPolicy(journal, options);
425
+ await validateIgnorePolicy();
426
+ }
427
+ await assertUnexcludedTargets(journal.root, journal.entries.flatMap((entry) => [entry.target, ...(entry.afterTarget ? [entry.afterTarget] : [])]), options);
428
+ for (const entry of journal.entries) {
429
+ if (touchesProtectedTarget(entry.target, options.protectedTargets))
430
+ throw new Error("Pending transaction touches the current session; resume a different session before guarded recovery.");
431
+ const { value, before } = await verifyTarget(directory, entry, journal, options);
432
+ if (scoped) {
433
+ await assertNoUnclaimedLegacyStage(directory, entry, options);
434
+ const stage = await inspectScopedRecoveryStage(directory, entry, options);
435
+ if (entry.recoveryWorkspace && !stage && value !== before)
436
+ throw new Error("Recovery workspace is missing; preserve evidence for review.");
437
+ if (entry.vacantInstall && value === "missing") {
438
+ if (!stage ||
439
+ stage.image.kind === "missing" ||
440
+ stage.image.value !== before ||
441
+ stage.partial.kind !== "missing" ||
442
+ scopedIdentity(stage.image.stat) !== entry.vacantInstall)
443
+ throw new Error("Recovery vacancy has no verified staging image; preserve evidence for review.");
444
+ }
445
+ }
446
+ }
447
+ for (const entry of journal.entries) {
448
+ if (!entry.recoveryStaged)
449
+ continue;
450
+ options.validateMutation?.();
451
+ options.signal?.throwIfAborted();
452
+ await assertSafeParents(journal.root, journal.sessionRoot, entry.target);
453
+ options.validateMutation?.();
454
+ options.signal?.throwIfAborted();
455
+ if (scoped)
456
+ await cleanScopedLegacyStage(directory, entry, options);
457
+ else
458
+ await fs.rm(recoveryStagePath(directory, entry), { recursive: true, force: true });
459
+ options.validateMutation?.();
460
+ options.signal?.throwIfAborted();
461
+ }
462
+ if (scoped && journal.version < AGENT_DIRECTORY_JOURNAL_VERSION) {
463
+ journal.version = AGENT_DIRECTORY_JOURNAL_VERSION;
464
+ for (const entry of journal.entries)
465
+ delete entry.recoveryStaged;
466
+ options.validateMutation?.();
467
+ options.signal?.throwIfAborted();
468
+ await persistJournal(directory, journal);
469
+ }
470
+ // Verify the complete group before removing any path. Recheck each destructive boundary.
471
+ for (const entry of [...journal.entries].sort((a, b) => a.target.length - b.target.length)) {
472
+ const { value: current, before } = await verifyTarget(directory, entry, journal, options);
473
+ const spellingMatches = async () => !entry.afterTarget || (await caseReplacementSpelling(entry.target, entry.afterTarget)) === entry.target;
474
+ if (current === before && (await spellingMatches())) {
475
+ if (entry.recoveryWorkspace) {
476
+ if (validateIgnorePolicy)
477
+ await validateIgnorePolicy();
478
+ await cleanScopedWorkspace(directory, entry, options);
479
+ }
480
+ continue;
481
+ }
482
+ options.signal?.throwIfAborted();
483
+ options.validateMutation?.();
484
+ if (entry.kind === "missing") {
485
+ await removeOwnedTarget(directory, entry, journal, options, { restoringBefore: before });
486
+ continue;
487
+ }
488
+ if (scoped) {
489
+ await restoreScopedEntry(directory, journal, entry, options, heldKeys, before, spellingMatches);
490
+ continue;
491
+ }
492
+ const temporary = await prepareLegacyRecoveryStage(directory, entry, options, () => persistJournal(directory, journal));
493
+ if (entry.kind === "file") {
494
+ try {
495
+ await fs.mkdir(path.dirname(entry.target), { recursive: true });
496
+ await fs.copyFile(path.join(directory, "before", entry.backupName), temporary);
497
+ // Windows requires write access to flush an existing regular file.
498
+ const handle = await fs.open(temporary, process.platform === "win32" ? "r+" : "r");
499
+ try {
500
+ await handle.sync();
501
+ }
502
+ finally {
503
+ await handle.close();
504
+ }
505
+ const { value: verified } = await verifyTarget(directory, entry, journal, options);
506
+ options.validateMutation?.();
507
+ options.signal?.throwIfAborted();
508
+ if (verified === before && (await spellingMatches()))
509
+ continue;
510
+ const needsCaseQueue = entry.afterTarget !== undefined &&
511
+ (await caseReplacementSpelling(entry.target, entry.afterTarget)) === entry.afterTarget;
512
+ if (needsCaseQueue) {
513
+ // Keep the installed-spelling queue while reserving the now-missing original spelling.
514
+ await removeOwnedTarget(directory, entry, journal, options);
515
+ }
516
+ else if (verified.startsWith("directory:") &&
517
+ !(await removeOwnedTarget(directory, entry, journal, options, { restoringBefore: before })))
518
+ continue;
519
+ await withMissingTargetQueues(entry.afterTarget && (needsCaseQueue || verified === "missing")
520
+ ? [entry.target, entry.afterTarget]
521
+ : verified.startsWith("directory:")
522
+ ? [entry.target]
523
+ : [], heldKeys, options, async () => {
524
+ const { value: atRename } = await verifyTarget(directory, entry, journal, options);
525
+ options.validateMutation?.();
526
+ options.signal?.throwIfAborted();
527
+ if (atRename === before && (await spellingMatches()))
528
+ return;
529
+ await retireRestorationIntent(directory, journal, entry, options);
530
+ const { value: atInstall } = await verifyTarget(directory, entry, journal, options, atRename === "missing");
531
+ options.validateMutation?.();
532
+ options.signal?.throwIfAborted();
533
+ if (atInstall === before && (await spellingMatches()))
534
+ return;
535
+ await fs.rename(temporary, entry.target);
536
+ await syncDirectory(path.dirname(entry.target));
537
+ });
538
+ }
539
+ finally {
540
+ await fs.rm(temporary, { force: true });
541
+ }
542
+ continue;
543
+ }
544
+ try {
545
+ await fs.mkdir(path.dirname(entry.target), { recursive: true });
546
+ await assertSafeParents(journal.root, journal.sessionRoot, entry.target);
547
+ if (entry.kind === "directory") {
548
+ await fs.cp(path.join(directory, "before", entry.backupName), temporary, {
549
+ recursive: true,
550
+ dereference: false,
551
+ verbatimSymlinks: true,
552
+ preserveTimestamps: true,
553
+ filter: () => {
554
+ options.validateMutation?.();
555
+ options.signal?.throwIfAborted();
556
+ return true;
557
+ },
558
+ });
559
+ }
560
+ else if (entry.linkTarget !== undefined)
561
+ await fs.symlink(entry.linkTarget, temporary);
562
+ if ((await legacyImage(temporary, true)) !== before)
563
+ throw new Error("Staged recovery image differs from the backup; evidence retained.");
564
+ options.validateMutation?.();
565
+ options.signal?.throwIfAborted();
566
+ if (!(await removeOwnedTarget(directory, entry, journal, options, { restoringBefore: before })))
567
+ continue;
568
+ await withMissingTargetQueues([entry.target], heldKeys, options, async () => {
569
+ const { value: atRename } = await verifyTarget(directory, entry, journal, options);
570
+ options.validateMutation?.();
571
+ options.signal?.throwIfAborted();
572
+ if (atRename === before)
573
+ return;
574
+ await retireRestorationIntent(directory, journal, entry, options);
575
+ const { value: atInstall } = await verifyTarget(directory, entry, journal, options, atRename === "missing");
576
+ options.validateMutation?.();
577
+ options.signal?.throwIfAborted();
578
+ if (atInstall === before)
579
+ return;
580
+ await fs.rename(temporary, entry.target);
581
+ await syncDirectory(path.dirname(entry.target));
582
+ });
583
+ }
584
+ finally {
585
+ await fs.rm(temporary, { recursive: true, force: true });
586
+ }
587
+ }
588
+ await syncMutationParents(journal.entries.map((entry) => entry.target), [journal.root, ...(journal.sessionRoot ? [journal.sessionRoot] : [])], options);
589
+ options.validateMutation?.();
590
+ options.signal?.throwIfAborted();
591
+ if (validateIgnorePolicy)
592
+ await validateIgnorePolicy();
593
+ await completeTransaction(directory, journal);
594
+ }
595
+ async function restoreScopedEntry(directory, journal, entry, options, heldKeys, before, spellingMatches) {
596
+ const validateIgnorePolicy = ignorePolicyValidator(options);
597
+ options.validateMutation?.();
598
+ options.signal?.throwIfAborted();
599
+ if (validateIgnorePolicy)
600
+ await validateIgnorePolicy();
601
+ await fs.mkdir(path.dirname(entry.target), { recursive: true });
602
+ await assertSafeParents(journal.root, journal.sessionRoot, entry.target);
603
+ if (!entry.vacantInstall) {
604
+ if (validateIgnorePolicy)
605
+ await validateIgnorePolicy();
606
+ await buildScopedRecoveryStage(directory, entry, options, () => persistJournal(directory, journal));
607
+ }
608
+ const verifyStage = async () => {
609
+ const stage = await inspectScopedRecoveryStage(directory, entry, options, true);
610
+ if (!stage || stage.image.kind === "missing" || stage.image.value !== before || stage.partial.kind !== "missing")
611
+ throw new Error("Staged recovery image changed; evidence retained.");
612
+ if (entry.vacantInstall && scopedIdentity(stage.image.stat) !== entry.vacantInstall)
613
+ throw new Error("Recovery vacancy has a different staging image; preserve evidence for review.");
614
+ const identity = stableScopedIdentity(stage.payload, stage.image.stat);
615
+ return { payload: stage.payload, identity, image: stage.image };
616
+ };
617
+ await verifyStage();
618
+ const { value: verified } = await verifyTarget(directory, entry, journal, options);
619
+ if (verified !== before || !(await spellingMatches())) {
620
+ const needsCaseQueue = entry.afterTarget !== undefined &&
621
+ (await caseReplacementSpelling(entry.target, entry.afterTarget)) === entry.afterTarget;
622
+ const needsRemoval = verified !== "missing" && (needsCaseQueue || verified.startsWith("directory:") || entry.kind === "directory");
623
+ const needsVacantTarget = needsRemoval || verified === "missing";
624
+ if (!needsRemoval ||
625
+ (await removeOwnedTarget(directory, entry, journal, options, {
626
+ restoringBefore: needsCaseQueue ? undefined : before,
627
+ }))) {
628
+ const queueTargets = needsVacantTarget ? [entry.target, ...(entry.afterTarget ? [entry.afterTarget] : [])] : [];
629
+ await withMissingTargetQueues(queueTargets, heldKeys, options, async () => {
630
+ if (validateIgnorePolicy)
631
+ await validateIgnorePolicy();
632
+ const { value: atRename } = await verifyTarget(directory, entry, journal, options);
633
+ if (atRename === before && (await spellingMatches()))
634
+ return;
635
+ if (needsVacantTarget && atRename !== "missing")
636
+ throw new Error("Transaction target changed after removal; preserve evidence for review.");
637
+ const stage = await verifyStage();
638
+ if (needsVacantTarget && !entry.vacantInstall) {
639
+ if (validateIgnorePolicy)
640
+ await validateIgnorePolicy();
641
+ entry.vacantInstall = stage.identity;
642
+ delete entry.removalPending;
643
+ delete entry.replacementStarted;
644
+ delete entry.scopedRemoval;
645
+ for (const child of journal.entries) {
646
+ if (isStrictlyInside(entry.target, child.target))
647
+ delete child.scopedRemoval;
648
+ }
649
+ options.validateMutation?.();
650
+ options.signal?.throwIfAborted();
651
+ await syncDirectory(path.dirname(entry.target));
652
+ options.validateMutation?.();
653
+ options.signal?.throwIfAborted();
654
+ await persistJournal(directory, journal);
655
+ await verifyStage();
656
+ }
657
+ if ((await scopedPathIdentity(stage.payload, options)) !== stage.identity)
658
+ throw new Error("Staged recovery image changed before restoration; preserve evidence for review.");
659
+ const atInstall = await verifyTarget(directory, entry, journal, options);
660
+ if (atInstall.value === before && (await spellingMatches()))
661
+ return;
662
+ if (atInstall.value !== atRename)
663
+ throw new Error("Transaction target changed before restoration; preserve evidence for review.");
664
+ options.validateMutation?.();
665
+ options.signal?.throwIfAborted();
666
+ if (validateIgnorePolicy && atInstall.scoped) {
667
+ await validateIgnorePolicy();
668
+ await recheckScopedImage(stage.payload, stage.image, options);
669
+ await recheckScopedImage(entry.target, atInstall.scoped, options);
670
+ }
671
+ await fs.rename(stage.payload, entry.target);
672
+ await syncDirectory(path.dirname(entry.target));
673
+ await syncDirectory(path.dirname(stage.payload));
674
+ if ((await verifyTarget(directory, entry, journal, options)).value !== before)
675
+ throw new Error("Restored transaction image changed; evidence retained.");
676
+ });
677
+ }
678
+ }
679
+ if (validateIgnorePolicy)
680
+ await validateIgnorePolicy();
681
+ await cleanScopedWorkspace(directory, entry, options);
682
+ }
683
+ async function removeOwnedTarget(directory, entry, journal, options, { apply, restoringBefore } = {}) {
684
+ const scoped = isScopedJournal(journal);
685
+ const validateIgnorePolicy = ignorePolicyValidator(options);
686
+ try {
687
+ if (validateIgnorePolicy)
688
+ await validateIgnorePolicy();
689
+ await assertUnexcludedTargets(journal.root, [entry.target, ...(entry.afterTarget ? [entry.afterTarget] : [])], options);
690
+ const current = await verifyTarget(directory, entry, journal, options);
691
+ options.validateMutation?.();
692
+ options.signal?.throwIfAborted();
693
+ if (restoringBefore !== undefined && current.value === restoringBefore)
694
+ return false;
695
+ if (scoped && apply && current.value !== current.before)
696
+ throw new Error("Reviewed removal image changed; preserve evidence for review.");
697
+ // Until replacement is armed, interrupted removal can recognize absence without accepting unknown bytes.
698
+ upgradeRemovalEvidence(journal);
699
+ for (const affected of journal.entries) {
700
+ if (affected.target !== entry.target && !isStrictlyInside(entry.target, affected.target))
701
+ continue;
702
+ affected.removalPending = true;
703
+ affected.replacementStarted = false;
704
+ if (affected.vacantInstall)
705
+ throw new Error("Transaction removal overlaps a recovery vacancy; preserve evidence for review.");
706
+ if (!current.scoped)
707
+ continue;
708
+ const relative = path.relative(entry.target, affected.target);
709
+ const observed = scopedDescendant(current.scoped, relative);
710
+ if (!observed || observed.kind === "missing")
711
+ continue;
712
+ const observedPath = path.join(entry.target, relative);
713
+ const mayChange = observed.kind === "directory" && observed.children.length > 0;
714
+ if (affected.scopedRemoval) {
715
+ if (mayChange)
716
+ stableScopedIdentity(observedPath, observed.stat);
717
+ continue;
718
+ }
719
+ const image = observed.value === affected.beforeImage
720
+ ? "before"
721
+ : observed.value === affected.afterImage || ownedScopedPostTree(observed, affected.postFiles ?? [], true)
722
+ ? "after"
723
+ : undefined;
724
+ if (!image)
725
+ continue;
726
+ affected.scopedRemoval = {
727
+ image,
728
+ identity: mayChange ? stableScopedIdentity(observedPath, observed.stat) : scopedIdentity(observed.stat),
729
+ };
730
+ }
731
+ options.validateMutation?.();
732
+ options.signal?.throwIfAborted();
733
+ await persistJournal(directory, journal);
734
+ const verified = await verifyTarget(directory, entry, journal, options);
735
+ options.validateMutation?.();
736
+ options.signal?.throwIfAborted();
737
+ if (restoringBefore !== undefined && verified.value === restoringBefore)
738
+ return false;
739
+ if (current.scoped) {
740
+ if (current.value !== verified.value)
741
+ throw new Error("Transaction removal image changed.");
742
+ await assertUnexcludedTargets(journal.root, [entry.target], options);
743
+ await removeScopedImage(entry.target, current.scoped, options, validateIgnorePolicy);
744
+ }
745
+ else {
746
+ await fs.rm(entry.target, { recursive: true, force: true });
747
+ }
748
+ await syncDirectory(path.dirname(entry.target));
749
+ return true;
750
+ }
751
+ catch (error) {
752
+ if (!scoped || error instanceof StaleIgnorePolicyError)
753
+ throw error;
754
+ throw new ScopedRemovalError("Scoped transaction removal stopped; preserve transaction and backup for review.", {
755
+ cause: error,
756
+ });
757
+ }
758
+ }
759
+ function upgradeRemovalEvidence(journal) {
760
+ if (journal.version < JOURNAL_VERSION) {
761
+ // Old pending markers may already have survived a committed replacement.
762
+ for (const entry of journal.entries)
763
+ entry.removalPending = false;
764
+ journal.version = JOURNAL_VERSION;
765
+ }
766
+ }
767
+ async function retireRemovalIntent(directory, journal, entries, options) {
768
+ options.validateMutation?.();
769
+ options.signal?.throwIfAborted();
770
+ if (!entries.length)
771
+ return;
772
+ upgradeRemovalEvidence(journal);
773
+ for (const entry of entries) {
774
+ entry.removalPending = false;
775
+ entry.replacementStarted = true;
776
+ delete entry.scopedRemoval;
777
+ }
778
+ await writeJson(path.join(directory, "journal.json"), journal, { maxBytes: MAX_TRANSACTION_JOURNAL_BYTES });
779
+ options.validateMutation?.();
780
+ options.signal?.throwIfAborted();
781
+ }
782
+ async function retireRestorationIntent(directory, journal, entry, options) {
783
+ // Installing a complete parent preimage supersedes descendant replacement progress too.
784
+ for (const child of journal.entries) {
785
+ if (isStrictlyInside(entry.target, child.target)) {
786
+ child.removalPending = false;
787
+ child.replacementStarted = false;
788
+ }
789
+ }
790
+ await retireRemovalIntent(directory, journal, [entry], options);
791
+ }
792
+ function persistJournal(directory, journal) {
793
+ return writeJson(path.join(directory, "journal.json"), journal, { maxBytes: MAX_TRANSACTION_JOURNAL_BYTES });
794
+ }
795
+ async function completeTransaction(directory, journal) {
796
+ // Publish completion before deleting any backup. A surviving journal after power loss
797
+ // may only retry cleanup, never roll back already accepted files.
798
+ await writeJson(path.join(directory, "journal.json"), {
799
+ ...journal,
800
+ version: isScopedJournal(journal) ? journal.version : journal.sessionRootTransition ? 7 : 6,
801
+ completed: true,
802
+ }, {
803
+ maxBytes: MAX_TRANSACTION_JOURNAL_BYTES,
804
+ });
805
+ await removeTransaction(directory);
806
+ }
807
+ async function removeTransaction(directory) {
808
+ await fs.rm(directory, { recursive: true, force: true });
809
+ // After evidence deletion, failure cannot safely trigger rollback or withhold acceptance.
810
+ // A failed cleanup fsync may leave obsolete evidence after power loss; live file durability
811
+ // was established before cleanup; a surviving completed journal allows only cleanup.
812
+ await syncDirectory(transactionRoot()).catch(() => { });
813
+ }