@narumitw/pi-sync 0.64.0 → 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 (77) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +76 -7
  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-F3VODLVQ.ts → chunk-IOM6E5FW.ts} +3 -3
  6. package/dist/chunks/{chunk-RW44KNFD.ts → chunk-JQ5BAWW2.ts} +182 -12
  7. package/dist/chunks/chunk-JQ5BAWW2.ts.map +7 -0
  8. package/dist/chunks/{chunk-NDEZ52SS.ts → chunk-OBVJTKVY.ts} +5 -5
  9. package/dist/chunks/{chunk-TJ7YNITN.ts → chunk-OWEOZZZE.ts} +2 -2
  10. package/dist/chunks/{chunk-VPSC7BXM.ts → chunk-SZJOUVCL.ts} +2 -2
  11. package/dist/chunks/{chunk-YT6PDRMM.ts → chunk-WJQ4TGN5.ts} +17 -17
  12. package/dist/chunks/chunk-WJQ4TGN5.ts.map +7 -0
  13. package/dist/chunks/{chunk-4VKWHVUO.ts → chunk-XUZV4OGI.ts} +3 -2
  14. package/dist/chunks/{chunk-4VKWHVUO.ts.map → chunk-XUZV4OGI.ts.map} +2 -2
  15. package/dist/chunks/{command-handler-N45GY7AV.ts → command-handler-YZ4DXQ7N.ts} +49 -10
  16. package/dist/chunks/command-handler-YZ4DXQ7N.ts.map +7 -0
  17. package/dist/chunks/{conflict-review-5E4M44BA.ts → conflict-review-J7L7S4AR.ts} +2 -2
  18. package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts → manager-result-dispatcher-XB75YLEG.ts} +4 -4
  19. package/dist/chunks/{manager-ui-EV23DPZQ.ts → manager-ui-RGA26Z6G.ts} +40 -38
  20. package/dist/chunks/manager-ui-RGA26Z6G.ts.map +7 -0
  21. package/dist/chunks/{merge-review-6YSLSMGS.ts → merge-review-AAC674C6.ts} +3 -3
  22. package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts → remote-selection-ui-WVMET5RI.ts} +3 -3
  23. package/dist/chunks/{setup-switch-HY7K3442.ts → setup-switch-644T6KHG.ts} +3 -3
  24. package/dist/chunks/{setup-wizard-LEKDQ3HK.ts → setup-wizard-YP2KF2WQ.ts} +5 -5
  25. package/dist/chunks/{sync-inspection-OS2LVOLV.ts → sync-inspection-NBBTSMKR.ts} +2 -2
  26. package/dist/chunks/{sync-operations-D3MDJUQQ.ts → sync-operations-AIEM2KL2.ts} +2 -2
  27. package/dist/daemon/dist/client.js +125 -287
  28. package/dist/daemon/dist/daemon-recovery.js +85 -2
  29. package/dist/daemon/dist/daemon-startup.js +257 -0
  30. package/dist/daemon/dist/engine/backends/git/git-backend.js +10 -1
  31. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +20 -9
  32. package/dist/daemon/dist/engine/backends/sync-backend.js +16 -0
  33. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +19 -6
  34. package/dist/daemon/dist/engine/sync/directional-action.js +124 -0
  35. package/dist/daemon/dist/engine/sync/remote-snapshot.js +3 -1
  36. package/dist/daemon/dist/engine/sync/sync-errors.js +20 -0
  37. package/dist/daemon/dist/engine/sync/sync-local.js +56 -3
  38. package/dist/daemon/dist/engine/sync/sync-mutations.js +300 -334
  39. package/dist/daemon/dist/engine/sync/sync-queries.js +2 -1
  40. package/dist/daemon/dist/engine/sync/sync-rollback.js +198 -0
  41. package/dist/daemon/dist/engine/sync/transfer-freshness.js +11 -5
  42. package/dist/daemon/dist/engine-service.js +68 -0
  43. package/dist/daemon/dist/foreground-queue-outcome.js +9 -0
  44. package/dist/daemon/dist/monitor.js +1 -0
  45. package/dist/daemon/dist/server.js +76 -11
  46. package/dist/daemon/dist/service-host.js +56 -8
  47. package/dist/daemon/package.json +1 -1
  48. package/dist/index.ts +6 -6
  49. package/docs/daemon-migration.md +3 -6
  50. package/package.json +2 -2
  51. package/src/commands/command-execution.ts +56 -2
  52. package/src/commands/command-handler.ts +2 -0
  53. package/src/commands/command.ts +2 -1
  54. package/src/daemon/directional-recovery.ts +103 -0
  55. package/src/daemon/pi-client.ts +112 -9
  56. package/src/ui/cancellable-operation.ts +5 -2
  57. package/src/ui/manager-state.ts +2 -2
  58. package/src/ui/manager-ui.ts +29 -24
  59. package/src/ui/merge-review.ts +8 -9
  60. package/src/ui/sync-confirmation.ts +7 -7
  61. package/dist/chunks/chunk-CKUGCBHP.ts.map +0 -7
  62. package/dist/chunks/chunk-RW44KNFD.ts.map +0 -7
  63. package/dist/chunks/chunk-YT6PDRMM.ts.map +0 -7
  64. package/dist/chunks/command-handler-N45GY7AV.ts.map +0 -7
  65. package/dist/chunks/manager-ui-EV23DPZQ.ts.map +0 -7
  66. /package/dist/chunks/{chunk-F3VODLVQ.ts.map → chunk-IOM6E5FW.ts.map} +0 -0
  67. /package/dist/chunks/{chunk-NDEZ52SS.ts.map → chunk-OBVJTKVY.ts.map} +0 -0
  68. /package/dist/chunks/{chunk-TJ7YNITN.ts.map → chunk-OWEOZZZE.ts.map} +0 -0
  69. /package/dist/chunks/{chunk-VPSC7BXM.ts.map → chunk-SZJOUVCL.ts.map} +0 -0
  70. /package/dist/chunks/{conflict-review-5E4M44BA.ts.map → conflict-review-J7L7S4AR.ts.map} +0 -0
  71. /package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts.map → manager-result-dispatcher-XB75YLEG.ts.map} +0 -0
  72. /package/dist/chunks/{merge-review-6YSLSMGS.ts.map → merge-review-AAC674C6.ts.map} +0 -0
  73. /package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts.map → remote-selection-ui-WVMET5RI.ts.map} +0 -0
  74. /package/dist/chunks/{setup-switch-HY7K3442.ts.map → setup-switch-644T6KHG.ts.map} +0 -0
  75. /package/dist/chunks/{setup-wizard-LEKDQ3HK.ts.map → setup-wizard-YP2KF2WQ.ts.map} +0 -0
  76. /package/dist/chunks/{sync-inspection-OS2LVOLV.ts.map → sync-inspection-NBBTSMKR.ts.map} +0 -0
  77. /package/dist/chunks/{sync-operations-D3MDJUQQ.ts.map → sync-operations-AIEM2KL2.ts.map} +0 -0
@@ -0,0 +1,257 @@
1
+ import { spawn } from "node:child_process";
2
+ import { setTimeout as delay } from "node:timers/promises";
3
+ import { fileURLToPath } from "node:url";
4
+ import lockfile from "proper-lockfile";
5
+ import { DaemonError, hello, requestDaemon } from "./client-transport.js";
6
+ import { canonicalRootGuard, clearUpgradeOwner, daemonPaths, privateDirectory, processExists, processExited, readIdentity, readProcessBirth, readUpgradeOwner, recordUpgradeOwner, runtimePaths, upgradeRepairStarted, } from "./identity.js";
7
+ import { OWNERSHIP_CLEANUP_REQUIRED, record } from "./protocol.js";
8
+ export async function checkUpgradeConsent(paths, assertRoot, signal) {
9
+ const { readConsent } = await import("./consent.js");
10
+ const { withStateDirectoryGuardForRoot } = await import("./engine/state/state-directory.js");
11
+ signal?.throwIfAborted();
12
+ await withStateDirectoryGuardForRoot(paths.root, () => {
13
+ signal?.throwIfAborted();
14
+ assertRoot();
15
+ const consent = readConsent(paths.root);
16
+ if (consent && Object.values(consent.setups).some((setup) => setup.afterExit))
17
+ throw new Error("Review or revoke unattended Pi Sync permission before stopping or replacing the daemon.");
18
+ });
19
+ signal?.throwIfAborted();
20
+ assertRoot();
21
+ }
22
+ export async function finishUpgrade(paths, owner, assertRoot, signal) {
23
+ await waitForProcessExit(owner, signal);
24
+ const current = await readIdentity(paths);
25
+ if (current?.instance === owner.instance)
26
+ throw new Error("The daemon exited without releasing its identity.");
27
+ if (current && owner.purpose === "cleanup")
28
+ throw new Error("Daemon owner changed during recovery. Review the current owner before retrying.");
29
+ await checkUpgradeConsent(paths, assertRoot, signal);
30
+ await clearUpgradeOwner(paths);
31
+ signal?.throwIfAborted();
32
+ assertRoot();
33
+ }
34
+ async function drainForUpgrade(paths, owner, { recorded, birth }, assertRoot, signal) {
35
+ await checkUpgradeConsent(paths, assertRoot, signal);
36
+ const barrier = recorded ?? { ...owner, birth };
37
+ try {
38
+ if (!recorded)
39
+ await recordUpgradeOwner(paths, barrier);
40
+ assertRoot();
41
+ const reply = await requestDaemon(paths, owner, "stop", {}, signal);
42
+ if (!record(reply) || reply.stopping !== true)
43
+ throw new Error("Daemon did not acknowledge stop.");
44
+ }
45
+ catch (error) {
46
+ signal?.throwIfAborted();
47
+ throw new Error("Pi Sync could not upgrade the older daemon safely. Check `pi-sync-daemon status --root <agent-directory>`. Do not force a second owner or remove recovery files.", { cause: error });
48
+ }
49
+ await finishUpgrade(paths, barrier, assertRoot, signal);
50
+ }
51
+ export async function acquireStartupLock(paths, signal) {
52
+ const deadline = performance.now() + 150_000;
53
+ for (;;) {
54
+ signal?.throwIfAborted();
55
+ try {
56
+ return await lockfile.lock(paths.directory, {
57
+ realpath: false,
58
+ lockfilePath: paths.startup,
59
+ stale: 30_000,
60
+ update: 5_000,
61
+ });
62
+ }
63
+ catch (error) {
64
+ signal?.throwIfAborted();
65
+ if (error.code !== "ELOCKED")
66
+ throw error;
67
+ if (performance.now() >= deadline)
68
+ throw new Error("Timed out waiting to start the Pi Sync daemon.", { cause: error });
69
+ await delay(50, undefined, { signal });
70
+ }
71
+ }
72
+ }
73
+ export async function ensureDaemon(root, signal, options) {
74
+ const paths = await runtimePaths(root);
75
+ const assertRoot = canonicalRootGuard(paths.root);
76
+ signal?.throwIfAborted();
77
+ await privateDirectory(paths.directory);
78
+ signal?.throwIfAborted();
79
+ const release = await acquireStartupLock(paths, signal);
80
+ try {
81
+ signal?.throwIfAborted();
82
+ let waited = false;
83
+ let upgraded = false;
84
+ for (;;) {
85
+ signal?.throwIfAborted();
86
+ const upgrade = await readUpgradeOwner(paths);
87
+ if (upgrade && options?.compatibleOnly)
88
+ throw new Error("A daemon upgrade or recovery is pending; no replacement was attempted.");
89
+ if (upgrade && (await upgradeRepairStarted(paths, upgrade)))
90
+ throw new Error("A daemon upgrade repair is incomplete. Run `pi-sync-daemon repair-upgrade` for this root.");
91
+ const existing = await readIdentity(paths);
92
+ if (upgrade && existing?.instance === upgrade.instance && existing.pid !== upgrade.pid)
93
+ throw new Error("The recorded upgrade owner changed; private state was retained.");
94
+ if (upgrade && (existing?.instance !== upgrade.instance || (await processExited(upgrade)))) {
95
+ await finishUpgrade(paths, upgrade, assertRoot, signal);
96
+ upgraded = true;
97
+ continue;
98
+ }
99
+ if (upgrade?.purpose === "cleanup")
100
+ throw Object.assign(new Error("Daemon recovery is incomplete. Use /sync daemon recover to finish the reviewed stop."), { code: OWNERSHIP_CLEANUP_REQUIRED });
101
+ if (!existing)
102
+ break;
103
+ const beforeHello = upgrade ? undefined : await readProcessBirth(existing.pid);
104
+ let status;
105
+ try {
106
+ status = await hello(paths, existing, signal);
107
+ }
108
+ catch (error) {
109
+ if (signal?.aborted)
110
+ throw signal.reason;
111
+ if (upgrade) {
112
+ await finishUpgrade(paths, upgrade, assertRoot, signal);
113
+ upgraded = true;
114
+ continue;
115
+ }
116
+ if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError" && !waited) {
117
+ waited = true;
118
+ await waitForDaemonExit(existing, signal);
119
+ continue;
120
+ }
121
+ if (processExists(existing.pid))
122
+ throw new Error("A daemon owner is alive but unavailable; use diagnostics instead of starting a second owner.", { cause: error });
123
+ break;
124
+ }
125
+ signal?.throwIfAborted();
126
+ assertRoot();
127
+ if (!status.needsUpgrade) {
128
+ if (upgrade)
129
+ throw new Error("The recorded upgrade owner changed; private state was retained.");
130
+ return { paths: daemonPaths(paths, existing.instance), identity: existing, ...status };
131
+ }
132
+ if (options?.compatibleOnly)
133
+ throw new Error("A compatible daemon could not be attached; an older owner was left unchanged.");
134
+ if (upgraded)
135
+ throw new Error("An older Pi Sync daemon started again. Close or upgrade other Pi sessions, then use /reload.");
136
+ const birth = beforeHello === undefined ? undefined : await readProcessBirth(existing.pid);
137
+ if (birth !== undefined && birth !== beforeHello)
138
+ throw new Error("The daemon process changed during authentication; private state was retained.");
139
+ await drainForUpgrade(paths, existing, { recorded: upgrade, birth }, assertRoot, signal);
140
+ upgraded = true;
141
+ }
142
+ signal?.throwIfAborted();
143
+ assertRoot();
144
+ const executable = process.versions.bun ? "node" : process.execPath;
145
+ const child = spawn(executable, [fileURLToPath(new URL("./cli.js", import.meta.url)), "serve", "--root", paths.root], {
146
+ detached: true,
147
+ stdio: ["ignore", "ignore", "ignore", "ipc"],
148
+ windowsHide: true,
149
+ });
150
+ const ready = await new Promise((resolve, reject) => {
151
+ let timer;
152
+ const abort = () => {
153
+ cleanup();
154
+ reject(signal?.reason);
155
+ };
156
+ const cleanup = () => {
157
+ if (timer)
158
+ clearTimeout(timer);
159
+ signal?.removeEventListener("abort", abort);
160
+ child.off("message", message);
161
+ child.off("error", failed);
162
+ child.off("exit", exited);
163
+ };
164
+ const failed = (error) => {
165
+ cleanup();
166
+ reject(error);
167
+ };
168
+ const exited = (code) => failed(new Error(`Daemon startup exited (${code}); private state was retained.`));
169
+ const message = (value) => {
170
+ if (!record(value))
171
+ return;
172
+ if (value.type === "booting") {
173
+ timer = setTimeout(() => failed(new Error("Daemon readiness timed out.")), 15_000);
174
+ timer.unref?.();
175
+ }
176
+ if (value.type === "error")
177
+ failed(new Error(typeof value.message === "string" ? value.message : "Daemon startup failed."));
178
+ if (value.type === "ready" && record(value.identity)) {
179
+ cleanup();
180
+ resolve(value.identity);
181
+ }
182
+ };
183
+ signal?.addEventListener("abort", abort, { once: true });
184
+ child.on("message", message);
185
+ child.once("error", failed);
186
+ child.once("exit", exited);
187
+ if (signal?.aborted)
188
+ abort();
189
+ }).finally(() => {
190
+ if (child.connected)
191
+ child.disconnect();
192
+ child.unref();
193
+ });
194
+ const status = await hello(paths, ready, signal);
195
+ signal?.throwIfAborted();
196
+ assertRoot();
197
+ if (status.needsUpgrade)
198
+ throw new Error("The daemon installation changed during startup. Use /reload to retry.");
199
+ return { paths: daemonPaths(paths, ready.instance), identity: ready, ...status };
200
+ }
201
+ finally {
202
+ await release();
203
+ }
204
+ }
205
+ export async function waitForDaemonExit({ pid }, signal) {
206
+ await waitForProcessExit({ pid }, signal);
207
+ }
208
+ async function waitForProcessExit(owner, signal) {
209
+ const deadline = Date.now() + 30_000;
210
+ signal?.throwIfAborted();
211
+ while (!(await processExited(owner))) {
212
+ signal?.throwIfAborted();
213
+ if (Date.now() >= deadline)
214
+ throw new Error("Closing daemon is still alive; replacement was not attempted.");
215
+ await delay(25, undefined, { signal });
216
+ }
217
+ signal?.throwIfAborted();
218
+ }
219
+ export async function findDaemon(root) {
220
+ let paths;
221
+ try {
222
+ paths = await runtimePaths(root);
223
+ }
224
+ catch (error) {
225
+ if (error.code === "ENOENT")
226
+ return undefined;
227
+ throw error;
228
+ }
229
+ const identity = await readIdentity(paths);
230
+ if (!identity || !processExists(identity.pid))
231
+ return undefined;
232
+ try {
233
+ const status = await hello(paths, identity);
234
+ return { paths: daemonPaths(paths, identity.instance), identity, ...status };
235
+ }
236
+ catch (error) {
237
+ if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError")
238
+ return undefined;
239
+ throw error;
240
+ }
241
+ }
242
+ export async function stopDaemon(root) {
243
+ const paths = await runtimePaths(root);
244
+ const identity = await readIdentity(paths);
245
+ if (!identity)
246
+ return false;
247
+ await requestDaemon(paths, identity, "stop", {});
248
+ const deadline = Date.now() + 30_000;
249
+ for (;;) {
250
+ const current = await readIdentity(paths);
251
+ if (!current || current.instance !== identity.instance)
252
+ return true;
253
+ if (Date.now() >= deadline)
254
+ throw new Error("Daemon did not drain; no replacement was attempted.");
255
+ await new Promise((resolve) => setTimeout(resolve, 25));
256
+ }
257
+ }
@@ -8,7 +8,7 @@ import { IGNORE_SNAPSHOT_VERSION } from "../../snapshot/snapshot-types.js";
8
8
  import { stateDir } from "../../state/state-directory.js";
9
9
  import { throwIfAborted } from "../../sync/signals.js";
10
10
  import { syncErrorGuidance } from "../../sync/sync-error-guidance.js";
11
- import { SyncBackendConflictError, SyncBackendPublicationOutcomeUnknownError, } from "../sync-backend.js";
11
+ import { SyncBackendConflictError, SyncBackendPublicationOutcomeUnknownError, verifyPreviousHeadInHistory, } from "../sync-backend.js";
12
12
  import { normalizeGitBranch, normalizeGitDirectory, normalizeGitRemote, normalizeGitRemoteIdentity, validateGitNamespace, } from "./git-config.js";
13
13
  import { GitCommandError, parseGitBlobBatch, readGitBlobs, runGit } from "./git-runner.js";
14
14
  import { GIT_MANIFEST_VERSION, MAX_GIT_MANIFEST_BYTES, MAX_GIT_TREE_OUTPUT_BYTES, parseGitTree, prepareGitSnapshot, requireGitManifest, validateGitPublicationTree, validateGitSnapshot, } from "./git-storage.js";
@@ -158,6 +158,15 @@ export class GitSyncBackend {
158
158
  throw this.redactedError(error);
159
159
  }
160
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
+ }
161
170
  if (options.validateIgnorePolicy) {
162
171
  await options.validateIgnorePolicy();
163
172
  throwIfAborted(options.signal);
@@ -9,7 +9,7 @@ import { syncErrorGuidance } from "../../sync/sync-error-guidance.js";
9
9
  import { portableSnapshotSelection } from "../../sync/sync-policy.js";
10
10
  import { capturePublicationImage, encodeForPublication } from "../publication-encoding.js";
11
11
  import { createLatestPointer, remoteHistoryEntry } from "../snapshot-pointer.js";
12
- import { SyncBackendConflictError, SyncBackendPublicationOutcomeUnknownError, } from "../sync-backend.js";
12
+ import { SyncBackendConflictError, SyncBackendPublicationOutcomeUnknownError, verifyPreviousHeadInHistory, } from "../sync-backend.js";
13
13
  import { S3Client, S3HttpError, S3ObjectAlreadyExistsError } from "./s3-client.js";
14
14
  import { requireS3Etag, verifyS3Conditions } from "./s3-conditions.js";
15
15
  const VERSION = 1;
@@ -104,18 +104,28 @@ export class S3SyncBackend {
104
104
  }
105
105
  const currentObject = await cancellableClient.getJson(latestKey(this.config));
106
106
  throwIfAborted(options.signal);
107
- let current;
108
- if (!currentObject.missing) {
109
- 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)
110
111
  this.registerChecksum(currentPointer.snapshot, currentPointer.sha256);
111
- current = remoteHead(currentPointer, this.identity, currentObject.etag);
112
- }
112
+ const current = currentPointer && remoteHead(currentPointer, this.identity, currentObject.etag);
113
113
  if (!matchesExpected(current, expected)) {
114
114
  throw new SyncBackendConflictError("Remote changed while pushing. Run /sync pull first, then retry.", {
115
115
  currentHead: current,
116
116
  });
117
117
  }
118
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
+ }
119
129
  if (options.validateIgnorePolicy)
120
130
  await options.validateIgnorePolicy();
121
131
  throwIfAborted(options.signal);
@@ -242,16 +252,17 @@ export class S3SyncBackend {
242
252
  return `Remote snapshot is active, but history could not be updated: ${errorMessage(error)}. Run /sync doctor before relying on history.`;
243
253
  }
244
254
  }
245
- async updateHistory(client, pointer) {
255
+ async updateHistory(client, pointer, keepRecent = false) {
246
256
  const object = await client.getJson(historyKey(this.config));
247
257
  const snapshots = object.missing ? [] : requireHistory(object.value, this.config.destination.namespace);
248
258
  const existing = snapshots.find((snapshot) => snapshot.snapshot === pointer.snapshot);
249
259
  if (existing) {
250
260
  if (!samePointer(existing, pointer))
251
261
  throw new Error("Remote history rebound an immutable snapshot reference.");
252
- return;
262
+ if (!keepRecent || snapshots.at(-1) === existing)
263
+ return;
253
264
  }
254
- const next = [...snapshots, pointer].slice(-100);
265
+ const next = [...snapshots.filter((snapshot) => snapshot !== existing), pointer].slice(-100);
255
266
  const condition = object.missing ? { ifAbsent: true } : { ifMatch: requireS3Etag(object.etag) };
256
267
  await client.putJson(historyKey(this.config), { version: VERSION, snapshots: next }, condition);
257
268
  }
@@ -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
  }
@@ -7,7 +7,7 @@ import { syncErrorGuidance } from "../../sync/sync-error-guidance.js";
7
7
  import { portableSnapshotSelection } from "../../sync/sync-policy.js";
8
8
  import { capturePublicationImage, encodeForPublication } from "../publication-encoding.js";
9
9
  import { createLatestPointer, remoteHistoryEntry } from "../snapshot-pointer.js";
10
- import { SyncBackendConflictError, SyncBackendPublicationOutcomeUnknownError, } from "../sync-backend.js";
10
+ import { SyncBackendConflictError, SyncBackendPublicationOutcomeUnknownError, verifyPreviousHeadInHistory, } from "../sync-backend.js";
11
11
  import { WebDavClient, WebDavHttpError, WebDavPreconditionError } from "./webdav-client.js";
12
12
  const VERSION = 1;
13
13
  const POST_COMMIT_TIMEOUT_MS = 30_000;
@@ -88,15 +88,27 @@ export class WebDavSyncBackend {
88
88
  }
89
89
  const currentObject = await client.getJson(latestPath(this.config));
90
90
  throwIfAborted(options.signal);
91
- const current = currentObject.missing
91
+ const currentPointer = currentObject.missing
92
92
  ? undefined
93
- : 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);
94
95
  if (!matchesExpected(current, expected)) {
95
96
  throw new SyncBackendConflictError("Remote changed while pushing. Run /sync pull first, then retry.", {
96
97
  currentHead: current,
97
98
  });
98
99
  }
99
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
+ }
100
112
  if (options.validateIgnorePolicy)
101
113
  await options.validateIgnorePolicy();
102
114
  throwIfAborted(options.signal);
@@ -286,7 +298,7 @@ export class WebDavSyncBackend {
286
298
  ? "webdav history: repaired active snapshot entry"
287
299
  : "webdav history: active snapshot entry present";
288
300
  }
289
- async ensureHistoryPointer(client, pointer) {
301
+ async ensureHistoryPointer(client, pointer, keepRecent = false) {
290
302
  const object = await client.getJson(historyPath(this.config));
291
303
  const snapshots = object.missing ? [] : requireHistory(object.value, this.config.destination.namespace);
292
304
  const existing = snapshots.find((entry) => entry.snapshot === pointer.snapshot);
@@ -294,9 +306,10 @@ export class WebDavSyncBackend {
294
306
  if (!samePointer(existing, pointer)) {
295
307
  throw new Error("Remote history rebound an immutable snapshot reference.");
296
308
  }
297
- return false;
309
+ if (!keepRecent || snapshots.at(-1) === existing)
310
+ return false;
298
311
  }
299
- const next = [...snapshots, pointer].slice(-100);
312
+ const next = [...snapshots.filter((entry) => entry !== existing), pointer].slice(-100);
300
313
  const condition = object.missing ? { ifAbsent: true } : { ifMatch: requireStrongEtag(object.etag, "history") };
301
314
  await client.putJson(historyPath(this.config), { version: VERSION, snapshots: next }, condition);
302
315
  return true;
@@ -0,0 +1,124 @@
1
+ import { createHash } from "node:crypto";
2
+ import { loadConfigForCheck, syncCheckConfigFingerprint } from "../settings/config.js";
3
+ import { effectiveSessionRoot } from "../snapshot/session-paths.js";
4
+ import { agentDirectoryInventory, filterSnapshotForConfigPolicy, snapshotWithoutSessions, } from "../snapshot/snapshot.js";
5
+ import { syncStateFingerprint } from "../state/sync-state-store.js";
6
+ import { safeTerminalText } from "../ui/terminal-text.js";
7
+ import { inspectCaseCleanup } from "./apply-review.js";
8
+ import { requireCompatibleRemoteSelection } from "./remote-snapshot.js";
9
+ import { inspectRemoteSelection, syncSelectionHasContent, syncSessionsSelected } from "./sync-policy.js";
10
+ import { fileHashMap, syncPolicyChanged } from "./sync-state.js";
11
+ import { checkLiveProtection } from "./transfer-freshness.js";
12
+ export function foregroundDirectionalAction(ctx, options) {
13
+ const action = options.directionalAction;
14
+ if (action &&
15
+ (options.auto ||
16
+ options.background ||
17
+ options.force ||
18
+ options.yes ||
19
+ options.reload ||
20
+ options.stale ||
21
+ options.args.length > 0 ||
22
+ options.agentRetryRefusal ||
23
+ !ctx.hasUI ||
24
+ (ctx.mode !== "tui" && ctx.mode !== "rpc")))
25
+ throw new Error("Single-action transfer requires a bound foreground Push or Pull.");
26
+ return action;
27
+ }
28
+ export async function validateDirectionalSettings(options, config, validateMutation) {
29
+ const current = await loadConfigForCheck(undefined, options.signal);
30
+ validateMutation();
31
+ options.directionalAction?.validate(current);
32
+ if (syncCheckConfigFingerprint(current) !== syncCheckConfigFingerprint(config))
33
+ throw new Error("Settings changed before the directional transfer could write.");
34
+ }
35
+ export async function checkpointDirectionalAction(options, evidence) {
36
+ const { direction, config, state, head, local, remote, sessionDir, protectedPaths } = evidence;
37
+ const hash = createHash("sha256")
38
+ .update(JSON.stringify([
39
+ direction,
40
+ syncCheckConfigFingerprint(config),
41
+ syncStateFingerprint(state),
42
+ head,
43
+ Object.entries(fileHashMap(local)).sort(),
44
+ [...(agentDirectoryInventory(local)?.entries ?? [])].filter(([, kind]) => kind === "directory").sort(),
45
+ remote && Object.entries(fileHashMap(remote)).sort(),
46
+ sessionDir,
47
+ [...protectedPaths].sort(),
48
+ ]))
49
+ .digest("hex");
50
+ await options.directionalAction?.checkpoint?.(hash);
51
+ }
52
+ export function requireDirectionalSelection(config, state, local, remote, sessionDir) {
53
+ if (!syncSelectionHasContent(config))
54
+ throw new Error("This setup has no managed content for the transfer.");
55
+ const current = config.ignorePolicy;
56
+ const remoteProjected = current && remote && filterSnapshotForConfigPolicy(remote, config, { sessionDir });
57
+ const managed = new Set([...local.files, ...(remoteProjected?.files ?? [])].map((file) => file.path));
58
+ const provesNarrowing = (priorPaths, priorSessions) => {
59
+ if (!current || (!priorSessions && current.sessions))
60
+ return false;
61
+ const prior = new Set(priorPaths);
62
+ return ([...managed].every((item) => prior.has(item)) &&
63
+ ((priorSessions && !current.sessions) ||
64
+ priorPaths.some((item) => !managed.has(item) && current.matches(item, false))));
65
+ };
66
+ if (remote) {
67
+ const selection = inspectRemoteSelection(config.include, remote, config.exclude, config);
68
+ if (!(selection.ignorePolicyComparison === "mismatch" &&
69
+ remote.selection?.version === 4 &&
70
+ provesNarrowing(remote.files.map((file) => file.path), remote.selection.sessions)))
71
+ requireCompatibleRemoteSelection(config, remote);
72
+ }
73
+ if (state.lastAppliedSnapshot &&
74
+ syncPolicyChanged(state, config) &&
75
+ !(state.scope === config.scope &&
76
+ state.ignorePolicyKey &&
77
+ provesNarrowing(Object.keys(state.lastFileHashes), state.include?.includes("sessions") === true)))
78
+ throw new Error("Managed content policy changed and this transfer cannot prove that it only narrows the accepted selection. Review the new policy before transferring.");
79
+ }
80
+ export function keepProtectedRemoteSessions(config, upload, remote, sessionDir, protectedPaths) {
81
+ if (!protectedPaths.size)
82
+ return upload;
83
+ const retained = (remote?.files ?? []).filter((file) => protectedPaths.has(file.path));
84
+ const selectedRemote = remote && filterSnapshotForConfigPolicy(remote, config, { sessionDir });
85
+ const uploaded = new Set(upload.files.map((file) => file.path));
86
+ const selected = new Set(selectedRemote?.files.map((file) => file.path));
87
+ if (retained.some((file) => !selected.has(file.path) && !uploaded.has(file.path)))
88
+ throw new Error("Push would remove a protected live session from remote storage.");
89
+ const files = [...upload.files.filter((file) => !protectedPaths.has(file.path)), ...retained];
90
+ return {
91
+ ...upload,
92
+ ...(upload.selection?.version === 4
93
+ ? { syncSessions: files.some((file) => file.path.startsWith("sessions/")) }
94
+ : {}),
95
+ files: files.sort((a, b) => a.path.localeCompare(b.path)),
96
+ };
97
+ }
98
+ export async function requireDirectionalPullBoundary(ctx, options, config, physical, snapshotOptions, protectedPaths, validateMutation) {
99
+ await validateDirectionalSettings(options, config, validateMutation);
100
+ if ((await effectiveSessionRoot(ctx, config, options.signal)) !== snapshotOptions.sessionDir)
101
+ throw new Error("Pi session storage changed before Pull could write.");
102
+ if ((await inspectCaseCleanup(physical, snapshotOptions)).length)
103
+ throw new Error("Pull would remove case-variant paths not represented in its local backup. Review a separate Pull instead.");
104
+ validateMutation();
105
+ checkLiveProtection(ctx, snapshotOptions.sessionDir, protectedPaths);
106
+ }
107
+ export function notifyDirectionalSuccess(ctx, options, message, warning = false) {
108
+ if (options.directionalAction?.notifySuccess)
109
+ options.directionalAction.notifySuccess(message);
110
+ else if (!options.silent)
111
+ ctx.ui.notify(message, warning ? "warning" : "info");
112
+ }
113
+ export function remoteRestoreGuidance(head, previous, config, sessionDir) {
114
+ const ref = head.snapshotRef === head.snapshotId ? "" : ` (reference ${safeTerminalText(head.snapshotRef)})`;
115
+ const version = `${safeTerminalText(head.snapshotId)}${ref}`;
116
+ const eligible = config.ignorePolicy || syncSessionsSelected(config) ? previous : snapshotWithoutSessions(previous);
117
+ const selected = filterSnapshotForConfigPolicy(eligible, config, { sessionDir });
118
+ return selected.files.length === previous.files.length
119
+ ? `Restore the previous remote version ${version} from /sync → History.`
120
+ : `History retains remote version ${version}. Rollback uses the current rules and does not restore excluded files. See “Recover excluded files from History” in the Pi Sync README.`;
121
+ }
122
+ export function localRestoreGuidance(backup) {
123
+ return `Local backup: ${safeTerminalText(backup)}. To restore locally, close Pi and follow the local backup restore steps in the Pi Sync README.`;
124
+ }
@@ -113,7 +113,9 @@ export async function readRemoteSnapshot(backend, config, signal, options = {})
113
113
  return { head: undefined, snapshot: undefined, selectionState: undefined };
114
114
  const { head, snapshot: rawSnapshot } = observed;
115
115
  const selectionState = inspectRemoteSelection(config.include, rawSnapshot, config.exclude, config);
116
- if (!options.allowSelectionDifference && selectionState.kind === "different")
116
+ if (options.validateSelection)
117
+ options.validateSelection(rawSnapshot);
118
+ else if (!options.allowSelectionDifference && selectionState.kind === "different")
117
119
  throw selectionMismatch(config, selectionState);
118
120
  const snapshot = selectionState.ignorePolicyComparison === "local-legacy-remote-ignore"
119
121
  ? undefined
@@ -1,3 +1,23 @@
1
+ export class PublicationStatePersistenceError extends Error {
2
+ head;
3
+ backupPath;
4
+ constructor(head, cause, backupPath) {
5
+ super(`Remote publication ${head.snapshotId} is active, but local sync state could not be saved${backupPath ? `; local backup: ${backupPath}` : ""}: ${errorMessage(cause)}`, { cause });
6
+ this.name = "PublicationStatePersistenceError";
7
+ this.head = head;
8
+ this.backupPath = backupPath;
9
+ }
10
+ }
11
+ export class RollbackPublicationError extends Error {
12
+ backupPath;
13
+ constructor(backupPath, cause) {
14
+ super(`Rollback applied locally with backup ${backupPath}, but remote publication failed: ${errorMessage(cause)}`, {
15
+ cause,
16
+ });
17
+ this.name = "RollbackPublicationError";
18
+ this.backupPath = backupPath;
19
+ }
20
+ }
1
21
  export class SetupPullRequiresUiError extends Error {
2
22
  }
3
23
  export class SyncDecisionRequiredError extends Error {