@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
@@ -5,7 +5,7 @@ import {
5
5
  } from "./chunk-DAZZ5BEJ.ts";
6
6
  import {
7
7
  currentPiDaemonClient
8
- } from "./chunk-RW44KNFD.ts";
8
+ } from "./chunk-JQ5BAWW2.ts";
9
9
  import "./chunk-H7VOTY5N.ts";
10
10
  import "./chunk-6YKOHBSC.ts";
11
11
  import "./chunk-R3SAMXB6.ts";
@@ -20,4 +20,4 @@ var inspectSync = async (config, _options, signal) => await currentPiDaemonClien
20
20
  export {
21
21
  inspectSync
22
22
  };
23
- //# sourceMappingURL=sync-inspection-OS2LVOLV.ts.map
23
+ //# sourceMappingURL=sync-inspection-NBBTSMKR.ts.map
@@ -2,7 +2,7 @@
2
2
  // @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
3
3
  import {
4
4
  remoteOperation
5
- } from "./chunk-RW44KNFD.ts";
5
+ } from "./chunk-JQ5BAWW2.ts";
6
6
  import "./chunk-H7VOTY5N.ts";
7
7
  import "./chunk-6YKOHBSC.ts";
8
8
  import "./chunk-R3SAMXB6.ts";
@@ -46,4 +46,4 @@ export {
46
46
  status,
47
47
  syncBoth
48
48
  };
49
- //# sourceMappingURL=sync-operations-D3MDJUQQ.ts.map
49
+ //# sourceMappingURL=sync-operations-AIEM2KL2.ts.map
@@ -1,277 +1,23 @@
1
- import { spawn } from "node:child_process";
2
1
  import { createHash, randomUUID } from "node:crypto";
3
2
  import { setTimeout as delay } from "node:timers/promises";
4
- import { fileURLToPath } from "node:url";
5
- import lockfile from "proper-lockfile";
6
- import { DaemonError, hello, requestDaemon } from "./client-transport.js";
7
- import { canonicalRootGuard, clearUpgradeOwner, daemonPaths, privateDirectory, processExists, processExited, readIdentity, 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";
8
7
  import { withCleanup } from "./lifecycle.js";
9
8
  import { presentPagedReview, reviewScope } from "./paged-review.js";
10
- import { MAX_REVIEW_BYTES, OWNERSHIP_CLEANUP_REQUIRED, operationPrefix, REVIEW_PAGE_CHARS, record, UNKNOWN_JOB_RESULT, } from "./protocol.js";
9
+ import { MAX_REVIEW_BYTES, operationPrefix, REVIEW_PAGE_CHARS, record, UNKNOWN_JOB_RESULT, } from "./protocol.js";
11
10
  import { STATE_WAIT_FAILURE_LIMIT, stateWaitJobs, stateWaitResult } from "./state-wait-jobs.js";
12
11
  export { DaemonError, hello, requestDaemon } from "./client-transport.js";
13
- export async function checkUpgradeConsent(paths, assertRoot, signal) {
14
- const { readConsent } = await import("./consent.js");
15
- const { withStateDirectoryGuardForRoot } = await import("./engine/state/state-directory.js");
16
- signal?.throwIfAborted();
17
- await withStateDirectoryGuardForRoot(paths.root, () => {
18
- signal?.throwIfAborted();
19
- assertRoot();
20
- // An older owner cannot report an in-memory revocation failure.
21
- const consent = readConsent(paths.root);
22
- if (consent && Object.values(consent.setups).some((setup) => setup.afterExit))
23
- throw new Error("Review or revoke unattended Pi Sync permission before stopping or replacing the daemon.");
24
- });
25
- signal?.throwIfAborted();
26
- assertRoot();
27
- }
28
- export async function finishUpgrade(paths, owner, assertRoot, signal) {
29
- await waitForProcessExit(owner, signal);
30
- const current = await readIdentity(paths);
31
- if (current?.instance === owner.instance)
32
- throw new Error("The daemon exited without releasing its identity.");
33
- if (current && owner.purpose === "cleanup")
34
- throw new Error("Daemon owner changed during recovery. Review the current owner before retrying.");
35
- await checkUpgradeConsent(paths, assertRoot, signal);
36
- await clearUpgradeOwner(paths);
37
- signal?.throwIfAborted();
38
- assertRoot();
39
- }
40
- async function drainForUpgrade(paths, owner, { recorded, birth }, assertRoot, signal) {
41
- await checkUpgradeConsent(paths, assertRoot, signal);
42
- const barrier = recorded ?? { ...owner, birth };
43
- try {
44
- // Publish this before stop can remove the identity. A retry keeps the original evidence.
45
- if (!recorded)
46
- await recordUpgradeOwner(paths, barrier);
47
- assertRoot();
48
- const reply = await requestDaemon(paths, owner, "stop", {}, signal);
49
- if (!record(reply) || reply.stopping !== true)
50
- throw new Error("Daemon did not acknowledge stop.");
51
- }
52
- catch (error) {
53
- signal?.throwIfAborted();
54
- 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 });
55
- }
56
- await finishUpgrade(paths, barrier, assertRoot, signal);
57
- }
58
- export async function acquireStartupLock(paths, signal) {
59
- // Include the handshake, stop, exit wait, boot, and final handshake budgets.
60
- const deadline = performance.now() + 150_000;
61
- for (;;) {
62
- signal?.throwIfAborted();
63
- try {
64
- return await lockfile.lock(paths.directory, {
65
- realpath: false,
66
- lockfilePath: paths.startup,
67
- stale: 30_000,
68
- update: 5_000,
69
- });
70
- }
71
- catch (error) {
72
- signal?.throwIfAborted();
73
- if (error.code !== "ELOCKED")
74
- throw error;
75
- if (performance.now() >= deadline)
76
- throw new Error("Timed out waiting to start the Pi Sync daemon.", { cause: error });
77
- await delay(50, undefined, { signal });
78
- }
79
- }
80
- }
81
- /** Explicit startup only: callers decide whether configuration or a user action authorizes it. */
82
- export async function ensureDaemon(root, signal) {
83
- const paths = await runtimePaths(root);
84
- const assertRoot = canonicalRootGuard(paths.root);
85
- signal?.throwIfAborted();
86
- await privateDirectory(paths.directory);
87
- signal?.throwIfAborted();
88
- const release = await acquireStartupLock(paths, signal);
89
- try {
90
- signal?.throwIfAborted();
91
- let waited = false;
92
- let upgraded = false;
93
- for (;;) {
94
- signal?.throwIfAborted();
95
- const upgrade = await readUpgradeOwner(paths);
96
- if (upgrade && (await upgradeRepairStarted(paths, upgrade)))
97
- throw new Error("A daemon upgrade repair is incomplete. Run `pi-sync-daemon repair-upgrade` for this root.");
98
- const existing = await readIdentity(paths);
99
- if (upgrade && existing?.instance === upgrade.instance && existing.pid !== upgrade.pid)
100
- throw new Error("The recorded upgrade owner changed; private state was retained.");
101
- if (upgrade && (existing?.instance !== upgrade.instance || (await processExited(upgrade)))) {
102
- await finishUpgrade(paths, upgrade, assertRoot, signal);
103
- upgraded = true;
104
- continue;
105
- }
106
- if (upgrade?.purpose === "cleanup")
107
- throw Object.assign(new Error("Daemon recovery is incomplete. Use /sync daemon recover to finish the reviewed stop."), { code: OWNERSHIP_CLEANUP_REQUIRED });
108
- if (!existing)
109
- break;
110
- // A sample taken only after hello could describe an unrelated process reusing the PID.
111
- const beforeHello = upgrade ? undefined : await readProcessBirth(existing.pid);
112
- let status;
113
- try {
114
- status = await hello(paths, existing, signal);
115
- }
116
- catch (error) {
117
- if (signal?.aborted)
118
- throw signal.reason;
119
- if (upgrade) {
120
- // The stop may have been accepted even if the old endpoint no longer replies.
121
- await finishUpgrade(paths, upgrade, assertRoot, signal);
122
- upgraded = true;
123
- continue;
124
- }
125
- if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError" && !waited) {
126
- waited = true;
127
- await waitForDaemonExit(existing, signal);
128
- continue;
129
- }
130
- if (processExists(existing.pid))
131
- throw new Error("A daemon owner is alive but unavailable; use diagnostics instead of starting a second owner.", { cause: error });
132
- break;
133
- }
134
- signal?.throwIfAborted();
135
- assertRoot();
136
- if (!status.needsUpgrade) {
137
- if (upgrade)
138
- throw new Error("The recorded upgrade owner changed; private state was retained.");
139
- return { paths: daemonPaths(paths, existing.instance), identity: existing, ...status };
140
- }
141
- if (upgraded)
142
- throw new Error("An older Pi Sync daemon started again. Close or upgrade other Pi sessions, then use /reload.");
143
- const birth = beforeHello === undefined ? undefined : await readProcessBirth(existing.pid);
144
- if (birth !== undefined && birth !== beforeHello)
145
- throw new Error("The daemon process changed during authentication; private state was retained.");
146
- await drainForUpgrade(paths, existing, { recorded: upgrade, birth }, assertRoot, signal);
147
- upgraded = true;
148
- }
149
- signal?.throwIfAborted();
150
- assertRoot();
151
- const executable = process.versions.bun ? "node" : process.execPath;
152
- const child = spawn(executable, [fileURLToPath(new URL("./cli.js", import.meta.url)), "serve", "--root", paths.root], {
153
- detached: true,
154
- stdio: ["ignore", "ignore", "ignore", "ipc"],
155
- windowsHide: true,
156
- });
157
- const ready = await new Promise((resolve, reject) => {
158
- let timer;
159
- const abort = () => {
160
- cleanup();
161
- reject(signal?.reason);
162
- };
163
- const cleanup = () => {
164
- if (timer)
165
- clearTimeout(timer);
166
- signal?.removeEventListener("abort", abort);
167
- child.off("message", message);
168
- child.off("error", failed);
169
- child.off("exit", exited);
170
- };
171
- const failed = (error) => {
172
- cleanup();
173
- reject(error);
174
- };
175
- const exited = (code) => failed(new Error(`Daemon startup exited (${code}); private state was retained.`));
176
- const message = (value) => {
177
- if (!record(value))
178
- return;
179
- if (value.type === "booting") {
180
- timer = setTimeout(() => failed(new Error("Daemon readiness timed out.")), 15_000);
181
- timer.unref?.();
182
- }
183
- if (value.type === "error")
184
- failed(new Error(typeof value.message === "string" ? value.message : "Daemon startup failed."));
185
- if (value.type === "ready" && record(value.identity)) {
186
- cleanup();
187
- resolve(value.identity);
188
- }
189
- };
190
- signal?.addEventListener("abort", abort, { once: true });
191
- child.on("message", message);
192
- child.once("error", failed);
193
- child.once("exit", exited);
194
- if (signal?.aborted)
195
- abort();
196
- }).finally(() => {
197
- if (child.connected)
198
- child.disconnect();
199
- child.unref();
200
- });
201
- // Never kill a published shared daemon on caller cancellation.
202
- const status = await hello(paths, ready, signal);
203
- signal?.throwIfAborted();
204
- assertRoot();
205
- if (status.needsUpgrade)
206
- throw new Error("The daemon installation changed during startup. Use /reload to retry.");
207
- return { paths: daemonPaths(paths, ready.instance), identity: ready, ...status };
208
- }
209
- finally {
210
- await release();
211
- }
212
- }
213
- /** Wait only for a previously authenticated owner; never kill it or infer exit from lost contact. */
214
- export async function waitForDaemonExit({ pid }, signal) {
215
- await waitForProcessExit({ pid }, signal);
216
- }
217
- async function waitForProcessExit(owner, signal) {
218
- const deadline = Date.now() + 30_000;
219
- signal?.throwIfAborted();
220
- while (!(await processExited(owner))) {
221
- signal?.throwIfAborted();
222
- if (Date.now() >= deadline)
223
- throw new Error("Closing daemon is still alive; replacement was not attempted.");
224
- await delay(25, undefined, { signal });
225
- }
226
- signal?.throwIfAborted();
227
- }
228
- /** Inspect an existing protocol-compatible owner without starting or replacing it. */
229
- export async function findDaemon(root) {
230
- let paths;
231
- try {
232
- paths = await runtimePaths(root);
233
- }
234
- catch (error) {
235
- if (error.code === "ENOENT")
236
- return undefined;
237
- throw error;
238
- }
239
- const identity = await readIdentity(paths);
240
- if (!identity || !processExists(identity.pid))
241
- return undefined;
242
- try {
243
- const status = await hello(paths, identity);
244
- return { paths: daemonPaths(paths, identity.instance), identity, ...status };
245
- }
246
- catch (error) {
247
- if (error instanceof DaemonError && error.remote.name === "DaemonStoppingError")
248
- return undefined;
249
- throw error;
250
- }
251
- }
252
- /** Gracefully stop an existing compatible owner without creating a new service. */
253
- export async function stopDaemon(root) {
254
- const paths = await runtimePaths(root);
255
- const identity = await readIdentity(paths);
256
- if (!identity)
257
- return false;
258
- // The authenticated stop response is itself instance/root/version bound, even
259
- // when a changed agent root makes ordinary health checks fail closed.
260
- await requestDaemon(paths, identity, "stop", {});
261
- const deadline = Date.now() + 30_000;
262
- for (;;) {
263
- const current = await readIdentity(paths);
264
- if (!current || current.instance !== identity.instance)
265
- return true;
266
- if (Date.now() >= deadline)
267
- throw new Error("Daemon did not drain; no replacement was attempted.");
268
- await new Promise((resolve) => setTimeout(resolve, 25));
269
- }
270
- }
12
+ export { acquireStartupLock, checkUpgradeConsent, ensureDaemon, findDaemon, finishUpgrade, stopDaemon, waitForDaemonExit, } from "./daemon-startup.js";
271
13
  const MAX_COMPLETED_CALLBACKS = 4096;
272
14
  const RELEASE_ATTEMPT_MS = 2_000;
273
15
  const RELEASE_BUDGET_MS = 25_000;
274
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.";
275
21
  const TRANSIENT_RELEASE_ERRORS = new Set(["ECONNRESET", "ECONNREFUSED", "EPIPE", "ENOENT", "ETIMEDOUT", "EAGAIN"]);
276
22
  export class DaemonConnection {
277
23
  paths;
@@ -292,6 +38,7 @@ export class DaemonConnection {
292
38
  resuming;
293
39
  resumeUncertain = false;
294
40
  pendingJobs = new Set();
41
+ foregroundRecovery;
295
42
  observesState = false;
296
43
  stateRevision;
297
44
  terminalJobs = new Set();
@@ -324,7 +71,7 @@ export class DaemonConnection {
324
71
  }
325
72
  /** Original submitted jobs must finish (or be reconciled) before repairing contact. */
326
73
  get hasPendingWork() {
327
- return this.pendingJobs.size > 0 || this.uncertain;
74
+ return this.pendingJobs.size > 0 || this.uncertain || this.foregroundRecovery !== undefined;
328
75
  }
329
76
  async attach(signal) {
330
77
  if (this.closed ||
@@ -474,6 +221,7 @@ export class DaemonConnection {
474
221
  async run(operation, payload, signal, onCommit, onSubmit) {
475
222
  if (this.closed ||
476
223
  this.uncertain ||
224
+ this.foregroundRecovery ||
477
225
  this.contactResumeState !== "idle" ||
478
226
  this.pausing ||
479
227
  this.disposing ||
@@ -485,11 +233,46 @@ export class DaemonConnection {
485
233
  const id = `${operationPrefix(identity)}${randomUUID()}`;
486
234
  const jobParams = { id, client: this.facts.id };
487
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
+ };
488
261
  this.pendingJobs.add(id);
489
262
  const abort = () => {
490
263
  void requestDaemon(paths, identity, "cancel", jobParams, transport).catch(() => { });
491
264
  };
492
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
+ };
493
276
  if (onCommit)
494
277
  this.commits.set(id, { notify: onCommit, signal });
495
278
  signal?.addEventListener("abort", abort, { once: true });
@@ -500,8 +283,22 @@ export class DaemonConnection {
500
283
  onSubmit?.(id);
501
284
  }
502
285
  catch { }
503
- await requestDaemon(paths, identity, "submit", { ...jobParams, operation, payload }, transport);
504
- let terminalObserved = this.observesState;
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;
505
302
  if (terminalObserved && !this.terminalJobs.has(id)) {
506
303
  const completion = Promise.withResolvers();
507
304
  this.jobWaiters.set(id, completion);
@@ -515,27 +312,32 @@ export class DaemonConnection {
515
312
  }
516
313
  }
517
314
  while (!this.closed) {
518
- const reply = await requestDaemon(paths, identity, "poll", { client: jobParams.client, cursor: this.cursor, job: id }, transport).catch((error) => {
315
+ let reply;
316
+ try {
317
+ reply = await rpc("poll", { client: jobParams.client, cursor: this.cursor, job: id });
318
+ }
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
+ }
519
328
  if (error instanceof DaemonError && error.message === UNKNOWN_JOB_RESULT)
520
329
  this.markWorkUncertain();
521
330
  throw error;
522
- });
331
+ }
523
332
  const job = record(reply) ? reply.job : undefined;
524
333
  const missing = terminalObserved && (job?.id !== id || (job.phase !== "done" && job.phase !== "failed"));
525
334
  if (missing)
526
335
  this.markWorkUncertain();
527
336
  this.consume(reply);
528
337
  if (missing)
529
- throw new Error(UNKNOWN_JOB_RESULT);
530
- if (job?.id === id && job.phase === "failed") {
531
- terminal = true;
532
- throw new DaemonError(job.error ?? { name: "Error", message: "Daemon operation failed." });
533
- }
534
- if (job?.id === id && job.phase === "done") {
535
- terminal = true;
536
- signal?.throwIfAborted();
537
- return job.result;
538
- }
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);
539
341
  await this.wait(25, true);
540
342
  }
541
343
  throw new Error("Daemon client closed before operation completed.");
@@ -547,17 +349,50 @@ export class DaemonConnection {
547
349
  if (callback.job === id && !callback.kind.startsWith("queue-"))
548
350
  callback.controller.abort();
549
351
  try {
550
- await requestDaemon(paths, identity, "cancel", jobParams);
352
+ if (foreground) {
353
+ if (!this.uncertain)
354
+ await rpc("cancel", jobParams);
355
+ }
356
+ else
357
+ await requestDaemon(paths, identity, "cancel", jobParams);
551
358
  }
552
359
  catch (error) {
553
360
  this.markWorkUncertain();
554
- throw new Error("Operation outcome is uncertain; reload to reconnect and reconcile, never replay the write.", { cause: error });
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 });
555
364
  }
556
365
  }
557
366
  }).finally(() => {
558
367
  this.pendingJobs.delete(id);
559
368
  });
560
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
+ }
561
396
  markWorkUncertain() {
562
397
  this.uncertain = true;
563
398
  for (const callback of this.callbacks.values())
@@ -926,14 +761,17 @@ export class DaemonConnection {
926
761
  this.consume(reply);
927
762
  }
928
763
  finally {
929
- this.closed = true;
930
- this.controller.abort(new DOMException("Client disposed", "AbortError"));
931
- this.callbackIO.abort(new DOMException("Client callback transport disposed", "AbortError"));
932
- for (const { controller } of this.callbacks.values())
933
- controller.abort();
934
- await Promise.allSettled([this.polling, this.updates, ...this.callbackTasks]);
764
+ await this.closeLocal();
935
765
  }
936
766
  })();
937
767
  return this.disposing;
938
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
+ }
939
777
  }
@@ -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))))