@narumitw/pi-sync 0.59.0 → 0.60.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/README.md +25 -17
- package/dist/chunks/{chunk-AMJRUXFT.ts → chunk-2JNFEZ3V.ts} +2 -6
- package/dist/chunks/{chunk-AMJRUXFT.ts.map → chunk-2JNFEZ3V.ts.map} +1 -1
- package/dist/chunks/{chunk-NGW4JMBF.ts → chunk-4RNCZZY7.ts} +33 -27
- package/dist/chunks/{chunk-NGW4JMBF.ts.map → chunk-4RNCZZY7.ts.map} +3 -3
- package/dist/chunks/{chunk-2ZZJXITS.ts → chunk-6LHIRS5R.ts} +30 -47
- package/dist/chunks/chunk-6LHIRS5R.ts.map +7 -0
- package/dist/chunks/{config-J5VZUY4J.ts → chunk-7AC2RX4M.ts} +6 -13
- package/dist/chunks/chunk-7AC2RX4M.ts.map +7 -0
- package/dist/chunks/{chunk-76HID27T.ts → chunk-BGGKHHO4.ts} +18 -14
- package/dist/chunks/{chunk-76HID27T.ts.map → chunk-BGGKHHO4.ts.map} +1 -1
- package/dist/chunks/chunk-BWWTOQOW.ts +737 -0
- package/dist/chunks/chunk-BWWTOQOW.ts.map +7 -0
- package/dist/chunks/chunk-CEMFCWIU.ts +20 -0
- package/dist/chunks/chunk-CEMFCWIU.ts.map +7 -0
- package/dist/chunks/chunk-CZNBKIM5.ts +20 -0
- package/dist/chunks/chunk-CZNBKIM5.ts.map +7 -0
- package/dist/chunks/{chunk-YIPK23JW.ts → chunk-ENFHHB5O.ts} +1 -16
- package/dist/chunks/{chunk-YIPK23JW.ts.map → chunk-ENFHHB5O.ts.map} +1 -1
- package/dist/chunks/{chunk-KHBPED6W.ts → chunk-GSQGBVKG.ts} +2 -2
- package/dist/chunks/chunk-HNKLBM3U.ts +18 -0
- package/dist/chunks/chunk-HNKLBM3U.ts.map +7 -0
- package/dist/chunks/{chunk-QPC5HT3A.ts → chunk-J5COV5TY.ts} +21 -2
- package/dist/chunks/chunk-J5COV5TY.ts.map +7 -0
- package/dist/chunks/chunk-JKBUYCPC.ts +52 -0
- package/dist/chunks/chunk-JKBUYCPC.ts.map +7 -0
- package/dist/chunks/chunk-JZKCOM62.ts +26 -0
- package/dist/chunks/chunk-JZKCOM62.ts.map +7 -0
- package/dist/chunks/chunk-M7RHV3H6.ts +33 -0
- package/dist/chunks/chunk-M7RHV3H6.ts.map +7 -0
- package/dist/chunks/chunk-NPT2G4FU.ts +15 -0
- package/dist/chunks/chunk-NPT2G4FU.ts.map +7 -0
- package/dist/chunks/chunk-PDBTD2K6.ts +11 -0
- package/dist/chunks/chunk-PDBTD2K6.ts.map +7 -0
- package/dist/chunks/chunk-UBE6XWOM.ts +29 -0
- package/dist/chunks/chunk-UBE6XWOM.ts.map +7 -0
- package/dist/chunks/{chunk-PQ75RPUP.ts → chunk-UZUUUY7C.ts} +8 -8
- package/dist/chunks/chunk-VZCWYXRS.ts +23 -0
- package/dist/chunks/chunk-VZCWYXRS.ts.map +7 -0
- package/dist/chunks/{chunk-DTPELCPW.ts → chunk-YWEYRRQI.ts} +45 -37
- package/dist/chunks/chunk-YWEYRRQI.ts.map +7 -0
- package/dist/chunks/{chunk-ECYCNZOE.ts → chunk-ZMNVNECV.ts} +5 -1
- package/dist/chunks/chunk-ZMNVNECV.ts.map +7 -0
- package/dist/chunks/{command-handler-SDGKIQH2.ts → command-handler-FO4XBBHF.ts} +80 -86
- package/dist/chunks/command-handler-FO4XBBHF.ts.map +7 -0
- package/dist/chunks/conflict-review-XBSME2ER.ts +18 -0
- package/dist/chunks/conflict-review-XBSME2ER.ts.map +7 -0
- package/dist/chunks/{continuous-record-OM64J27R.ts → continuous-record-ZHUXVO4E.ts} +5 -13
- package/dist/chunks/continuous-record-ZHUXVO4E.ts.map +7 -0
- package/dist/chunks/continuous-storage-SQBAXACF.ts +27 -0
- package/dist/chunks/continuous-storage-SQBAXACF.ts.map +7 -0
- package/dist/chunks/{file-selection-7HEVPO4T.ts → file-selection-S6CNNNQI.ts} +11 -14
- package/dist/chunks/{file-selection-7HEVPO4T.ts.map → file-selection-S6CNNNQI.ts.map} +1 -1
- package/dist/chunks/manager-result-dispatcher-I2AMCCE7.ts +18 -0
- package/dist/chunks/{manager-ui-65ZETN6F.ts → manager-ui-AY5ZU6B4.ts} +180 -164
- package/dist/chunks/manager-ui-AY5ZU6B4.ts.map +7 -0
- package/dist/chunks/merge-review-SGDLMVS4.ts +10 -0
- package/dist/chunks/remote-selection-ui-GZHPDQ4L.ts +17 -0
- package/dist/chunks/{setup-switch-AB27ADDI.ts → setup-switch-M3BAFGJM.ts} +9 -13
- package/dist/chunks/{setup-wizard-5FILKFLQ.ts → setup-wizard-NFAWP4KF.ts} +18 -21
- package/dist/chunks/{setup-wizard-5FILKFLQ.ts.map → setup-wizard-NFAWP4KF.ts.map} +1 -1
- package/dist/chunks/{snapshot-G3W2GOGB.ts → snapshot-D4SFDP5J.ts} +8 -13
- package/dist/chunks/snapshot-D4SFDP5J.ts.map +7 -0
- package/dist/chunks/snapshot-transaction-directory-TNKBQ3UQ.ts +13 -0
- package/dist/chunks/snapshot-transaction-directory-TNKBQ3UQ.ts.map +7 -0
- package/dist/chunks/state-directory-JZSZVVPX.ts +17 -0
- package/dist/chunks/sync-inspection-BJ4KPPNO.ts +23 -0
- package/dist/chunks/sync-inspection-BJ4KPPNO.ts.map +7 -0
- package/dist/chunks/sync-operations-TLWER2TT.ts +45 -0
- package/dist/chunks/sync-operations-TLWER2TT.ts.map +7 -0
- package/dist/chunks/{sync-state-H4TFZZ7S.ts → sync-state-FVCJJ7MY.ts} +5 -11
- package/dist/chunks/sync-state-FVCJJ7MY.ts.map +7 -0
- package/dist/index.ts +269 -313
- package/dist/index.ts.map +4 -4
- package/docs/daemon-migration.md +93 -0
- package/docs/tui-contract.md +12 -0
- package/package.json +3 -6
- package/skills/configure-pi-sync/SKILL.md +1 -1
- package/skills/configure-pi-sync/references/configuration.md +19 -6
- package/src/backends/backend-factory.ts +2 -23
- package/src/backends/backend-identity.ts +5 -40
- package/src/backends/backend-types.ts +1 -81
- package/src/backends/git/git-backend.ts +6 -784
- package/src/backends/git/git-config.ts +8 -130
- package/src/backends/git/git-runner.ts +7 -255
- package/src/backends/git/git-storage.ts +14 -293
- package/src/backends/s3/s3-backend.ts +11 -523
- package/src/backends/s3/s3-client.ts +2 -399
- package/src/backends/s3/s3-conditions.ts +2 -67
- package/src/backends/snapshot-pointer.ts +2 -27
- package/src/backends/sync-backend.ts +6 -101
- package/src/backends/webdav/webdav-backend.ts +10 -622
- package/src/backends/webdav/webdav-client.ts +6 -370
- package/src/backends/webdav/webdav-config.ts +8 -82
- package/src/commands/command-execution.ts +40 -36
- package/src/commands/command.ts +23 -1
- package/src/daemon/apply-gate.ts +146 -0
- package/src/daemon/pi-client.ts +591 -0
- package/src/daemon/recovery.ts +103 -0
- package/src/paths.ts +12 -83
- package/src/settings/config-errors.ts +2 -6
- package/src/settings/config-file.ts +19 -693
- package/src/settings/config.ts +16 -263
- package/src/settings/settings-management.ts +11 -254
- package/src/settings/settings-store.ts +10 -48
- package/src/settings/settings-types.ts +1 -157
- package/src/settings/settings-validation.ts +17 -435
- package/src/snapshot/session-paths.ts +11 -111
- package/src/snapshot/snapshot-apply.ts +9 -322
- package/src/snapshot/snapshot-case-replacement.ts +6 -80
- package/src/snapshot/snapshot-codec.ts +2 -59
- package/src/snapshot/snapshot-exclude-safety.ts +2 -44
- package/src/snapshot/snapshot-mutation-queues.ts +6 -142
- package/src/snapshot/snapshot-paths.ts +2 -11
- package/src/snapshot/snapshot-root-transition.ts +6 -154
- package/src/snapshot/snapshot-transaction-directory.ts +5 -16
- package/src/snapshot/snapshot-transaction-plan.ts +2 -72
- package/src/snapshot/snapshot-transaction.ts +6 -946
- package/src/snapshot/snapshot-types.ts +1 -43
- package/src/snapshot/snapshot.ts +19 -447
- package/src/state/json-file.ts +2 -47
- package/src/state/lock-policy.ts +2 -2
- package/src/state/lock.ts +10 -292
- package/src/state/lockfile-fs.ts +2 -25
- package/src/state/merge-baseline-store.ts +8 -208
- package/src/state/mutation-directory-sync.ts +2 -34
- package/src/state/operation-availability.ts +7 -59
- package/src/state/state-directory.ts +8 -243
- package/src/state/state-types.ts +1 -25
- package/src/state/sync-state-store.ts +11 -75
- package/src/sync/agent-candidate.ts +7 -256
- package/src/sync/agent-plan.ts +2 -107
- package/src/sync/agent-policy.ts +10 -13
- package/src/sync/agent-refusal-retry.ts +2 -54
- package/src/sync/agent-request.ts +2 -19
- package/src/sync/agent-runner.ts +2 -191
- package/src/sync/agent-store.ts +7 -182
- package/src/sync/agent-sync.ts +2 -141
- package/src/sync/apply-review.ts +2 -63
- package/src/sync/automatic-sync.ts +55 -111
- package/src/sync/conflict-artifact-ownership.ts +2 -63
- package/src/sync/conflict-artifacts.ts +8 -195
- package/src/sync/conflict-groups.ts +2 -68
- package/src/sync/conflict-preview.ts +2 -56
- package/src/sync/conflict-resolution.ts +2 -93
- package/src/sync/conflict-retention.ts +2 -72
- package/src/sync/conflict-review.ts +3 -92
- package/src/sync/content-conflicts.ts +2 -73
- package/src/sync/continuous-errors.ts +7 -85
- package/src/sync/continuous-lease.ts +2 -216
- package/src/sync/continuous-record.ts +10 -261
- package/src/sync/continuous-storage.ts +12 -64
- package/src/sync/continuous-sync.ts +2 -563
- package/src/sync/continuous-watch.ts +2 -61
- package/src/sync/exclude-policy.ts +6 -84
- package/src/sync/field-migration.ts +2 -39
- package/src/sync/file-merge-planner.ts +2 -143
- package/src/sync/json-document.ts +7 -184
- package/src/sync/local-field-policy.ts +2 -29
- package/src/sync/local-fields.ts +9 -119
- package/src/sync/merge-apply.ts +2 -439
- package/src/sync/merge-journal.ts +10 -228
- package/src/sync/merge-transfer-error.ts +2 -72
- package/src/sync/merged-sync.ts +2 -919
- package/src/sync/mutation-owner.ts +2 -22
- package/src/sync/package-merge.ts +2 -87
- package/src/sync/partial-progress.ts +2 -55
- package/src/sync/remote-snapshot.ts +7 -79
- package/src/sync/session-merge.ts +2 -194
- package/src/sync/settings-conflicts.ts +2 -64
- package/src/sync/settings-merge.ts +6 -121
- package/src/sync/signals.ts +2 -8
- package/src/sync/startup-check.ts +15 -31
- package/src/sync/startup-timings.ts +2 -94
- package/src/sync/sync-decision.ts +3 -111
- package/src/sync/sync-error-guidance.ts +2 -46
- package/src/sync/sync-errors.ts +7 -23
- package/src/sync/sync-inspection.ts +10 -59
- package/src/sync/sync-local.ts +2 -44
- package/src/sync/sync-mutations.ts +10 -788
- package/src/sync/sync-operations.ts +32 -11
- package/src/sync/sync-policy.ts +34 -474
- package/src/sync/sync-queries.ts +2 -247
- package/src/sync/sync-state.ts +18 -157
- package/src/sync/text-merge.ts +10 -133
- package/src/sync-extension.ts +192 -142
- package/src/ui/manager-state.ts +35 -23
- package/src/ui/manager-ui.ts +80 -36
- package/src/ui/sync-attention.ts +7 -49
- package/dist/chunks/agent-candidate-ZHN7FTZT.ts +0 -30
- package/dist/chunks/agent-plan-ILFEUJ2E.ts +0 -124
- package/dist/chunks/agent-plan-ILFEUJ2E.ts.map +0 -7
- package/dist/chunks/agent-refusal-retry-HRMHCX2A.ts +0 -73
- package/dist/chunks/agent-refusal-retry-HRMHCX2A.ts.map +0 -7
- package/dist/chunks/agent-runner-FCRV2Z75.ts +0 -185
- package/dist/chunks/agent-runner-FCRV2Z75.ts.map +0 -7
- package/dist/chunks/agent-store-CCKN4DPR.ts +0 -175
- package/dist/chunks/agent-store-CCKN4DPR.ts.map +0 -7
- package/dist/chunks/agent-sync-EGA2I5W7.ts +0 -22
- package/dist/chunks/chunk-25QCU3LY.ts +0 -220
- package/dist/chunks/chunk-25QCU3LY.ts.map +0 -7
- package/dist/chunks/chunk-2JZFHNLM.ts +0 -113
- package/dist/chunks/chunk-2JZFHNLM.ts.map +0 -7
- package/dist/chunks/chunk-2UKUKIBI.ts +0 -25
- package/dist/chunks/chunk-2UKUKIBI.ts.map +0 -7
- package/dist/chunks/chunk-2ZZJXITS.ts.map +0 -7
- package/dist/chunks/chunk-3JTZF7Z5.ts +0 -77
- package/dist/chunks/chunk-3JTZF7Z5.ts.map +0 -7
- package/dist/chunks/chunk-3ST7RSYN.ts +0 -21
- package/dist/chunks/chunk-3ST7RSYN.ts.map +0 -7
- package/dist/chunks/chunk-4NVHHDN2.ts +0 -61
- package/dist/chunks/chunk-4NVHHDN2.ts.map +0 -7
- package/dist/chunks/chunk-5SFMBY5P.ts +0 -26
- package/dist/chunks/chunk-5SFMBY5P.ts.map +0 -7
- package/dist/chunks/chunk-6OFMB6KK.ts +0 -215
- package/dist/chunks/chunk-6OFMB6KK.ts.map +0 -7
- package/dist/chunks/chunk-6XU5HZAN.ts +0 -205
- package/dist/chunks/chunk-6XU5HZAN.ts.map +0 -7
- package/dist/chunks/chunk-6YGRZSCN.ts +0 -128
- package/dist/chunks/chunk-6YGRZSCN.ts.map +0 -7
- package/dist/chunks/chunk-7D5SF7P3.ts +0 -29
- package/dist/chunks/chunk-7D5SF7P3.ts.map +0 -7
- package/dist/chunks/chunk-7WYF2KUO.ts +0 -1161
- package/dist/chunks/chunk-7WYF2KUO.ts.map +0 -7
- package/dist/chunks/chunk-APDNHB2T.ts +0 -2037
- package/dist/chunks/chunk-APDNHB2T.ts.map +0 -7
- package/dist/chunks/chunk-AR2DGDUI.ts +0 -55
- package/dist/chunks/chunk-AR2DGDUI.ts.map +0 -7
- package/dist/chunks/chunk-DT7M4VQS.ts +0 -69
- package/dist/chunks/chunk-DT7M4VQS.ts.map +0 -7
- package/dist/chunks/chunk-DTPELCPW.ts.map +0 -7
- package/dist/chunks/chunk-ECYCNZOE.ts.map +0 -7
- package/dist/chunks/chunk-FHE2DCA2.ts +0 -61
- package/dist/chunks/chunk-FHE2DCA2.ts.map +0 -7
- package/dist/chunks/chunk-G4RUXRWZ.ts +0 -48
- package/dist/chunks/chunk-G4RUXRWZ.ts.map +0 -7
- package/dist/chunks/chunk-ILXMZ2HU.ts +0 -58
- package/dist/chunks/chunk-ILXMZ2HU.ts.map +0 -7
- package/dist/chunks/chunk-LA3HQMFG.ts +0 -115
- package/dist/chunks/chunk-LA3HQMFG.ts.map +0 -7
- package/dist/chunks/chunk-M6VQJIOU.ts +0 -54
- package/dist/chunks/chunk-M6VQJIOU.ts.map +0 -7
- package/dist/chunks/chunk-MKC3PXCN.ts +0 -369
- package/dist/chunks/chunk-MKC3PXCN.ts.map +0 -7
- package/dist/chunks/chunk-OQBE2OMB.ts +0 -88
- package/dist/chunks/chunk-OQBE2OMB.ts.map +0 -7
- package/dist/chunks/chunk-P3YD4ONV.ts +0 -123
- package/dist/chunks/chunk-P3YD4ONV.ts.map +0 -7
- package/dist/chunks/chunk-PRUEIIK7.ts +0 -24
- package/dist/chunks/chunk-PRUEIIK7.ts.map +0 -7
- package/dist/chunks/chunk-PWMWOJP4.ts +0 -17
- package/dist/chunks/chunk-PWMWOJP4.ts.map +0 -7
- package/dist/chunks/chunk-QPC5HT3A.ts.map +0 -7
- package/dist/chunks/chunk-QQVK2XFC.ts +0 -64
- package/dist/chunks/chunk-QQVK2XFC.ts.map +0 -7
- package/dist/chunks/chunk-RDOX3VH5.ts +0 -140
- package/dist/chunks/chunk-RDOX3VH5.ts.map +0 -7
- package/dist/chunks/chunk-S7D6XWHI.ts +0 -258
- package/dist/chunks/chunk-S7D6XWHI.ts.map +0 -7
- package/dist/chunks/chunk-SHPNS7FM.ts +0 -64
- package/dist/chunks/chunk-SHPNS7FM.ts.map +0 -7
- package/dist/chunks/chunk-SWRVXVFD.ts +0 -248
- package/dist/chunks/chunk-SWRVXVFD.ts.map +0 -7
- package/dist/chunks/chunk-T2SJD3N7.ts +0 -99
- package/dist/chunks/chunk-T2SJD3N7.ts.map +0 -7
- package/dist/chunks/chunk-T2TYBLXK.ts +0 -27
- package/dist/chunks/chunk-T2TYBLXK.ts.map +0 -7
- package/dist/chunks/chunk-UZSDS4HF.ts +0 -403
- package/dist/chunks/chunk-UZSDS4HF.ts.map +0 -7
- package/dist/chunks/chunk-VPODHKOX.ts +0 -229
- package/dist/chunks/chunk-VPODHKOX.ts.map +0 -7
- package/dist/chunks/chunk-WEKGW7HV.ts +0 -162
- package/dist/chunks/chunk-WEKGW7HV.ts.map +0 -7
- package/dist/chunks/chunk-WUHRVSWI.ts +0 -369
- package/dist/chunks/chunk-WUHRVSWI.ts.map +0 -7
- package/dist/chunks/chunk-X7R6DCVF.ts +0 -28
- package/dist/chunks/chunk-X7R6DCVF.ts.map +0 -7
- package/dist/chunks/chunk-XJHQPB3E.ts +0 -107
- package/dist/chunks/chunk-XJHQPB3E.ts.map +0 -7
- package/dist/chunks/chunk-XZ3ZTHKR.ts +0 -1184
- package/dist/chunks/chunk-XZ3ZTHKR.ts.map +0 -7
- package/dist/chunks/chunk-YDVQYUHE.ts +0 -34
- package/dist/chunks/chunk-YDVQYUHE.ts.map +0 -7
- package/dist/chunks/chunk-YEULK7MK.ts +0 -415
- package/dist/chunks/chunk-YEULK7MK.ts.map +0 -7
- package/dist/chunks/chunk-YHT4YTYG.ts +0 -31
- package/dist/chunks/chunk-YHT4YTYG.ts.map +0 -7
- package/dist/chunks/chunk-ZW5ZLGBI.ts +0 -154
- package/dist/chunks/chunk-ZW5ZLGBI.ts.map +0 -7
- package/dist/chunks/command-handler-SDGKIQH2.ts.map +0 -7
- package/dist/chunks/conflict-artifacts-MYSH3L2J.ts +0 -33
- package/dist/chunks/conflict-review-J6ZSPNWL.ts +0 -190
- package/dist/chunks/conflict-review-J6ZSPNWL.ts.map +0 -7
- package/dist/chunks/continuous-sync-BH5SWIRV.ts +0 -590
- package/dist/chunks/continuous-sync-BH5SWIRV.ts.map +0 -7
- package/dist/chunks/git-backend-6CKI6CUG.ts +0 -1074
- package/dist/chunks/git-backend-6CKI6CUG.ts.map +0 -7
- package/dist/chunks/local-fields-SR7PH66U.ts +0 -27
- package/dist/chunks/local-fields-SR7PH66U.ts.map +0 -7
- package/dist/chunks/manager-result-dispatcher-CXUP5WDP.ts +0 -33
- package/dist/chunks/manager-result-dispatcher-CXUP5WDP.ts.map +0 -7
- package/dist/chunks/manager-ui-65ZETN6F.ts.map +0 -7
- package/dist/chunks/merge-baseline-store-4Y2X7P2D.ts +0 -26
- package/dist/chunks/merge-baseline-store-4Y2X7P2D.ts.map +0 -7
- package/dist/chunks/remote-selection-ui-W55BQDJQ.ts +0 -32
- package/dist/chunks/remote-selection-ui-W55BQDJQ.ts.map +0 -7
- package/dist/chunks/s3-backend-FDK7JSDQ.ts +0 -845
- package/dist/chunks/s3-backend-FDK7JSDQ.ts.map +0 -7
- package/dist/chunks/setup-switch-AB27ADDI.ts.map +0 -7
- package/dist/chunks/snapshot-G3W2GOGB.ts.map +0 -7
- package/dist/chunks/snapshot-transaction-SGRUWT73.ts +0 -25
- package/dist/chunks/snapshot-transaction-SGRUWT73.ts.map +0 -7
- package/dist/chunks/sync-inspection-MDYHZHT7.ts +0 -26
- package/dist/chunks/sync-inspection-MDYHZHT7.ts.map +0 -7
- package/dist/chunks/sync-operations-ZAUP65FH.ts +0 -1032
- package/dist/chunks/sync-operations-ZAUP65FH.ts.map +0 -7
- package/dist/chunks/sync-state-H4TFZZ7S.ts.map +0 -7
- package/dist/chunks/webdav-backend-UNMIAXM5.ts +0 -852
- package/dist/chunks/webdav-backend-UNMIAXM5.ts.map +0 -7
- /package/dist/chunks/{chunk-KHBPED6W.ts.map → chunk-GSQGBVKG.ts.map} +0 -0
- /package/dist/chunks/{chunk-PQ75RPUP.ts.map → chunk-UZUUUY7C.ts.map} +0 -0
- /package/dist/chunks/{agent-candidate-ZHN7FTZT.ts.map → manager-result-dispatcher-I2AMCCE7.ts.map} +0 -0
- /package/dist/chunks/{agent-sync-EGA2I5W7.ts.map → merge-review-SGDLMVS4.ts.map} +0 -0
- /package/dist/chunks/{config-J5VZUY4J.ts.map → remote-selection-ui-GZHPDQ4L.ts.map} +0 -0
- /package/dist/chunks/{conflict-artifacts-MYSH3L2J.ts.map → setup-switch-M3BAFGJM.ts.map} +0 -0
- /package/dist/chunks/{continuous-record-OM64J27R.ts.map → state-directory-JZSZVVPX.ts.map} +0 -0
|
@@ -1,2037 +0,0 @@
|
|
|
1
|
-
// @generated by scripts/build-runtime.mjs; do not edit.
|
|
2
|
-
// @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
|
|
3
|
-
import {
|
|
4
|
-
conflictArtifactFingerprint,
|
|
5
|
-
conflictDirectory,
|
|
6
|
-
conflictGroups,
|
|
7
|
-
readConflictArtifact,
|
|
8
|
-
saveConflictArtifact
|
|
9
|
-
} from "./chunk-VPODHKOX.ts";
|
|
10
|
-
import {
|
|
11
|
-
clearMergeJournal,
|
|
12
|
-
mergeJournalIdentity,
|
|
13
|
-
readMergeJournal,
|
|
14
|
-
writeMergeJournal
|
|
15
|
-
} from "./chunk-WEKGW7HV.ts";
|
|
16
|
-
import {
|
|
17
|
-
fileHashMap,
|
|
18
|
-
hasLocalChanges,
|
|
19
|
-
hasRemoteChanges,
|
|
20
|
-
sameHashes,
|
|
21
|
-
syncPolicyChanged
|
|
22
|
-
} from "./chunk-6YGRZSCN.ts";
|
|
23
|
-
import {
|
|
24
|
-
formatRemoteSelectionStatus,
|
|
25
|
-
readSnapshotForHead,
|
|
26
|
-
requireCompatibleRemoteSelection
|
|
27
|
-
} from "./chunk-OQBE2OMB.ts";
|
|
28
|
-
import {
|
|
29
|
-
createSyncBackend
|
|
30
|
-
} from "./chunk-2UKUKIBI.ts";
|
|
31
|
-
import {
|
|
32
|
-
confirmMergeReview
|
|
33
|
-
} from "./chunk-KHBPED6W.ts";
|
|
34
|
-
import {
|
|
35
|
-
backupLocal,
|
|
36
|
-
protectedSessionPaths
|
|
37
|
-
} from "./chunk-ILXMZ2HU.ts";
|
|
38
|
-
import {
|
|
39
|
-
overlayLocalFields,
|
|
40
|
-
portableSnapshot,
|
|
41
|
-
sameLocalFields
|
|
42
|
-
} from "./chunk-P3YD4ONV.ts";
|
|
43
|
-
import {
|
|
44
|
-
createStartupTimings
|
|
45
|
-
} from "./chunk-M6VQJIOU.ts";
|
|
46
|
-
import {
|
|
47
|
-
captureMutationOwner
|
|
48
|
-
} from "./chunk-T2TYBLXK.ts";
|
|
49
|
-
import {
|
|
50
|
-
safeTerminalText,
|
|
51
|
-
snapshotPathLabel
|
|
52
|
-
} from "./chunk-AMJRUXFT.ts";
|
|
53
|
-
import {
|
|
54
|
-
SyncDecisionRequiredError
|
|
55
|
-
} from "./chunk-7D5SF7P3.ts";
|
|
56
|
-
import {
|
|
57
|
-
loadConfig,
|
|
58
|
-
syncCheckConfigFingerprint,
|
|
59
|
-
syncConfigReviewIdentity
|
|
60
|
-
} from "./chunk-XZ3ZTHKR.ts";
|
|
61
|
-
import {
|
|
62
|
-
applySnapshotTransaction,
|
|
63
|
-
assertCanonicalMutationTargets,
|
|
64
|
-
assertUnexcludedTargets,
|
|
65
|
-
recoverPendingSnapshotTransactions,
|
|
66
|
-
syncMutationParents
|
|
67
|
-
} from "./chunk-7WYF2KUO.ts";
|
|
68
|
-
import {
|
|
69
|
-
mergeAcceptedSettingsPackages,
|
|
70
|
-
mergeSettingsJson,
|
|
71
|
-
resolveContentConflicts
|
|
72
|
-
} from "./chunk-6OFMB6KK.ts";
|
|
73
|
-
import {
|
|
74
|
-
TEXT_MERGE_WORK_LIMIT,
|
|
75
|
-
hasCurrentMergeBaseline,
|
|
76
|
-
pruneMergeBaselines,
|
|
77
|
-
readMergeAncestor,
|
|
78
|
-
readMergeAncestors,
|
|
79
|
-
stageMergeBaseline
|
|
80
|
-
} from "./chunk-UZSDS4HF.ts";
|
|
81
|
-
import {
|
|
82
|
-
mergePathIdentity,
|
|
83
|
-
planFileMerge
|
|
84
|
-
} from "./chunk-XJHQPB3E.ts";
|
|
85
|
-
import {
|
|
86
|
-
readStateForConfig,
|
|
87
|
-
statePathForConfig,
|
|
88
|
-
syncStateFingerprint,
|
|
89
|
-
writeStateForConfig
|
|
90
|
-
} from "./chunk-4NVHHDN2.ts";
|
|
91
|
-
import {
|
|
92
|
-
syncDirectory
|
|
93
|
-
} from "./chunk-AR2DGDUI.ts";
|
|
94
|
-
import {
|
|
95
|
-
createSnapshot,
|
|
96
|
-
filterSnapshotForConfigPolicy,
|
|
97
|
-
isSessionFilePath,
|
|
98
|
-
isSessionPath,
|
|
99
|
-
mergeRemotePreservedFiles,
|
|
100
|
-
regenerateSnapshotIdentity,
|
|
101
|
-
scanSnapshot,
|
|
102
|
-
snapshotIncludesSessions,
|
|
103
|
-
snapshotTarget
|
|
104
|
-
} from "./chunk-MKC3PXCN.ts";
|
|
105
|
-
import {
|
|
106
|
-
configuredSnapshotPathMatcher,
|
|
107
|
-
includeFromSelectionConfig,
|
|
108
|
-
inspectRemoteSelection,
|
|
109
|
-
syncSessionsSelected
|
|
110
|
-
} from "./chunk-WUHRVSWI.ts";
|
|
111
|
-
import {
|
|
112
|
-
agentDir,
|
|
113
|
-
effectiveSessionRoot,
|
|
114
|
-
requireStableMergeSessionRoot,
|
|
115
|
-
sessionStorageRoot,
|
|
116
|
-
snapshotOptionsForContext
|
|
117
|
-
} from "./chunk-LA3HQMFG.ts";
|
|
118
|
-
import {
|
|
119
|
-
compileSyncExclude
|
|
120
|
-
} from "./chunk-3JTZF7Z5.ts";
|
|
121
|
-
import {
|
|
122
|
-
assertWithinRoot,
|
|
123
|
-
isDeniedPath,
|
|
124
|
-
isPathInside,
|
|
125
|
-
parentPaths,
|
|
126
|
-
safeJoin,
|
|
127
|
-
toPosix
|
|
128
|
-
} from "./chunk-FHE2DCA2.ts";
|
|
129
|
-
import {
|
|
130
|
-
ContinuousError
|
|
131
|
-
} from "./chunk-DT7M4VQS.ts";
|
|
132
|
-
import {
|
|
133
|
-
SyncBackendConflictError,
|
|
134
|
-
expectedRemoteHead
|
|
135
|
-
} from "./chunk-YDVQYUHE.ts";
|
|
136
|
-
import {
|
|
137
|
-
startupTransferEnabled
|
|
138
|
-
} from "./chunk-PRUEIIK7.ts";
|
|
139
|
-
|
|
140
|
-
// src/ui/merged-sync-summary.ts
|
|
141
|
-
import { truncateToWidth } from "@earendil-works/pi-tui";
|
|
142
|
-
|
|
143
|
-
// src/ui/transfer-changes.ts
|
|
144
|
-
function transferChanges(before, after, protectedPaths = /* @__PURE__ */ new Set()) {
|
|
145
|
-
const beforeMap = before ? fileHashMap(before) : {};
|
|
146
|
-
const afterMap = fileHashMap(after);
|
|
147
|
-
return [.../* @__PURE__ */ new Set([...Object.keys(beforeMap), ...Object.keys(afterMap)])].sort().flatMap((filePath) => {
|
|
148
|
-
if (protectedPaths.has(filePath)) return [];
|
|
149
|
-
if (!Object.hasOwn(beforeMap, filePath)) return [{ path: filePath, action: "Add" }];
|
|
150
|
-
if (!Object.hasOwn(afterMap, filePath)) return [{ path: filePath, action: "Delete" }];
|
|
151
|
-
return beforeMap[filePath] !== afterMap[filePath] ? [{ path: filePath, action: "Update" }] : [];
|
|
152
|
-
});
|
|
153
|
-
}
|
|
154
|
-
function transferCounts(changes) {
|
|
155
|
-
return {
|
|
156
|
-
add: changes.filter((change) => change.action === "Add").length,
|
|
157
|
-
update: changes.filter((change) => change.action === "Update").length,
|
|
158
|
-
remove: changes.filter((change) => change.action === "Delete").length
|
|
159
|
-
};
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
// src/ui/merged-sync-summary.ts
|
|
163
|
-
function mergedSyncSummary(input) {
|
|
164
|
-
const local = transferChanges(input.localBefore, input.localAfter);
|
|
165
|
-
const remote = transferChanges(input.remoteBefore, input.remoteAfter);
|
|
166
|
-
const all = [...local, ...remote];
|
|
167
|
-
const updatesOnly = all.length > 0 && all.every((change) => change.action === "Update");
|
|
168
|
-
const verb = updatesOnly ? "Update" : "Apply changes to";
|
|
169
|
-
const title = local.length && remote.length ? "Apply local and remote changes?" : all.length ? `${verb} ${all.length} ${local.length ? "local" : "remote"} ${all.length === 1 ? "file" : "files"}?` : input.publish ? "Publish a new remote snapshot?" : "Pi Sync is already up to date.";
|
|
170
|
-
const confirmationLabel = local.length && remote.length ? "apply local and remote changes" : all.length ? `${updatesOnly ? "update" : "apply changes to"} ${local.length ? "local" : "remote"} ${all.length === 1 ? "file" : "files"}` : "publish remote snapshot";
|
|
171
|
-
const sources = new Map(
|
|
172
|
-
input.decisions.filter((item) => item.kind === "accepted").map((item) => [item.path, item.source])
|
|
173
|
-
);
|
|
174
|
-
const label = (change, side) => {
|
|
175
|
-
const source = sources.get(change.path);
|
|
176
|
-
const suffix = source === "merged" ? " (merged content)" : side === "local" && source === "remote" ? change.action === "Delete" ? " (deleted remotely)" : " from remote" : "";
|
|
177
|
-
return `${change.action} ${snapshotPathLabel(change.path)}${suffix}`;
|
|
178
|
-
};
|
|
179
|
-
const section = (items, side, compact) => {
|
|
180
|
-
const heading = side === "local" ? "Local changes" : "Remote file changes";
|
|
181
|
-
if (!items.length) return [`${heading}: none`];
|
|
182
|
-
const counts = ["Add", "Update", "Delete"].flatMap((action) => {
|
|
183
|
-
const count = items.filter((item) => item.action === action).length;
|
|
184
|
-
return count ? [`${count} ${action.toLowerCase()}`] : [];
|
|
185
|
-
});
|
|
186
|
-
return [
|
|
187
|
-
`${heading}: ${counts.join(", ")}`,
|
|
188
|
-
...(compact ? items.slice(0, 3) : items).map(
|
|
189
|
-
(item) => ` ${compact ? truncateToWidth(label(item, side), 80) : label(item, side)}`
|
|
190
|
-
),
|
|
191
|
-
...compact && items.length > 3 ? [` ${items.length - 3} more files \u2014 View details`] : []
|
|
192
|
-
];
|
|
193
|
-
};
|
|
194
|
-
const context = [`Setup: ${safeTerminalText(input.setupName)}`, `Remote: ${safeTerminalText(input.destination)}`];
|
|
195
|
-
const safety = [
|
|
196
|
-
`Remote snapshot publication: ${input.publish ? "yes" : "no"}`,
|
|
197
|
-
"Remote removals affect the active snapshot; retained history is not erased.",
|
|
198
|
-
`Sessions: ${input.sessions ? "included \u2014 may contain private conversations" : "not included"}`,
|
|
199
|
-
input.groups.length ? `Unresolved groups: ${input.groups.length} \u2014 these paths stay unchanged on each side` : "Conflicts: none",
|
|
200
|
-
...input.publish && input.capability === "read-check-write-verify" ? ["Warning: simultaneous remote writes can still race; visible changes are rejected."] : [],
|
|
201
|
-
...input.publish && input.capability === "conditional-required" ? ["Remote publication requires verified conditional writes; verification failure stops the transfer."] : [],
|
|
202
|
-
"The current session is protected. A backup and recovery journal will be saved.",
|
|
203
|
-
"Resources will not reload automatically."
|
|
204
|
-
];
|
|
205
|
-
return {
|
|
206
|
-
title,
|
|
207
|
-
confirmationLabel,
|
|
208
|
-
lines: [
|
|
209
|
-
...context.map((line) => truncateToWidth(line, 100)),
|
|
210
|
-
...section(local, "local", true),
|
|
211
|
-
...section(remote, "remote", true),
|
|
212
|
-
...safety
|
|
213
|
-
],
|
|
214
|
-
content: [
|
|
215
|
-
...context,
|
|
216
|
-
"",
|
|
217
|
-
...section(local, "local", false),
|
|
218
|
-
"",
|
|
219
|
-
...section(remote, "remote", false),
|
|
220
|
-
"",
|
|
221
|
-
...safety,
|
|
222
|
-
...input.groups.flatMap(
|
|
223
|
-
(group) => group.paths.map((filePath) => `Unchanged (unresolved): ${snapshotPathLabel(filePath)}`)
|
|
224
|
-
)
|
|
225
|
-
].join("\n")
|
|
226
|
-
};
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
// src/sync/conflict-artifact-ownership.ts
|
|
230
|
-
import fs from "node:fs/promises";
|
|
231
|
-
import path from "node:path";
|
|
232
|
-
async function releaseConflictArtifacts(config, statePath, created) {
|
|
233
|
-
if (!created.length || statePathForConfig(config) !== statePath) return;
|
|
234
|
-
try {
|
|
235
|
-
const state = await readStateForConfig(config);
|
|
236
|
-
if (statePathForConfig(config) !== statePath) return;
|
|
237
|
-
const journal = await readMergeJournal(config);
|
|
238
|
-
if (statePathForConfig(config) !== statePath) return;
|
|
239
|
-
const referenced = /* @__PURE__ */ new Set([
|
|
240
|
-
...(state.unresolved ?? []).map((group) => group.artifact),
|
|
241
|
-
...(journal?.progress?.groups ?? []).map((group) => group.artifact)
|
|
242
|
-
]);
|
|
243
|
-
for (const lease of created) {
|
|
244
|
-
if (referenced.has(lease.token) || lease.target !== path.join(conflictDirectory(config), `${lease.token}.json`))
|
|
245
|
-
continue;
|
|
246
|
-
try {
|
|
247
|
-
const stat = await fs.lstat(lease.target);
|
|
248
|
-
if (!stat.isFile() || stat.nlink !== 1 || stat.dev !== lease.dev || stat.ino !== lease.ino || stat.size !== lease.size)
|
|
249
|
-
continue;
|
|
250
|
-
const artifact = JSON.parse(await fs.readFile(lease.target, "utf8"));
|
|
251
|
-
if (conflictArtifactFingerprint(artifact) !== lease.fingerprint || statePathForConfig(config) !== statePath)
|
|
252
|
-
continue;
|
|
253
|
-
const latest = await fs.lstat(lease.target);
|
|
254
|
-
if (latest.dev !== lease.dev || latest.ino !== lease.ino || latest.nlink !== 1 || statePathForConfig(config) !== statePath)
|
|
255
|
-
continue;
|
|
256
|
-
await fs.unlink(lease.target);
|
|
257
|
-
await syncDirectory(path.dirname(lease.target));
|
|
258
|
-
} catch {
|
|
259
|
-
}
|
|
260
|
-
}
|
|
261
|
-
} catch {
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
// src/sync/conflict-resolution.ts
|
|
266
|
-
async function resolveReviewedGroup(config, backend, state, local, remote, head, plan, resolution, protectedPaths) {
|
|
267
|
-
const artifact = await readConflictArtifact(config, backend.identity, resolution.token);
|
|
268
|
-
const group = artifact.groups[resolution.group];
|
|
269
|
-
if (conflictArtifactFingerprint(artifact) !== resolution.artifactIdentity || !group || plan.kind !== "planned" || !state.unresolved?.some(
|
|
270
|
-
(item) => item.artifact === resolution.token && JSON.stringify(item.paths) === JSON.stringify(group.paths)
|
|
271
|
-
) || syncStateFingerprint(state) !== resolution.stateIdentity || state.lastObservedSnapshot !== head.snapshotId || !state.lastObservedRevision || !backend.sameRevision(state.lastObservedRevision, head.revision))
|
|
272
|
-
throw new Error("Conflict review is stale; refresh sync and review again.");
|
|
273
|
-
const ours = fileHashMap(local);
|
|
274
|
-
const theirs = fileHashMap(remote);
|
|
275
|
-
const oldOurs = fileHashMap(artifact.local);
|
|
276
|
-
const oldTheirs = fileHashMap(artifact.remote);
|
|
277
|
-
if (group.paths.some(
|
|
278
|
-
(filePath) => ours[filePath] !== oldOurs[filePath] || theirs[filePath] !== oldTheirs[filePath] || state.lastFileHashes[filePath] !== artifact.state.lastFileHashes[filePath]
|
|
279
|
-
))
|
|
280
|
-
throw new Error("Conflict versions changed; no resolution was applied.");
|
|
281
|
-
if (group.paths.some(
|
|
282
|
-
(filePath) => [...protectedPaths].some((value) => mergePathIdentity(value) === mergePathIdentity(filePath))
|
|
283
|
-
))
|
|
284
|
-
throw new Error(
|
|
285
|
-
"Current session conflict cannot be resolved from the loaded session; preserve evidence and close Pi."
|
|
286
|
-
);
|
|
287
|
-
const selected = resolution.source === "local" ? local : remote;
|
|
288
|
-
const paths = new Set(group.paths);
|
|
289
|
-
for (const snapshot of [selected, local]) {
|
|
290
|
-
const layout = planFileMerge({
|
|
291
|
-
baseline: {},
|
|
292
|
-
local: snapshot.files.filter((file) => paths.has(file.path)),
|
|
293
|
-
remote: [],
|
|
294
|
-
selectionCompatible: true
|
|
295
|
-
});
|
|
296
|
-
if (layout.kind !== "planned" || layout.conflicts.length)
|
|
297
|
-
throw new Error(
|
|
298
|
-
"Selected/current local group still has path collisions; preserve evidence, repair the layout manually and refresh sync."
|
|
299
|
-
);
|
|
300
|
-
}
|
|
301
|
-
const selectedFiles = new Map(selected.files.map((file) => [file.path, file]));
|
|
302
|
-
const decisions = plan.decisions.map(
|
|
303
|
-
(item) => paths.has(item.path) ? {
|
|
304
|
-
kind: "accepted",
|
|
305
|
-
path: item.path,
|
|
306
|
-
source: resolution.source,
|
|
307
|
-
file: selectedFiles.get(item.path)
|
|
308
|
-
} : item
|
|
309
|
-
);
|
|
310
|
-
return {
|
|
311
|
-
kind: "planned",
|
|
312
|
-
decisions,
|
|
313
|
-
conflicts: decisions.filter((item) => item.kind === "conflict")
|
|
314
|
-
};
|
|
315
|
-
}
|
|
316
|
-
|
|
317
|
-
// src/sync/conflict-retention.ts
|
|
318
|
-
import fs2 from "node:fs/promises";
|
|
319
|
-
import path2 from "node:path";
|
|
320
|
-
async function pruneCompletedConflicts(config, backend, state, local, remote, validate) {
|
|
321
|
-
validate();
|
|
322
|
-
const directory = conflictDirectory(config);
|
|
323
|
-
let names;
|
|
324
|
-
try {
|
|
325
|
-
const stat = await fs2.lstat(directory);
|
|
326
|
-
validate();
|
|
327
|
-
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Unsafe conflict retention directory.");
|
|
328
|
-
names = await fs2.readdir(directory);
|
|
329
|
-
validate();
|
|
330
|
-
} catch (error) {
|
|
331
|
-
if (error.code === "ENOENT") return;
|
|
332
|
-
throw error;
|
|
333
|
-
}
|
|
334
|
-
const pinned = new Set(state.unresolved?.map((group) => group.artifact) ?? []);
|
|
335
|
-
const ours = fileHashMap(local);
|
|
336
|
-
const theirs = fileHashMap(remote);
|
|
337
|
-
const completed = [];
|
|
338
|
-
for (const name of names) {
|
|
339
|
-
validate();
|
|
340
|
-
const token = name.replace(/\.json$/u, "");
|
|
341
|
-
if (!/^[a-f0-9-]{36}\.json$/u.test(name) || pinned.has(token)) continue;
|
|
342
|
-
try {
|
|
343
|
-
const artifact = await readConflictArtifact(config, backend, token);
|
|
344
|
-
validate();
|
|
345
|
-
const originalLocal = fileHashMap(artifact.local);
|
|
346
|
-
const originalRemote = fileHashMap(artifact.remote);
|
|
347
|
-
if (!artifact.groups.every(
|
|
348
|
-
(group) => group.paths.every(
|
|
349
|
-
(filePath) => state.lastFileHashes[filePath] === ours[filePath] && ours[filePath] === theirs[filePath] && (ours[filePath] === originalLocal[filePath] || ours[filePath] === originalRemote[filePath])
|
|
350
|
-
)
|
|
351
|
-
))
|
|
352
|
-
continue;
|
|
353
|
-
const stat = await fs2.lstat(path2.join(directory, name));
|
|
354
|
-
validate();
|
|
355
|
-
if (stat.isFile()) completed.push({ token, modified: stat.mtimeMs });
|
|
356
|
-
} catch {
|
|
357
|
-
validate();
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
completed.sort((left, right) => right.modified - left.modified || left.token.localeCompare(right.token));
|
|
361
|
-
for (const entry of completed.slice(32)) {
|
|
362
|
-
validate();
|
|
363
|
-
await fs2.rm(path2.join(directory, `${entry.token}.json`));
|
|
364
|
-
validate();
|
|
365
|
-
}
|
|
366
|
-
if (completed.length > 32) {
|
|
367
|
-
await syncDirectory(directory);
|
|
368
|
-
validate();
|
|
369
|
-
}
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
// src/sync/merge-apply.ts
|
|
373
|
-
import { createHash as createHash2, randomUUID } from "node:crypto";
|
|
374
|
-
import fs4 from "node:fs/promises";
|
|
375
|
-
import path4 from "node:path";
|
|
376
|
-
import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
|
|
377
|
-
|
|
378
|
-
// src/snapshot/snapshot-apply.ts
|
|
379
|
-
import { createHash } from "node:crypto";
|
|
380
|
-
import fs3 from "node:fs/promises";
|
|
381
|
-
import path3 from "node:path";
|
|
382
|
-
function sha256(value) {
|
|
383
|
-
return createHash("sha256").update(value).digest("hex");
|
|
384
|
-
}
|
|
385
|
-
function fileHashMap2(snapshot) {
|
|
386
|
-
return Object.fromEntries(snapshot.files.map((file) => [file.path, file.sha256]));
|
|
387
|
-
}
|
|
388
|
-
async function applySnapshot(snapshot, protectedRelativePaths = /* @__PURE__ */ new Set(), options = {}) {
|
|
389
|
-
const root = agentDir();
|
|
390
|
-
const { sessionDir } = options;
|
|
391
|
-
const excluded = compileSyncExclude(options.exclude);
|
|
392
|
-
snapshot = { ...snapshot, files: snapshot.files.filter((file) => !excluded(file.path)) };
|
|
393
|
-
const transactionOptions = {
|
|
394
|
-
sessionDir,
|
|
395
|
-
exclude: options.exclude,
|
|
396
|
-
signal: options.signal,
|
|
397
|
-
validateMutation: options.validateMutation,
|
|
398
|
-
protectedTargets: [...protectedRelativePaths].map((relative) => snapshotTarget(root, relative, sessionDir)),
|
|
399
|
-
expectedPreimages: new Map(
|
|
400
|
-
Object.entries(options.expectedFileHashes ?? {}).filter(([relative]) => !excluded(relative)).map(([relative, hash]) => [
|
|
401
|
-
snapshotTarget(root, relative, sessionDir),
|
|
402
|
-
hash === null ? "missing" : `file:${hash}`
|
|
403
|
-
])
|
|
404
|
-
)
|
|
405
|
-
};
|
|
406
|
-
options.validateMutation?.();
|
|
407
|
-
await recoverPendingSnapshotTransactions(transactionOptions);
|
|
408
|
-
const current = await createSnapshot(snapshot.profile, {
|
|
409
|
-
...options,
|
|
410
|
-
...options.include === void 0 ? { syncSessions: snapshotIncludesSessions(snapshot) } : {},
|
|
411
|
-
sessionDir
|
|
412
|
-
});
|
|
413
|
-
const plan = await addTopLevelCaseVariantDeletes(
|
|
414
|
-
root,
|
|
415
|
-
protectSnapshotApplyPlan(
|
|
416
|
-
root,
|
|
417
|
-
preflightSnapshotApply(root, snapshot, current, { sessionDir, exclude: options.exclude }),
|
|
418
|
-
protectedRelativePaths,
|
|
419
|
-
sessionDir
|
|
420
|
-
),
|
|
421
|
-
snapshot
|
|
422
|
-
);
|
|
423
|
-
await preflightSnapshotMutations(root, plan, sessionDir, options);
|
|
424
|
-
await applySnapshotTransaction(plan, transactionOptions);
|
|
425
|
-
return appliedFileHashMap(snapshot, current, protectedRelativePaths);
|
|
426
|
-
}
|
|
427
|
-
function preflightSnapshotApply(root, snapshot, current, options = {}) {
|
|
428
|
-
const seenPaths = /* @__PURE__ */ new Set();
|
|
429
|
-
const remotePaths = /* @__PURE__ */ new Set();
|
|
430
|
-
const writes = [];
|
|
431
|
-
const deletes = [];
|
|
432
|
-
const excluded = compileSyncExclude(options.exclude);
|
|
433
|
-
for (const file of snapshot.files) {
|
|
434
|
-
const normalized = toPosix(file.path);
|
|
435
|
-
if (!isSafeSnapshotPath(file.path)) {
|
|
436
|
-
throw new Error(`Unsafe path in snapshot: ${file.path}`);
|
|
437
|
-
}
|
|
438
|
-
if (isSessionPath(normalized) && !isSessionFilePath(normalized)) {
|
|
439
|
-
throw new Error(`Unsafe session path in snapshot: ${file.path}`);
|
|
440
|
-
}
|
|
441
|
-
if (excluded(normalized)) continue;
|
|
442
|
-
if (seenPaths.has(normalized)) throw new Error(`Duplicate path in snapshot: ${normalized}`);
|
|
443
|
-
seenPaths.add(normalized);
|
|
444
|
-
remotePaths.add(normalized);
|
|
445
|
-
const target = snapshotTarget(root, normalized, options.sessionDir);
|
|
446
|
-
const content = decodeBase64Strict(file.contentBase64, normalized);
|
|
447
|
-
if (sha256(content) !== file.sha256) throw new Error(`Checksum mismatch in snapshot file: ${normalized}`);
|
|
448
|
-
writes.push({ target, content });
|
|
449
|
-
}
|
|
450
|
-
const deletePaths = /* @__PURE__ */ new Set();
|
|
451
|
-
for (const file of current.files) {
|
|
452
|
-
const normalized = toPosix(file.path);
|
|
453
|
-
if (excluded(normalized)) continue;
|
|
454
|
-
if (!remotePaths.has(normalized)) {
|
|
455
|
-
deletePaths.add(snapshotTarget(root, normalized, options.sessionDir));
|
|
456
|
-
}
|
|
457
|
-
for (const remotePath of parentPaths(normalized)) {
|
|
458
|
-
if (remotePaths.has(remotePath)) {
|
|
459
|
-
deletePaths.add(snapshotTarget(root, remotePath, options.sessionDir));
|
|
460
|
-
}
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
deletes.push(...deletePaths);
|
|
464
|
-
return { writes, deletes };
|
|
465
|
-
}
|
|
466
|
-
function protectSnapshotApplyPlan(root, plan, protectedRelativePaths, sessionDir) {
|
|
467
|
-
if (protectedRelativePaths.size === 0) return plan;
|
|
468
|
-
const protectedTargets = new Set(
|
|
469
|
-
[...protectedRelativePaths].map((relativePath) => snapshotTarget(root, relativePath, sessionDir))
|
|
470
|
-
);
|
|
471
|
-
return {
|
|
472
|
-
writes: plan.writes.filter((item) => !protectedTargets.has(item.target)),
|
|
473
|
-
deletes: plan.deletes.filter((target) => !protectedTargets.has(target))
|
|
474
|
-
};
|
|
475
|
-
}
|
|
476
|
-
async function addTopLevelCaseVariantDeletes(root, plan, snapshot) {
|
|
477
|
-
const topLevelPaths = /* @__PURE__ */ new Map();
|
|
478
|
-
for (const file of snapshot.files) {
|
|
479
|
-
const normalized = toPosix(file.path);
|
|
480
|
-
if (!normalized.includes("/") && isSafeSnapshotPath(file.path)) {
|
|
481
|
-
topLevelPaths.set(normalized.toLowerCase(), normalized);
|
|
482
|
-
}
|
|
483
|
-
}
|
|
484
|
-
if (topLevelPaths.size === 0) return plan;
|
|
485
|
-
let entries;
|
|
486
|
-
try {
|
|
487
|
-
entries = await fs3.readdir(root, { withFileTypes: true });
|
|
488
|
-
} catch (error) {
|
|
489
|
-
if (error.code === "ENOENT") return plan;
|
|
490
|
-
throw error;
|
|
491
|
-
}
|
|
492
|
-
const deletes = new Set(plan.deletes);
|
|
493
|
-
for (const entry of entries) {
|
|
494
|
-
const canonicalPath = topLevelPaths.get(entry.name.toLowerCase());
|
|
495
|
-
if (canonicalPath && entry.name !== canonicalPath && (entry.isFile() || entry.isSymbolicLink())) {
|
|
496
|
-
deletes.add(safeJoin(root, entry.name));
|
|
497
|
-
}
|
|
498
|
-
}
|
|
499
|
-
return { ...plan, deletes: [...deletes] };
|
|
500
|
-
}
|
|
501
|
-
function appliedFileHashMap(snapshot, current, protectedRelativePaths) {
|
|
502
|
-
const hashes = fileHashMap2(snapshot);
|
|
503
|
-
if (protectedRelativePaths.size === 0) return hashes;
|
|
504
|
-
const currentHashes = fileHashMap2(current);
|
|
505
|
-
for (const relativePath of protectedRelativePaths) {
|
|
506
|
-
const normalized = toPosix(relativePath);
|
|
507
|
-
if (currentHashes[normalized]) {
|
|
508
|
-
hashes[normalized] = currentHashes[normalized];
|
|
509
|
-
} else {
|
|
510
|
-
delete hashes[normalized];
|
|
511
|
-
}
|
|
512
|
-
}
|
|
513
|
-
return hashes;
|
|
514
|
-
}
|
|
515
|
-
function isSafeSnapshotPath(relativePath) {
|
|
516
|
-
if (relativePath.includes("\\")) return false;
|
|
517
|
-
const normalized = toPosix(relativePath);
|
|
518
|
-
return Boolean(normalized) && normalized !== "." && normalized !== ".." && !normalized.startsWith("../") && !path3.posix.isAbsolute(normalized) && path3.posix.normalize(normalized) === normalized && !isDeniedPath(normalized);
|
|
519
|
-
}
|
|
520
|
-
function decodeBase64Strict(value, filePath) {
|
|
521
|
-
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(value) || value.length % 4 !== 0) {
|
|
522
|
-
throw new Error(`Invalid base64 content in snapshot file: ${filePath}`);
|
|
523
|
-
}
|
|
524
|
-
return Buffer.from(value, "base64");
|
|
525
|
-
}
|
|
526
|
-
async function preflightSnapshotMutations(root, plan, sessionDir, options = {}) {
|
|
527
|
-
assertMutationCurrent(options);
|
|
528
|
-
await assertUnexcludedTargets(root, [...plan.deletes, ...plan.writes.map((item) => item.target)], {
|
|
529
|
-
...options,
|
|
530
|
-
sessionDir
|
|
531
|
-
});
|
|
532
|
-
assertMutationCurrent(options);
|
|
533
|
-
const deletePaths = new Set(plan.deletes);
|
|
534
|
-
for (const target of plan.deletes) {
|
|
535
|
-
await assertNoSymlinkParents(rootForTarget(root, target, sessionDir), target, options);
|
|
536
|
-
assertMutationCurrent(options);
|
|
537
|
-
}
|
|
538
|
-
for (const item of plan.writes) {
|
|
539
|
-
await prepareSnapshotWrite(rootForTarget(root, item.target, sessionDir), item.target, deletePaths, options);
|
|
540
|
-
assertMutationCurrent(options);
|
|
541
|
-
}
|
|
542
|
-
}
|
|
543
|
-
function assertMutationCurrent(options) {
|
|
544
|
-
options.validateMutation?.();
|
|
545
|
-
options.signal?.throwIfAborted();
|
|
546
|
-
}
|
|
547
|
-
async function guardedStat(target, options) {
|
|
548
|
-
assertMutationCurrent(options);
|
|
549
|
-
let stat;
|
|
550
|
-
try {
|
|
551
|
-
stat = await fs3.lstat(target);
|
|
552
|
-
} catch (error) {
|
|
553
|
-
assertMutationCurrent(options);
|
|
554
|
-
if (error.code === "ENOENT") return void 0;
|
|
555
|
-
throw error;
|
|
556
|
-
}
|
|
557
|
-
assertMutationCurrent(options);
|
|
558
|
-
return stat;
|
|
559
|
-
}
|
|
560
|
-
function rootForTarget(root, target, sessionDir) {
|
|
561
|
-
const sessionRoot = sessionDir ? sessionStorageRoot(root, sessionDir) : void 0;
|
|
562
|
-
if (sessionRoot && isPathInside(sessionRoot, target)) return sessionRoot;
|
|
563
|
-
return root;
|
|
564
|
-
}
|
|
565
|
-
async function prepareSnapshotWrite(root, target, deletePaths, options) {
|
|
566
|
-
const parentWillBeReplaced = await ensureSafeDirectory(root, path3.dirname(target), deletePaths, options);
|
|
567
|
-
assertMutationCurrent(options);
|
|
568
|
-
if (parentWillBeReplaced) return;
|
|
569
|
-
const stat = await guardedStat(target, options);
|
|
570
|
-
assertMutationCurrent(options);
|
|
571
|
-
if (stat?.isSymbolicLink()) throw new Error(`Refusing to overwrite symlink during snapshot apply: ${target}`);
|
|
572
|
-
if (stat?.isDirectory() && !deletePaths.has(target)) {
|
|
573
|
-
throw new Error(`Refusing to overwrite directory during snapshot apply: ${target}`);
|
|
574
|
-
}
|
|
575
|
-
}
|
|
576
|
-
async function ensureSafeDirectory(root, directory, deletePaths, options) {
|
|
577
|
-
assertMutationCurrent(options);
|
|
578
|
-
assertWithinRoot(root, directory);
|
|
579
|
-
const rootPath = path3.resolve(root);
|
|
580
|
-
const relative = path3.relative(rootPath, path3.resolve(directory));
|
|
581
|
-
let current = rootPath;
|
|
582
|
-
for (const part of relative.split(path3.sep).filter(Boolean)) {
|
|
583
|
-
current = path3.join(current, part);
|
|
584
|
-
const stat = await guardedStat(current, options);
|
|
585
|
-
assertMutationCurrent(options);
|
|
586
|
-
if (stat) {
|
|
587
|
-
if (stat.isSymbolicLink()) throw new Error(`Refusing to follow symlink during snapshot apply: ${current}`);
|
|
588
|
-
if (!stat.isDirectory()) {
|
|
589
|
-
if (deletePaths.has(current)) return true;
|
|
590
|
-
throw new Error(`Snapshot path parent is not a directory: ${current}`);
|
|
591
|
-
}
|
|
592
|
-
} else {
|
|
593
|
-
await fs3.mkdir(current);
|
|
594
|
-
assertMutationCurrent(options);
|
|
595
|
-
await syncDirectory(path3.dirname(current));
|
|
596
|
-
assertMutationCurrent(options);
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
return false;
|
|
600
|
-
}
|
|
601
|
-
async function assertNoSymlinkParents(root, target, options) {
|
|
602
|
-
assertMutationCurrent(options);
|
|
603
|
-
assertWithinRoot(root, target);
|
|
604
|
-
const rootPath = path3.resolve(root);
|
|
605
|
-
const relative = path3.relative(rootPath, path3.resolve(target));
|
|
606
|
-
let current = rootPath;
|
|
607
|
-
const parts = relative.split(path3.sep).filter(Boolean);
|
|
608
|
-
for (const part of parts.slice(0, -1)) {
|
|
609
|
-
current = path3.join(current, part);
|
|
610
|
-
const stat = await guardedStat(current, options);
|
|
611
|
-
assertMutationCurrent(options);
|
|
612
|
-
if (!stat) return;
|
|
613
|
-
if (stat.isSymbolicLink()) throw new Error(`Refusing to follow symlink during snapshot apply: ${current}`);
|
|
614
|
-
if (!stat.isDirectory()) throw new Error(`Snapshot path parent is not a directory: ${current}`);
|
|
615
|
-
}
|
|
616
|
-
}
|
|
617
|
-
|
|
618
|
-
// src/sync/merge-apply.ts
|
|
619
|
-
async function preflightMergedTargets(before, after, options, protectedTarget) {
|
|
620
|
-
const root = agentDir();
|
|
621
|
-
const beforeHashes = Object.assign(/* @__PURE__ */ Object.create(null), fileHashMap(before));
|
|
622
|
-
const afterHashes = Object.assign(/* @__PURE__ */ Object.create(null), fileHashMap(after));
|
|
623
|
-
const paths = [.../* @__PURE__ */ new Set([...Object.keys(beforeHashes), ...Object.keys(afterHashes)])].sort();
|
|
624
|
-
const changed = new Set(paths.filter((item) => beforeHashes[item] !== afterHashes[item]));
|
|
625
|
-
await assertUnexcludedTargets(
|
|
626
|
-
root,
|
|
627
|
-
[...changed].map((item) => snapshotTarget(root, item, options.sessionDir)),
|
|
628
|
-
options
|
|
629
|
-
);
|
|
630
|
-
await assertCanonicalMergedTargets(root, changed, options);
|
|
631
|
-
await assertDistinctMergedTargets(root, paths, changed, options, protectedTarget, new Set(Object.keys(afterHashes)));
|
|
632
|
-
const removed = replacementPaths(
|
|
633
|
-
new Set(paths.filter((item) => changed.has(item) && !afterHashes[item])),
|
|
634
|
-
afterHashes
|
|
635
|
-
);
|
|
636
|
-
const removedTargets = new Set([...removed].map((item) => snapshotTarget(root, item, options.sessionDir)));
|
|
637
|
-
for (const relative of paths) {
|
|
638
|
-
if (changed.has(relative)) await assertFilesystemTarget(root, relative, options, removedTargets, beforeHashes);
|
|
639
|
-
}
|
|
640
|
-
await assertCanonicalMutationTargets(
|
|
641
|
-
[...changed].map((relative) => snapshotTarget(root, relative, options.sessionDir)),
|
|
642
|
-
options
|
|
643
|
-
);
|
|
644
|
-
}
|
|
645
|
-
function replacementPaths(removed, afterHashes) {
|
|
646
|
-
for (const relative of [...removed]) {
|
|
647
|
-
let parent = path4.posix.dirname(relative);
|
|
648
|
-
while (parent !== ".") {
|
|
649
|
-
if (afterHashes[parent]) {
|
|
650
|
-
for (let directory = path4.posix.dirname(relative); directory !== parent; directory = path4.posix.dirname(directory))
|
|
651
|
-
removed.add(directory);
|
|
652
|
-
removed.add(parent);
|
|
653
|
-
break;
|
|
654
|
-
}
|
|
655
|
-
parent = path4.posix.dirname(parent);
|
|
656
|
-
}
|
|
657
|
-
}
|
|
658
|
-
return removed;
|
|
659
|
-
}
|
|
660
|
-
async function assertCanonicalMergedTargets(root, changed, options) {
|
|
661
|
-
const topLevel = new Map(
|
|
662
|
-
[...changed].filter((relative) => !relative.includes("/")).map((relative) => [relative.toLowerCase(), relative])
|
|
663
|
-
);
|
|
664
|
-
if (topLevel.size === 0) return;
|
|
665
|
-
options.signal?.throwIfAborted();
|
|
666
|
-
options.validateMutation?.();
|
|
667
|
-
let names;
|
|
668
|
-
try {
|
|
669
|
-
names = await fs4.readdir(root);
|
|
670
|
-
} catch (error) {
|
|
671
|
-
options.signal?.throwIfAborted();
|
|
672
|
-
options.validateMutation?.();
|
|
673
|
-
if (error.code !== "ENOENT") throw error;
|
|
674
|
-
return;
|
|
675
|
-
}
|
|
676
|
-
options.signal?.throwIfAborted();
|
|
677
|
-
options.validateMutation?.();
|
|
678
|
-
for (const name of names) {
|
|
679
|
-
const canonical = topLevel.get(name.toLowerCase());
|
|
680
|
-
if (canonical !== void 0 && name !== canonical)
|
|
681
|
-
throw new Error(
|
|
682
|
-
"Merged target has a noncanonical case variant; normalize selected top-level file spelling before retrying. Journal retained if already committed."
|
|
683
|
-
);
|
|
684
|
-
}
|
|
685
|
-
}
|
|
686
|
-
async function assertDistinctMergedTargets(root, paths, changed, options, protectedTarget, finalPaths = new Set(paths)) {
|
|
687
|
-
const protectedKey = protectedTarget ? mergePathIdentity(await resolvedTargetIdentity(path4.resolve(protectedTarget), options)) : void 0;
|
|
688
|
-
options.signal?.throwIfAborted();
|
|
689
|
-
options.validateMutation?.();
|
|
690
|
-
const keys = /* @__PURE__ */ new Map();
|
|
691
|
-
for (const relative of paths) {
|
|
692
|
-
options.signal?.throwIfAborted();
|
|
693
|
-
const target = snapshotTarget(root, relative, options.sessionDir);
|
|
694
|
-
const key = mergePathIdentity(await resolvedTargetIdentity(target, options));
|
|
695
|
-
options.signal?.throwIfAborted();
|
|
696
|
-
options.validateMutation?.();
|
|
697
|
-
const existing = keys.get(key);
|
|
698
|
-
if (existing && (mergePathIdentity(existing) !== mergePathIdentity(relative) || finalPaths.has(existing) && finalPaths.has(relative)))
|
|
699
|
-
throw new Error("Merged paths resolve to the same file; reviewed directional recovery is required.");
|
|
700
|
-
if (key === protectedKey && changed.has(relative))
|
|
701
|
-
throw new Error("A merged transfer targets the current session; review is required.");
|
|
702
|
-
keys.set(key, relative);
|
|
703
|
-
}
|
|
704
|
-
}
|
|
705
|
-
async function assertReviewedTree(directory, relative, beforeHashes) {
|
|
706
|
-
for (const name of await fs4.readdir(directory)) {
|
|
707
|
-
const child = path4.join(directory, name);
|
|
708
|
-
const childRelative = `${relative}/${name}`;
|
|
709
|
-
const stat = await fs4.lstat(child);
|
|
710
|
-
if (stat.isDirectory()) {
|
|
711
|
-
await assertReviewedTree(child, childRelative, beforeHashes);
|
|
712
|
-
} else if (stat.isFile() && stat.nlink === 1 && beforeHashes[childRelative] === createHash2("sha256").update(await fs4.readFile(child)).digest("hex")) {
|
|
713
|
-
} else {
|
|
714
|
-
throw new Error("Reviewed directory contains unknown or changed files; publication refused.");
|
|
715
|
-
}
|
|
716
|
-
}
|
|
717
|
-
}
|
|
718
|
-
function hasBlockingFileAncestor(target, files) {
|
|
719
|
-
for (let parent = path4.dirname(target); parent !== path4.dirname(parent); parent = path4.dirname(parent))
|
|
720
|
-
if (files.has(parent)) return true;
|
|
721
|
-
return false;
|
|
722
|
-
}
|
|
723
|
-
async function resolvedTargetIdentity(target, options) {
|
|
724
|
-
let ancestor = target;
|
|
725
|
-
while (true) {
|
|
726
|
-
options.signal?.throwIfAborted();
|
|
727
|
-
try {
|
|
728
|
-
const resolved = await fs4.realpath(ancestor);
|
|
729
|
-
return path4.resolve(resolved, path4.relative(ancestor, target));
|
|
730
|
-
} catch (error) {
|
|
731
|
-
const code = error.code;
|
|
732
|
-
if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
|
|
733
|
-
const parent = path4.dirname(ancestor);
|
|
734
|
-
if (parent === ancestor) return target;
|
|
735
|
-
ancestor = parent;
|
|
736
|
-
}
|
|
737
|
-
}
|
|
738
|
-
}
|
|
739
|
-
async function assertFilesystemTarget(root, relative, options, removedTargets = /* @__PURE__ */ new Set(), beforeHashes) {
|
|
740
|
-
const target = snapshotTarget(root, relative, options.sessionDir);
|
|
741
|
-
const boundary = relative.startsWith("sessions/") && options.sessionDir ? path4.resolve(sessionStorageRoot(root, options.sessionDir)) : path4.resolve(root);
|
|
742
|
-
for (let parent = path4.dirname(target); mergePathIdentity(parent) !== mergePathIdentity(boundary); parent = path4.dirname(parent)) {
|
|
743
|
-
options.signal?.throwIfAborted();
|
|
744
|
-
if (path4.dirname(parent) === parent) throw new Error("Unowned merged target.");
|
|
745
|
-
try {
|
|
746
|
-
const stat = await fs4.lstat(parent);
|
|
747
|
-
if ((!stat.isDirectory() || stat.isSymbolicLink()) && !(stat.isFile() && stat.nlink === 1 && removedTargets.has(parent)))
|
|
748
|
-
throw new Error("Unsafe merge filesystem layout; review the selected paths before transfer.");
|
|
749
|
-
} catch (error) {
|
|
750
|
-
const code = error.code;
|
|
751
|
-
if (code !== "ENOENT") throw error;
|
|
752
|
-
}
|
|
753
|
-
}
|
|
754
|
-
options.signal?.throwIfAborted();
|
|
755
|
-
try {
|
|
756
|
-
const stat = await fs4.lstat(target);
|
|
757
|
-
if (!stat.isFile() && !removedTargets.has(target) || stat.isFile() && stat.nlink > 1)
|
|
758
|
-
throw new Error("Merge target is non-regular or hard-linked; review a directional operation before transfer.");
|
|
759
|
-
if (stat.isDirectory() && beforeHashes) await assertReviewedTree(target, relative, beforeHashes);
|
|
760
|
-
} catch (error) {
|
|
761
|
-
const code = error.code;
|
|
762
|
-
if (code !== "ENOENT" && !(code === "ENOTDIR" && removedTargets.size > 0)) throw error;
|
|
763
|
-
}
|
|
764
|
-
}
|
|
765
|
-
async function applyMergedSnapshot(before, after, protectedPaths, options, validate, protectedTarget) {
|
|
766
|
-
const root = agentDir();
|
|
767
|
-
const beforeHashes = Object.assign(/* @__PURE__ */ Object.create(null), fileHashMap(before));
|
|
768
|
-
const afterHashes = Object.assign(/* @__PURE__ */ Object.create(null), fileHashMap(after));
|
|
769
|
-
const paths = [.../* @__PURE__ */ new Set([...Object.keys(beforeHashes), ...Object.keys(afterHashes)])].sort();
|
|
770
|
-
const replacements = replacementPaths(
|
|
771
|
-
new Set(paths.filter((item) => beforeHashes[item] && !afterHashes[item])),
|
|
772
|
-
afterHashes
|
|
773
|
-
);
|
|
774
|
-
const intermediateDirectories = [...replacements].filter((item) => !beforeHashes[item] && !afterHashes[item]);
|
|
775
|
-
const changed = [
|
|
776
|
-
.../* @__PURE__ */ new Set([...paths.filter((item) => beforeHashes[item] !== afterHashes[item]), ...intermediateDirectories])
|
|
777
|
-
].sort();
|
|
778
|
-
const protectedKeys = new Set([...protectedPaths].map(mergePathIdentity));
|
|
779
|
-
if (changed.some((item) => protectedKeys.has(mergePathIdentity(item)))) {
|
|
780
|
-
throw new Error("A merged transfer targets the current session; review is required.");
|
|
781
|
-
}
|
|
782
|
-
const targets = changed.map((item) => snapshotTarget(root, item, options.sessionDir));
|
|
783
|
-
const relativeByTarget = new Map(targets.map((target, index) => [target, changed[index]]));
|
|
784
|
-
const targetSet = new Set(targets);
|
|
785
|
-
await assertDistinctMergedTargets(
|
|
786
|
-
root,
|
|
787
|
-
paths,
|
|
788
|
-
new Set(changed),
|
|
789
|
-
options,
|
|
790
|
-
protectedTarget,
|
|
791
|
-
new Set(Object.keys(afterHashes))
|
|
792
|
-
);
|
|
793
|
-
await assertCanonicalMutationTargets(targets, options);
|
|
794
|
-
const targetsByQueue = /* @__PURE__ */ new Map();
|
|
795
|
-
const queueTargets = [];
|
|
796
|
-
const deferredTargets = [];
|
|
797
|
-
for (const target of targets) {
|
|
798
|
-
let key = path4.resolve(target);
|
|
799
|
-
try {
|
|
800
|
-
key = await fs4.realpath(target);
|
|
801
|
-
} catch (error) {
|
|
802
|
-
const code = error.code;
|
|
803
|
-
if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
|
|
804
|
-
}
|
|
805
|
-
options.signal?.throwIfAborted();
|
|
806
|
-
options.validateMutation?.();
|
|
807
|
-
const aliases = targetsByQueue.get(key) ?? [];
|
|
808
|
-
aliases.push(target);
|
|
809
|
-
targetsByQueue.set(key, aliases);
|
|
810
|
-
}
|
|
811
|
-
for (const [key, aliases] of targetsByQueue) {
|
|
812
|
-
queueTargets.push(key);
|
|
813
|
-
if (aliases.length > 1) deferredTargets.push(...aliases.filter((target) => path4.resolve(target) !== key));
|
|
814
|
-
}
|
|
815
|
-
async function acquire(index) {
|
|
816
|
-
const target = queueTargets[index];
|
|
817
|
-
if (target) return withFileMutationQueue(target, () => acquire(index + 1));
|
|
818
|
-
await validate();
|
|
819
|
-
await assertCanonicalMergedTargets(root, changed, options);
|
|
820
|
-
await validate();
|
|
821
|
-
const current = await createSnapshot(before.profile, options);
|
|
822
|
-
const currentHashes = Object.assign(/* @__PURE__ */ Object.create(null), fileHashMap(current));
|
|
823
|
-
const blockingFiles = new Set(
|
|
824
|
-
paths.filter(
|
|
825
|
-
(relative) => beforeHashes[relative] && !afterHashes[relative] || afterHashes[relative] && currentHashes[relative] === afterHashes[relative]
|
|
826
|
-
).map((relative) => snapshotTarget(root, relative, options.sessionDir))
|
|
827
|
-
);
|
|
828
|
-
for (const item of changed) {
|
|
829
|
-
if (currentHashes[item] !== beforeHashes[item] && currentHashes[item] !== afterHashes[item]) {
|
|
830
|
-
throw new Error(
|
|
831
|
-
"Local content changed during merged transfer; journal retained for review. No newer bytes were replaced."
|
|
832
|
-
);
|
|
833
|
-
}
|
|
834
|
-
const target2 = snapshotTarget(root, item, options.sessionDir);
|
|
835
|
-
try {
|
|
836
|
-
const stat = await fs4.lstat(target2);
|
|
837
|
-
if (!stat.isFile() && !stat.isDirectory() || stat.isFile() && stat.nlink > 1)
|
|
838
|
-
throw new Error("Merged transfer target is no longer an independent regular file.");
|
|
839
|
-
} catch (error) {
|
|
840
|
-
const code = error.code;
|
|
841
|
-
if (code !== "ENOENT" && !(code === "ENOTDIR" && hasBlockingFileAncestor(target2, blockingFiles))) throw error;
|
|
842
|
-
}
|
|
843
|
-
}
|
|
844
|
-
const plan = preflightSnapshotApply(root, after, current, options);
|
|
845
|
-
plan.writes = plan.writes.filter((item) => targetSet.has(item.target));
|
|
846
|
-
plan.deletes = plan.deletes.filter((target2) => targetSet.has(target2));
|
|
847
|
-
await preflightSnapshotMutations(root, plan, options.sessionDir, options);
|
|
848
|
-
const deletedTargets = new Set(plan.deletes);
|
|
849
|
-
for (const relative of intermediateDirectories) {
|
|
850
|
-
for (let parent = path4.posix.dirname(relative); parent !== "."; parent = path4.posix.dirname(parent)) {
|
|
851
|
-
if (afterHashes[parent] && deletedTargets.has(snapshotTarget(root, parent, options.sessionDir))) {
|
|
852
|
-
plan.deletes.push(snapshotTarget(root, relative, options.sessionDir));
|
|
853
|
-
break;
|
|
854
|
-
}
|
|
855
|
-
}
|
|
856
|
-
}
|
|
857
|
-
plan.deletes.sort(
|
|
858
|
-
(left, right) => right.split(path4.sep).length - left.split(path4.sep).length || left.localeCompare(right)
|
|
859
|
-
);
|
|
860
|
-
const removed = replacementPaths(
|
|
861
|
-
new Set(paths.filter((relative) => deletedTargets.has(snapshotTarget(root, relative, options.sessionDir)))),
|
|
862
|
-
afterHashes
|
|
863
|
-
);
|
|
864
|
-
const removedTargets = new Set([...removed].map((item) => snapshotTarget(root, item, options.sessionDir)));
|
|
865
|
-
await assertCanonicalMergedTargets(root, changed, options);
|
|
866
|
-
await validate();
|
|
867
|
-
const revalidateTarget = async (target2) => {
|
|
868
|
-
await validate();
|
|
869
|
-
const relative = relativeByTarget.get(target2);
|
|
870
|
-
if (!relative) throw new Error("Unowned merge target.");
|
|
871
|
-
await assertFilesystemTarget(root, relative, options, removedTargets, currentHashes);
|
|
872
|
-
await validate();
|
|
873
|
-
let hash;
|
|
874
|
-
try {
|
|
875
|
-
const stat = await fs4.lstat(target2);
|
|
876
|
-
if (stat.isDirectory() && removed.has(relative)) {
|
|
877
|
-
if ((await fs4.readdir(target2)).length)
|
|
878
|
-
throw new Error("Reviewed directory has remaining contents; journal retained for review.");
|
|
879
|
-
} else {
|
|
880
|
-
if (!stat.isFile() || stat.nlink > 1)
|
|
881
|
-
throw new Error("Merged transfer target is no longer an independent regular file.");
|
|
882
|
-
hash = createHash2("sha256").update(await fs4.readFile(target2)).digest("hex");
|
|
883
|
-
}
|
|
884
|
-
} catch (error) {
|
|
885
|
-
if (error.code !== "ENOENT") throw error;
|
|
886
|
-
}
|
|
887
|
-
options.signal?.throwIfAborted();
|
|
888
|
-
options.validateMutation?.();
|
|
889
|
-
if (hash !== beforeHashes[relative] && hash !== afterHashes[relative])
|
|
890
|
-
throw new Error("Local content changed at the apply boundary; journal retained, newer bytes untouched.");
|
|
891
|
-
};
|
|
892
|
-
for (const target2 of plan.deletes) {
|
|
893
|
-
await revalidateTarget(target2);
|
|
894
|
-
try {
|
|
895
|
-
const stat = await fs4.lstat(target2);
|
|
896
|
-
await validate();
|
|
897
|
-
if (stat.isDirectory())
|
|
898
|
-
await fs4.rmdir(target2);
|
|
899
|
-
else await fs4.rm(target2, { force: true });
|
|
900
|
-
} catch (error) {
|
|
901
|
-
if (error.code !== "ENOENT") throw error;
|
|
902
|
-
}
|
|
903
|
-
await syncDirectory(path4.dirname(target2));
|
|
904
|
-
}
|
|
905
|
-
const requireAbsentDestinations = async () => {
|
|
906
|
-
await validate();
|
|
907
|
-
for (const target2 of deferredTargets) {
|
|
908
|
-
try {
|
|
909
|
-
await fs4.lstat(target2);
|
|
910
|
-
} catch (error) {
|
|
911
|
-
if (error.code !== "ENOENT") throw error;
|
|
912
|
-
continue;
|
|
913
|
-
}
|
|
914
|
-
throw new Error("Case replacement destination changed before queue reservation; journal retained for review.");
|
|
915
|
-
}
|
|
916
|
-
await validate();
|
|
917
|
-
};
|
|
918
|
-
async function acquireDestinations(index2) {
|
|
919
|
-
const target2 = deferredTargets[index2];
|
|
920
|
-
if (target2) return withFileMutationQueue(target2, () => acquireDestinations(index2 + 1));
|
|
921
|
-
await requireAbsentDestinations();
|
|
922
|
-
await writeTargets();
|
|
923
|
-
}
|
|
924
|
-
await requireAbsentDestinations();
|
|
925
|
-
await acquireDestinations(0);
|
|
926
|
-
async function writeTargets() {
|
|
927
|
-
for (const item of plan.writes) {
|
|
928
|
-
await validate();
|
|
929
|
-
const relative = relativeByTarget.get(item.target);
|
|
930
|
-
if (!relative) throw new Error("Unowned merge write target.");
|
|
931
|
-
await assertFilesystemTarget(root, relative, options, /* @__PURE__ */ new Set());
|
|
932
|
-
await fs4.mkdir(path4.dirname(item.target), { recursive: true });
|
|
933
|
-
const temporary = path4.join(path4.dirname(item.target), `.pi-sync.json.${randomUUID()}.apply`);
|
|
934
|
-
let mode = 384;
|
|
935
|
-
try {
|
|
936
|
-
mode = (await fs4.stat(item.target)).mode & 511;
|
|
937
|
-
} catch (error) {
|
|
938
|
-
if (error.code !== "ENOENT") throw error;
|
|
939
|
-
}
|
|
940
|
-
try {
|
|
941
|
-
const handle = await fs4.open(temporary, "wx", mode);
|
|
942
|
-
try {
|
|
943
|
-
await handle.writeFile(item.content);
|
|
944
|
-
await handle.sync();
|
|
945
|
-
} finally {
|
|
946
|
-
await handle.close();
|
|
947
|
-
}
|
|
948
|
-
await revalidateTarget(item.target);
|
|
949
|
-
await fs4.rename(temporary, item.target);
|
|
950
|
-
await syncDirectory(path4.dirname(item.target));
|
|
951
|
-
} finally {
|
|
952
|
-
await fs4.rm(temporary, { force: true });
|
|
953
|
-
}
|
|
954
|
-
}
|
|
955
|
-
await syncMutationParents(
|
|
956
|
-
targets,
|
|
957
|
-
[root, ...options.sessionDir ? [sessionStorageRoot(root, options.sessionDir)] : []],
|
|
958
|
-
options
|
|
959
|
-
);
|
|
960
|
-
await validate();
|
|
961
|
-
}
|
|
962
|
-
}
|
|
963
|
-
await acquire(0);
|
|
964
|
-
}
|
|
965
|
-
|
|
966
|
-
// src/sync/merge-transfer-error.ts
|
|
967
|
-
var MAX_CAUSES = 4;
|
|
968
|
-
var MAX_DETAIL_LENGTH = 600;
|
|
969
|
-
function mergeTransferError(error, backend) {
|
|
970
|
-
const messages = [];
|
|
971
|
-
const seen = /* @__PURE__ */ new Set();
|
|
972
|
-
let current = error;
|
|
973
|
-
while (current instanceof Error && !seen.has(current) && seen.size < MAX_CAUSES) {
|
|
974
|
-
seen.add(current);
|
|
975
|
-
const code = current.code;
|
|
976
|
-
const status = current.status;
|
|
977
|
-
const metadata = [
|
|
978
|
-
typeof code === "string" && /^[A-Z][A-Z0-9_]{1,63}$/u.test(code) ? code : void 0,
|
|
979
|
-
typeof status === "number" && Number.isInteger(status) && status >= 100 && status <= 599 ? `HTTP ${status}` : void 0
|
|
980
|
-
].filter(Boolean);
|
|
981
|
-
const message = `${current.message}${metadata.length ? ` (${metadata.join(", ")})` : ""}`;
|
|
982
|
-
if (message && !messages.includes(message)) messages.push(message);
|
|
983
|
-
current = current.cause;
|
|
984
|
-
}
|
|
985
|
-
let detail = messages.join(" \u2192 ") || "No error details available.";
|
|
986
|
-
for (const secret of credentialVariants(backend)) detail = detail.replaceAll(secret, "[REDACTED]");
|
|
987
|
-
detail = detail.replace(/\b(Bearer|Basic)\s+[^\s<>"']+/giu, "$1 [REDACTED]");
|
|
988
|
-
detail = safeTerminalText(detail);
|
|
989
|
-
if (detail.length > MAX_DETAIL_LENGTH) detail = `${detail.slice(0, MAX_DETAIL_LENGTH)}\u2026 (details truncated)`;
|
|
990
|
-
return new Error(
|
|
991
|
-
`Merged transfer interrupted; journal and backup retained. Run /sync sync to reconcile before further mutations. Transfer failure: ${detail}`,
|
|
992
|
-
{ cause: error }
|
|
993
|
-
);
|
|
994
|
-
}
|
|
995
|
-
function credentialVariants(backend) {
|
|
996
|
-
const secrets = [];
|
|
997
|
-
let address;
|
|
998
|
-
switch (backend.type) {
|
|
999
|
-
case "s3":
|
|
1000
|
-
secrets.push(backend.profile.accessKeyId, backend.profile.secretAccessKey, backend.profile.sessionToken ?? "");
|
|
1001
|
-
address = backend.profile.endpoint;
|
|
1002
|
-
break;
|
|
1003
|
-
case "webdav":
|
|
1004
|
-
secrets.push(
|
|
1005
|
-
backend.profile.username,
|
|
1006
|
-
backend.profile.password,
|
|
1007
|
-
Buffer.from(`${backend.profile.username}:${backend.profile.password}`).toString("base64")
|
|
1008
|
-
);
|
|
1009
|
-
address = backend.profile.url;
|
|
1010
|
-
break;
|
|
1011
|
-
case "git":
|
|
1012
|
-
address = backend.profile.remote;
|
|
1013
|
-
break;
|
|
1014
|
-
}
|
|
1015
|
-
try {
|
|
1016
|
-
const url = new URL(address);
|
|
1017
|
-
secrets.push(url.username, url.password, ...url.searchParams.values());
|
|
1018
|
-
for (const value of [url.username, url.password]) secrets.push(decodeURIComponent(value));
|
|
1019
|
-
} catch {
|
|
1020
|
-
}
|
|
1021
|
-
return [
|
|
1022
|
-
...new Set(
|
|
1023
|
-
secrets.filter(Boolean).flatMap((value) => [value, encodeURIComponent(value), JSON.stringify(value).slice(1, -1)])
|
|
1024
|
-
)
|
|
1025
|
-
].sort((left, right) => right.length - left.length);
|
|
1026
|
-
}
|
|
1027
|
-
|
|
1028
|
-
// src/sync/partial-progress.ts
|
|
1029
|
-
function acceptedMergeFiles(decisions, localFiles, withheld) {
|
|
1030
|
-
const localByPath = new Map(localFiles.map((file) => [file.path, file]));
|
|
1031
|
-
return decisions.flatMap((decision) => {
|
|
1032
|
-
const file = withheld.has(decision.path) ? localByPath.get(decision.path) : decision.kind === "accepted" ? decision.file : void 0;
|
|
1033
|
-
return file ? [file] : [];
|
|
1034
|
-
});
|
|
1035
|
-
}
|
|
1036
|
-
function progressState(config, head, snapshot, progress) {
|
|
1037
|
-
const withheld = new Set(progress.groups.flatMap((group) => group.paths));
|
|
1038
|
-
const current = fileHashMap(snapshot);
|
|
1039
|
-
const hashes = Object.assign(/* @__PURE__ */ Object.create(null), progress.previous.lastFileHashes);
|
|
1040
|
-
for (const key of /* @__PURE__ */ new Set([...Object.keys(hashes), ...Object.keys(current)])) {
|
|
1041
|
-
if (withheld.has(key)) continue;
|
|
1042
|
-
const value = current[key];
|
|
1043
|
-
if (value === void 0) delete hashes[key];
|
|
1044
|
-
else hashes[key] = value;
|
|
1045
|
-
}
|
|
1046
|
-
return {
|
|
1047
|
-
...progress.previous,
|
|
1048
|
-
version: 3,
|
|
1049
|
-
profile: config.snapshotIdentity,
|
|
1050
|
-
lastFileHashes: hashes,
|
|
1051
|
-
include: [...config.include],
|
|
1052
|
-
exclude: config.exclude === void 0 ? void 0 : [...config.exclude],
|
|
1053
|
-
localFields: config.localFields,
|
|
1054
|
-
lastObservedSnapshot: head.snapshotId,
|
|
1055
|
-
lastObservedRevision: head.revision,
|
|
1056
|
-
unresolved: progress.groups
|
|
1057
|
-
};
|
|
1058
|
-
}
|
|
1059
|
-
|
|
1060
|
-
// src/sync/settings-conflicts.ts
|
|
1061
|
-
import { createHash as createHash3 } from "node:crypto";
|
|
1062
|
-
async function resolveSettingsConflicts(config, state, local, remote, plan) {
|
|
1063
|
-
if (plan.kind !== "planned") return { plan, fields: [] };
|
|
1064
|
-
const fields = [];
|
|
1065
|
-
const decisions = [...plan.decisions];
|
|
1066
|
-
for (let index = 0; index < decisions.length; index++) {
|
|
1067
|
-
const decision = decisions[index];
|
|
1068
|
-
if (decision?.path !== "settings.json") continue;
|
|
1069
|
-
if (decision.kind === "conflict" ? decision.reason !== "both-changed" : !config.agentMode) continue;
|
|
1070
|
-
const left = local.files.find((file) => file.path === decision.path);
|
|
1071
|
-
const right = remote.files.find((file) => file.path === decision.path);
|
|
1072
|
-
if (!left || !right) continue;
|
|
1073
|
-
const ancestor = await readMergeAncestor(config, state, decision.path);
|
|
1074
|
-
if (!ancestor) continue;
|
|
1075
|
-
const leftBytes = Buffer.from(left.contentBase64, "base64");
|
|
1076
|
-
const rightBytes = Buffer.from(right.contentBase64, "base64");
|
|
1077
|
-
let content;
|
|
1078
|
-
if (decision.kind === "accepted") {
|
|
1079
|
-
if (!decision.file) continue;
|
|
1080
|
-
const patched = mergeAcceptedSettingsPackages(
|
|
1081
|
-
ancestor,
|
|
1082
|
-
leftBytes,
|
|
1083
|
-
rightBytes,
|
|
1084
|
-
Buffer.from(decision.file.contentBase64, "base64")
|
|
1085
|
-
);
|
|
1086
|
-
if (!patched) continue;
|
|
1087
|
-
content = patched;
|
|
1088
|
-
} else {
|
|
1089
|
-
const merged = mergeSettingsJson(ancestor, leftBytes, rightBytes, void 0, Boolean(config.agentMode));
|
|
1090
|
-
if (merged.kind === "review") {
|
|
1091
|
-
fields.push(...merged.fields);
|
|
1092
|
-
continue;
|
|
1093
|
-
}
|
|
1094
|
-
content = merged.content;
|
|
1095
|
-
}
|
|
1096
|
-
decisions[index] = {
|
|
1097
|
-
kind: "accepted",
|
|
1098
|
-
path: decision.path,
|
|
1099
|
-
source: "merged",
|
|
1100
|
-
file: {
|
|
1101
|
-
path: decision.path,
|
|
1102
|
-
contentBase64: content.toString("base64"),
|
|
1103
|
-
sha256: createHash3("sha256").update(content).digest("hex")
|
|
1104
|
-
}
|
|
1105
|
-
};
|
|
1106
|
-
}
|
|
1107
|
-
return {
|
|
1108
|
-
plan: { kind: "planned", decisions, conflicts: decisions.filter((decision) => decision.kind === "conflict") },
|
|
1109
|
-
fields
|
|
1110
|
-
};
|
|
1111
|
-
}
|
|
1112
|
-
|
|
1113
|
-
// src/ui/sync-format.ts
|
|
1114
|
-
function formatDiff(local, remote) {
|
|
1115
|
-
const localMap = fileHashMap(local);
|
|
1116
|
-
const remoteMap = fileHashMap(remote);
|
|
1117
|
-
const allPaths = [.../* @__PURE__ */ new Set([...Object.keys(localMap), ...Object.keys(remoteMap)])].sort();
|
|
1118
|
-
const lines = [
|
|
1119
|
-
`local: ${local.files.length} files`,
|
|
1120
|
-
`remote: ${safeTerminalText(remote.id)} (${remote.files.length} files)`,
|
|
1121
|
-
""
|
|
1122
|
-
];
|
|
1123
|
-
let changed = 0;
|
|
1124
|
-
for (const filePath of allPaths) {
|
|
1125
|
-
if (!Object.hasOwn(localMap, filePath)) {
|
|
1126
|
-
lines.push(`Remote only: ${snapshotPathLabel(filePath)}`);
|
|
1127
|
-
changed += 1;
|
|
1128
|
-
} else if (!Object.hasOwn(remoteMap, filePath)) {
|
|
1129
|
-
lines.push(`Local only: ${snapshotPathLabel(filePath)}`);
|
|
1130
|
-
changed += 1;
|
|
1131
|
-
} else if (localMap[filePath] !== remoteMap[filePath]) {
|
|
1132
|
-
lines.push(`Different: ${snapshotPathLabel(filePath)}`);
|
|
1133
|
-
changed += 1;
|
|
1134
|
-
}
|
|
1135
|
-
}
|
|
1136
|
-
if (changed === 0) lines.push("No file differences.");
|
|
1137
|
-
return lines.join("\n");
|
|
1138
|
-
}
|
|
1139
|
-
function formatSnapshotOnlyDiff(title, snapshot) {
|
|
1140
|
-
return [
|
|
1141
|
-
`${safeTerminalText(title)}: ${safeTerminalText(snapshot.id)}`,
|
|
1142
|
-
...snapshot.files.map((file) => `Add: ${snapshotPathLabel(file.path)}`)
|
|
1143
|
-
].join("\n");
|
|
1144
|
-
}
|
|
1145
|
-
function formatPushSummary(config, destination, upload, head, preservedRemoteFileCount = 0, remote) {
|
|
1146
|
-
return [
|
|
1147
|
-
`Sync setup: ${safeTerminalText(config.setupName)}`,
|
|
1148
|
-
`Storage location: ${safeTerminalText(destination)}`,
|
|
1149
|
-
`Direction: Local \u2192 Remote. Source: ${safeTerminalText(agentDir())}.`,
|
|
1150
|
-
`Publish a snapshot containing ${upload.files.length} files; unchanged and preserved files are not counted as changes.`,
|
|
1151
|
-
`Sessions: ${upload.syncSessions ? "included \u2014 may contain private conversations" : "not included"}`,
|
|
1152
|
-
...excludedPolicyLines(config),
|
|
1153
|
-
head ? `Remote latest: ${safeTerminalText(head.snapshotId)}` : "Remote latest: empty",
|
|
1154
|
-
"Publication effect: the backend's active head will reference the new immutable snapshot. Removed paths leave the active snapshot; retained history is not erased.",
|
|
1155
|
-
...remote && inspectRemoteSelection(config.include, remote, config.exclude).kind === "different" ? ["Included-content policy effect: replace the differing remote selection with this setup's local selection."] : [],
|
|
1156
|
-
formatPublicationPreview(remote, upload),
|
|
1157
|
-
config.skipSecretScan ? "Warning: possible-secret scanning is disabled for this push." : preservedRemoteFileCount > 0 ? `Possible secrets in locally managed files were scanned before this prompt; ${preservedRemoteFileCount} preserved remote file(s) were not rescanned.` : "Possible secrets were scanned before this prompt."
|
|
1158
|
-
].join("\n");
|
|
1159
|
-
}
|
|
1160
|
-
function excludedPolicyLines(config) {
|
|
1161
|
-
return config.exclude === void 0 ? [] : [
|
|
1162
|
-
`Excluded paths: ${config.exclude.map(safeTerminalText).join(", ") || "none"}`,
|
|
1163
|
-
"Excluded local files remain untouched; matching paths are omitted from new publications, not erased from history."
|
|
1164
|
-
];
|
|
1165
|
-
}
|
|
1166
|
-
function formatApplyPreview(local, remote, protectedPaths = /* @__PURE__ */ new Set(), additionalRemovals = []) {
|
|
1167
|
-
return formatDirectionalChanges(
|
|
1168
|
-
local,
|
|
1169
|
-
remote,
|
|
1170
|
-
{
|
|
1171
|
-
add: "Add locally",
|
|
1172
|
-
update: "Update locally",
|
|
1173
|
-
remove: "Remove locally"
|
|
1174
|
-
},
|
|
1175
|
-
protectedPaths,
|
|
1176
|
-
additionalRemovals
|
|
1177
|
-
);
|
|
1178
|
-
}
|
|
1179
|
-
function formatPullSummary(config, destination, local, remote, protectedPaths, additionalRemovals = []) {
|
|
1180
|
-
return [
|
|
1181
|
-
`Sync setup: ${safeTerminalText(config.setupName)}`,
|
|
1182
|
-
`Storage location: ${safeTerminalText(destination)}`,
|
|
1183
|
-
"Direction: Remote \u2192 Local.",
|
|
1184
|
-
`Snapshot: ${safeTerminalText(remote.id)}`,
|
|
1185
|
-
...excludedPolicyLines(config),
|
|
1186
|
-
`Sessions: ${remote.syncSessions ? "included \u2014 may contain private conversations" : "not included"}`,
|
|
1187
|
-
`Protected live sessions: ${protectedPaths.size || "none"}`,
|
|
1188
|
-
formatApplyPreview(local, remote, protectedPaths, additionalRemovals),
|
|
1189
|
-
...additionalRemovals.length ? ["Case-variant aliases listed above are removed before writing canonical paths."] : [],
|
|
1190
|
-
"A local backup is created before these writes/deletes. The remote active snapshot is unchanged."
|
|
1191
|
-
].join("\n");
|
|
1192
|
-
}
|
|
1193
|
-
function formatRollbackSummary(config, destination, local, remote, requestedSnapshot, protectedPaths, additionalRemovals = []) {
|
|
1194
|
-
return [
|
|
1195
|
-
`Sync setup: ${safeTerminalText(config.setupName)}`,
|
|
1196
|
-
`Storage location: ${safeTerminalText(destination)}`,
|
|
1197
|
-
"Direction: Historical snapshot \u2192 Local and remote active head.",
|
|
1198
|
-
`Snapshot: ${safeTerminalText(requestedSnapshot)}`,
|
|
1199
|
-
...excludedPolicyLines(config),
|
|
1200
|
-
`Sessions: ${remote.syncSessions ? "included \u2014 may contain private conversations" : "not included"}`,
|
|
1201
|
-
`Protected live sessions: ${protectedPaths.size || "none"}`,
|
|
1202
|
-
formatApplyPreview(local, remote, protectedPaths, additionalRemovals),
|
|
1203
|
-
...additionalRemovals.length ? ["Case-variant aliases listed above are removed before writing canonical paths."] : [],
|
|
1204
|
-
"A local backup is created before applying; the backend's active head will change."
|
|
1205
|
-
].join("\n");
|
|
1206
|
-
}
|
|
1207
|
-
function formatPublicationPreview(remote, upload) {
|
|
1208
|
-
return formatDirectionalChanges(remote, upload, {
|
|
1209
|
-
add: "Add remotely",
|
|
1210
|
-
update: "Update remotely",
|
|
1211
|
-
remove: "Remove remotely"
|
|
1212
|
-
});
|
|
1213
|
-
}
|
|
1214
|
-
function formatDirectionalChanges(before, after, labels, protectedPaths = /* @__PURE__ */ new Set(), additionalRemovals = []) {
|
|
1215
|
-
const changes = transferChanges(before, after, protectedPaths);
|
|
1216
|
-
const known = new Set(changes.map((change) => change.path));
|
|
1217
|
-
for (const filePath of additionalRemovals) {
|
|
1218
|
-
if (!known.has(filePath) && !protectedPaths.has(filePath)) {
|
|
1219
|
-
changes.push({ path: filePath, action: "Delete" });
|
|
1220
|
-
known.add(filePath);
|
|
1221
|
-
}
|
|
1222
|
-
}
|
|
1223
|
-
const counts = transferCounts(changes);
|
|
1224
|
-
const label = { Add: labels.add, Update: labels.update, Delete: labels.remove };
|
|
1225
|
-
return [
|
|
1226
|
-
`Changes: ${counts.add} add \xB7 ${counts.update} update \xB7 ${counts.remove} remove`,
|
|
1227
|
-
...changes.map((change) => `${label[change.action]}: ${snapshotPathLabel(change.path)}`),
|
|
1228
|
-
...changes.length ? [] : ["No file changes."]
|
|
1229
|
-
].join("\n");
|
|
1230
|
-
}
|
|
1231
|
-
function countPreservedRemoteFiles(local, upload) {
|
|
1232
|
-
const localPaths = new Set(local.files.map((file) => file.path));
|
|
1233
|
-
return upload.files.filter((file) => !localPaths.has(file.path)).length;
|
|
1234
|
-
}
|
|
1235
|
-
function publicationCapabilityDescription(capability) {
|
|
1236
|
-
switch (capability) {
|
|
1237
|
-
case "lease-protected":
|
|
1238
|
-
return "lease-protected (exact expected-ref update)";
|
|
1239
|
-
case "atomic-conditional":
|
|
1240
|
-
return "atomic-conditional (verified atomic precondition)";
|
|
1241
|
-
case "conditional-required":
|
|
1242
|
-
return "conditional-required (read-only until atomic preconditions are verified)";
|
|
1243
|
-
case "read-check-write-verify":
|
|
1244
|
-
return "read-check-write-verify (visible races rejected; simultaneous unseen races remain possible)";
|
|
1245
|
-
}
|
|
1246
|
-
}
|
|
1247
|
-
|
|
1248
|
-
// src/sync/sync-decision.ts
|
|
1249
|
-
function createSyncDecision(options) {
|
|
1250
|
-
const { config, state, local, remote, kind } = options;
|
|
1251
|
-
const policyChanged = Boolean(state.lastAppliedSnapshot) && syncPolicyChanged(state, config);
|
|
1252
|
-
const previousInclude = includeFromSelectionConfig(state);
|
|
1253
|
-
const currentInclude = [...config.include];
|
|
1254
|
-
const causes = {
|
|
1255
|
-
localChanged: options.localChanged,
|
|
1256
|
-
remoteChanged: options.remoteChanged,
|
|
1257
|
-
policyChanged
|
|
1258
|
-
};
|
|
1259
|
-
const causeLines = kind === "first-sync-settings-diverged" ? ["This machine and the remote have different Pi settings on first sync."] : kind === "first-sync-sessions-diverged" ? ["Pi settings match, but local and remote sessions differ on first sync."] : kind === "remote-empty" ? ["The remote storage location is empty."] : [
|
|
1260
|
-
...causes.localChanged ? ["Local content changed since the last sync."] : [],
|
|
1261
|
-
...causes.remoteChanged ? ["Remote content changed since the last sync."] : [],
|
|
1262
|
-
...causes.policyChanged ? ["Included content changed since the last sync."] : []
|
|
1263
|
-
];
|
|
1264
|
-
const comparison = remote ? formatDiff(local, remote) : formatSnapshotOnlyDiff("Remote is empty. Local push would upload", local);
|
|
1265
|
-
const review = [
|
|
1266
|
-
`Sync setup: ${safeTerminalText(config.setupName)}`,
|
|
1267
|
-
"",
|
|
1268
|
-
"Why a decision is required:",
|
|
1269
|
-
...causeLines,
|
|
1270
|
-
...policyChanged ? [
|
|
1271
|
-
"",
|
|
1272
|
-
`Previously included: ${safeList(previousInclude)}`,
|
|
1273
|
-
`Currently included: ${safeList(currentInclude)}`,
|
|
1274
|
-
`Previously excluded: ${safeList(state.exclude ?? [])}`,
|
|
1275
|
-
`Currently excluded: ${safeList(config.exclude ?? [])}`
|
|
1276
|
-
] : [],
|
|
1277
|
-
"",
|
|
1278
|
-
"Observed differences:",
|
|
1279
|
-
...comparison.split("\n").map(safeTerminalText)
|
|
1280
|
-
].join("\n");
|
|
1281
|
-
return new SyncDecisionRequiredError({
|
|
1282
|
-
kind,
|
|
1283
|
-
setupName: config.setupName,
|
|
1284
|
-
configIdentity: syncConfigReviewIdentity(config),
|
|
1285
|
-
causes,
|
|
1286
|
-
...policyChanged ? { previousInclude: [...previousInclude] } : {},
|
|
1287
|
-
currentInclude,
|
|
1288
|
-
...policyChanged && state.exclude !== void 0 ? { previousExclude: [...state.exclude] } : {},
|
|
1289
|
-
...config.exclude === void 0 ? {} : { currentExclude: [...config.exclude] },
|
|
1290
|
-
review,
|
|
1291
|
-
directions: kind === "remote-empty" ? ["push"] : ["push", "pull"],
|
|
1292
|
-
directMessage: options.directMessage
|
|
1293
|
-
});
|
|
1294
|
-
}
|
|
1295
|
-
function safeList(values) {
|
|
1296
|
-
return values.length > 0 ? values.map(safeTerminalText).join(", ") : "none";
|
|
1297
|
-
}
|
|
1298
|
-
|
|
1299
|
-
// src/sync/merged-sync.ts
|
|
1300
|
-
var MAX_ATTEMPTS = 3;
|
|
1301
|
-
async function mergeSync(ctx, options, factory = createSyncBackend, resolution) {
|
|
1302
|
-
const timings = options.startupTimings ?? createStartupTimings();
|
|
1303
|
-
const sessionOwner = captureMutationOwner(ctx, options.signal);
|
|
1304
|
-
const validateOwner = (config2) => {
|
|
1305
|
-
sessionOwner();
|
|
1306
|
-
options.background?.validate(config2);
|
|
1307
|
-
};
|
|
1308
|
-
const isCurrent = () => {
|
|
1309
|
-
try {
|
|
1310
|
-
validateOwner();
|
|
1311
|
-
return true;
|
|
1312
|
-
} catch {
|
|
1313
|
-
return false;
|
|
1314
|
-
}
|
|
1315
|
-
};
|
|
1316
|
-
const validateRetryAuthorization = (config2) => {
|
|
1317
|
-
if (options.agentRetryRefusal && (!config2.agentMode || options.auto || options.background || !ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)))
|
|
1318
|
-
throw new Error("Refused-candidate retry requires foreground Autonomous sync in TUI or RPC.");
|
|
1319
|
-
};
|
|
1320
|
-
const config = await loadConfig(options.setup);
|
|
1321
|
-
validateOwner(config);
|
|
1322
|
-
validateRetryAuthorization(config);
|
|
1323
|
-
const configToken = syncCheckConfigFingerprint(config);
|
|
1324
|
-
const modelToken = JSON.stringify(ctx.model);
|
|
1325
|
-
const sessionRoot = syncSessionsSelected(config) ? await effectiveSessionRoot(ctx) : void 0;
|
|
1326
|
-
validateOwner();
|
|
1327
|
-
const snapshotOptions = {
|
|
1328
|
-
...snapshotOptionsForContext(ctx, config),
|
|
1329
|
-
sessionDir: sessionRoot,
|
|
1330
|
-
signal: options.signal
|
|
1331
|
-
};
|
|
1332
|
-
const validate = () => timings.measure("transfer authorization", async () => {
|
|
1333
|
-
validateOwner();
|
|
1334
|
-
const latest = await loadConfig(options.setup);
|
|
1335
|
-
validateOwner(latest);
|
|
1336
|
-
validateRetryAuthorization(latest);
|
|
1337
|
-
if (configToken !== syncCheckConfigFingerprint(latest))
|
|
1338
|
-
throw new Error("Sync setup or settings changed during transfer; reopen sync.");
|
|
1339
|
-
if (sessionRoot !== void 0) {
|
|
1340
|
-
const currentRoot = await effectiveSessionRoot(ctx);
|
|
1341
|
-
validateOwner();
|
|
1342
|
-
if (currentRoot !== sessionRoot)
|
|
1343
|
-
throw new Error("Session storage root changed during transfer; evidence retained for review.");
|
|
1344
|
-
}
|
|
1345
|
-
if (config.agentMode && JSON.stringify(ctx.model) !== modelToken)
|
|
1346
|
-
throw new Error("Autonomous sync paused: selected model changed during transfer.");
|
|
1347
|
-
if (options.auto && (!startupTransferEnabled(latest) || !ctx.isIdle()))
|
|
1348
|
-
throw new Error("Automatic transfer is no longer authorized at this idle boundary.");
|
|
1349
|
-
});
|
|
1350
|
-
await validate();
|
|
1351
|
-
const backend = await timings.measure("transfer backend initialization", () => factory(config));
|
|
1352
|
-
await validate();
|
|
1353
|
-
const pending = await timings.measure("transfer journal read", () => readMergeJournal(config));
|
|
1354
|
-
await validate();
|
|
1355
|
-
if (pending && options.agentRetryRefusal)
|
|
1356
|
-
throw new Error("A pending merge journal requires ordinary Sync now before retrying a refused candidate.");
|
|
1357
|
-
if (pending) {
|
|
1358
|
-
const recovered = await timings.measure(
|
|
1359
|
-
"transfer journal recovery",
|
|
1360
|
-
() => completeJournal(
|
|
1361
|
-
ctx,
|
|
1362
|
-
config,
|
|
1363
|
-
backend,
|
|
1364
|
-
pending,
|
|
1365
|
-
validate,
|
|
1366
|
-
timings,
|
|
1367
|
-
options.signal,
|
|
1368
|
-
options.auto,
|
|
1369
|
-
options.background?.validate
|
|
1370
|
-
)
|
|
1371
|
-
);
|
|
1372
|
-
if (!recovered) {
|
|
1373
|
-
if ((options.auto || !options.silent) && !options.signal?.aborted)
|
|
1374
|
-
ctx.ui.notify(
|
|
1375
|
-
"Interrupted candidate is not active; local content and baseline were unchanged. Evidence was reconciled without retrying publication. Run sync again for a fresh plan.",
|
|
1376
|
-
"warning"
|
|
1377
|
-
);
|
|
1378
|
-
return "cancelled";
|
|
1379
|
-
}
|
|
1380
|
-
if ((options.auto || !options.silent) && !options.signal?.aborted)
|
|
1381
|
-
ctx.ui.notify("Recovered the committed merged transfer. Run sync again to inspect newer changes.", "info");
|
|
1382
|
-
return "applied";
|
|
1383
|
-
}
|
|
1384
|
-
if ((options.auto || config.agentMode) && backend.capability === "read-check-write-verify") {
|
|
1385
|
-
throw new Error(
|
|
1386
|
-
"Automatic transfer requires conditional publication or a lease; this backend supports only read/check/write/verify. Disable Autonomous sync and use manual sync."
|
|
1387
|
-
);
|
|
1388
|
-
}
|
|
1389
|
-
const textBudget = { remaining: TEXT_MERGE_WORK_LIMIT };
|
|
1390
|
-
const createdArtifacts = [];
|
|
1391
|
-
const ownedStatePath = statePathForConfig(config);
|
|
1392
|
-
try {
|
|
1393
|
-
for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
|
|
1394
|
-
await validate();
|
|
1395
|
-
const state = await timings.measure("transfer state read", () => readStateForConfig(config));
|
|
1396
|
-
if (state.unresolved?.length && !config.partialSync)
|
|
1397
|
-
throw new Error(
|
|
1398
|
-
"Partial progress remains unresolved; re-enable partial sync or review an explicit force direction."
|
|
1399
|
-
);
|
|
1400
|
-
const localRaw = await timings.measure(
|
|
1401
|
-
"transfer local snapshot",
|
|
1402
|
-
() => createSnapshot(config.snapshotIdentity, snapshotOptions)
|
|
1403
|
-
);
|
|
1404
|
-
const local = portableSnapshot(localRaw, config.localFields);
|
|
1405
|
-
if (!sameLocalFields(state.localFields, config.localFields))
|
|
1406
|
-
throw new Error("Local-field rules changed; review and confirm a directional migration first.");
|
|
1407
|
-
const head = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
|
|
1408
|
-
await validate();
|
|
1409
|
-
if (options.auto && !resolution && !config.partialSync && head && state.lastAppliedSnapshot && state.lastRemoteRevision && !state.unresolved?.length && head.snapshotId === state.lastAppliedSnapshot && backend.sameRevision(head.revision, state.lastRemoteRevision) && inspectRemoteSelection(config.include, { selection: head.selection, files: [] }, config.exclude).kind === "same" && matchesAcceptedState(state, config, head, local)) {
|
|
1410
|
-
const unchanged = await timings.measure("transfer unchanged verification", async () => {
|
|
1411
|
-
if (!await hasCurrentMergeBaseline(config, local, state)) return false;
|
|
1412
|
-
await validate();
|
|
1413
|
-
const currentLocal = await timings.measure(
|
|
1414
|
-
"transfer local snapshot",
|
|
1415
|
-
() => createSnapshot(config.snapshotIdentity, snapshotOptions)
|
|
1416
|
-
);
|
|
1417
|
-
await validate();
|
|
1418
|
-
const currentState = await timings.measure("transfer state read", () => readStateForConfig(config));
|
|
1419
|
-
await validate();
|
|
1420
|
-
return sameHashes(fileHashMap(currentLocal), fileHashMap(localRaw)) && syncStateFingerprint(currentState) === syncStateFingerprint(state);
|
|
1421
|
-
});
|
|
1422
|
-
await validate();
|
|
1423
|
-
if (unchanged) {
|
|
1424
|
-
timings.markUnchanged();
|
|
1425
|
-
return "applied";
|
|
1426
|
-
}
|
|
1427
|
-
}
|
|
1428
|
-
const rawRemote = head ? await timings.measure("transfer snapshot download", () => readSnapshotForHead(backend, head, options.signal)) : void 0;
|
|
1429
|
-
await validate();
|
|
1430
|
-
if (rawRemote) {
|
|
1431
|
-
const files = [...local.files, ...rawRemote.files];
|
|
1432
|
-
if (files.length > 16384 || files.reduce((bytes, file) => bytes + file.contentBase64.length * 0.75, 0) > 64 * 1024 * 1024) {
|
|
1433
|
-
throw new Error(
|
|
1434
|
-
"Merged transfer exceeds the 64 MiB / 16,384 input-file bound; review an explicit push or pull instead."
|
|
1435
|
-
);
|
|
1436
|
-
}
|
|
1437
|
-
}
|
|
1438
|
-
const remote = rawRemote ? portableSnapshot(filterSnapshotForConfigPolicy(rawRemote, config), rawRemote.localFields) : void 0;
|
|
1439
|
-
if (rawRemote) {
|
|
1440
|
-
requireCompatibleRemoteSelection(config, rawRemote);
|
|
1441
|
-
const validation = await timings.measure(
|
|
1442
|
-
"transfer merge planning",
|
|
1443
|
-
() => planFileMerge({
|
|
1444
|
-
baseline: state.lastFileHashes,
|
|
1445
|
-
local: local.files,
|
|
1446
|
-
remote: rawRemote.files,
|
|
1447
|
-
selectionCompatible: true
|
|
1448
|
-
})
|
|
1449
|
-
);
|
|
1450
|
-
await validate();
|
|
1451
|
-
const managedPaths = /* @__PURE__ */ new Set([
|
|
1452
|
-
...Object.keys(state.lastFileHashes),
|
|
1453
|
-
...[...local.files, ...remote?.files ?? []].map((file) => file.path)
|
|
1454
|
-
]);
|
|
1455
|
-
if (validation.kind === "planned" && validation.conflicts.some(
|
|
1456
|
-
(item) => item.reason === "path-collision" && (!config.partialSync || !managedPaths.has(item.path))
|
|
1457
|
-
))
|
|
1458
|
-
throw new Error("Remote snapshot contains path collisions; review a directional recovery before merging.");
|
|
1459
|
-
}
|
|
1460
|
-
const review = (message, kind = "both-changed") => createSyncDecision({
|
|
1461
|
-
kind,
|
|
1462
|
-
config,
|
|
1463
|
-
state,
|
|
1464
|
-
local,
|
|
1465
|
-
remote,
|
|
1466
|
-
localChanged: hasLocalChanges(local, state, config),
|
|
1467
|
-
remoteChanged: remote ? hasRemoteChanges(remote, state, config) : Boolean(state.lastAppliedSnapshot),
|
|
1468
|
-
directMessage: message
|
|
1469
|
-
});
|
|
1470
|
-
if (!state.lastAppliedSnapshot) throw review("Choose the initial source before enabling automatic transfer.");
|
|
1471
|
-
if (syncPolicyChanged(state, config))
|
|
1472
|
-
throw review("Included content changed; review the selection before merging.", "remote-or-policy-changed");
|
|
1473
|
-
if (!head || !remote || !rawRemote)
|
|
1474
|
-
throw review("The established remote is missing; choose an explicit recovery direction.", "remote-empty");
|
|
1475
|
-
const selectionState = inspectRemoteSelection(config.include, rawRemote, config.exclude);
|
|
1476
|
-
const selectionCompatible = selectionState.kind === "same";
|
|
1477
|
-
let plan = await timings.measure(
|
|
1478
|
-
"transfer merge planning",
|
|
1479
|
-
() => planFileMerge({
|
|
1480
|
-
baseline: state.lastFileHashes,
|
|
1481
|
-
local: local.files,
|
|
1482
|
-
remote: remote.files,
|
|
1483
|
-
selectionCompatible,
|
|
1484
|
-
protectedPaths: protectedSessionPaths(ctx, sessionRoot)
|
|
1485
|
-
})
|
|
1486
|
-
);
|
|
1487
|
-
await validate();
|
|
1488
|
-
let resolved = { plan, fields: [] };
|
|
1489
|
-
if (config.mergeSettings || config.agentMode) {
|
|
1490
|
-
try {
|
|
1491
|
-
resolved = await timings.measure(
|
|
1492
|
-
"transfer settings merge",
|
|
1493
|
-
() => resolveSettingsConflicts(config, state, local, remote, plan)
|
|
1494
|
-
);
|
|
1495
|
-
} catch (error) {
|
|
1496
|
-
if (!config.partialSync) throw error;
|
|
1497
|
-
}
|
|
1498
|
-
}
|
|
1499
|
-
await validate();
|
|
1500
|
-
plan = await timings.measure(
|
|
1501
|
-
"transfer content merge",
|
|
1502
|
-
() => resolveContentConflicts(config, state, local, remote, resolved.plan, protectedSessionPaths(ctx, sessionRoot), {
|
|
1503
|
-
textBudget,
|
|
1504
|
-
signal: options.signal
|
|
1505
|
-
})
|
|
1506
|
-
);
|
|
1507
|
-
await validate();
|
|
1508
|
-
if (resolution) {
|
|
1509
|
-
plan = await resolveReviewedGroup(
|
|
1510
|
-
config,
|
|
1511
|
-
backend,
|
|
1512
|
-
state,
|
|
1513
|
-
local,
|
|
1514
|
-
remote,
|
|
1515
|
-
head,
|
|
1516
|
-
plan,
|
|
1517
|
-
resolution,
|
|
1518
|
-
protectedSessionPaths(ctx, sessionRoot)
|
|
1519
|
-
);
|
|
1520
|
-
await validate();
|
|
1521
|
-
}
|
|
1522
|
-
if (config.agentMode && !resolution) {
|
|
1523
|
-
const { resolveAgentPlan } = await import("./agent-plan-ILFEUJ2E.ts");
|
|
1524
|
-
await validate();
|
|
1525
|
-
plan = await resolveAgentPlan(
|
|
1526
|
-
ctx,
|
|
1527
|
-
options,
|
|
1528
|
-
config,
|
|
1529
|
-
backend,
|
|
1530
|
-
state,
|
|
1531
|
-
local,
|
|
1532
|
-
localRaw,
|
|
1533
|
-
remote,
|
|
1534
|
-
head,
|
|
1535
|
-
plan,
|
|
1536
|
-
snapshotOptions,
|
|
1537
|
-
validate
|
|
1538
|
-
);
|
|
1539
|
-
await validate();
|
|
1540
|
-
if (plan.kind !== "planned" || plan.conflicts.length && !config.partialSync)
|
|
1541
|
-
throw new ContinuousError(
|
|
1542
|
-
"unsafe",
|
|
1543
|
-
"Autonomous sync paused: unsupported or refused conflict groups remain; no transfer was performed."
|
|
1544
|
-
);
|
|
1545
|
-
}
|
|
1546
|
-
if (plan.kind !== "planned" || plan.conflicts.length && (!config.partialSync || options.auto && !config.agentMode)) {
|
|
1547
|
-
const decision = review(
|
|
1548
|
-
selectionCompatible ? `Conflicting or protected paths require review; no merged transfer was performed. Use /sync diff and an explicit direction.${resolved.fields.length ? ` Settings fields: ${resolved.fields.map(safeTerminalText).join(", ")}` : ""}` : "Remote selection metadata is unavailable; review the included content and choose an explicit direction before merging.",
|
|
1549
|
-
selectionCompatible ? "both-changed" : "remote-or-policy-changed"
|
|
1550
|
-
);
|
|
1551
|
-
if (!selectionCompatible)
|
|
1552
|
-
decision.decision.review += `
|
|
1553
|
-
|
|
1554
|
-
${formatRemoteSelectionStatus(selectionState)}
|
|
1555
|
-
An explicit direction adopts this setup's included-content policy; no automatic merge was performed.`;
|
|
1556
|
-
throw decision;
|
|
1557
|
-
}
|
|
1558
|
-
if (plan.kind !== "planned") throw new Error("Cannot partition an unverified merge plan.");
|
|
1559
|
-
const groups = conflictGroups(plan, config);
|
|
1560
|
-
const withheld = new Set(groups.flatMap((group) => group.paths));
|
|
1561
|
-
const persistProgress = async () => {
|
|
1562
|
-
if (!groups.length) return;
|
|
1563
|
-
let ancestors = [];
|
|
1564
|
-
try {
|
|
1565
|
-
const configured = configuredSnapshotPathMatcher(config);
|
|
1566
|
-
ancestors = (await readMergeAncestors(config, state) ?? []).filter(
|
|
1567
|
-
(file) => withheld.has(file.path) && configured(file.path)
|
|
1568
|
-
);
|
|
1569
|
-
} catch {
|
|
1570
|
-
}
|
|
1571
|
-
await validate();
|
|
1572
|
-
const previousArtifacts = /* @__PURE__ */ new Map();
|
|
1573
|
-
for (const token of new Set(state.unresolved?.map((group) => group.artifact) ?? [])) {
|
|
1574
|
-
try {
|
|
1575
|
-
const artifact2 = await readConflictArtifact(config, backend.identity, token);
|
|
1576
|
-
previousArtifacts.set(token, {
|
|
1577
|
-
artifact: artifact2,
|
|
1578
|
-
local: fileHashMap(artifact2.local),
|
|
1579
|
-
remote: fileHashMap(artifact2.remote)
|
|
1580
|
-
});
|
|
1581
|
-
} catch {
|
|
1582
|
-
}
|
|
1583
|
-
await validate();
|
|
1584
|
-
}
|
|
1585
|
-
const localHashes = fileHashMap(local);
|
|
1586
|
-
const remoteHashes = fileHashMap(remote);
|
|
1587
|
-
const previousGroups = new Map(state.unresolved?.map((item) => [JSON.stringify(item.paths), item]));
|
|
1588
|
-
const pending2 = groups.map((group) => {
|
|
1589
|
-
const previous = previousGroups.get(JSON.stringify(group.paths));
|
|
1590
|
-
const original = previous ? previousArtifacts.get(previous.artifact) : void 0;
|
|
1591
|
-
if (!original || !previous) return { group };
|
|
1592
|
-
return group.paths.every(
|
|
1593
|
-
(filePath) => localHashes[filePath] === original.local[filePath] && remoteHashes[filePath] === original.remote[filePath] && state.lastFileHashes[filePath] === original.artifact.state.lastFileHashes[filePath]
|
|
1594
|
-
) ? { group, artifact: previous.artifact } : { group };
|
|
1595
|
-
});
|
|
1596
|
-
let artifact;
|
|
1597
|
-
const newGroups = pending2.filter((item) => !item.artifact).map((item) => item.group);
|
|
1598
|
-
const newPaths = new Set(newGroups.flatMap((group) => group.paths));
|
|
1599
|
-
if (newGroups.length)
|
|
1600
|
-
artifact = await saveConflictArtifact(
|
|
1601
|
-
config,
|
|
1602
|
-
backend.identity,
|
|
1603
|
-
{
|
|
1604
|
-
state,
|
|
1605
|
-
local: { ...local, files: local.files.filter((file) => newPaths.has(file.path)) },
|
|
1606
|
-
remote: { ...remote, files: remote.files.filter((file) => newPaths.has(file.path)) },
|
|
1607
|
-
ancestors: ancestors.filter((file) => newPaths.has(file.path)),
|
|
1608
|
-
groups: newGroups,
|
|
1609
|
-
observed: { snapshotId: head.snapshotId, revision: head.revision }
|
|
1610
|
-
},
|
|
1611
|
-
captureMutationOwner(ctx, options.signal),
|
|
1612
|
-
(created) => createdArtifacts.push(created)
|
|
1613
|
-
);
|
|
1614
|
-
await validate();
|
|
1615
|
-
return {
|
|
1616
|
-
previous: state,
|
|
1617
|
-
groups: pending2.map((item) => ({ paths: item.group.paths, artifact: item.artifact ?? artifact ?? "" }))
|
|
1618
|
-
};
|
|
1619
|
-
};
|
|
1620
|
-
let progress;
|
|
1621
|
-
const accepted = regenerateSnapshotIdentity({
|
|
1622
|
-
...local,
|
|
1623
|
-
files: acceptedMergeFiles(plan.decisions, local.files, withheld)
|
|
1624
|
-
});
|
|
1625
|
-
const after = overlayLocalFields(accepted, localRaw, config.localFields);
|
|
1626
|
-
if (syncSessionsSelected(config)) requireStableMergeSessionRoot(localRaw, after);
|
|
1627
|
-
const publication = regenerateSnapshotIdentity({
|
|
1628
|
-
...accepted,
|
|
1629
|
-
version: accepted.version === 4 ? 4 : config.partialSync ? 3 : accepted.version,
|
|
1630
|
-
files: [
|
|
1631
|
-
...accepted.files.filter((file) => !withheld.has(file.path)),
|
|
1632
|
-
...remote.files.filter((file) => withheld.has(file.path))
|
|
1633
|
-
]
|
|
1634
|
-
});
|
|
1635
|
-
const upload = mergeRemotePreservedFiles(publication, rawRemote, config);
|
|
1636
|
-
const publish = !sameHashes(fileHashMap(publication), fileHashMap(remote)) || Boolean(config.partialSync && rawRemote.version !== 3 && rawRemote.version !== 4);
|
|
1637
|
-
const apply = !sameHashes(fileHashMap(localRaw), fileHashMap(after));
|
|
1638
|
-
if (!publish && !apply) {
|
|
1639
|
-
const beforeEvidence = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
|
|
1640
|
-
await validate();
|
|
1641
|
-
if (!beforeEvidence || !backend.sameRevision(beforeEvidence.revision, head.revision))
|
|
1642
|
-
throw new ContinuousError(
|
|
1643
|
-
"stale",
|
|
1644
|
-
"Remote changed before baseline acceptance; retry from a fresh observation."
|
|
1645
|
-
);
|
|
1646
|
-
progress = await persistProgress();
|
|
1647
|
-
await validate();
|
|
1648
|
-
const currentLocal = await timings.measure(
|
|
1649
|
-
"transfer local snapshot",
|
|
1650
|
-
() => createSnapshot(config.snapshotIdentity, snapshotOptions)
|
|
1651
|
-
);
|
|
1652
|
-
await validate();
|
|
1653
|
-
if (!sameHashes(fileHashMap(currentLocal), fileHashMap(localRaw)) || syncStateFingerprint(await timings.measure("transfer state read", () => readStateForConfig(config))) !== syncStateFingerprint(state))
|
|
1654
|
-
throw new ContinuousError(
|
|
1655
|
-
"stale",
|
|
1656
|
-
"Local content or baseline changed before baseline acceptance; retry from a fresh observation."
|
|
1657
|
-
);
|
|
1658
|
-
await validate();
|
|
1659
|
-
const currentHead = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
|
|
1660
|
-
await validate();
|
|
1661
|
-
if (!currentHead || !backend.sameRevision(currentHead.revision, head.revision))
|
|
1662
|
-
throw new ContinuousError(
|
|
1663
|
-
"stale",
|
|
1664
|
-
"Remote changed before baseline acceptance; retry from a fresh observation."
|
|
1665
|
-
);
|
|
1666
|
-
await options.agentAcceptance?.commitCandidate?.();
|
|
1667
|
-
await validate();
|
|
1668
|
-
await timings.measure(
|
|
1669
|
-
"transfer baseline write",
|
|
1670
|
-
() => writeAcceptedState(config, head, accepted, validate, progress)
|
|
1671
|
-
);
|
|
1672
|
-
await timings.measure(
|
|
1673
|
-
"transfer cleanup",
|
|
1674
|
-
() => pruneMergeBaselines(
|
|
1675
|
-
config,
|
|
1676
|
-
acceptedState(config, head, accepted, progress),
|
|
1677
|
-
captureMutationOwner(ctx, options.signal)
|
|
1678
|
-
)
|
|
1679
|
-
);
|
|
1680
|
-
await validate();
|
|
1681
|
-
await timings.measure(
|
|
1682
|
-
"transfer cleanup",
|
|
1683
|
-
() => pruneCompletedConflicts(
|
|
1684
|
-
config,
|
|
1685
|
-
backend.identity,
|
|
1686
|
-
acceptedState(config, head, accepted, progress),
|
|
1687
|
-
accepted,
|
|
1688
|
-
remote,
|
|
1689
|
-
captureMutationOwner(ctx, options.signal)
|
|
1690
|
-
)
|
|
1691
|
-
);
|
|
1692
|
-
await validate();
|
|
1693
|
-
if (!options.silent)
|
|
1694
|
-
ctx.ui.notify(
|
|
1695
|
-
progress ? `No independent transfer required; ${groups.length} conflict groups remain withheld. Review /sync conflicts.` : "Pi Sync is already up to date.",
|
|
1696
|
-
progress ? "warning" : "info"
|
|
1697
|
-
);
|
|
1698
|
-
return "applied";
|
|
1699
|
-
}
|
|
1700
|
-
await timings.measure(
|
|
1701
|
-
"transfer preflight",
|
|
1702
|
-
() => preflightMergedTargets(localRaw, after, snapshotOptions, ctx.sessionManager.getSessionFile?.())
|
|
1703
|
-
);
|
|
1704
|
-
await validate();
|
|
1705
|
-
if (!config.skipSecretScan && scanSnapshot(upload).length)
|
|
1706
|
-
throw new ContinuousError(
|
|
1707
|
-
"unsafe",
|
|
1708
|
-
"Refusing to merge possible secrets. Review managed content before syncing."
|
|
1709
|
-
);
|
|
1710
|
-
if (!options.yes && !config.agentMode) {
|
|
1711
|
-
const summary = mergedSyncSummary({
|
|
1712
|
-
setupName: config.setupName,
|
|
1713
|
-
destination: backend.destination,
|
|
1714
|
-
localBefore: localRaw,
|
|
1715
|
-
localAfter: after,
|
|
1716
|
-
remoteBefore: rawRemote,
|
|
1717
|
-
remoteAfter: upload,
|
|
1718
|
-
publish,
|
|
1719
|
-
sessions: syncSessionsSelected(config),
|
|
1720
|
-
groups,
|
|
1721
|
-
decisions: plan.decisions,
|
|
1722
|
-
capability: backend.capability
|
|
1723
|
-
});
|
|
1724
|
-
if (!await confirmMergeReview(
|
|
1725
|
-
ctx,
|
|
1726
|
-
summary.title,
|
|
1727
|
-
summary.content,
|
|
1728
|
-
options.signal,
|
|
1729
|
-
isCurrent,
|
|
1730
|
-
summary.confirmationLabel,
|
|
1731
|
-
summary.lines
|
|
1732
|
-
))
|
|
1733
|
-
return "cancelled";
|
|
1734
|
-
}
|
|
1735
|
-
await validate();
|
|
1736
|
-
const refreshed = await timings.measure(
|
|
1737
|
-
"transfer local snapshot",
|
|
1738
|
-
() => createSnapshot(config.snapshotIdentity, snapshotOptions)
|
|
1739
|
-
);
|
|
1740
|
-
if (!sameHashes(fileHashMap(refreshed), fileHashMap(localRaw)))
|
|
1741
|
-
throw new ContinuousError("stale", "Local content changed during review; no merged transfer was performed.");
|
|
1742
|
-
if (syncStateFingerprint(await timings.measure("transfer state read", () => readStateForConfig(config))) !== syncStateFingerprint(state))
|
|
1743
|
-
throw new ContinuousError("stale", "Sync baseline changed during review; retry from a fresh observation.");
|
|
1744
|
-
await validate();
|
|
1745
|
-
const refreshedHead = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
|
|
1746
|
-
await validate();
|
|
1747
|
-
if (!refreshedHead || !backend.sameRevision(refreshedHead.revision, head.revision))
|
|
1748
|
-
throw new ContinuousError("stale", "Remote changed during review; no merged transfer was performed.");
|
|
1749
|
-
await options.agentAcceptance?.commitCandidate?.();
|
|
1750
|
-
await validate();
|
|
1751
|
-
progress = await persistProgress();
|
|
1752
|
-
await validate();
|
|
1753
|
-
const backup = await timings.measure(
|
|
1754
|
-
"transfer backup",
|
|
1755
|
-
() => backupLocal(config.snapshotIdentity, snapshotOptions, options.signal)
|
|
1756
|
-
);
|
|
1757
|
-
await validate();
|
|
1758
|
-
const journal = {
|
|
1759
|
-
version: 1,
|
|
1760
|
-
identity: mergeJournalIdentity(config, backend.identity),
|
|
1761
|
-
before: localRaw,
|
|
1762
|
-
after,
|
|
1763
|
-
accepted,
|
|
1764
|
-
...progress ? { progress } : {},
|
|
1765
|
-
upload: publish ? upload : rawRemote,
|
|
1766
|
-
expectedHead: head,
|
|
1767
|
-
backup,
|
|
1768
|
-
stateIdentity: syncStateFingerprint(state),
|
|
1769
|
-
...sessionRoot !== void 0 ? { sessionRoot } : {},
|
|
1770
|
-
...!publish ? { committedHead: head, applyOnly: true } : {}
|
|
1771
|
-
};
|
|
1772
|
-
await timings.measure("transfer journal write", () => writeMergeJournal(config, journal));
|
|
1773
|
-
const atCommitState = syncStateFingerprint(
|
|
1774
|
-
await timings.measure("transfer state read", () => readStateForConfig(config))
|
|
1775
|
-
);
|
|
1776
|
-
await validate();
|
|
1777
|
-
const atCommit = await timings.measure(
|
|
1778
|
-
"transfer local snapshot",
|
|
1779
|
-
() => createSnapshot(config.snapshotIdentity, snapshotOptions)
|
|
1780
|
-
);
|
|
1781
|
-
await validate();
|
|
1782
|
-
if (!sameHashes(fileHashMap(atCommit), fileHashMap(localRaw)) || atCommitState !== journal.stateIdentity) {
|
|
1783
|
-
await validate();
|
|
1784
|
-
await clearMergeJournal(config);
|
|
1785
|
-
throw new ContinuousError(
|
|
1786
|
-
"stale",
|
|
1787
|
-
"Local content or baseline changed before publication; candidate retired without transfer. Review a fresh sync."
|
|
1788
|
-
);
|
|
1789
|
-
}
|
|
1790
|
-
try {
|
|
1791
|
-
await timings.measure(
|
|
1792
|
-
"transfer preflight",
|
|
1793
|
-
() => preflightMergedTargets(atCommit, after, snapshotOptions, ctx.sessionManager.getSessionFile?.())
|
|
1794
|
-
);
|
|
1795
|
-
await validate();
|
|
1796
|
-
} catch (error) {
|
|
1797
|
-
await validate();
|
|
1798
|
-
await clearMergeJournal(config);
|
|
1799
|
-
throw error;
|
|
1800
|
-
}
|
|
1801
|
-
try {
|
|
1802
|
-
if (publish) {
|
|
1803
|
-
const result = await timings.measure(
|
|
1804
|
-
"transfer remote publication",
|
|
1805
|
-
() => backend.publishSnapshot(upload, expectedRemoteHead(head), {
|
|
1806
|
-
signal: options.signal,
|
|
1807
|
-
onCommit: options.onCommit
|
|
1808
|
-
})
|
|
1809
|
-
);
|
|
1810
|
-
journal.committedHead = result.head;
|
|
1811
|
-
journal.warnings = result.warnings;
|
|
1812
|
-
await timings.measure("transfer journal write", () => writeMergeJournal(config, journal));
|
|
1813
|
-
} else options.onCommit?.();
|
|
1814
|
-
} catch (error) {
|
|
1815
|
-
if (error instanceof SyncBackendConflictError && error.phase === "before-commit" && !error.candidateMayHaveBeenActive) {
|
|
1816
|
-
await clearMergeJournal(config);
|
|
1817
|
-
if (attempt + 1 < MAX_ATTEMPTS) continue;
|
|
1818
|
-
throw new Error("Remote changed before commit in all three attempts; retry later.", { cause: error });
|
|
1819
|
-
}
|
|
1820
|
-
throw mergeTransferError(error, config.backend);
|
|
1821
|
-
}
|
|
1822
|
-
const completed = await timings.measure(
|
|
1823
|
-
"transfer journal recovery",
|
|
1824
|
-
() => completeJournal(
|
|
1825
|
-
ctx,
|
|
1826
|
-
config,
|
|
1827
|
-
backend,
|
|
1828
|
-
journal,
|
|
1829
|
-
validate,
|
|
1830
|
-
timings,
|
|
1831
|
-
options.signal,
|
|
1832
|
-
options.auto,
|
|
1833
|
-
options.background?.validate
|
|
1834
|
-
)
|
|
1835
|
-
);
|
|
1836
|
-
if (!completed) {
|
|
1837
|
-
if (!options.signal?.aborted && (options.auto || !options.silent))
|
|
1838
|
-
ctx.ui.notify(
|
|
1839
|
-
"Remote changed before local apply; candidate retired without transfer. Run sync again.",
|
|
1840
|
-
"warning"
|
|
1841
|
-
);
|
|
1842
|
-
return "cancelled";
|
|
1843
|
-
}
|
|
1844
|
-
if (!options.signal?.aborted && (options.auto || !options.silent))
|
|
1845
|
-
ctx.ui.notify(
|
|
1846
|
-
[
|
|
1847
|
-
`Synced independent changes for \u201C${safeTerminalText(config.setupName)}\u201D. ${apply ? "Local files changed; reload or restart Pi when ready to use changed resources." : "Remote updated."} No automatic reload.`,
|
|
1848
|
-
...progress ? [
|
|
1849
|
-
`Partial progress: ${groups.length} dependency groups remain unresolved; neither side's withheld versions or baseline hashes were replaced. Review /sync conflicts.`
|
|
1850
|
-
] : [],
|
|
1851
|
-
...(journal.warnings ?? []).map(safeTerminalText)
|
|
1852
|
-
].join("\n"),
|
|
1853
|
-
progress || journal.warnings?.length ? "warning" : "info"
|
|
1854
|
-
);
|
|
1855
|
-
return "applied";
|
|
1856
|
-
}
|
|
1857
|
-
} finally {
|
|
1858
|
-
await timings.measure("transfer cleanup", () => releaseConflictArtifacts(config, ownedStatePath, createdArtifacts));
|
|
1859
|
-
}
|
|
1860
|
-
}
|
|
1861
|
-
async function completeJournal(ctx, config, backend, journal, validate, timings, signal, auto = false, validateBackground) {
|
|
1862
|
-
if (journal.identity !== mergeJournalIdentity(config, backend.identity) || !sameLocalFields(journal.upload.localFields, config.localFields))
|
|
1863
|
-
throw new Error(
|
|
1864
|
-
"Merge journal belongs to a different setup, selection or local-field policy; preserve it for reviewed recovery."
|
|
1865
|
-
);
|
|
1866
|
-
await validate();
|
|
1867
|
-
const sessionRoot = syncSessionsSelected(config) ? await effectiveSessionRoot(ctx) : void 0;
|
|
1868
|
-
await validate();
|
|
1869
|
-
if (sessionRoot !== void 0 && journal.sessionRoot !== sessionRoot) {
|
|
1870
|
-
throw new Error(
|
|
1871
|
-
"Merge journal session root is missing or differs from this context; preserve evidence and use reviewed directional recovery."
|
|
1872
|
-
);
|
|
1873
|
-
}
|
|
1874
|
-
const snapshotOptions = { ...snapshotOptionsForContext(ctx, config), sessionDir: sessionRoot, signal };
|
|
1875
|
-
const head = await timings.measure("transfer remote head", () => backend.readHead(signal));
|
|
1876
|
-
if (!journal.committedHead && head && (backend.sameRevision(head.revision, journal.expectedHead.revision) || backend.matchesUncommittedRecoveryHead?.(head, journal.expectedHead))) {
|
|
1877
|
-
await validate();
|
|
1878
|
-
const local = await timings.measure(
|
|
1879
|
-
"transfer local snapshot",
|
|
1880
|
-
() => createSnapshot(config.snapshotIdentity, snapshotOptions)
|
|
1881
|
-
);
|
|
1882
|
-
if (!sameHashes(fileHashMap(local), fileHashMap(journal.before)) || syncStateFingerprint(await timings.measure("transfer state read", () => readStateForConfig(config))) !== journal.stateIdentity) {
|
|
1883
|
-
throw new Error(
|
|
1884
|
-
"Uncertain publication is not active, but local content or baseline changed; keep the journal for reviewed recovery."
|
|
1885
|
-
);
|
|
1886
|
-
}
|
|
1887
|
-
await clearMergeJournal(config);
|
|
1888
|
-
return false;
|
|
1889
|
-
}
|
|
1890
|
-
await validate();
|
|
1891
|
-
if (journal.committedHead && (!head || !backend.sameRevision(head.revision, journal.committedHead.revision))) {
|
|
1892
|
-
const state2 = await timings.measure("transfer state read", () => readStateForConfig(config));
|
|
1893
|
-
await validate();
|
|
1894
|
-
if (matchesAcceptedState(state2, config, journal.committedHead, journal.accepted ?? journal.after, journal.progress)) {
|
|
1895
|
-
await clearMergeJournal(config);
|
|
1896
|
-
await validate();
|
|
1897
|
-
await pruneMergeBaselines(config, state2, captureMutationOwner(ctx, signal));
|
|
1898
|
-
await validate();
|
|
1899
|
-
return true;
|
|
1900
|
-
}
|
|
1901
|
-
}
|
|
1902
|
-
if (journal.applyOnly && (!head || !backend.sameRevision(head.revision, journal.expectedHead.revision))) {
|
|
1903
|
-
const local = await timings.measure(
|
|
1904
|
-
"transfer local snapshot",
|
|
1905
|
-
() => createSnapshot(config.snapshotIdentity, snapshotOptions)
|
|
1906
|
-
);
|
|
1907
|
-
const state2 = await timings.measure("transfer state read", () => readStateForConfig(config));
|
|
1908
|
-
await validate();
|
|
1909
|
-
if (sameHashes(fileHashMap(local), fileHashMap(journal.before)) && syncStateFingerprint(state2) === journal.stateIdentity) {
|
|
1910
|
-
await clearMergeJournal(config);
|
|
1911
|
-
return false;
|
|
1912
|
-
}
|
|
1913
|
-
throw new Error("Apply-only remote head advanced after local changes; preserve the journal for reviewed recovery.");
|
|
1914
|
-
}
|
|
1915
|
-
if (!head || head.snapshotId !== journal.upload.id || journal.committedHead && !backend.sameRevision(head.revision, journal.committedHead.revision)) {
|
|
1916
|
-
throw new Error(
|
|
1917
|
-
"Publication outcome cannot be reconciled with the current remote head. Journal and backup retained; do not retry publication or restore old bytes blindly."
|
|
1918
|
-
);
|
|
1919
|
-
}
|
|
1920
|
-
const observed = await timings.measure(
|
|
1921
|
-
"transfer snapshot download",
|
|
1922
|
-
() => readSnapshotForHead(backend, head, signal)
|
|
1923
|
-
);
|
|
1924
|
-
requireCompatibleRemoteSelection(config, observed);
|
|
1925
|
-
if (!sameHashes(fileHashMap(observed), fileHashMap(journal.upload)) || JSON.stringify(observed.selection) !== JSON.stringify(journal.upload.selection))
|
|
1926
|
-
throw new Error("Remote snapshot does not match the recorded merge publication.");
|
|
1927
|
-
const state = await timings.measure("transfer state read", () => readStateForConfig(config));
|
|
1928
|
-
if (matchesAcceptedState(state, config, head, journal.accepted ?? journal.after, journal.progress)) {
|
|
1929
|
-
await validate();
|
|
1930
|
-
await clearMergeJournal(config);
|
|
1931
|
-
await validate();
|
|
1932
|
-
await pruneMergeBaselines(config, state, captureMutationOwner(ctx, signal));
|
|
1933
|
-
await validate();
|
|
1934
|
-
return true;
|
|
1935
|
-
}
|
|
1936
|
-
if (syncStateFingerprint(state) !== journal.stateIdentity) {
|
|
1937
|
-
throw new Error("Sync baseline changed after the interrupted merge; preserve its journal and review recovery.");
|
|
1938
|
-
}
|
|
1939
|
-
if (inspectRemoteSelection(config.include, observed, config.exclude).kind !== "same")
|
|
1940
|
-
throw new Error(
|
|
1941
|
-
"Pending merge has unavailable remote selection metadata; preserve its journal and choose a reviewed explicit direction."
|
|
1942
|
-
);
|
|
1943
|
-
if (syncSessionsSelected(config)) requireStableMergeSessionRoot(journal.before, journal.after);
|
|
1944
|
-
await validate();
|
|
1945
|
-
const validateOwner = captureMutationOwner(ctx, signal);
|
|
1946
|
-
const validateMutation = () => {
|
|
1947
|
-
validateOwner();
|
|
1948
|
-
validateBackground?.();
|
|
1949
|
-
if (auto && !ctx.isIdle()) throw new Error("Automatic file apply is no longer idle; evidence retained.");
|
|
1950
|
-
};
|
|
1951
|
-
await timings.measure(
|
|
1952
|
-
"transfer local apply",
|
|
1953
|
-
() => applyMergedSnapshot(
|
|
1954
|
-
journal.before,
|
|
1955
|
-
journal.after,
|
|
1956
|
-
protectedSessionPaths(ctx, sessionRoot),
|
|
1957
|
-
{ ...snapshotOptions, validateMutation },
|
|
1958
|
-
validate,
|
|
1959
|
-
ctx.sessionManager.getSessionFile?.()
|
|
1960
|
-
)
|
|
1961
|
-
);
|
|
1962
|
-
await validate();
|
|
1963
|
-
const headAtAcceptance = await timings.measure("transfer remote head", () => backend.readHead(signal));
|
|
1964
|
-
await validate();
|
|
1965
|
-
if (!headAtAcceptance || !backend.sameRevision(headAtAcceptance.revision, head.revision))
|
|
1966
|
-
throw new Error("Remote changed during merged apply; journal and backup retained for review.");
|
|
1967
|
-
await timings.measure(
|
|
1968
|
-
"transfer baseline write",
|
|
1969
|
-
() => writeAcceptedState(config, head, journal.accepted ?? journal.after, validate, journal.progress)
|
|
1970
|
-
);
|
|
1971
|
-
await validate();
|
|
1972
|
-
await clearMergeJournal(config);
|
|
1973
|
-
await validate();
|
|
1974
|
-
await timings.measure(
|
|
1975
|
-
"transfer cleanup",
|
|
1976
|
-
() => pruneMergeBaselines(
|
|
1977
|
-
config,
|
|
1978
|
-
acceptedState(config, head, journal.accepted ?? journal.after, journal.progress),
|
|
1979
|
-
captureMutationOwner(ctx, signal)
|
|
1980
|
-
)
|
|
1981
|
-
);
|
|
1982
|
-
await validate();
|
|
1983
|
-
await timings.measure(
|
|
1984
|
-
"transfer cleanup",
|
|
1985
|
-
() => pruneCompletedConflicts(
|
|
1986
|
-
config,
|
|
1987
|
-
backend.identity,
|
|
1988
|
-
acceptedState(config, head, journal.accepted ?? journal.after, journal.progress),
|
|
1989
|
-
journal.accepted ?? journal.after,
|
|
1990
|
-
journal.upload,
|
|
1991
|
-
captureMutationOwner(ctx, signal)
|
|
1992
|
-
)
|
|
1993
|
-
);
|
|
1994
|
-
await validate();
|
|
1995
|
-
return true;
|
|
1996
|
-
}
|
|
1997
|
-
function matchesAcceptedState(state, config, head, snapshot, progress) {
|
|
1998
|
-
return [true, false].some(
|
|
1999
|
-
(canonical) => syncStateFingerprint(state) === syncStateFingerprint(acceptedState(config, head, snapshot, progress, canonical))
|
|
2000
|
-
);
|
|
2001
|
-
}
|
|
2002
|
-
function acceptedState(config, head, snapshot, progress, canonical = true) {
|
|
2003
|
-
if (progress) return progressState(config, head, snapshot, progress);
|
|
2004
|
-
return {
|
|
2005
|
-
version: 1,
|
|
2006
|
-
profile: config.snapshotIdentity,
|
|
2007
|
-
lastAppliedSnapshot: head.snapshotId,
|
|
2008
|
-
lastRemoteRevision: head.revision,
|
|
2009
|
-
lastFileHashes: fileHashMap(canonical ? portableSnapshot(snapshot, config.localFields) : snapshot),
|
|
2010
|
-
include: [...config.include],
|
|
2011
|
-
...config.exclude === void 0 ? {} : { exclude: [...config.exclude] },
|
|
2012
|
-
...config.localFields !== void 0 ? { localFields: config.localFields } : {}
|
|
2013
|
-
};
|
|
2014
|
-
}
|
|
2015
|
-
async function writeAcceptedState(config, head, snapshot, validate, progress) {
|
|
2016
|
-
const accepted = portableSnapshot(snapshot, config.localFields);
|
|
2017
|
-
const state = acceptedState(config, head, accepted, progress);
|
|
2018
|
-
await stageMergeBaseline(config, accepted, state, progress?.previous);
|
|
2019
|
-
await validate();
|
|
2020
|
-
await writeStateForConfig(config, state);
|
|
2021
|
-
await validate();
|
|
2022
|
-
}
|
|
2023
|
-
|
|
2024
|
-
export {
|
|
2025
|
-
applySnapshot,
|
|
2026
|
-
addTopLevelCaseVariantDeletes,
|
|
2027
|
-
formatDiff,
|
|
2028
|
-
formatSnapshotOnlyDiff,
|
|
2029
|
-
formatPushSummary,
|
|
2030
|
-
formatPullSummary,
|
|
2031
|
-
formatRollbackSummary,
|
|
2032
|
-
countPreservedRemoteFiles,
|
|
2033
|
-
publicationCapabilityDescription,
|
|
2034
|
-
createSyncDecision,
|
|
2035
|
-
mergeSync
|
|
2036
|
-
};
|
|
2037
|
-
//# sourceMappingURL=chunk-APDNHB2T.ts.map
|