@narumitw/pi-sync 0.63.1 → 0.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +86 -10
  3. package/dist/chunks/{chunk-CKUGCBHP.ts → chunk-AYGMIMCV.ts} +2 -2
  4. package/dist/chunks/chunk-AYGMIMCV.ts.map +7 -0
  5. package/dist/chunks/{chunk-27F5W7DX.ts → chunk-DAZZ5BEJ.ts} +3 -1
  6. package/dist/chunks/chunk-DAZZ5BEJ.ts.map +7 -0
  7. package/dist/chunks/{chunk-VQ47JBLF.ts → chunk-FI2F5JBS.ts} +2 -2
  8. package/dist/chunks/{chunk-V76KCWHO.ts → chunk-IOM6E5FW.ts} +4 -4
  9. package/dist/chunks/{chunk-B5F3JLD3.ts → chunk-JQ5BAWW2.ts} +482 -78
  10. package/dist/chunks/chunk-JQ5BAWW2.ts.map +7 -0
  11. package/dist/chunks/{chunk-LBNC5AOM.ts → chunk-OBVJTKVY.ts} +12 -12
  12. package/dist/chunks/{chunk-EXDWEFIJ.ts → chunk-OWEOZZZE.ts} +6 -6
  13. package/dist/chunks/{chunk-SXCH4Q5O.ts → chunk-SZJOUVCL.ts} +3 -3
  14. package/dist/chunks/{chunk-HSCAFOT5.ts → chunk-TZMVSTAM.ts} +5 -5
  15. package/dist/chunks/{chunk-POWOMJ7S.ts → chunk-WJQ4TGN5.ts} +58 -31
  16. package/dist/chunks/chunk-WJQ4TGN5.ts.map +7 -0
  17. package/dist/chunks/{chunk-HLCML3OW.ts → chunk-XUZV4OGI.ts} +5 -3
  18. package/dist/chunks/chunk-XUZV4OGI.ts.map +7 -0
  19. package/dist/chunks/{command-handler-GMRRFWOL.ts → command-handler-YZ4DXQ7N.ts} +81 -30
  20. package/dist/chunks/command-handler-YZ4DXQ7N.ts.map +7 -0
  21. package/dist/chunks/{conflict-review-JWEA7DPQ.ts → conflict-review-J7L7S4AR.ts} +2 -2
  22. package/dist/chunks/{file-selection-KID23GAD.ts → file-selection-DDQN4LVD.ts} +9 -9
  23. package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts → manager-result-dispatcher-XB75YLEG.ts} +5 -5
  24. package/dist/chunks/{manager-ui-T5J5WG7T.ts → manager-ui-RGA26Z6G.ts} +103 -83
  25. package/dist/chunks/manager-ui-RGA26Z6G.ts.map +7 -0
  26. package/dist/chunks/{merge-review-OQDXNTJU.ts → merge-review-AAC674C6.ts} +3 -2
  27. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts +59 -0
  28. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts.map +7 -0
  29. package/dist/chunks/{remote-selection-ui-GPITNEBF.ts → remote-selection-ui-WVMET5RI.ts} +4 -4
  30. package/dist/chunks/{setup-switch-L54X5U5I.ts → setup-switch-644T6KHG.ts} +4 -4
  31. package/dist/chunks/{setup-wizard-LL6YMGUR.ts → setup-wizard-YP2KF2WQ.ts} +9 -9
  32. package/dist/chunks/{sync-inspection-SRU6HGGK.ts → sync-inspection-NBBTSMKR.ts} +5 -5
  33. package/dist/chunks/{sync-operations-UGSCONZ7.ts → sync-operations-AIEM2KL2.ts} +2 -2
  34. package/dist/daemon/dist/cli.js +2 -0
  35. package/dist/daemon/dist/client-transport.js +66 -0
  36. package/dist/daemon/dist/client.js +222 -354
  37. package/dist/daemon/dist/consent.js +33 -11
  38. package/dist/daemon/dist/daemon-debug.js +33 -0
  39. package/dist/daemon/dist/daemon-recovery.js +158 -0
  40. package/dist/daemon/dist/daemon-startup.js +257 -0
  41. package/dist/daemon/dist/engine/backends/git/git-backend.js +49 -13
  42. package/dist/daemon/dist/engine/backends/git/git-runner.js +6 -1
  43. package/dist/daemon/dist/engine/backends/git/git-storage.js +5 -9
  44. package/dist/daemon/dist/engine/backends/publication-encoding.js +19 -0
  45. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +30 -21
  46. package/dist/daemon/dist/engine/backends/sync-backend.js +16 -0
  47. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +34 -32
  48. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +10 -0
  49. package/dist/daemon/dist/engine/debug-log.js +134 -0
  50. package/dist/daemon/dist/engine/paths.js +7 -1
  51. package/dist/daemon/dist/engine/settings/config-file.js +62 -17
  52. package/dist/daemon/dist/engine/settings/config.js +49 -14
  53. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +30 -8
  54. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +3 -1
  55. package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +32 -0
  56. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +34 -0
  57. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +50 -7
  58. package/dist/daemon/dist/engine/snapshot/snapshot.js +64 -25
  59. package/dist/daemon/dist/engine/state/lock.js +157 -17
  60. package/dist/daemon/dist/engine/sync/continuous-sync.js +35 -11
  61. package/dist/daemon/dist/engine/sync/directional-action.js +124 -0
  62. package/dist/daemon/dist/engine/sync/initialization.js +2 -2
  63. package/dist/daemon/dist/engine/sync/local-fields.js +42 -19
  64. package/dist/daemon/dist/engine/sync/merged-sync.js +13 -10
  65. package/dist/daemon/dist/engine/sync/remote-snapshot.js +21 -4
  66. package/dist/daemon/dist/engine/sync/session-push.js +13 -4
  67. package/dist/daemon/dist/engine/sync/startup-bootstrap.js +105 -0
  68. package/dist/daemon/dist/engine/sync/startup-recovery-evidence.js +37 -0
  69. package/dist/daemon/dist/engine/sync/startup-timings.js +80 -8
  70. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +6 -1
  71. package/dist/daemon/dist/engine/sync/sync-errors.js +20 -0
  72. package/dist/daemon/dist/engine/sync/sync-inspection.js +4 -7
  73. package/dist/daemon/dist/engine/sync/sync-local.js +59 -4
  74. package/dist/daemon/dist/engine/sync/sync-mutations.js +309 -337
  75. package/dist/daemon/dist/engine/sync/sync-policy.js +9 -1
  76. package/dist/daemon/dist/engine/sync/sync-queries.js +2 -1
  77. package/dist/daemon/dist/engine/sync/sync-rollback.js +198 -0
  78. package/dist/daemon/dist/engine/sync/sync-state.js +12 -4
  79. package/dist/daemon/dist/engine/sync/transfer-freshness.js +11 -5
  80. package/dist/daemon/dist/engine-service.js +122 -10
  81. package/dist/daemon/dist/foreground-queue-outcome.js +9 -0
  82. package/dist/daemon/dist/identity.js +36 -6
  83. package/dist/daemon/dist/index.js +2 -1
  84. package/dist/daemon/dist/monitor.js +21 -1
  85. package/dist/daemon/dist/paged-review.js +177 -0
  86. package/dist/daemon/dist/participant-ledger.js +149 -0
  87. package/dist/daemon/dist/protocol.js +4 -0
  88. package/dist/daemon/dist/server.js +340 -127
  89. package/dist/daemon/dist/service-host.js +83 -15
  90. package/dist/daemon/dist/state-wait-jobs.js +23 -0
  91. package/dist/daemon/dist/state-wait.js +34 -0
  92. package/dist/daemon/package.json +1 -1
  93. package/dist/index.ts +128 -48
  94. package/dist/index.ts.map +2 -2
  95. package/docs/continuous-sync-verification.md +2 -0
  96. package/docs/daemon-migration.md +31 -6
  97. package/docs/tui-contract.md +7 -1
  98. package/package.json +2 -2
  99. package/skills/configure-pi-sync/references/configuration.md +23 -13
  100. package/src/commands/command-execution.ts +67 -5
  101. package/src/commands/command-handler.ts +12 -3
  102. package/src/commands/command.ts +4 -2
  103. package/src/daemon/client-debug.ts +45 -0
  104. package/src/daemon/directional-recovery.ts +103 -0
  105. package/src/daemon/ownership-recovery.ts +50 -0
  106. package/src/daemon/pi-client.ts +399 -71
  107. package/src/daemon/startup-bootstrap-client.ts +26 -0
  108. package/src/settings/config.ts +1 -0
  109. package/src/sync/automatic-sync.ts +61 -18
  110. package/src/sync/startup-check.ts +13 -5
  111. package/src/sync-extension.ts +46 -8
  112. package/src/ui/cancellable-operation.ts +5 -2
  113. package/src/ui/manager-state.ts +31 -23
  114. package/src/ui/manager-ui.ts +45 -25
  115. package/src/ui/merge-review.ts +53 -18
  116. package/src/ui/settings-ui.ts +2 -2
  117. package/src/ui/sync-confirmation.ts +14 -17
  118. package/src/ui/sync-setups-ui.ts +15 -12
  119. package/dist/chunks/chunk-27F5W7DX.ts.map +0 -7
  120. package/dist/chunks/chunk-B5F3JLD3.ts.map +0 -7
  121. package/dist/chunks/chunk-CKUGCBHP.ts.map +0 -7
  122. package/dist/chunks/chunk-HLCML3OW.ts.map +0 -7
  123. package/dist/chunks/chunk-POWOMJ7S.ts.map +0 -7
  124. package/dist/chunks/command-handler-GMRRFWOL.ts.map +0 -7
  125. package/dist/chunks/manager-ui-T5J5WG7T.ts.map +0 -7
  126. /package/dist/chunks/{chunk-VQ47JBLF.ts.map → chunk-FI2F5JBS.ts.map} +0 -0
  127. /package/dist/chunks/{chunk-V76KCWHO.ts.map → chunk-IOM6E5FW.ts.map} +0 -0
  128. /package/dist/chunks/{chunk-LBNC5AOM.ts.map → chunk-OBVJTKVY.ts.map} +0 -0
  129. /package/dist/chunks/{chunk-EXDWEFIJ.ts.map → chunk-OWEOZZZE.ts.map} +0 -0
  130. /package/dist/chunks/{chunk-SXCH4Q5O.ts.map → chunk-SZJOUVCL.ts.map} +0 -0
  131. /package/dist/chunks/{chunk-HSCAFOT5.ts.map → chunk-TZMVSTAM.ts.map} +0 -0
  132. /package/dist/chunks/{conflict-review-JWEA7DPQ.ts.map → conflict-review-J7L7S4AR.ts.map} +0 -0
  133. /package/dist/chunks/{file-selection-KID23GAD.ts.map → file-selection-DDQN4LVD.ts.map} +0 -0
  134. /package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts.map → manager-result-dispatcher-XB75YLEG.ts.map} +0 -0
  135. /package/dist/chunks/{merge-review-OQDXNTJU.ts.map → merge-review-AAC674C6.ts.map} +0 -0
  136. /package/dist/chunks/{remote-selection-ui-GPITNEBF.ts.map → remote-selection-ui-WVMET5RI.ts.map} +0 -0
  137. /package/dist/chunks/{setup-switch-L54X5U5I.ts.map → setup-switch-644T6KHG.ts.map} +0 -0
  138. /package/dist/chunks/{setup-wizard-LL6YMGUR.ts.map → setup-wizard-YP2KF2WQ.ts.map} +0 -0
  139. /package/dist/chunks/{sync-inspection-SRU6HGGK.ts.map → sync-inspection-NBBTSMKR.ts.map} +0 -0
  140. /package/dist/chunks/{sync-operations-UGSCONZ7.ts.map → sync-operations-AIEM2KL2.ts.map} +0 -0
@@ -3,11 +3,12 @@ import { createHash, randomUUID } from "node:crypto";
3
3
  import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { posixJoin } from "../../paths.js";
6
+ import { snapshotFileFromBlob } from "../../snapshot/snapshot-payload.js";
6
7
  import { IGNORE_SNAPSHOT_VERSION } from "../../snapshot/snapshot-types.js";
7
8
  import { stateDir } from "../../state/state-directory.js";
8
9
  import { throwIfAborted } from "../../sync/signals.js";
9
10
  import { syncErrorGuidance } from "../../sync/sync-error-guidance.js";
10
- import { SyncBackendConflictError, SyncBackendPublicationOutcomeUnknownError, } from "../sync-backend.js";
11
+ import { SyncBackendConflictError, SyncBackendPublicationOutcomeUnknownError, verifyPreviousHeadInHistory, } from "../sync-backend.js";
11
12
  import { normalizeGitBranch, normalizeGitDirectory, normalizeGitRemote, normalizeGitRemoteIdentity, validateGitNamespace, } from "./git-config.js";
12
13
  import { GitCommandError, parseGitBlobBatch, readGitBlobs, runGit } from "./git-runner.js";
13
14
  import { GIT_MANIFEST_VERSION, MAX_GIT_MANIFEST_BYTES, MAX_GIT_TREE_OUTPUT_BYTES, parseGitTree, prepareGitSnapshot, requireGitManifest, validateGitPublicationTree, validateGitSnapshot, } from "./git-storage.js";
@@ -30,9 +31,11 @@ export class GitSyncBackend {
30
31
  afterLsRemoteForTest;
31
32
  afterPayloadWriteForTest;
32
33
  cacheReady;
34
+ cachedPublication;
33
35
  constructor(config, options = {}) {
34
36
  this.config = config;
35
37
  assertGitDestination(config);
38
+ this.config = { ...config, profile: { ...config.profile }, destination: { ...config.destination } };
36
39
  this.allowLocalRemotes = options.allowLocalRemotes === true;
37
40
  if (!this.allowLocalRemotes)
38
41
  assertProductionRemote(config.profile.remote);
@@ -53,22 +56,37 @@ export class GitSyncBackend {
53
56
  const sha = await this.fetchRemoteHead(signal);
54
57
  if (!sha)
55
58
  return undefined;
56
- const { manifest } = await this.readPublication(sha, signal);
57
- return remoteHead(sha, manifest, this.identity);
59
+ return this.headForSha(sha, signal);
60
+ }
61
+ async readHeadAndSnapshot(signal) {
62
+ const commit = await this.fetchRemoteHead(signal);
63
+ if (!commit)
64
+ return undefined;
65
+ const publication = await this.readCachedPublication(commit, signal);
66
+ await this.requireReachablePublication(commit, commit, undefined, signal);
67
+ const snapshot = await this.readPublicationSnapshot(publication, signal);
68
+ return { head: remoteHead(commit, publication.manifest, this.identity), snapshot };
58
69
  }
59
70
  async readSnapshot(reference, signal) {
60
71
  const head = await this.fetchRemoteHead(signal);
61
72
  if (!head)
62
73
  throw new Error(`Git snapshot publication was not found: ${reference}`);
63
74
  const commit = await this.resolveSnapshotReference(reference, head, signal);
75
+ await this.requireReachablePublication(reference, commit, head, signal);
76
+ return this.readPublicationSnapshot(await this.readCachedPublication(commit, signal), signal);
77
+ }
78
+ async requireReachablePublication(reference, commit, head, signal) {
64
79
  try {
65
80
  await this.git(["cat-file", "-e", `${commit}^{commit}`], { signal });
66
- await this.git(["merge-base", "--is-ancestor", commit, head], { signal });
81
+ if (head !== undefined)
82
+ await this.git(["merge-base", "--is-ancestor", commit, head], { signal });
67
83
  }
68
84
  catch (error) {
85
+ throwIfAborted(signal);
69
86
  throw new Error(`Git snapshot publication was not found: ${reference}`, { cause: error });
70
87
  }
71
- const { manifest, payloadEntries } = await this.readPublication(commit, signal);
88
+ }
89
+ async readPublicationSnapshot({ manifest, payloadEntries }, signal) {
72
90
  let blobs;
73
91
  try {
74
92
  blobs = await readGitBlobs(payloadEntries.map((entry) => entry.object), {
@@ -88,10 +106,10 @@ export class GitSyncBackend {
88
106
  throwIfAborted(signal);
89
107
  const files = manifest.files.map((file, index) => {
90
108
  const content = blobs[index];
91
- if (!content || content.byteLength !== file.size || sha256(content) !== file.sha256) {
92
- throw new Error(`Git snapshot file checksum or size mismatch: ${file.path}`);
93
- }
94
- return { path: file.path, contentBase64: content.toString("base64"), sha256: file.sha256 };
109
+ const mismatch = `Git snapshot file checksum or size mismatch: ${file.path}`;
110
+ if (!content || content.byteLength !== file.size)
111
+ throw new Error(mismatch);
112
+ return snapshotFileFromBlob(file.path, content, file.sha256, mismatch);
95
113
  });
96
114
  const snapshot = {
97
115
  version: manifest.snapshotVersion,
@@ -100,8 +118,8 @@ export class GitSyncBackend {
100
118
  machine: manifest.machine,
101
119
  profile: manifest.profile,
102
120
  ...(manifest.snapshotSyncSessions === undefined ? {} : { syncSessions: manifest.snapshotSyncSessions }),
103
- ...(manifest.selection === undefined ? {} : { selection: manifest.selection }),
104
- ...(manifest.localFields === undefined ? {} : { localFields: manifest.localFields }),
121
+ ...(manifest.selection === undefined ? {} : { selection: structuredClone(manifest.selection) }),
122
+ ...(manifest.localFields === undefined ? {} : { localFields: [...manifest.localFields] }),
105
123
  files,
106
124
  };
107
125
  validateGitSnapshot(snapshot, manifest, this.config.destination.namespace);
@@ -140,6 +158,15 @@ export class GitSyncBackend {
140
158
  throw this.redactedError(error);
141
159
  }
142
160
  throwIfAborted(options.signal);
161
+ if (options.preservePreviousHead && observed) {
162
+ try {
163
+ await verifyPreviousHeadInHistory(this, await this.headForSha(observed, options.signal), options.signal);
164
+ }
165
+ catch (error) {
166
+ throwIfAborted(options.signal);
167
+ throw new Error(`Cannot verify the previous Git publication ${observed} in History; remote head was not updated.`, { cause: error });
168
+ }
169
+ }
143
170
  if (options.validateIgnorePolicy) {
144
171
  await options.validateIgnorePolicy();
145
172
  throwIfAborted(options.signal);
@@ -294,9 +321,18 @@ export class GitSyncBackend {
294
321
  return matches[0];
295
322
  }
296
323
  async headForSha(sha, signal) {
297
- const { manifest } = await this.readPublication(sha, signal);
324
+ const { manifest } = await this.readCachedPublication(sha, signal);
298
325
  return remoteHead(sha, manifest, this.identity);
299
326
  }
327
+ async readCachedPublication(commit, signal) {
328
+ throwIfAborted(signal);
329
+ if (this.cachedPublication?.commit === commit)
330
+ return this.cachedPublication.publication;
331
+ const publication = await this.readPublication(commit, signal);
332
+ throwIfAborted(signal);
333
+ this.cachedPublication = { commit, publication };
334
+ return publication;
335
+ }
300
336
  async fetchRemoteHead(signal) {
301
337
  await this.ensureCache(signal);
302
338
  const result = await this.git(["ls-remote", "--refs", this.config.profile.remote, this.remoteRef()], { signal });
@@ -611,7 +647,7 @@ function remoteHead(sha, manifest, identity) {
611
647
  createdAt: manifest.createdAt,
612
648
  machine: manifest.machine,
613
649
  syncSessions: manifest.syncSessions,
614
- ...(manifest.selection === undefined ? {} : { selection: manifest.selection }),
650
+ ...(manifest.selection === undefined ? {} : { selection: structuredClone(manifest.selection) }),
615
651
  };
616
652
  }
617
653
  function matchesExpected(current, expected, identity) {
@@ -33,7 +33,12 @@ export async function runGit(args, options = {}) {
33
33
  ];
34
34
  if (options.allowFileProtocol)
35
35
  protocolArgs.push("-c", "protocol.file.allow=always");
36
- const commandArgs = [...(options.gitDir ? [`--git-dir=${options.gitDir}`] : []), ...protocolArgs, ...args];
36
+ const commandArgs = [
37
+ "--no-replace-objects",
38
+ ...(options.gitDir ? [`--git-dir=${options.gitDir}`] : []),
39
+ ...protocolArgs,
40
+ ...args,
41
+ ];
37
42
  const inheritedEnvironment = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith("GIT_") &&
38
43
  key !== "PAGER" &&
39
44
  key !== "EDITOR" &&
@@ -1,8 +1,8 @@
1
- import { createHash } from "node:crypto";
2
1
  import { assertAgentDirectorySettingsSize, MAX_AGENT_DIRECTORY_BYTES } from "../../snapshot/snapshot-bounds.js";
2
+ import { materializeSnapshotFilePayload } from "../../snapshot/snapshot-payload.js";
3
3
  import { IGNORE_SNAPSHOT_VERSION, isSupportedSnapshotVersion, } from "../../snapshot/snapshot-types.js";
4
4
  import { sameLocalFields, validateIgnoreSnapshotIdentity, validateIgnoreSnapshotSessionFlag, validatePortableSnapshot, validateSnapshotFieldPolicy, } from "../../sync/local-fields.js";
5
- import { assertAgentDirectoryPathLayout, configuredSnapshotPathMatcher, portableSnapshotSelection, sameSnapshotSelection, snapshotSelectionInclude, validateSnapshotSelection, } from "../../sync/sync-policy.js";
5
+ import { assertAgentDirectoryPathLayout, assertSnapshotExcludesDebugLog, assertSnapshotPathExcludesDebugLog, configuredSnapshotPathMatcher, portableSnapshotSelection, sameSnapshotSelection, snapshotSelectionInclude, validateSnapshotSelection, } from "../../sync/sync-policy.js";
6
6
  export const GIT_MANIFEST_VERSION = 2;
7
7
  export const MAX_GIT_MANIFEST_BYTES = 1024 * 1024;
8
8
  export const MAX_GIT_TREE_OUTPUT_BYTES = 16 * 1024 * 1024;
@@ -76,6 +76,7 @@ export function requireGitManifest(value) {
76
76
  throw new Error("Git publication manifest file is malformed.");
77
77
  }
78
78
  const file = rawFile;
79
+ assertSnapshotPathExcludesDebugLog(file.path);
79
80
  if (!hasExactKeys(file, ["path", "sha256", "size"]) ||
80
81
  !isSafeSnapshotPath(file.path) ||
81
82
  (selected !== undefined && !selected(file.path)) ||
@@ -129,6 +130,7 @@ export function validateGitSnapshot(snapshot, manifest, namespace) {
129
130
  }
130
131
  }
131
132
  export function prepareGitSnapshot(snapshot, namespace) {
133
+ assertSnapshotExcludesDebugLog(snapshot);
132
134
  if (snapshot.version !== IGNORE_SNAPSHOT_VERSION)
133
135
  snapshotSelectionInclude(snapshot);
134
136
  validatePortableSnapshot(snapshot);
@@ -159,10 +161,7 @@ export function prepareGitSnapshot(snapshot, namespace) {
159
161
  paths.has(file.path)) {
160
162
  throw new Error("Invalid Git snapshot file.");
161
163
  }
162
- const content = Buffer.from(file.contentBase64, "base64");
163
- if (content.toString("base64") !== file.contentBase64 || sha256(content) !== file.sha256) {
164
- throw new Error("Git snapshot file checksum mismatch.");
165
- }
164
+ const content = materializeSnapshotFilePayload(file, "Git snapshot file checksum mismatch.");
166
165
  if (!isGitPayloadSizeAllowed(content.byteLength)) {
167
166
  throw new Error(`Git snapshot file exceeds GitHub's ${MAX_GIT_PAYLOAD_BYTES}-byte regular-Git limit: ${file.path}`);
168
167
  }
@@ -243,9 +242,6 @@ function assertNoPathConflicts(paths) {
243
242
  }
244
243
  }
245
244
  }
246
- function sha256(value) {
247
- return createHash("sha256").update(value).digest("hex");
248
- }
249
245
  function hasControlCharacter(value) {
250
246
  // biome-ignore lint/suspicious/noControlCharactersInRegex: Reject untrusted terminal/ref controls.
251
247
  return /[\u0000-\u001f\u007f-\u009f]/u.test(value);
@@ -0,0 +1,19 @@
1
+ import { encodeSnapshot } from "../snapshot/snapshot-codec.js";
2
+ export function capturePublicationImage(snapshot) {
3
+ if (!Array.isArray(snapshot.files))
4
+ throw new Error("Invalid snapshot publication files.");
5
+ return {
6
+ ...snapshot,
7
+ selection: structuredClone(snapshot.selection),
8
+ localFields: snapshot.localFields && [...snapshot.localFields],
9
+ files: snapshot.files.map((file) => ({ ...file })),
10
+ };
11
+ }
12
+ export async function encodeForPublication(image, prepareRemote) {
13
+ const [prepared, encoding] = await Promise.allSettled([prepareRemote(), encodeSnapshot(image)]);
14
+ if (prepared.status === "rejected")
15
+ throw prepared.reason;
16
+ if (encoding.status === "rejected")
17
+ throw encoding.reason;
18
+ return encoding.value;
19
+ }
@@ -1,13 +1,15 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import { encodeKey, posixJoin } from "../../paths.js";
3
3
  import { sessionTokenWarnings } from "../../settings/config.js";
4
- import { decodeSnapshot, encodeSnapshot } from "../../snapshot/snapshot-codec.js";
4
+ import { decodeSnapshot } from "../../snapshot/snapshot-codec.js";
5
+ import { assertSnapshotFilePayload } from "../../snapshot/snapshot-payload.js";
5
6
  import { validatePortableSnapshot } from "../../sync/local-fields.js";
6
7
  import { throwIfAborted } from "../../sync/signals.js";
7
8
  import { syncErrorGuidance } from "../../sync/sync-error-guidance.js";
8
9
  import { portableSnapshotSelection } from "../../sync/sync-policy.js";
10
+ import { capturePublicationImage, encodeForPublication } from "../publication-encoding.js";
9
11
  import { createLatestPointer, remoteHistoryEntry } from "../snapshot-pointer.js";
10
- import { SyncBackendConflictError, SyncBackendPublicationOutcomeUnknownError, } from "../sync-backend.js";
12
+ import { SyncBackendConflictError, SyncBackendPublicationOutcomeUnknownError, verifyPreviousHeadInHistory, } from "../sync-backend.js";
11
13
  import { S3Client, S3HttpError, S3ObjectAlreadyExistsError } from "./s3-client.js";
12
14
  import { requireS3Etag, verifyS3Conditions } from "./s3-conditions.js";
13
15
  const VERSION = 1;
@@ -74,16 +76,15 @@ export class S3SyncBackend {
74
76
  }
75
77
  async publishSnapshot(snapshot, expected, options = {}) {
76
78
  throwIfAborted(options.signal);
77
- assertSnapshotIdentity(snapshot, this.config.destination.namespace);
79
+ const image = capturePublicationImage(snapshot);
80
+ assertSnapshotIdentity(image, this.config.destination.namespace);
78
81
  if (options.validateIgnorePolicy)
79
82
  await options.validateIgnorePolicy();
80
83
  throwIfAborted(options.signal);
81
- await verifyS3Conditions(this.config, options.signal);
84
+ const encoded = await encodeForPublication(image, () => verifyS3Conditions(this.config, options.signal));
82
85
  throwIfAborted(options.signal);
83
- const stagedKey = snapshotKey(this.config, snapshot.id);
84
- const encoded = await encodeSnapshot(snapshot);
85
- throwIfAborted(options.signal);
86
- const pointer = pointerFor(this.config, snapshot, sha256(encoded));
86
+ const stagedKey = snapshotKey(this.config, image.id);
87
+ const pointer = pointerFor(this.config, image, sha256(encoded));
87
88
  const cancellableClient = new S3Client(this.config, options.signal);
88
89
  if (options.validateIgnorePolicy)
89
90
  await options.validateIgnorePolicy();
@@ -98,23 +99,33 @@ export class S3SyncBackend {
98
99
  throw error;
99
100
  const existing = await cancellableClient.getBuffer(stagedKey);
100
101
  if (!existing.value || sha256(existing.value) !== pointer.sha256) {
101
- throw new SyncBackendConflictError(`Immutable snapshot id already exists with different content: ${snapshot.id}`);
102
+ throw new SyncBackendConflictError(`Immutable snapshot id already exists with different content: ${image.id}`);
102
103
  }
103
104
  }
104
105
  const currentObject = await cancellableClient.getJson(latestKey(this.config));
105
106
  throwIfAborted(options.signal);
106
- let current;
107
- if (!currentObject.missing) {
108
- const currentPointer = requirePointer(currentObject.value, "Remote latest pointer is malformed.", this.config.destination.namespace);
107
+ const currentPointer = currentObject.missing
108
+ ? undefined
109
+ : requirePointer(currentObject.value, "Remote latest pointer is malformed.", this.config.destination.namespace);
110
+ if (currentPointer)
109
111
  this.registerChecksum(currentPointer.snapshot, currentPointer.sha256);
110
- current = remoteHead(currentPointer, this.identity, currentObject.etag);
111
- }
112
+ const current = currentPointer && remoteHead(currentPointer, this.identity, currentObject.etag);
112
113
  if (!matchesExpected(current, expected)) {
113
114
  throw new SyncBackendConflictError("Remote changed while pushing. Run /sync pull first, then retry.", {
114
115
  currentHead: current,
115
116
  });
116
117
  }
117
118
  const condition = currentObject.missing ? { ifAbsent: true } : { ifMatch: requireS3Etag(currentObject.etag) };
119
+ if (options.preservePreviousHead && current && currentPointer) {
120
+ try {
121
+ await this.updateHistory(cancellableClient, currentPointer, true);
122
+ await verifyPreviousHeadInHistory(this, current, options.signal);
123
+ }
124
+ catch (error) {
125
+ throwIfAborted(options.signal);
126
+ throw new Error(`Cannot verify the previous remote snapshot ${current.snapshotId} in History; remote head was not updated.`, { cause: error });
127
+ }
128
+ }
118
129
  if (options.validateIgnorePolicy)
119
130
  await options.validateIgnorePolicy();
120
131
  throwIfAborted(options.signal);
@@ -241,16 +252,17 @@ export class S3SyncBackend {
241
252
  return `Remote snapshot is active, but history could not be updated: ${errorMessage(error)}. Run /sync doctor before relying on history.`;
242
253
  }
243
254
  }
244
- async updateHistory(client, pointer) {
255
+ async updateHistory(client, pointer, keepRecent = false) {
245
256
  const object = await client.getJson(historyKey(this.config));
246
257
  const snapshots = object.missing ? [] : requireHistory(object.value, this.config.destination.namespace);
247
258
  const existing = snapshots.find((snapshot) => snapshot.snapshot === pointer.snapshot);
248
259
  if (existing) {
249
260
  if (!samePointer(existing, pointer))
250
261
  throw new Error("Remote history rebound an immutable snapshot reference.");
251
- return;
262
+ if (!keepRecent || snapshots.at(-1) === existing)
263
+ return;
252
264
  }
253
- const next = [...snapshots, pointer].slice(-100);
265
+ const next = [...snapshots.filter((snapshot) => snapshot !== existing), pointer].slice(-100);
254
266
  const condition = object.missing ? { ifAbsent: true } : { ifMatch: requireS3Etag(object.etag) };
255
267
  await client.putJson(historyKey(this.config), { version: VERSION, snapshots: next }, condition);
256
268
  }
@@ -389,10 +401,7 @@ function validateSnapshotBundle(snapshot) {
389
401
  paths.has(file.path)) {
390
402
  throw new Error("Remote snapshot bundle is malformed.");
391
403
  }
392
- const content = Buffer.from(file.contentBase64, "base64");
393
- if (content.toString("base64") !== file.contentBase64 || sha256(content) !== file.sha256) {
394
- throw new Error("Remote snapshot file checksum mismatch.");
395
- }
404
+ assertSnapshotFilePayload(file, "Remote snapshot file checksum mismatch.");
396
405
  paths.add(file.path);
397
406
  }
398
407
  }
@@ -1,3 +1,5 @@
1
+ import { sameSnapshotSelection } from "../sync/sync-policy.js";
2
+ export const HISTORY_PREVIEW_LIMIT = 20;
1
3
  export class SyncBackendConflictError extends Error {
2
4
  code = "SYNC_BACKEND_CONFLICT";
3
5
  phase;
@@ -18,6 +20,20 @@ export class SyncBackendPublicationOutcomeUnknownError extends Error {
18
20
  this.name = "SyncBackendPublicationOutcomeUnknownError";
19
21
  }
20
22
  }
23
+ export async function verifyPreviousHeadInHistory(backend, head, signal) {
24
+ const entries = await backend.listHistory(signal);
25
+ if (!entries
26
+ .slice(-(HISTORY_PREVIEW_LIMIT - 1))
27
+ .some((entry) => entry.snapshotRef === head.snapshotRef &&
28
+ entry.snapshotId === head.snapshotId &&
29
+ entry.createdAt === head.createdAt &&
30
+ entry.machine === head.machine &&
31
+ entry.syncSessions === head.syncSessions))
32
+ throw new Error(`Cannot replace remote snapshot ${head.snapshotId}: it is not available in History.`);
33
+ const snapshot = await backend.readSnapshot(head.snapshotRef, signal);
34
+ if (snapshot.id !== head.snapshotId || (head.selection && !sameSnapshotSelection(head.selection, snapshot.selection)))
35
+ throw new Error(`Cannot replace remote snapshot ${head.snapshotId}: History resolved to a different snapshot.`);
36
+ }
21
37
  export function expectedRemoteHead(head) {
22
38
  return head ? { kind: "revision", revision: head.revision } : { kind: "missing" };
23
39
  }
@@ -1,11 +1,13 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
- import { decodeSnapshot, encodeSnapshot } from "../../snapshot/snapshot-codec.js";
2
+ import { decodeSnapshot } from "../../snapshot/snapshot-codec.js";
3
+ import { assertSnapshotFilePayload } from "../../snapshot/snapshot-payload.js";
3
4
  import { validatePortableSnapshot } from "../../sync/local-fields.js";
4
5
  import { throwIfAborted } from "../../sync/signals.js";
5
6
  import { syncErrorGuidance } from "../../sync/sync-error-guidance.js";
6
7
  import { portableSnapshotSelection } from "../../sync/sync-policy.js";
8
+ import { capturePublicationImage, encodeForPublication } from "../publication-encoding.js";
7
9
  import { createLatestPointer, remoteHistoryEntry } from "../snapshot-pointer.js";
8
- import { SyncBackendConflictError, SyncBackendPublicationOutcomeUnknownError, } from "../sync-backend.js";
10
+ import { SyncBackendConflictError, SyncBackendPublicationOutcomeUnknownError, verifyPreviousHeadInHistory, } from "../sync-backend.js";
9
11
  import { WebDavClient, WebDavHttpError, WebDavPreconditionError } from "./webdav-client.js";
10
12
  const VERSION = 1;
11
13
  const POST_COMMIT_TIMEOUT_MS = 30_000;
@@ -16,7 +18,6 @@ export class WebDavSyncBackend {
16
18
  destination;
17
19
  conditionalVerified = false;
18
20
  checksums = new Map();
19
- capabilityCheck;
20
21
  constructor(config, postCommitTimeoutMs = POST_COMMIT_TIMEOUT_MS) {
21
22
  this.config = config;
22
23
  this.postCommitTimeoutMs = postCommitTimeoutMs;
@@ -58,18 +59,19 @@ export class WebDavSyncBackend {
58
59
  }
59
60
  async publishSnapshot(snapshot, expected, options = {}) {
60
61
  throwIfAborted(options.signal);
61
- assertSnapshotIdentity(snapshot, this.config.destination.namespace);
62
+ const image = capturePublicationImage(snapshot);
63
+ assertSnapshotIdentity(image, this.config.destination.namespace);
62
64
  if (options.validateIgnorePolicy)
63
65
  await options.validateIgnorePolicy();
64
66
  throwIfAborted(options.signal);
65
- await this.ensureAtomicConditions(options.signal);
66
- throwIfAborted(options.signal);
67
67
  const client = new WebDavClient(this.config, options.signal);
68
- await client.ensureCollection(snapshotsPath(this.config));
69
- const encoded = await encodeSnapshot(snapshot);
68
+ const encoded = await encodeForPublication(image, async () => {
69
+ await this.runCapabilityProbe(options.signal);
70
+ await client.ensureCollection(snapshotsPath(this.config));
71
+ });
70
72
  throwIfAborted(options.signal);
71
- const pointer = createLatestPointer(this.config.destination.namespace, snapshot, sha256(encoded));
72
- const stagedPath = snapshotPath(this.config, snapshot.id);
73
+ const pointer = createLatestPointer(this.config.destination.namespace, image, sha256(encoded));
74
+ const stagedPath = snapshotPath(this.config, image.id);
73
75
  if (options.validateIgnorePolicy)
74
76
  await options.validateIgnorePolicy();
75
77
  throwIfAborted(options.signal);
@@ -81,20 +83,32 @@ export class WebDavSyncBackend {
81
83
  throw error;
82
84
  const existing = await client.getBuffer(stagedPath);
83
85
  if (!existing.value || sha256(existing.value) !== pointer.sha256) {
84
- throw new SyncBackendConflictError(`Immutable snapshot id already exists with different content: ${snapshot.id}`);
86
+ throw new SyncBackendConflictError(`Immutable snapshot id already exists with different content: ${image.id}`);
85
87
  }
86
88
  }
87
89
  const currentObject = await client.getJson(latestPath(this.config));
88
90
  throwIfAborted(options.signal);
89
- const current = currentObject.missing
91
+ const currentPointer = currentObject.missing
90
92
  ? undefined
91
- : remoteHead(requirePointer(currentObject.value, this.config.destination.namespace), this.identity, currentObject.etag);
93
+ : requirePointer(currentObject.value, this.config.destination.namespace);
94
+ const current = currentPointer && remoteHead(currentPointer, this.identity, currentObject.etag);
92
95
  if (!matchesExpected(current, expected)) {
93
96
  throw new SyncBackendConflictError("Remote changed while pushing. Run /sync pull first, then retry.", {
94
97
  currentHead: current,
95
98
  });
96
99
  }
97
100
  const condition = publicationCondition(currentObject, expected, this.identity);
101
+ if (options.preservePreviousHead && current && currentPointer) {
102
+ try {
103
+ this.registerChecksum(currentPointer.snapshot, currentPointer.sha256);
104
+ await this.ensureHistoryPointer(client, currentPointer, true);
105
+ await verifyPreviousHeadInHistory(this, current, options.signal);
106
+ }
107
+ catch (error) {
108
+ throwIfAborted(options.signal);
109
+ throw new Error(`Cannot verify the previous remote snapshot ${current.snapshotId} in History; remote head was not updated.`, { cause: error });
110
+ }
111
+ }
98
112
  if (options.validateIgnorePolicy)
99
113
  await options.validateIgnorePolicy();
100
114
  throwIfAborted(options.signal);
@@ -173,7 +187,6 @@ export class WebDavSyncBackend {
173
187
  }, { key: "webdav-cleanup", level: "info", message: "webdav probe cleanup: ok" });
174
188
  }
175
189
  catch (error) {
176
- this.capabilityCheck = undefined;
177
190
  this.conditionalVerified = false;
178
191
  if (error instanceof Error && error.name === "AbortError")
179
192
  throw error;
@@ -202,18 +215,8 @@ export class WebDavSyncBackend {
202
215
  }
203
216
  return diagnostics;
204
217
  }
205
- ensureAtomicConditions(signal) {
206
- if (this.capabilityCheck)
207
- return this.capabilityCheck;
208
- this.conditionalVerified = false;
209
- const check = this.runCapabilityProbe(signal).finally(() => {
210
- if (this.capabilityCheck === check)
211
- this.capabilityCheck = undefined;
212
- });
213
- this.capabilityCheck = check;
214
- return check;
215
- }
216
218
  async runCapabilityProbe(signal) {
219
+ this.conditionalVerified = false;
217
220
  throwIfAborted(signal);
218
221
  const probeCollection = joinRemote(rootPath(this.config), ".pi-sync-probes", randomUUID());
219
222
  const probe = `${probeCollection}/conditional.txt`;
@@ -259,6 +262,7 @@ export class WebDavSyncBackend {
259
262
  }
260
263
  if (operationError)
261
264
  throw operationError;
265
+ throwIfAborted(signal);
262
266
  this.conditionalVerified = true;
263
267
  }
264
268
  async resolveChecksum(reference, signal) {
@@ -294,7 +298,7 @@ export class WebDavSyncBackend {
294
298
  ? "webdav history: repaired active snapshot entry"
295
299
  : "webdav history: active snapshot entry present";
296
300
  }
297
- async ensureHistoryPointer(client, pointer) {
301
+ async ensureHistoryPointer(client, pointer, keepRecent = false) {
298
302
  const object = await client.getJson(historyPath(this.config));
299
303
  const snapshots = object.missing ? [] : requireHistory(object.value, this.config.destination.namespace);
300
304
  const existing = snapshots.find((entry) => entry.snapshot === pointer.snapshot);
@@ -302,9 +306,10 @@ export class WebDavSyncBackend {
302
306
  if (!samePointer(existing, pointer)) {
303
307
  throw new Error("Remote history rebound an immutable snapshot reference.");
304
308
  }
305
- return false;
309
+ if (!keepRecent || snapshots.at(-1) === existing)
310
+ return false;
306
311
  }
307
- const next = [...snapshots, pointer].slice(-100);
312
+ const next = [...snapshots.filter((entry) => entry !== existing), pointer].slice(-100);
308
313
  const condition = object.missing ? { ifAbsent: true } : { ifMatch: requireStrongEtag(object.etag, "history") };
309
314
  await client.putJson(historyPath(this.config), { version: VERSION, snapshots: next }, condition);
310
315
  return true;
@@ -442,10 +447,7 @@ function validateSnapshotBundle(snapshot) {
442
447
  typeof file.sha256 !== "string") {
443
448
  throw new Error("Remote snapshot bundle is malformed.");
444
449
  }
445
- const content = Buffer.from(file.contentBase64, "base64");
446
- if (content.toString("base64") !== file.contentBase64 || sha256(content) !== file.sha256) {
447
- throw new Error("Remote snapshot bundle is malformed.");
448
- }
450
+ assertSnapshotFilePayload(file, "Remote snapshot bundle is malformed.");
449
451
  paths.add(file.path);
450
452
  }
451
453
  }
@@ -110,6 +110,16 @@ export class WebDavClient {
110
110
  }
111
111
  async ensureCollection(remotePath) {
112
112
  const segments = safeSegments(remotePath);
113
+ if (segments.length === 0)
114
+ return;
115
+ try {
116
+ await this.makeCollection(segments.join("/"));
117
+ return;
118
+ }
119
+ catch (error) {
120
+ if (segments.length < 2 || !(error instanceof WebDavHttpError) || (error.status !== 409 && error.status !== 404))
121
+ throw error;
122
+ }
113
123
  for (let index = 1; index <= segments.length; index += 1) {
114
124
  await this.makeCollection(segments.slice(0, index).join("/"));
115
125
  }