@narumitw/pi-sync 0.64.0 → 0.66.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 (116) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +80 -11
  3. package/dist/chunks/{chunk-TJ7YNITN.ts → chunk-5YOLQKNZ.ts} +39 -3
  4. package/dist/chunks/chunk-5YOLQKNZ.ts.map +7 -0
  5. package/dist/chunks/{chunk-NDEZ52SS.ts → chunk-ASU3GZPW.ts} +11 -93
  6. package/dist/chunks/chunk-ASU3GZPW.ts.map +7 -0
  7. package/dist/chunks/{chunk-CKUGCBHP.ts → chunk-AYGMIMCV.ts} +2 -2
  8. package/dist/chunks/chunk-AYGMIMCV.ts.map +7 -0
  9. package/dist/chunks/{chunk-F3VODLVQ.ts → chunk-BESRBKVO.ts} +3 -3
  10. package/dist/chunks/{chunk-TZMVSTAM.ts → chunk-BYVHABNR.ts} +4 -4
  11. package/dist/chunks/chunk-ECYCNZOE.ts +12 -0
  12. package/dist/chunks/chunk-ECYCNZOE.ts.map +7 -0
  13. package/dist/chunks/{chunk-RW44KNFD.ts → chunk-JQ5BAWW2.ts} +182 -12
  14. package/dist/chunks/chunk-JQ5BAWW2.ts.map +7 -0
  15. package/dist/chunks/{chunk-MANNB4WZ.ts → chunk-KNEUL4XN.ts} +1 -7
  16. package/dist/chunks/chunk-KNEUL4XN.ts.map +7 -0
  17. package/dist/chunks/{chunk-VPSC7BXM.ts → chunk-SZJOUVCL.ts} +2 -2
  18. package/dist/chunks/{chunk-YT6PDRMM.ts → chunk-WJQ4TGN5.ts} +17 -17
  19. package/dist/chunks/chunk-WJQ4TGN5.ts.map +7 -0
  20. package/dist/chunks/{chunk-4VKWHVUO.ts → chunk-XUZV4OGI.ts} +3 -2
  21. package/dist/chunks/{chunk-4VKWHVUO.ts.map → chunk-XUZV4OGI.ts.map} +2 -2
  22. package/dist/chunks/chunk-Z5JMOXJM.ts +106 -0
  23. package/dist/chunks/chunk-Z5JMOXJM.ts.map +7 -0
  24. package/dist/chunks/{command-handler-N45GY7AV.ts → command-handler-44EFGPWH.ts} +54 -13
  25. package/dist/chunks/command-handler-44EFGPWH.ts.map +7 -0
  26. package/dist/chunks/{conflict-review-5E4M44BA.ts → conflict-review-J7L7S4AR.ts} +2 -2
  27. package/dist/chunks/{file-selection-DDQN4LVD.ts → file-selection-XWACUTAH.ts} +8 -8
  28. package/dist/chunks/ignore-file-ui-OHFISFVC.ts +21 -0
  29. package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts → manager-result-dispatcher-WXE2BAQO.ts} +4 -4
  30. package/dist/chunks/{manager-ui-EV23DPZQ.ts → manager-ui-CVZLMXJ5.ts} +90 -76
  31. package/dist/chunks/manager-ui-CVZLMXJ5.ts.map +7 -0
  32. package/dist/chunks/{merge-review-6YSLSMGS.ts → merge-review-AAC674C6.ts} +3 -3
  33. package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts → remote-selection-ui-E4XZCQ7A.ts} +3 -3
  34. package/dist/chunks/{setup-switch-HY7K3442.ts → setup-switch-644T6KHG.ts} +3 -3
  35. package/dist/chunks/setup-switch-644T6KHG.ts.map +7 -0
  36. package/dist/chunks/{setup-wizard-LEKDQ3HK.ts → setup-wizard-IEW56AZE.ts} +10 -8
  37. package/dist/chunks/{setup-wizard-LEKDQ3HK.ts.map → setup-wizard-IEW56AZE.ts.map} +1 -1
  38. package/dist/chunks/{sync-inspection-OS2LVOLV.ts → sync-inspection-NBBTSMKR.ts} +2 -2
  39. package/dist/chunks/{sync-operations-D3MDJUQQ.ts → sync-operations-AIEM2KL2.ts} +2 -2
  40. package/dist/daemon/dist/client.js +125 -287
  41. package/dist/daemon/dist/consent.js +14 -2
  42. package/dist/daemon/dist/daemon-recovery.js +85 -2
  43. package/dist/daemon/dist/daemon-startup.js +257 -0
  44. package/dist/daemon/dist/engine/backends/git/git-backend.js +15 -4
  45. package/dist/daemon/dist/engine/backends/git/git-storage.js +15 -3
  46. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +20 -9
  47. package/dist/daemon/dist/engine/backends/sync-backend.js +16 -0
  48. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +19 -6
  49. package/dist/daemon/dist/engine/ignore/adoption-journal.js +143 -0
  50. package/dist/daemon/dist/engine/ignore/snapshot-ignore-rules.js +39 -0
  51. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +2 -2
  52. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +6 -6
  53. package/dist/daemon/dist/engine/snapshot/snapshot-types.js +5 -1
  54. package/dist/daemon/dist/engine/snapshot/snapshot.js +5 -2
  55. package/dist/daemon/dist/engine/sync/conflict-review.js +2 -0
  56. package/dist/daemon/dist/engine/sync/continuous-watch.js +3 -2
  57. package/dist/daemon/dist/engine/sync/directional-action.js +119 -0
  58. package/dist/daemon/dist/engine/sync/ignore-adoption-recovery.js +50 -0
  59. package/dist/daemon/dist/engine/sync/ignore-adoption.js +401 -0
  60. package/dist/daemon/dist/engine/sync/ignore-publication.js +23 -0
  61. package/dist/daemon/dist/engine/sync/initialization.js +12 -0
  62. package/dist/daemon/dist/engine/sync/local-fields.js +6 -3
  63. package/dist/daemon/dist/engine/sync/merge-journal.js +2 -2
  64. package/dist/daemon/dist/engine/sync/merged-sync.js +14 -3
  65. package/dist/daemon/dist/engine/sync/remote-snapshot.js +3 -1
  66. package/dist/daemon/dist/engine/sync/sync-errors.js +20 -0
  67. package/dist/daemon/dist/engine/sync/sync-local.js +57 -3
  68. package/dist/daemon/dist/engine/sync/sync-mutations.js +375 -346
  69. package/dist/daemon/dist/engine/sync/sync-policy.js +5 -5
  70. package/dist/daemon/dist/engine/sync/sync-queries.js +3 -2
  71. package/dist/daemon/dist/engine/sync/sync-rollback.js +204 -0
  72. package/dist/daemon/dist/engine/sync/transfer-freshness.js +11 -5
  73. package/dist/daemon/dist/engine/ui/ignore-rule-preview.js +18 -0
  74. package/dist/daemon/dist/engine-service.js +69 -1
  75. package/dist/daemon/dist/foreground-queue-outcome.js +9 -0
  76. package/dist/daemon/dist/monitor.js +1 -0
  77. package/dist/daemon/dist/server.js +76 -11
  78. package/dist/daemon/dist/service-host.js +56 -8
  79. package/dist/daemon/package.json +1 -1
  80. package/dist/index.ts +6 -6
  81. package/docs/daemon-migration.md +3 -6
  82. package/docs/tui-contract.md +3 -3
  83. package/package.json +2 -2
  84. package/skills/configure-pi-sync/references/configuration.md +10 -8
  85. package/src/commands/command-execution.ts +56 -2
  86. package/src/commands/command-handler.ts +2 -0
  87. package/src/commands/command.ts +2 -1
  88. package/src/daemon/directional-recovery.ts +103 -0
  89. package/src/daemon/pi-client.ts +112 -9
  90. package/src/ui/cancellable-operation.ts +5 -2
  91. package/src/ui/ignore-file-ui.ts +13 -5
  92. package/src/ui/manager-state.ts +17 -10
  93. package/src/ui/manager-ui.ts +30 -25
  94. package/src/ui/merge-review.ts +8 -9
  95. package/src/ui/remote-selection-ui.ts +43 -2
  96. package/src/ui/settings-ui.ts +30 -30
  97. package/src/ui/sync-confirmation.ts +7 -7
  98. package/dist/chunks/chunk-CKUGCBHP.ts.map +0 -7
  99. package/dist/chunks/chunk-MANNB4WZ.ts.map +0 -7
  100. package/dist/chunks/chunk-NDEZ52SS.ts.map +0 -7
  101. package/dist/chunks/chunk-RW44KNFD.ts.map +0 -7
  102. package/dist/chunks/chunk-TJ7YNITN.ts.map +0 -7
  103. package/dist/chunks/chunk-YT6PDRMM.ts.map +0 -7
  104. package/dist/chunks/command-handler-N45GY7AV.ts.map +0 -7
  105. package/dist/chunks/manager-ui-EV23DPZQ.ts.map +0 -7
  106. /package/dist/chunks/{chunk-F3VODLVQ.ts.map → chunk-BESRBKVO.ts.map} +0 -0
  107. /package/dist/chunks/{chunk-TZMVSTAM.ts.map → chunk-BYVHABNR.ts.map} +0 -0
  108. /package/dist/chunks/{chunk-VPSC7BXM.ts.map → chunk-SZJOUVCL.ts.map} +0 -0
  109. /package/dist/chunks/{conflict-review-5E4M44BA.ts.map → conflict-review-J7L7S4AR.ts.map} +0 -0
  110. /package/dist/chunks/{file-selection-DDQN4LVD.ts.map → file-selection-XWACUTAH.ts.map} +0 -0
  111. /package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts.map → ignore-file-ui-OHFISFVC.ts.map} +0 -0
  112. /package/dist/chunks/{merge-review-6YSLSMGS.ts.map → manager-result-dispatcher-WXE2BAQO.ts.map} +0 -0
  113. /package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts.map → merge-review-AAC674C6.ts.map} +0 -0
  114. /package/dist/chunks/{setup-switch-HY7K3442.ts.map → remote-selection-ui-E4XZCQ7A.ts.map} +0 -0
  115. /package/dist/chunks/{sync-inspection-OS2LVOLV.ts.map → sync-inspection-NBBTSMKR.ts.map} +0 -0
  116. /package/dist/chunks/{sync-operations-D3MDJUQQ.ts.map → sync-operations-AIEM2KL2.ts.map} +0 -0
@@ -1,7 +1,90 @@
1
- import { acquireStartupLock, checkUpgradeConsent, finishUpgrade, hello, requestDaemon } from "./client.js";
2
- import { canonicalRootGuard, processExists, processExited, readIdentity, readProcessBirth, readUpgradeOwner, recordUpgradeOwner, runtimePaths, upgradeRepairStarted, } from "./identity.js";
1
+ import { DaemonError, hello, requestDaemon } from "./client-transport.js";
2
+ import { acquireStartupLock, checkUpgradeConsent, finishUpgrade } from "./daemon-startup.js";
3
+ import { canonicalRootGuard, clearUpgradeOwner, processExists, processExited, readIdentity, readProcessBirth, readUpgradeOwner, recordUpgradeOwner, runtimePaths, upgradeRepairStarted, } from "./identity.js";
3
4
  import { withCleanup } from "./lifecycle.js";
4
5
  import { record } from "./protocol.js";
6
+ export async function stopDaemonAfterForegroundQueueFailure(paths, identity, { job, client, generation, birth }, signal) {
7
+ const assertRoot = canonicalRootGuard(paths.root);
8
+ if (process.platform === "linux" && birth === undefined)
9
+ throw new Error("Daemon process identity could not be verified during queue cleanup.");
10
+ const barrier = { ...identity, birth, purpose: "cleanup" };
11
+ const samePublished = (current) => current !== undefined && sameOwner(current, identity) && current.token === identity.token;
12
+ const release = await acquireStartupLock(paths, signal);
13
+ await withCleanup(async () => {
14
+ signal.throwIfAborted();
15
+ assertRoot();
16
+ if (await readUpgradeOwner(paths))
17
+ throw new Error("A daemon upgrade or recovery is already pending.");
18
+ await checkUpgradeConsent(paths, assertRoot, signal);
19
+ const requireCurrent = async () => {
20
+ const sampled = birth === undefined ? undefined : await readProcessBirth(identity.pid);
21
+ const current = await readIdentity(paths);
22
+ signal.throwIfAborted();
23
+ assertRoot();
24
+ if (!current && (await processExited(barrier))) {
25
+ if (await readIdentity(paths))
26
+ throw new Error("Daemon owner changed during queue cleanup.");
27
+ signal.throwIfAborted();
28
+ assertRoot();
29
+ return false;
30
+ }
31
+ if (!samePublished(current) || !processExists(identity.pid) || birth !== sampled)
32
+ throw new Error("Daemon owner changed or could not be verified during queue cleanup.");
33
+ return true;
34
+ };
35
+ if (!(await requireCurrent()))
36
+ return;
37
+ const params = { job, client, generation };
38
+ let checked;
39
+ try {
40
+ checked = await requestDaemon(paths, identity, "foreground-stop", { ...params, check: true }, signal);
41
+ }
42
+ catch (error) {
43
+ if (!(await requireCurrent()))
44
+ return;
45
+ throw error;
46
+ }
47
+ if (!record(checked) || checked.eligible !== true)
48
+ throw new Error(record(checked) && typeof checked.blocked === "string"
49
+ ? checked.blocked
50
+ : "Daemon queue cleanup could not be verified.");
51
+ if (!(await requireCurrent()))
52
+ return;
53
+ signal.throwIfAborted();
54
+ await recordUpgradeOwner(paths, barrier);
55
+ if (!(await requireCurrent()))
56
+ return finishUpgrade(paths, barrier, assertRoot, signal);
57
+ let reply;
58
+ try {
59
+ assertRoot();
60
+ reply = await requestDaemon(paths, identity, "foreground-stop", params, signal);
61
+ }
62
+ catch (error) {
63
+ signal.throwIfAborted();
64
+ const current = await readIdentity(paths);
65
+ signal.throwIfAborted();
66
+ assertRoot();
67
+ if (current && !samePublished(current))
68
+ throw new Error("Daemon owner changed during recovery. Keep the recorded evidence.", { cause: error });
69
+ if (current && error instanceof DaemonError)
70
+ throw new Error("Daemon stop could not be confirmed. Queue grants and recovery evidence were retained.", {
71
+ cause: error,
72
+ });
73
+ return finishUpgrade(paths, barrier, assertRoot, signal);
74
+ }
75
+ if (record(reply) && typeof reply.blocked === "string") {
76
+ const current = await readIdentity(paths);
77
+ signal.throwIfAborted();
78
+ assertRoot();
79
+ if (samePublished(current))
80
+ await clearUpgradeOwner(paths);
81
+ throw new Error(reply.blocked);
82
+ }
83
+ if (!record(reply) || reply.stopping !== true)
84
+ throw new Error("Daemon stop could not be confirmed. Queue grants and recovery evidence were retained.");
85
+ await finishUpgrade(paths, barrier, assertRoot, signal);
86
+ }, release);
87
+ }
5
88
  async function recoveryOwner(paths) {
6
89
  const pending = await readUpgradeOwner(paths);
7
90
  if (pending && (pending.purpose !== "cleanup" || (await upgradeRepairStarted(paths, pending))))
@@ -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
+ }
@@ -4,11 +4,11 @@ import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { posixJoin } from "../../paths.js";
6
6
  import { snapshotFileFromBlob } from "../../snapshot/snapshot-payload.js";
7
- import { IGNORE_SNAPSHOT_VERSION } from "../../snapshot/snapshot-types.js";
7
+ import { isIgnoreSnapshotVersion } 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";
@@ -119,6 +119,7 @@ export class GitSyncBackend {
119
119
  profile: manifest.profile,
120
120
  ...(manifest.snapshotSyncSessions === undefined ? {} : { syncSessions: manifest.snapshotSyncSessions }),
121
121
  ...(manifest.selection === undefined ? {} : { selection: structuredClone(manifest.selection) }),
122
+ ...(manifest.ignoreRules === undefined ? {} : { ignoreRules: structuredClone(manifest.ignoreRules) }),
122
123
  ...(manifest.localFields === undefined ? {} : { localFields: [...manifest.localFields] }),
123
124
  files,
124
125
  };
@@ -143,6 +144,7 @@ export class GitSyncBackend {
143
144
  syncSessions: snapshot.syncSessions === true || snapshot.files.some((file) => file.path.startsWith("sessions/")),
144
145
  ...(snapshot.syncSessions === undefined ? {} : { snapshotSyncSessions: snapshot.syncSessions }),
145
146
  ...(snapshot.selection === undefined ? {} : { selection: snapshot.selection }),
147
+ ...(snapshot.ignoreRules === undefined ? {} : { ignoreRules: snapshot.ignoreRules }),
146
148
  ...(snapshot.localFields === undefined ? {} : { localFields: snapshot.localFields }),
147
149
  files: files.map(({ path: filePath, sha256: fileSha, size }) => ({
148
150
  path: filePath,
@@ -158,6 +160,15 @@ export class GitSyncBackend {
158
160
  throw this.redactedError(error);
159
161
  }
160
162
  throwIfAborted(options.signal);
163
+ if (options.preservePreviousHead && observed) {
164
+ try {
165
+ await verifyPreviousHeadInHistory(this, await this.headForSha(observed, options.signal), options.signal);
166
+ }
167
+ catch (error) {
168
+ throwIfAborted(options.signal);
169
+ throw new Error(`Cannot verify the previous Git publication ${observed} in History; remote head was not updated.`, { cause: error });
170
+ }
171
+ }
161
172
  if (options.validateIgnorePolicy) {
162
173
  await options.validateIgnorePolicy();
163
174
  throwIfAborted(options.signal);
@@ -557,7 +568,7 @@ export class GitSyncBackend {
557
568
  (await this.git(["show", `${commit}:${this.manifestPath()}`], { signal, maxOutputBytes: MAX_GIT_MANIFEST_BYTES }))
558
569
  .stdout;
559
570
  const manifest = parseGitManifest(bytes);
560
- const entries = await this.readPublicationTree(commit, signal, manifest.snapshotVersion === IGNORE_SNAPSHOT_VERSION);
571
+ const entries = await this.readPublicationTree(commit, signal, isIgnoreSnapshotVersion(manifest.snapshotVersion));
561
572
  const payloadEntries = validateGitPublicationTree(entries, manifest, this.manifestPath(), (filePath) => this.filePath(filePath));
562
573
  return { manifest, payloadEntries };
563
574
  }
@@ -624,7 +635,7 @@ function parseGitManifest(bytes) {
624
635
  if (parsed &&
625
636
  typeof parsed === "object" &&
626
637
  "snapshotVersion" in parsed &&
627
- parsed.snapshotVersion === IGNORE_SNAPSHOT_VERSION &&
638
+ isIgnoreSnapshotVersion(parsed.snapshotVersion) &&
628
639
  !isUtf8(bytes)) {
629
640
  throw new Error("Git publication manifest is not valid UTF-8.");
630
641
  }
@@ -1,6 +1,7 @@
1
+ import { validateSnapshotIgnoreRules } from "../../ignore/snapshot-ignore-rules.js";
1
2
  import { assertAgentDirectorySettingsSize, MAX_AGENT_DIRECTORY_BYTES } from "../../snapshot/snapshot-bounds.js";
2
3
  import { materializeSnapshotFilePayload } from "../../snapshot/snapshot-payload.js";
3
- import { IGNORE_SNAPSHOT_VERSION, isSupportedSnapshotVersion, } from "../../snapshot/snapshot-types.js";
4
+ import { isIgnoreSnapshotVersion, isSupportedSnapshotVersion, } from "../../snapshot/snapshot-types.js";
4
5
  import { sameLocalFields, validateIgnoreSnapshotIdentity, validateIgnoreSnapshotSessionFlag, validatePortableSnapshot, validateSnapshotFieldPolicy, } from "../../sync/local-fields.js";
5
6
  import { assertAgentDirectoryPathLayout, assertSnapshotExcludesDebugLog, assertSnapshotPathExcludesDebugLog, configuredSnapshotPathMatcher, portableSnapshotSelection, sameSnapshotSelection, snapshotSelectionInclude, validateSnapshotSelection, } from "../../sync/sync-policy.js";
6
7
  export const GIT_MANIFEST_VERSION = 2;
@@ -48,6 +49,7 @@ export function requireGitManifest(value) {
48
49
  "syncSessions",
49
50
  ...(manifest.snapshotSyncSessions === undefined ? [] : ["snapshotSyncSessions"]),
50
51
  ...(manifest.selection === undefined ? [] : ["selection"]),
52
+ ...(Object.hasOwn(manifest, "ignoreRules") ? ["ignoreRules"] : []),
51
53
  ...(manifest.localFields === undefined ? [] : ["localFields"]),
52
54
  "files",
53
55
  ])) {
@@ -56,6 +58,11 @@ export function requireGitManifest(value) {
56
58
  validateSnapshotFieldPolicy({ version: manifest.snapshotVersion, localFields: manifest.localFields });
57
59
  const selection = manifest.selection === undefined ? undefined : portableSnapshotSelection(manifest.selection);
58
60
  validateSnapshotSelection({ version: manifest.snapshotVersion, selection });
61
+ const policy = validateSnapshotIgnoreRules({
62
+ version: manifest.snapshotVersion,
63
+ selection,
64
+ ...(Object.hasOwn(manifest, "ignoreRules") ? { ignoreRules: manifest.ignoreRules } : {}),
65
+ });
59
66
  const ignoreSnapshot = selection?.version === 4;
60
67
  if (ignoreSnapshot) {
61
68
  validateIgnoreSnapshotIdentity({
@@ -66,7 +73,9 @@ export function requireGitManifest(value) {
66
73
  });
67
74
  validateIgnoreSnapshotSessionFlag(selection, manifest.snapshotSyncSessions);
68
75
  }
69
- const selected = selection?.scope ? configuredSnapshotPathMatcher(selection) : undefined;
76
+ const selected = selection?.scope
77
+ ? configuredSnapshotPathMatcher(policy ? { ...selection, ignorePolicy: policy } : selection)
78
+ : undefined;
70
79
  const byteLimit = ignoreSnapshot ? MAX_AGENT_DIRECTORY_BYTES : MAX_GIT_SNAPSHOT_BYTES;
71
80
  let total = 0;
72
81
  let hasSessionFiles = false;
@@ -121,6 +130,9 @@ export function validateGitSnapshot(snapshot, manifest, namespace) {
121
130
  snapshot.syncSessions !== manifest.snapshotSyncSessions ||
122
131
  syncSessions !== manifest.syncSessions ||
123
132
  !sameSnapshotSelection(snapshot.selection, manifest.selection) ||
133
+ (snapshot.ignoreRules === null) !== (manifest.ignoreRules === null) ||
134
+ snapshot.ignoreRules?.filename !== manifest.ignoreRules?.filename ||
135
+ snapshot.ignoreRules?.text !== manifest.ignoreRules?.text ||
124
136
  prepared.length !== manifest.files.length ||
125
137
  prepared.some((file, index) => {
126
138
  const expected = manifest.files[index];
@@ -131,7 +143,7 @@ export function validateGitSnapshot(snapshot, manifest, namespace) {
131
143
  }
132
144
  export function prepareGitSnapshot(snapshot, namespace) {
133
145
  assertSnapshotExcludesDebugLog(snapshot);
134
- if (snapshot.version !== IGNORE_SNAPSHOT_VERSION)
146
+ if (!isIgnoreSnapshotVersion(snapshot.version))
135
147
  snapshotSelectionInclude(snapshot);
136
148
  validatePortableSnapshot(snapshot);
137
149
  if (typeof snapshot.id !== "string" ||
@@ -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;