@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
@@ -1,332 +1,23 @@
1
- import { spawn } from "node:child_process";
2
1
  import { createHash, randomUUID } from "node:crypto";
3
- import { request as httpRequest } from "node:http";
4
2
  import { setTimeout as delay } from "node:timers/promises";
5
- import { fileURLToPath } from "node:url";
6
- import lockfile from "proper-lockfile";
7
- import { lt, valid } from "semver";
8
- import { DAEMON_BUILD_VERSION } from "./build-version.js";
9
- import { canonicalRootGuard, clearUpgradeOwner, daemonPaths, privateDirectory, processExists, processExited, readIdentity, readJsonBody, readProcessBirth, readUpgradeOwner, recordUpgradeOwner, runtimePaths, upgradeRepairStarted, } from "./identity.js";
3
+ import { DaemonError, requestDaemon } from "./client-transport.js";
4
+ import { stopDaemonAfterForegroundQueueFailure } from "./daemon-recovery.js";
5
+ import { isForegroundDirection, isForegroundQueueOutcome } from "./foreground-queue-outcome.js";
6
+ import { canonicalRootGuard, readProcessBirth } from "./identity.js";
10
7
  import { withCleanup } from "./lifecycle.js";
11
- import { MAX_MESSAGE_BYTES, MAX_REVIEW_BYTES, operationPrefix, REVIEW_PAGE_CHARS, record, } from "./protocol.js";
12
- export class DaemonError extends Error {
13
- remote;
14
- constructor(remote) {
15
- super(remote.message);
16
- this.name = remote.name;
17
- this.remote = remote;
18
- }
19
- }
20
- export async function requestDaemon(paths, identity, method, params, signal) {
21
- signal?.throwIfAborted();
22
- const body = JSON.stringify({
23
- version: 1,
24
- root: paths.root,
25
- instance: identity.instance,
26
- token: identity.token,
27
- method,
28
- params,
29
- });
30
- if (Buffer.byteLength(body) > MAX_MESSAGE_BYTES)
31
- throw new Error("Daemon request exceeds its byte limit.");
32
- return new Promise((resolve, reject) => {
33
- const request = httpRequest({
34
- socketPath: daemonPaths(paths, identity.instance).endpoint,
35
- path: "/v1",
36
- method: "POST",
37
- signal,
38
- headers: { "content-type": "application/json", "content-length": Buffer.byteLength(body) },
39
- }, (response) => {
40
- void readJsonBody(response)
41
- .then((value) => {
42
- if (!record(value))
43
- throw new Error("Invalid daemon response.");
44
- if (record(value.error) && typeof value.error.message === "string")
45
- throw new DaemonError(value.error);
46
- if (response.statusCode !== 200 || !Object.hasOwn(value, "result"))
47
- throw new Error("Invalid daemon response.");
48
- resolve(value.result);
49
- })
50
- .catch(reject);
51
- });
52
- // Admission can wait behind a complete apply. The request owner's signal
53
- // cancels that wait; an idle timeout must not let admission escape the fence.
54
- request.setTimeout(method === "attach" || method === "resume-contact" ? 0 : 30_000, () => request.destroy(new Error("Daemon request timed out.")));
55
- request.once("error", reject);
56
- request.end(body);
57
- });
58
- }
59
- async function hello(paths, identity, signal) {
60
- const value = await requestDaemon(paths, identity, "hello", {}, signal);
61
- if (!record(value) ||
62
- value.version !== 1 ||
63
- value.root !== paths.root ||
64
- value.instance !== identity.instance ||
65
- value.pid !== identity.pid)
66
- throw new Error("Daemon handshake mismatch.");
67
- const version = value.buildVersion;
68
- if (Object.hasOwn(value, "buildVersion") && (typeof version !== "string" || valid(version) !== version))
69
- throw new Error("Invalid daemon build version.");
70
- // The old @narumitw/sync-daemon used the same wire protocol without a build version.
71
- return { needsUpgrade: typeof version !== "string" || lt(version, DAEMON_BUILD_VERSION) };
72
- }
73
- async function checkUpgradeConsent(paths, assertRoot, signal) {
74
- const { readConsent } = await import("./consent.js");
75
- const { withStateDirectoryGuardForRoot } = await import("./engine/state/state-directory.js");
76
- signal?.throwIfAborted();
77
- await withStateDirectoryGuardForRoot(paths.root, () => {
78
- signal?.throwIfAborted();
79
- assertRoot();
80
- // An older owner cannot report an in-memory revocation failure.
81
- const consent = readConsent(paths.root);
82
- if (consent && Object.values(consent.setups).some((setup) => setup.afterExit))
83
- throw new Error("Review or revoke unattended Pi Sync permission before restarting the older daemon.");
84
- });
85
- signal?.throwIfAborted();
86
- assertRoot();
87
- }
88
- async function finishUpgrade(paths, owner, assertRoot, signal) {
89
- await waitForProcessExit(owner, signal);
90
- if ((await readIdentity(paths))?.instance === owner.instance)
91
- throw new Error("The daemon exited without releasing its identity.");
92
- await checkUpgradeConsent(paths, assertRoot, signal);
93
- await clearUpgradeOwner(paths);
94
- signal?.throwIfAborted();
95
- assertRoot();
96
- }
97
- async function drainForUpgrade(paths, owner, { recorded, birth }, assertRoot, signal) {
98
- await checkUpgradeConsent(paths, assertRoot, signal);
99
- const barrier = recorded ?? { ...owner, birth };
100
- try {
101
- // Publish this before stop can remove the identity. A retry keeps the original evidence.
102
- if (!recorded)
103
- await recordUpgradeOwner(paths, barrier);
104
- assertRoot();
105
- const reply = await requestDaemon(paths, owner, "stop", {}, signal);
106
- if (!record(reply) || reply.stopping !== true)
107
- throw new Error("Daemon did not acknowledge stop.");
108
- }
109
- catch (error) {
110
- signal?.throwIfAborted();
111
- 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 });
112
- }
113
- await finishUpgrade(paths, barrier, assertRoot, signal);
114
- }
115
- export async function acquireStartupLock(paths, signal) {
116
- // Include the handshake, stop, exit wait, boot, and final handshake budgets.
117
- const deadline = performance.now() + 150_000;
118
- for (;;) {
119
- signal?.throwIfAborted();
120
- try {
121
- return await lockfile.lock(paths.directory, {
122
- realpath: false,
123
- lockfilePath: paths.startup,
124
- stale: 30_000,
125
- update: 5_000,
126
- });
127
- }
128
- catch (error) {
129
- signal?.throwIfAborted();
130
- if (error.code !== "ELOCKED")
131
- throw error;
132
- if (performance.now() >= deadline)
133
- throw new Error("Timed out waiting to start the Pi Sync daemon.", { cause: error });
134
- await delay(50, undefined, { signal });
135
- }
136
- }
137
- }
138
- /** Explicit startup only: callers decide whether configuration or a user action authorizes it. */
139
- export async function ensureDaemon(root, signal) {
140
- const paths = await runtimePaths(root);
141
- const assertRoot = canonicalRootGuard(paths.root);
142
- signal?.throwIfAborted();
143
- await privateDirectory(paths.directory);
144
- signal?.throwIfAborted();
145
- const release = await acquireStartupLock(paths, signal);
146
- try {
147
- signal?.throwIfAborted();
148
- let waited = false;
149
- let upgraded = false;
150
- for (;;) {
151
- signal?.throwIfAborted();
152
- const upgrade = await readUpgradeOwner(paths);
153
- if (upgrade && (await upgradeRepairStarted(paths, upgrade)))
154
- throw new Error("A daemon upgrade repair is incomplete. Run `pi-sync-daemon repair-upgrade` for this root.");
155
- const existing = await readIdentity(paths);
156
- if (upgrade && existing?.instance === upgrade.instance && existing.pid !== upgrade.pid)
157
- throw new Error("The recorded upgrade owner changed; private state was retained.");
158
- if (upgrade && (existing?.instance !== upgrade.instance || (await processExited(upgrade)))) {
159
- await finishUpgrade(paths, upgrade, assertRoot, signal);
160
- upgraded = true;
161
- continue;
162
- }
163
- if (!existing)
164
- break;
165
- // A sample taken only after hello could describe an unrelated process reusing the PID.
166
- const beforeHello = upgrade ? undefined : await readProcessBirth(existing.pid);
167
- let status;
168
- try {
169
- status = await hello(paths, existing, signal);
170
- }
171
- catch (error) {
172
- if (signal?.aborted)
173
- throw signal.reason;
174
- if (upgrade) {
175
- // The stop may have been accepted even if the old endpoint no longer replies.
176
- await finishUpgrade(paths, upgrade, assertRoot, signal);
177
- upgraded = true;
178
- continue;
179
- }
180
- if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError" && !waited) {
181
- waited = true;
182
- await waitForDaemonExit(existing, signal);
183
- continue;
184
- }
185
- if (processExists(existing.pid))
186
- throw new Error("A daemon owner is alive but unavailable; use diagnostics instead of starting a second owner.", { cause: error });
187
- break;
188
- }
189
- signal?.throwIfAborted();
190
- assertRoot();
191
- if (!status.needsUpgrade) {
192
- if (upgrade)
193
- throw new Error("The recorded upgrade owner changed; private state was retained.");
194
- return { paths: daemonPaths(paths, existing.instance), identity: existing, ...status };
195
- }
196
- if (upgraded)
197
- throw new Error("An older Pi Sync daemon started again. Close or upgrade other Pi sessions, then use /reload.");
198
- const birth = beforeHello === undefined ? undefined : await readProcessBirth(existing.pid);
199
- if (birth !== undefined && birth !== beforeHello)
200
- throw new Error("The daemon process changed during authentication; private state was retained.");
201
- await drainForUpgrade(paths, existing, { recorded: upgrade, birth }, assertRoot, signal);
202
- upgraded = true;
203
- }
204
- signal?.throwIfAborted();
205
- assertRoot();
206
- const executable = process.versions.bun ? "node" : process.execPath;
207
- const child = spawn(executable, [fileURLToPath(new URL("./cli.js", import.meta.url)), "serve", "--root", paths.root], {
208
- detached: true,
209
- stdio: ["ignore", "ignore", "ignore", "ipc"],
210
- windowsHide: true,
211
- });
212
- const ready = await new Promise((resolve, reject) => {
213
- let timer;
214
- const abort = () => {
215
- cleanup();
216
- reject(signal?.reason);
217
- };
218
- const cleanup = () => {
219
- if (timer)
220
- clearTimeout(timer);
221
- signal?.removeEventListener("abort", abort);
222
- child.off("message", message);
223
- child.off("error", failed);
224
- child.off("exit", exited);
225
- };
226
- const failed = (error) => {
227
- cleanup();
228
- reject(error);
229
- };
230
- const exited = (code) => failed(new Error(`Daemon startup exited (${code}); private state was retained.`));
231
- const message = (value) => {
232
- if (!record(value))
233
- return;
234
- if (value.type === "booting") {
235
- timer = setTimeout(() => failed(new Error("Daemon readiness timed out.")), 15_000);
236
- timer.unref?.();
237
- }
238
- if (value.type === "error")
239
- failed(new Error(typeof value.message === "string" ? value.message : "Daemon startup failed."));
240
- if (value.type === "ready" && record(value.identity)) {
241
- cleanup();
242
- resolve(value.identity);
243
- }
244
- };
245
- signal?.addEventListener("abort", abort, { once: true });
246
- child.on("message", message);
247
- child.once("error", failed);
248
- child.once("exit", exited);
249
- if (signal?.aborted)
250
- abort();
251
- }).finally(() => {
252
- if (child.connected)
253
- child.disconnect();
254
- child.unref();
255
- });
256
- // Never kill a published shared daemon on caller cancellation.
257
- const status = await hello(paths, ready, signal);
258
- signal?.throwIfAborted();
259
- assertRoot();
260
- if (status.needsUpgrade)
261
- throw new Error("The daemon installation changed during startup. Use /reload to retry.");
262
- return { paths: daemonPaths(paths, ready.instance), identity: ready, ...status };
263
- }
264
- finally {
265
- await release();
266
- }
267
- }
268
- /** Wait only for a previously authenticated owner; never kill it or infer exit from lost contact. */
269
- export async function waitForDaemonExit({ pid }, signal) {
270
- await waitForProcessExit({ pid }, signal);
271
- }
272
- async function waitForProcessExit(owner, signal) {
273
- const deadline = Date.now() + 30_000;
274
- signal?.throwIfAborted();
275
- while (!(await processExited(owner))) {
276
- signal?.throwIfAborted();
277
- if (Date.now() >= deadline)
278
- throw new Error("Closing daemon is still alive; replacement was not attempted.");
279
- await delay(25, undefined, { signal });
280
- }
281
- signal?.throwIfAborted();
282
- }
283
- /** Inspect an existing protocol-compatible owner without starting or replacing it. */
284
- export async function findDaemon(root) {
285
- let paths;
286
- try {
287
- paths = await runtimePaths(root);
288
- }
289
- catch (error) {
290
- if (error.code === "ENOENT")
291
- return undefined;
292
- throw error;
293
- }
294
- const identity = await readIdentity(paths);
295
- if (!identity || !processExists(identity.pid))
296
- return undefined;
297
- try {
298
- const status = await hello(paths, identity);
299
- return { paths: daemonPaths(paths, identity.instance), identity, ...status };
300
- }
301
- catch (error) {
302
- if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError")
303
- return undefined;
304
- throw error;
305
- }
306
- }
307
- /** Gracefully stop an existing compatible owner without creating a new service. */
308
- export async function stopDaemon(root) {
309
- const paths = await runtimePaths(root);
310
- const identity = await readIdentity(paths);
311
- if (!identity)
312
- return false;
313
- // The authenticated stop response is itself instance/root/version bound, even
314
- // when a changed agent root makes ordinary health checks fail closed.
315
- await requestDaemon(paths, identity, "stop", {});
316
- const deadline = Date.now() + 30_000;
317
- for (;;) {
318
- const current = await readIdentity(paths);
319
- if (!current || current.instance !== identity.instance)
320
- return true;
321
- if (Date.now() >= deadline)
322
- throw new Error("Daemon did not drain; no replacement was attempted.");
323
- await new Promise((resolve) => setTimeout(resolve, 25));
324
- }
325
- }
8
+ import { presentPagedReview, reviewScope } from "./paged-review.js";
9
+ import { MAX_REVIEW_BYTES, operationPrefix, REVIEW_PAGE_CHARS, record, UNKNOWN_JOB_RESULT, } from "./protocol.js";
10
+ import { STATE_WAIT_FAILURE_LIMIT, stateWaitJobs, stateWaitResult } from "./state-wait-jobs.js";
11
+ export { DaemonError, hello, requestDaemon } from "./client-transport.js";
12
+ export { acquireStartupLock, checkUpgradeConsent, ensureDaemon, findDaemon, finishUpgrade, stopDaemon, waitForDaemonExit, } from "./daemon-startup.js";
326
13
  const MAX_COMPLETED_CALLBACKS = 4096;
327
14
  const RELEASE_ATTEMPT_MS = 2_000;
328
15
  const RELEASE_BUDGET_MS = 25_000;
329
16
  const RELEASE_MAX_ATTEMPTS = 20;
17
+ const FOREGROUND_RPC_MS = 3_000;
18
+ const FOREGROUND_DRAIN_MS = 30_000;
19
+ const FOREGROUND_RECOVERY_MS = 45_000;
20
+ const FOREGROUND_UNKNOWN_RESULT = "The daemon's transfer result could not be verified. Changes may have been made; recovery evidence was retained.";
330
21
  const TRANSIENT_RELEASE_ERRORS = new Set(["ECONNRESET", "ECONNREFUSED", "EPIPE", "ENOENT", "ETIMEDOUT", "EAGAIN"]);
331
22
  export class DaemonConnection {
332
23
  paths;
@@ -347,6 +38,11 @@ export class DaemonConnection {
347
38
  resuming;
348
39
  resumeUncertain = false;
349
40
  pendingJobs = new Set();
41
+ foregroundRecovery;
42
+ observesState = false;
43
+ stateRevision;
44
+ terminalJobs = new Set();
45
+ jobWaiters = new Map();
350
46
  uncertain = false;
351
47
  reportedError = false;
352
48
  commits = new Map();
@@ -375,7 +71,7 @@ export class DaemonConnection {
375
71
  }
376
72
  /** Original submitted jobs must finish (or be reconciled) before repairing contact. */
377
73
  get hasPendingWork() {
378
- return this.pendingJobs.size > 0 || this.uncertain;
74
+ return this.pendingJobs.size > 0 || this.uncertain || this.foregroundRecovery !== undefined;
379
75
  }
380
76
  async attach(signal) {
381
77
  if (this.closed ||
@@ -388,7 +84,7 @@ export class DaemonConnection {
388
84
  this.admitting = true;
389
85
  this.lifecycleRevision++;
390
86
  this.contactRevision++;
391
- const request = requestDaemon(this.paths, this.identity, "attach", this.facts, signal ? AbortSignal.any([signal, this.controller.signal]) : this.controller.signal);
87
+ const request = requestDaemon(this.paths, this.identity, "attach", this.facts, signal ? AbortSignal.any([signal, this.controller.signal]) : this.controller.signal, this.options.mergeReview ? { reviewDetails: 1 } : undefined);
392
88
  // Poll during attach: stopping a previous controller may need release answers
393
89
  // from this reattached participant before the attach response can complete.
394
90
  this.polling ??= this.poll();
@@ -397,6 +93,9 @@ export class DaemonConnection {
397
93
  const result = await request;
398
94
  admitted = true;
399
95
  this.publishContact(this.consume(result));
96
+ this.observesState = record(result) && result.stateWait === 1;
97
+ this.stateRevision = undefined;
98
+ this.terminalJobs.clear();
400
99
  this.attached = true;
401
100
  return this;
402
101
  }
@@ -519,9 +218,10 @@ export class DaemonConnection {
519
218
  sameClient(facts) {
520
219
  return facts.id === this.facts.id && facts.pid === this.facts.pid && facts.generation === this.facts.generation;
521
220
  }
522
- async run(operation, payload, signal, onCommit) {
221
+ async run(operation, payload, signal, onCommit, onSubmit) {
523
222
  if (this.closed ||
524
223
  this.uncertain ||
224
+ this.foregroundRecovery ||
525
225
  this.contactResumeState !== "idle" ||
526
226
  this.pausing ||
527
227
  this.disposing ||
@@ -529,32 +229,115 @@ export class DaemonConnection {
529
229
  this.contactState === "inactive")
530
230
  throw new Error("Daemon client is unavailable; confirm contact and drain work before submitting.");
531
231
  signal?.throwIfAborted();
532
- const id = `${operationPrefix(this.identity)}${randomUUID()}`;
232
+ const { paths, identity } = this;
233
+ const id = `${operationPrefix(identity)}${randomUUID()}`;
234
+ const jobParams = { id, client: this.facts.id };
235
+ const transport = this.controller.signal;
236
+ const foreground = isForegroundDirection(operation);
237
+ const assertRoot = foreground ? canonicalRootGuard(paths.root) : undefined;
238
+ const generation = this.facts.generation;
239
+ let birth;
240
+ const rpc = async (method, params) => {
241
+ if (!foreground)
242
+ return requestDaemon(paths, identity, method, params, transport);
243
+ const timeout = method === "cancel" ? FOREGROUND_DRAIN_MS : FOREGROUND_RPC_MS;
244
+ const attempt = () => requestDaemon(paths, identity, method, params, AbortSignal.any([transport, AbortSignal.timeout(timeout)]));
245
+ try {
246
+ return await attempt();
247
+ }
248
+ catch (error) {
249
+ if (transport.aborted ||
250
+ error instanceof DaemonError ||
251
+ method === "cancel" ||
252
+ (method === "submit" && signal?.aborted))
253
+ throw error;
254
+ return attempt().catch((retryError) => {
255
+ if (method === "submit")
256
+ throw new AggregateError([error, retryError], FOREGROUND_UNKNOWN_RESULT);
257
+ throw retryError;
258
+ });
259
+ }
260
+ };
533
261
  this.pendingJobs.add(id);
534
262
  const abort = () => {
535
- void requestDaemon(this.paths, this.identity, "cancel", { id, client: this.facts.id }, this.controller.signal).catch(() => { });
263
+ void requestDaemon(paths, identity, "cancel", jobParams, transport).catch(() => { });
536
264
  };
537
265
  let terminal = false;
266
+ const finish = (job) => {
267
+ terminal = true;
268
+ if (job.phase === "failed")
269
+ throw new DaemonError(job.error ?? { name: "Error", message: "Daemon operation failed." });
270
+ if (!foreground)
271
+ signal?.throwIfAborted();
272
+ if (assertRoot && isForegroundQueueOutcome(job.result))
273
+ this.foregroundRecovery = { job: id, generation, birth, assertRoot };
274
+ return job.result;
275
+ };
538
276
  if (onCommit)
539
277
  this.commits.set(id, { notify: onCommit, signal });
540
278
  signal?.addEventListener("abort", abort, { once: true });
541
279
  if (signal?.aborted)
542
280
  abort();
543
281
  return withCleanup(async () => {
544
- await requestDaemon(this.paths, this.identity, "submit", { id, client: this.facts.id, operation, payload }, this.controller.signal);
282
+ try {
283
+ onSubmit?.(id);
284
+ }
285
+ catch { }
286
+ if (foreground) {
287
+ birth = await readProcessBirth(identity.pid);
288
+ signal?.throwIfAborted();
289
+ transport.throwIfAborted();
290
+ assertRoot?.();
291
+ }
292
+ let lostSubmit = false;
293
+ try {
294
+ await rpc("submit", { ...jobParams, operation, payload });
295
+ }
296
+ catch (error) {
297
+ if (!foreground || error instanceof DaemonError || transport.aborted)
298
+ throw error;
299
+ lostSubmit = true;
300
+ }
301
+ let terminalObserved = this.observesState && !lostSubmit;
302
+ if (terminalObserved && !this.terminalJobs.has(id)) {
303
+ const completion = Promise.withResolvers();
304
+ this.jobWaiters.set(id, completion);
305
+ const keepAlive = setInterval(() => { }, 30_000);
306
+ try {
307
+ terminalObserved = (await completion.promise) === "terminal";
308
+ }
309
+ finally {
310
+ this.jobWaiters.delete(id);
311
+ clearInterval(keepAlive);
312
+ }
313
+ }
545
314
  while (!this.closed) {
546
- const reply = await requestDaemon(this.paths, this.identity, "poll", { client: this.facts.id, cursor: this.cursor, job: id }, this.controller.signal);
547
- this.consume(reply);
548
- const job = record(reply) ? reply.job : undefined;
549
- if (job?.id === id && job.phase === "failed") {
550
- terminal = true;
551
- throw new DaemonError(job.error ?? { name: "Error", message: "Daemon operation failed." });
315
+ let reply;
316
+ try {
317
+ reply = await rpc("poll", { client: jobParams.client, cursor: this.cursor, job: id });
552
318
  }
553
- if (job?.id === id && job.phase === "done") {
554
- terminal = true;
555
- signal?.throwIfAborted();
556
- return job.result;
319
+ catch (error) {
320
+ if (foreground && !transport.aborted) {
321
+ const drained = await rpc("cancel", jobParams).catch(() => undefined);
322
+ const job = drained;
323
+ if (job?.id === id && (job.phase === "done" || job.phase === "failed"))
324
+ return finish(job);
325
+ this.markWorkUncertain();
326
+ throw new Error(FOREGROUND_UNKNOWN_RESULT, { cause: error });
327
+ }
328
+ if (error instanceof DaemonError && error.message === UNKNOWN_JOB_RESULT)
329
+ this.markWorkUncertain();
330
+ throw error;
557
331
  }
332
+ const job = record(reply) ? reply.job : undefined;
333
+ const missing = terminalObserved && (job?.id !== id || (job.phase !== "done" && job.phase !== "failed"));
334
+ if (missing)
335
+ this.markWorkUncertain();
336
+ this.consume(reply);
337
+ if (missing)
338
+ throw new Error(foreground ? FOREGROUND_UNKNOWN_RESULT : UNKNOWN_JOB_RESULT);
339
+ if (job?.id === id && (job.phase === "done" || job.phase === "failed"))
340
+ return finish(job);
558
341
  await this.wait(25, true);
559
342
  }
560
343
  throw new Error("Daemon client closed before operation completed.");
@@ -566,17 +349,55 @@ export class DaemonConnection {
566
349
  if (callback.job === id && !callback.kind.startsWith("queue-"))
567
350
  callback.controller.abort();
568
351
  try {
569
- await requestDaemon(this.paths, this.identity, "cancel", { id, client: this.facts.id });
352
+ if (foreground) {
353
+ if (!this.uncertain)
354
+ await rpc("cancel", jobParams);
355
+ }
356
+ else
357
+ await requestDaemon(paths, identity, "cancel", jobParams);
570
358
  }
571
359
  catch (error) {
572
- this.uncertain = true;
573
- for (const callback of this.callbacks.values())
574
- if (callback.kind !== "queue-release")
575
- callback.controller.abort();
576
- throw new Error("Operation outcome is uncertain; reload to reconnect and reconcile, never replay the write.", { cause: error });
360
+ this.markWorkUncertain();
361
+ throw new Error(foreground
362
+ ? FOREGROUND_UNKNOWN_RESULT
363
+ : "Operation outcome is uncertain; reload to reconnect and reconcile, never replay the write.", { cause: error });
577
364
  }
578
365
  }
579
- }).finally(() => this.pendingJobs.delete(id));
366
+ }).finally(() => {
367
+ this.pendingJobs.delete(id);
368
+ });
369
+ }
370
+ async recoverForeground(job, signal) {
371
+ signal.throwIfAborted();
372
+ const target = this.foregroundRecovery;
373
+ if (!target ||
374
+ target.job !== job ||
375
+ target.generation !== this.facts.generation ||
376
+ target.attempted ||
377
+ !this.attached ||
378
+ this.closed ||
379
+ this.admitting ||
380
+ this.disposing ||
381
+ this.pausing ||
382
+ this.pendingJobs.size ||
383
+ this.uncertain ||
384
+ this.contactResumeState !== "idle")
385
+ throw new Error("The current Pi session could not verify a completed transfer for daemon recovery.");
386
+ target.assertRoot();
387
+ target.attempted = true;
388
+ const owned = AbortSignal.any([signal, this.controller.signal, AbortSignal.timeout(FOREGROUND_RECOVERY_MS)]);
389
+ await stopDaemonAfterForegroundQueueFailure(this.paths, this.identity, {
390
+ ...target,
391
+ client: this.facts.id,
392
+ }, owned);
393
+ await this.closeLocal();
394
+ target.assertRoot();
395
+ }
396
+ markWorkUncertain() {
397
+ this.uncertain = true;
398
+ for (const callback of this.callbacks.values())
399
+ if (callback.kind !== "queue-release")
400
+ callback.controller.abort();
580
401
  }
581
402
  publishContact(contact) {
582
403
  this.contactRevision++;
@@ -637,6 +458,7 @@ export class DaemonConnection {
637
458
  this.uncertain = true;
638
459
  const controller = new AbortController();
639
460
  const foreground = this.pendingJobs.has(callback.job);
461
+ const reviewGeneration = callback.review?.offer !== undefined ? this.facts.generation : undefined;
640
462
  this.callbacks.set(callback.id, {
641
463
  controller,
642
464
  kind: callback.kind,
@@ -665,7 +487,10 @@ export class DaemonConnection {
665
487
  await requestDaemon(this.paths, this.identity, "answer", {
666
488
  client: this.facts.id,
667
489
  id: callback.id,
668
- ...(failed ? { error: "Client callback cancelled or failed." } : { value }),
490
+ ...(reviewGeneration !== undefined ? { generation: reviewGeneration } : {}),
491
+ ...(failed || (reviewGeneration !== undefined && controller.signal.aborted)
492
+ ? { error: "Client callback cancelled or failed." }
493
+ : { value }),
669
494
  }, this.callbackIO.signal);
670
495
  }
671
496
  finally {
@@ -755,6 +580,11 @@ export class DaemonConnection {
755
580
  const reference = callback.review;
756
581
  if (!reference)
757
582
  return this.options.callback(callback, signal);
583
+ if (reference.offer !== undefined) {
584
+ if (!this.options.mergeReview)
585
+ throw new Error("Exact review offer requires an opted-in presenter.");
586
+ return presentPagedReview(reviewScope(this.identity, this.facts, callback), callback, AbortSignal.any([signal, this.callbackIO.signal]), this.options.mergeReview, (params, owned) => requestDaemon(this.paths, this.identity, "review-page", params, owned));
587
+ }
758
588
  if (callback.kind !== "merge-review" ||
759
589
  !record(callback.payload) ||
760
590
  !Number.isSafeInteger(reference.pages) ||
@@ -816,14 +646,44 @@ export class DaemonConnection {
816
646
  /* Error presentation must not own a task. */
817
647
  }
818
648
  }
649
+ async observeState() {
650
+ const jobs = stateWaitJobs(this.jobWaiters);
651
+ const reply = await requestDaemon(this.paths, this.identity, "state-wait", {
652
+ client: this.facts.id,
653
+ generation: this.facts.generation,
654
+ cursor: this.cursor,
655
+ revision: this.stateRevision,
656
+ jobs,
657
+ }, this.controller.signal, { onSocket: (socket) => socket.unref() });
658
+ return stateWaitResult(reply);
659
+ }
819
660
  async poll() {
661
+ await withCleanup(() => this.pollUntilClosed(), async () => {
662
+ for (const waiter of this.jobWaiters.values())
663
+ waiter.reject(this.controller.signal.reason ?? new Error("Daemon client closed."));
664
+ });
665
+ }
666
+ async pollUntilClosed() {
667
+ let failures = 0;
820
668
  while (!this.closed) {
821
669
  try {
822
670
  const revision = this.contactRevision;
823
- const reply = await requestDaemon(this.paths, this.identity, "poll", { client: this.facts.id, cursor: this.cursor }, this.controller.signal);
671
+ const state = this.observesState && !this.admitting ? await this.observeState() : undefined;
672
+ const reply = state?.reply ??
673
+ (await requestDaemon(this.paths, this.identity, "poll", { client: this.facts.id, cursor: this.cursor }, this.controller.signal));
824
674
  // An older poll must not undo typed update expiry or a successful resume.
825
675
  if (revision === this.contactRevision) {
676
+ if (state?.missing.some((id) => this.jobWaiters.has(id)))
677
+ this.markWorkUncertain();
826
678
  const contact = this.consume(reply);
679
+ if (state) {
680
+ this.stateRevision = state.version;
681
+ this.terminalJobs = new Set(state.finished);
682
+ for (const id of state.missing)
683
+ this.jobWaiters.get(id)?.reject(new Error(UNKNOWN_JOB_RESULT));
684
+ for (const id of state.finished)
685
+ this.jobWaiters.get(id)?.resolve("terminal");
686
+ }
827
687
  this.reportedError = false;
828
688
  if (revision === this.contactRevision &&
829
689
  this.attached &&
@@ -838,11 +698,16 @@ export class DaemonConnection {
838
698
  this.options.contact?.(contact);
839
699
  }
840
700
  }
841
- await this.wait(100);
701
+ failures = 0;
702
+ if (!state)
703
+ await this.wait(100);
842
704
  }
843
705
  catch (error) {
844
706
  if (this.closed)
845
707
  return;
708
+ if (++failures >= STATE_WAIT_FAILURE_LIMIT)
709
+ for (const waiter of this.jobWaiters.values())
710
+ waiter.resolve("poll");
846
711
  if (this.attached)
847
712
  this.reportError(error);
848
713
  try {
@@ -896,14 +761,17 @@ export class DaemonConnection {
896
761
  this.consume(reply);
897
762
  }
898
763
  finally {
899
- this.closed = true;
900
- this.controller.abort(new DOMException("Client disposed", "AbortError"));
901
- this.callbackIO.abort(new DOMException("Client callback transport disposed", "AbortError"));
902
- for (const { controller } of this.callbacks.values())
903
- controller.abort();
904
- await Promise.allSettled([this.polling, this.updates, ...this.callbackTasks]);
764
+ await this.closeLocal();
905
765
  }
906
766
  })();
907
767
  return this.disposing;
908
768
  }
769
+ async closeLocal() {
770
+ this.closed = true;
771
+ this.controller.abort(new DOMException("Client disposed", "AbortError"));
772
+ this.callbackIO.abort(new DOMException("Client callback transport disposed", "AbortError"));
773
+ for (const { controller } of this.callbacks.values())
774
+ controller.abort();
775
+ await Promise.allSettled([this.polling, this.updates, ...this.callbackTasks]);
776
+ }
909
777
  }