@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
@@ -19,20 +19,22 @@ import {
19
19
  // src/daemon/pi-client.ts
20
20
  import { AsyncLocalStorage } from "node:async_hooks";
21
21
  import { randomUUID as randomUUID2 } from "node:crypto";
22
- import { realpathSync } from "node:fs";
22
+ import { lstatSync, realpathSync } from "node:fs";
23
23
  import fs from "node:fs/promises";
24
24
  import path2 from "node:path";
25
25
  import { getAgentDir } from "@earendil-works/pi-coding-agent";
26
26
  import {
27
27
  DaemonConnection as DaemonConnection2,
28
- DaemonError,
28
+ DaemonError as DaemonError2,
29
29
  documentFingerprint,
30
30
  ensureDaemon,
31
31
  findDaemon as findDaemon2,
32
32
  MAX_SETTINGS_BYTES,
33
33
  modelSignature,
34
+ OWNERSHIP_CLEANUP_REQUIRED,
34
35
  waitForDaemonExit
35
36
  } from "#pi-sync-daemon";
37
+ import { appendDebugEvent } from "#pi-sync-daemon/engine/debug-log";
36
38
  import { configureEngineHost } from "#pi-sync-daemon/engine/host";
37
39
  import {
38
40
  peekLocalConfigDocument
@@ -167,6 +169,117 @@ var PiApplyGate = class {
167
169
  }
168
170
  };
169
171
 
172
+ // src/daemon/client-debug.ts
173
+ import { debugOperation } from "#pi-sync-daemon/engine/debug-log";
174
+ function observeDebugJob(operation, append) {
175
+ const kind = debugOperation(operation);
176
+ if (!kind) return void 0;
177
+ let operationId;
178
+ const record = (outcome) => append({ event: "job", operation: kind, outcome, ...operationId ? { operationId } : {} });
179
+ return {
180
+ onSubmit(id) {
181
+ operationId = id;
182
+ record("started");
183
+ },
184
+ returned(result) {
185
+ if (result === "cancelled") record("cancelled");
186
+ else if (result === "archived" || kind === "initialize" && typeof result === "object" && result !== null && "handoverRequired" in result && result.handoverRequired === true)
187
+ record("blocked");
188
+ else if (kind === "migrate-state" && typeof result === "object" && result !== null && "status" in result && result.status === "cancelled")
189
+ record("cancelled");
190
+ else record("completed");
191
+ },
192
+ rejected(error, cancelled) {
193
+ if (cancelled || error instanceof Error && error.name === "AbortError") record("cancelled");
194
+ else if (error instanceof Error && (error.name === "SyncDecisionRequiredError" || error.name === "RemoteSelectionMismatchError"))
195
+ record("blocked");
196
+ else record("failed");
197
+ }
198
+ };
199
+ }
200
+
201
+ // src/daemon/directional-recovery.ts
202
+ function isForegroundDirection(operation) {
203
+ return operation === "push.foreground" || operation === "pull.foreground";
204
+ }
205
+ var DirectionalCheckpoint = class {
206
+ constructor(connection, expected) {
207
+ this.connection = connection;
208
+ this.expected = expected;
209
+ }
210
+ connection;
211
+ expected;
212
+ job;
213
+ fingerprint;
214
+ accept(connection, job, fingerprint2) {
215
+ if (connection !== this.connection || this.job !== job || typeof fingerprint2 !== "string" || !/^[a-f0-9]{64}$/u.test(fingerprint2) || this.expected !== void 0 && fingerprint2 !== this.expected || this.fingerprint !== void 0 && fingerprint2 !== this.fingerprint)
216
+ return false;
217
+ this.fingerprint = fingerprint2;
218
+ return true;
219
+ }
220
+ };
221
+ function recoveryOutcome(value) {
222
+ if (!value || typeof value !== "object" || !("foregroundQueueCleanup" in value)) return;
223
+ if (value.foregroundQueueCleanup === "before-mutation") return { phase: "unchanged" };
224
+ if (value.foregroundQueueCleanup === "verified-result" && "result" in value)
225
+ return { phase: "completed", result: value.result };
226
+ }
227
+ function restoreMessage(value) {
228
+ return value && typeof value === "object" && "message" in value && typeof value.message === "string" ? ` ${value.message}` : "";
229
+ }
230
+ var CompletedDirectionalRecoveryError = class extends Error {
231
+ };
232
+ function cancelledAfterCompletion(result, cause) {
233
+ const error = new CompletedDirectionalRecoveryError(
234
+ `The transfer finished, but file-queue recovery was cancelled.${restoreMessage(result)}`,
235
+ { cause }
236
+ );
237
+ error.name = "AbortError";
238
+ return error;
239
+ }
240
+ async function runDirectionalRecovery(connection, signal, run, recover, markCleanupRequired) {
241
+ signal.throwIfAborted();
242
+ const attempt2 = new DirectionalCheckpoint(connection);
243
+ const result = await run(attempt2);
244
+ const primary = recoveryOutcome(result);
245
+ if (!primary) return result;
246
+ markCleanupRequired();
247
+ let replacement;
248
+ const bounded = AbortSignal.any([signal, AbortSignal.timeout(45e3)]);
249
+ try {
250
+ bounded.throwIfAborted();
251
+ if (!attempt2.job || primary.phase === "unchanged" && !attempt2.fingerprint)
252
+ throw new Error("The original transfer scope could not be verified.");
253
+ replacement = await recover(connection, attempt2.job, bounded);
254
+ bounded.throwIfAborted();
255
+ } catch (error) {
256
+ if (signal.aborted) {
257
+ if (primary.phase === "completed") throw cancelledAfterCompletion(primary.result, signal.reason);
258
+ throw signal.reason;
259
+ }
260
+ const detail = bounded.aborted ? "The daemon did not recover in time." : errorMessage(error);
261
+ if (primary.phase === "completed")
262
+ throw new CompletedDirectionalRecoveryError(
263
+ `The transfer finished, but file-queue recovery stopped. ${detail}${restoreMessage(primary.result)}`,
264
+ { cause: error }
265
+ );
266
+ throw new Error(`No transfer was applied, but file-queue recovery stopped. ${detail}`, { cause: error });
267
+ }
268
+ if (primary.phase === "completed") return primary.result;
269
+ const retry = new DirectionalCheckpoint(replacement, attempt2.fingerprint);
270
+ const retried = await run(retry, attempt2.fingerprint);
271
+ const remaining = recoveryOutcome(retried);
272
+ if (!remaining) return retried;
273
+ markCleanupRequired();
274
+ if (remaining.phase === "completed") {
275
+ if (signal.aborted) throw cancelledAfterCompletion(remaining.result, signal.reason);
276
+ throw new CompletedDirectionalRecoveryError(
277
+ `Transfer finished, but file-queue cleanup is still uncertain after one recovery attempt.${restoreMessage(remaining.result)}`
278
+ );
279
+ }
280
+ throw new Error("File-queue release could not be verified after one recovery attempt. No transfer was applied.");
281
+ }
282
+
170
283
  // src/daemon/queue-release-ui.ts
171
284
  function createQueueReleaseUI(show, warn) {
172
285
  const retries = /* @__PURE__ */ new Map();
@@ -325,6 +438,28 @@ async function recoverDetachedClients(address) {
325
438
  );
326
439
  }
327
440
 
441
+ // src/daemon/startup-bootstrap-client.ts
442
+ import { DaemonError, requestDaemon } from "#pi-sync-daemon";
443
+ async function requestStartupBootstrap(connection, fingerprint2, debug, signal) {
444
+ let result;
445
+ try {
446
+ const { id: client, generation } = connection.facts;
447
+ result = await requestDaemon(
448
+ connection.paths,
449
+ connection.identity,
450
+ "startup.bootstrap",
451
+ { client, generation, fingerprint: fingerprint2, debug },
452
+ signal
453
+ );
454
+ } catch (error) {
455
+ if (error instanceof DaemonError && error.name === "Error" && error.message === "Unknown daemon method.")
456
+ return false;
457
+ throw error;
458
+ }
459
+ if (typeof result !== "boolean") throw new Error("Invalid startup bootstrap response.");
460
+ return result;
461
+ }
462
+
328
463
  // src/daemon/pi-client.ts
329
464
  var scope = new AsyncLocalStorage();
330
465
  var clients = /* @__PURE__ */ new WeakMap();
@@ -483,7 +618,7 @@ async function remoteOperation(ctx, operation, options) {
483
618
  return client.run(operation, payload, signal, ctx, onCommit, reload);
484
619
  }
485
620
  function remoteErrorNamed(error, name) {
486
- return error instanceof DaemonError && error.remote.name === name;
621
+ return error instanceof DaemonError2 && error.remote.name === name;
487
622
  }
488
623
  var PiDaemonClient = class {
489
624
  constructor(ctx, signal, publish) {
@@ -506,6 +641,7 @@ var PiDaemonClient = class {
506
641
  protectionOnly = false;
507
642
  partialConnection;
508
643
  work = Promise.resolve();
644
+ factsQueue = Promise.resolve();
509
645
  closing = false;
510
646
  paused = false;
511
647
  pausing;
@@ -535,9 +671,12 @@ var PiDaemonClient = class {
535
671
  uiContext;
536
672
  reloadRequest;
537
673
  pendingReload;
674
+ directionalCheckpoint;
675
+ recoveringDirectionalOwner = false;
538
676
  busy = /* @__PURE__ */ new Set();
539
677
  initialized = false;
540
678
  startupDebug = false;
679
+ debug = false;
541
680
  participantIdentity = { id: randomUUID2(), generation: randomUUID2() };
542
681
  get id() {
543
682
  return this.participantIdentity.id;
@@ -546,6 +685,8 @@ var PiDaemonClient = class {
546
685
  return this.participantIdentity.generation;
547
686
  }
548
687
  root;
688
+ cleanupRequired = false;
689
+ recoveredOwner;
549
690
  rawRoot;
550
691
  gate;
551
692
  manager;
@@ -557,6 +698,20 @@ var PiDaemonClient = class {
557
698
  if (getAgentDir() !== this.rawRoot || canonicalPath(path2.resolve(this.rawRoot)) !== this.root)
558
699
  throw new Error("Agent directory changed; reload before synchronization.");
559
700
  }
701
+ get debugEnabled() {
702
+ return this.debug;
703
+ }
704
+ setDebugPreference(debug) {
705
+ this.debug = debug && this.ctx.hasUI && (this.ctx.mode === "tui" || this.ctx.mode === "rpc");
706
+ }
707
+ recordDebug(event) {
708
+ if (!this.debug || this.protectionOnly || this.pendingReload || !this.ownsContactUI()) return;
709
+ try {
710
+ this.validate();
711
+ appendDebugEvent(this.root, "pi-sync", event);
712
+ } catch {
713
+ }
714
+ }
560
715
  modelBinding() {
561
716
  const model = this.ctx.model;
562
717
  if (!model) return void 0;
@@ -576,8 +731,8 @@ var PiDaemonClient = class {
576
731
  cwd: this.ctx.cwd,
577
732
  mode: this.ctx.mode,
578
733
  hasUI: !protectionOnly && this.ctx.hasUI,
579
- idle: !protectionOnly && !this.paused && !this.busy.size && this.ctx.isIdle(),
580
- ready: !protectionOnly && this.initialized,
734
+ idle: !protectionOnly && !this.recoveringDirectionalOwner && !this.paused && !this.busy.size && this.ctx.isIdle(),
735
+ ready: !protectionOnly && !this.recoveringDirectionalOwner && this.initialized,
581
736
  startupDebug: this.startupDebug,
582
737
  sessionFile: canonicalPath(manager.getSessionFile?.()),
583
738
  sessionId: manager.getSessionId?.(),
@@ -611,9 +766,18 @@ var PiDaemonClient = class {
611
766
  }
612
767
  async attachExisting({ allowUpgrade = false } = {}) {
613
768
  this.validate();
614
- const address = await findDaemon2(this.root);
769
+ this.assertNoDirectionalRecovery();
770
+ if (!allowUpgrade && !this.paused && this.connection?.contactState === "active") return !this.protectionOnly;
771
+ const address = await findDaemon2(this.root).catch((error) => {
772
+ this.recordDebug({ event: "connection", outcome: "failed" });
773
+ throw error;
774
+ });
615
775
  this.validate();
616
- if (!address) return false;
776
+ this.assertNoDirectionalRecovery();
777
+ if (!address) {
778
+ this.recordDebug({ event: "connection", outcome: "skipped" });
779
+ return false;
780
+ }
617
781
  const upgrade = allowUpgrade && address.needsUpgrade && this.ctx.hasUI && ["tui", "rpc"].includes(this.ctx.mode);
618
782
  let upgradeFailure;
619
783
  if (upgrade) {
@@ -623,7 +787,7 @@ var PiDaemonClient = class {
623
787
  return true;
624
788
  } catch (error) {
625
789
  this.validate();
626
- if (this.paused) throw error;
790
+ if (this.paused || this.recoveringDirectionalOwner) throw error;
627
791
  upgradeFailure = safeTerminalText(errorMessage(error));
628
792
  }
629
793
  }
@@ -644,14 +808,24 @@ var PiDaemonClient = class {
644
808
  }
645
809
  async finishReattachment() {
646
810
  this.validate();
647
- if (this.connection) {
648
- await recoverDetachedClients({ paths: this.connection.paths, identity: this.connection.identity });
649
- this.validate();
650
- await this.connection.attach(this.signal);
651
- this.validate();
652
- }
811
+ const connection = this.connection;
812
+ if (!connection) return;
813
+ await recoverDetachedClients(connection);
814
+ await this.queueFacts(async () => {
815
+ this.validateFactsScope(connection);
816
+ await connection.attach(this.signal);
817
+ this.validateFactsScope(connection);
818
+ });
819
+ }
820
+ assertNoDirectionalRecovery() {
821
+ if (this.recoveringDirectionalOwner)
822
+ throw new Error("Pi Sync is recovering the daemon for a transfer. Retry after recovery finishes.");
653
823
  }
654
824
  async connect(existing, requestSignal) {
825
+ this.assertNoDirectionalRecovery();
826
+ return this.attachConnection(existing, requestSignal);
827
+ }
828
+ async attachConnection(existing, requestSignal) {
655
829
  const startupSignal = requestSignal ? AbortSignal.any([this.signal, requestSignal]) : this.signal;
656
830
  const validateStartup = () => {
657
831
  this.validate();
@@ -683,7 +857,8 @@ var PiDaemonClient = class {
683
857
  if (daemon.paths.root !== this.root) throw new Error("Daemon root changed before attach.");
684
858
  const protectionOnly = daemon.needsUpgrade === true;
685
859
  const connection2 = new DaemonConnection2(daemon.paths, daemon.identity, this.facts(protectionOnly), {
686
- callback: (callback, signal) => this.callback(callback, signal, protectionOnly),
860
+ callback: (callback, signal) => this.callback(connection2, callback, signal, protectionOnly),
861
+ mergeReview: !protectionOnly && this.ctx.hasUI ? (callback, loadDetails, signal) => this.pagedMergeReview(connection2, callback, loadDetails, signal) : void 0,
687
862
  event: (event) => {
688
863
  if (event.kind === "commit") return;
689
864
  if (this.signal.aborted || this.disposed || this.closing || clients.get(this.manager) !== this) return;
@@ -703,7 +878,7 @@ var PiDaemonClient = class {
703
878
  contact: (state) => this.observeContact(connection2, state),
704
879
  queueRelease: (event) => this.observeQueueRelease(connection2, event),
705
880
  error: () => {
706
- if (this.ownsContactUI() && connection2.facts.hasUI && !this.releaseUI.retrying)
881
+ if (!this.recoveringDirectionalOwner && this.ownsContactUI() && connection2.facts.hasUI && !this.releaseUI.retrying)
707
882
  this.showContactStatus("sync service unavailable", "blocked", true);
708
883
  }
709
884
  });
@@ -711,7 +886,7 @@ var PiDaemonClient = class {
711
886
  try {
712
887
  await connection2.attach(startupSignal);
713
888
  } catch (error) {
714
- if (!(error instanceof DaemonError) || error.remote.name !== "DaemonStoppingError") throw error;
889
+ if (!(error instanceof DaemonError2) || error.remote.name !== "DaemonStoppingError") throw error;
715
890
  await connection2.dispose().catch(() => {
716
891
  });
717
892
  this.partialConnection = void 0;
@@ -734,10 +909,18 @@ var PiDaemonClient = class {
734
909
  this.partialConnection = void 0;
735
910
  return connection2;
736
911
  }
737
- })().catch((error) => {
738
- this.connecting = void 0;
739
- throw error;
740
- });
912
+ })().then(
913
+ (connection2) => {
914
+ this.recordDebug({ event: "connection", outcome: startupSignal.aborted ? "cancelled" : "completed" });
915
+ return connection2;
916
+ },
917
+ (error) => {
918
+ this.connecting = void 0;
919
+ const outcome = startupSignal.aborted ? "cancelled" : existing && remoteErrorNamed(error, "DaemonStoppingError") ? "skipped" : "failed";
920
+ this.recordDebug({ event: "connection", outcome });
921
+ throw error;
922
+ }
923
+ );
741
924
  const connection = await this.connecting;
742
925
  validateStartup();
743
926
  if (!existing && this.protectionOnly)
@@ -797,68 +980,98 @@ var PiDaemonClient = class {
797
980
  this.contactFactsUnpublished = false;
798
981
  this.clearConnectionStatus();
799
982
  }
800
- async resumeContact(connection) {
983
+ queueFacts(publish) {
984
+ const result = this.factsQueue.then(publish);
985
+ this.factsQueue = result.then(
986
+ () => {
987
+ },
988
+ () => {
989
+ }
990
+ );
991
+ return result;
992
+ }
993
+ async queueFactsWithAbortableWait(signal, publish) {
994
+ signal.throwIfAborted();
995
+ const cancelled = Promise.withResolvers();
996
+ const abort = () => cancelled.reject(signal.reason);
997
+ signal.addEventListener("abort", abort, { once: true });
998
+ const queued = this.queueFacts(() => {
999
+ signal.removeEventListener("abort", abort);
1000
+ signal.throwIfAborted();
1001
+ return publish();
1002
+ });
1003
+ return Promise.race([queued, cancelled.promise]);
1004
+ }
1005
+ validateFactsScope(connection, signal) {
801
1006
  this.validate();
802
- if (this.paused || this.connection !== connection) throw new Error("Pi Sync is paused for a session change.");
1007
+ signal?.throwIfAborted();
1008
+ if (this.paused) throw new Error("Pi Sync is paused for a session change.");
1009
+ if (connection && connection !== (this.connection ?? this.partialConnection))
1010
+ throw new Error("Synchronization session was replaced.");
1011
+ }
1012
+ async resumeContact(connection) {
1013
+ this.validateFactsScope(connection);
803
1014
  if (this.contactRepair) return this.contactRepair.done;
804
- if (connection.contactState === "active" && connection.contactResumeState !== "uncertain") return;
805
- if (this.gate.size || connection.hasPendingWork || connection.contactResumeState === "uncertain") {
806
- throw new Error(
807
- "Pi Sync cannot reconnect while previous work is still running or uncertain. Check sync recovery before retrying."
808
- );
809
- }
810
- const earlier = this.contactAttempt;
811
- if (connection.contactState !== "expired" || earlier) {
812
- throw new Error("Pi Sync could not restore contact. Review pending work before using /reload.", {
813
- cause: earlier?.error
814
- });
815
- }
816
1015
  const controller = new AbortController();
817
1016
  const signal = AbortSignal.any([this.signal, controller.signal]);
818
- const attempt2 = {};
819
- this.contactAttempt = attempt2;
820
- const done = Promise.resolve().then(async () => {
1017
+ const done = this.queueFacts(async () => {
1018
+ this.validateFactsScope(connection, signal);
1019
+ if (connection.contactState === "active" && connection.contactResumeState !== "uncertain") return;
1020
+ if (this.gate.size || connection.hasPendingWork || connection.contactResumeState === "uncertain") {
1021
+ throw new Error(
1022
+ "Pi Sync cannot reconnect while previous work is still running or uncertain. Check sync recovery before retrying."
1023
+ );
1024
+ }
1025
+ const earlier = this.contactAttempt;
1026
+ if (connection.contactState !== "expired" || earlier) {
1027
+ throw new Error("Pi Sync could not restore contact. Review pending work before using /reload.", {
1028
+ cause: earlier?.error
1029
+ });
1030
+ }
1031
+ const attempt2 = {};
1032
+ this.contactAttempt = attempt2;
821
1033
  try {
822
- this.validate();
823
- signal.throwIfAborted();
824
1034
  this.showContactStatus("sync reconnecting", "retry");
825
1035
  await connection.resumeContact({ ...this.facts(), idle: false, ready: false }, signal);
826
- this.validate();
827
- signal.throwIfAborted();
1036
+ this.validateFactsScope(connection, signal);
828
1037
  this.contactFactsUnpublished = true;
829
1038
  this.contactAttempt = void 0;
830
- await connection.update(this.facts());
831
- this.validate();
832
- signal.throwIfAborted();
833
- this.confirmContact(connection);
1039
+ await this.publishCurrentFacts(connection, signal);
1040
+ this.recordDebug({ event: "connection", outcome: "completed" });
834
1041
  } catch (error) {
1042
+ this.recordDebug({ event: "connection", outcome: signal.aborted ? "cancelled" : "failed" });
835
1043
  attempt2.error = error;
836
- if (this.ownsContactUI() && !signal.aborted)
1044
+ if (this.ownsContactUI() && !signal.aborted) {
1045
+ this.validateFactsScope(connection, signal);
837
1046
  this.showContactStatus("sync reconnect blocked; check /sync daemon status", "blocked");
1047
+ }
838
1048
  throw error;
839
- } finally {
840
- if (this.contactRepair?.controller === controller) this.contactRepair = void 0;
841
1049
  }
1050
+ }).finally(() => {
1051
+ if (this.contactRepair?.controller === controller) this.contactRepair = void 0;
842
1052
  });
843
1053
  this.contactRepair = { controller, done };
844
1054
  return done;
845
1055
  }
846
- async publishFacts(connection) {
847
- if (this.contactRepair) await this.contactRepair.done;
848
- this.validate();
849
- if (this.paused) throw new Error("Pi Sync is paused for a session change.");
1056
+ async publishCurrentFacts(connection, signal) {
1057
+ this.validateFactsScope(connection, signal);
850
1058
  if (connection.contactResumeState === "uncertain")
851
1059
  throw new Error("Pi Sync cannot verify the previous reconnect. Review pending work before using /reload.");
1060
+ await connection.update(this.facts());
1061
+ this.validateFactsScope(connection, signal);
1062
+ this.confirmContact(connection);
1063
+ }
1064
+ async publishFacts(connection, signal) {
1065
+ if (this.contactRepair) await this.contactRepair.done;
1066
+ const publish = () => this.queueFacts(() => this.publishCurrentFacts(connection, signal));
852
1067
  try {
853
- await connection.update(this.facts());
1068
+ await publish();
854
1069
  } catch (error) {
1070
+ this.validateFactsScope(connection, signal);
855
1071
  if (!connection.facts.hasUI || !remoteErrorNamed(error, "ClientContactExpiredError")) throw error;
856
1072
  await this.resumeContact(connection);
857
- this.validate();
858
- await connection.update(this.facts());
1073
+ await publish();
859
1074
  }
860
- this.validate();
861
- this.confirmContact(connection);
862
1075
  }
863
1076
  confirmContact(connection) {
864
1077
  if (connection.contactState === "expired" || connection.contactState === "inactive")
@@ -867,9 +1080,11 @@ var PiDaemonClient = class {
867
1080
  }
868
1081
  async verifyConnection(signal) {
869
1082
  const connection = await this.connect(void 0, signal);
870
- signal?.throwIfAborted();
871
- await this.publishFacts(connection);
872
- signal?.throwIfAborted();
1083
+ this.validateFactsScope(connection, signal);
1084
+ this.assertNoDirectionalRecovery();
1085
+ await this.publishFacts(connection, signal);
1086
+ this.validateFactsScope(connection, signal);
1087
+ this.assertNoDirectionalRecovery();
873
1088
  return connection;
874
1089
  }
875
1090
  async readSettings(repair = false) {
@@ -884,8 +1099,32 @@ var PiDaemonClient = class {
884
1099
  }
885
1100
  return decode(await this.run(repair ? "settings.repair-read" : "settings.read", {}));
886
1101
  }
1102
+ canReportDirectionalResult() {
1103
+ try {
1104
+ this.validateFactsScope();
1105
+ return !this.pendingReload;
1106
+ } catch {
1107
+ return false;
1108
+ }
1109
+ }
1110
+ get ownershipCleanupRequired() {
1111
+ return this.cleanupRequired;
1112
+ }
1113
+ confirmRecoveryExit(owner) {
1114
+ this.cleanupRequired = true;
1115
+ this.recoveredOwner = owner;
1116
+ }
1117
+ recordOwnershipFailure(error) {
1118
+ if (error instanceof DaemonError2 && error.remote.properties?.code === OWNERSHIP_CLEANUP_REQUIRED || error instanceof Error && ("code" in error && error.code === OWNERSHIP_CLEANUP_REQUIRED || error.message === "Daemon ownership cleanup is uncertain; stop and reconcile before restarting." || error.message === "Daemon ownership cleanup is uncertain; stop and reconcile before retrying." || error.message === "File-queue release is uncertain; stop the daemon and keep grants quarantined until owner exit."))
1119
+ this.cleanupRequired = true;
1120
+ }
887
1121
  run(operation, payload, signal, ctx = this.ctx, onCommit, reload) {
888
- const result = this.work.then(() => this.runCurrent(operation, payload, signal, ctx, onCommit, reload));
1122
+ const diagnostics = this.debug ? observeDebugJob(operation, (event) => this.recordDebug(event)) : void 0;
1123
+ const result = this.work.then(() => this.runCurrent(operation, payload, signal, ctx, onCommit, reload, diagnostics)).catch((error) => {
1124
+ diagnostics?.rejected(error, Boolean(signal?.aborted || reload?.signal.aborted));
1125
+ this.recordOwnershipFailure(error);
1126
+ throw error;
1127
+ });
889
1128
  this.work = result.then(
890
1129
  () => {
891
1130
  },
@@ -894,7 +1133,34 @@ var PiDaemonClient = class {
894
1133
  );
895
1134
  return result;
896
1135
  }
897
- async runCurrent(operation, payload, signal, ctx = this.ctx, onCommit, reload) {
1136
+ async recoverDirectionalOwner(connection, job, signal, assertRoot) {
1137
+ this.validateFactsScope(connection, signal);
1138
+ this.recoveringDirectionalOwner = true;
1139
+ try {
1140
+ this.stopContactRepair(true);
1141
+ await this.factsQueue;
1142
+ this.validateFactsScope(connection, signal);
1143
+ await connection.recoverForeground(job, signal);
1144
+ if (this.connection !== connection) throw new Error("The Pi participant changed during daemon recovery.");
1145
+ this.confirmRecoveryExit(connection.identity);
1146
+ await this.gate.releaseAfterDrain();
1147
+ this.connection = void 0;
1148
+ this.connecting = void 0;
1149
+ this.cleanupRequired = false;
1150
+ this.validateFactsScope(void 0, signal);
1151
+ assertRoot();
1152
+ const replacement = await ensureDaemon(this.root, signal, { compatibleOnly: true });
1153
+ this.validateFactsScope(void 0, signal);
1154
+ assertRoot();
1155
+ const attached = await this.attachConnection(replacement, signal);
1156
+ this.validateFactsScope(attached, signal);
1157
+ assertRoot();
1158
+ return attached;
1159
+ } finally {
1160
+ this.recoveringDirectionalOwner = false;
1161
+ }
1162
+ }
1163
+ async runCurrent(operation, payload, signal, ctx = this.ctx, onCommit, reload, diagnostics) {
898
1164
  this.validate();
899
1165
  signal?.throwIfAborted();
900
1166
  reload?.signal.throwIfAborted();
@@ -911,7 +1177,7 @@ var PiDaemonClient = class {
911
1177
  signal?.throwIfAborted();
912
1178
  if (this.paused)
913
1179
  await connection.update(this.facts());
914
- else await this.publishFacts(connection);
1180
+ else await this.publishFacts(connection, signal);
915
1181
  this.validate();
916
1182
  signal?.throwIfAborted();
917
1183
  this.uiContext = ctx;
@@ -922,7 +1188,43 @@ var PiDaemonClient = class {
922
1188
  const clearForeground = () => this.releaseUI.finishForeground(Boolean(this.releaseContext()));
923
1189
  runSignal.addEventListener("abort", clearForeground, { once: true });
924
1190
  try {
925
- const result = await connection.run(operation, payload, runSignal, onCommit);
1191
+ const root = isForegroundDirection(operation) ? lstatSync(this.root) : void 0;
1192
+ const assertRoot = () => {
1193
+ const current2 = lstatSync(this.root);
1194
+ if (!root || !current2.isDirectory() || current2.dev !== root.dev || current2.ino !== root.ino)
1195
+ throw new Error("The agent directory changed during the transfer.");
1196
+ };
1197
+ const intent = root ? structuredClone(payload) : payload;
1198
+ const result = root ? await runDirectionalRecovery(
1199
+ connection,
1200
+ runSignal,
1201
+ async (checkpoint, retryCheckpoint) => {
1202
+ const current2 = checkpoint.connection;
1203
+ this.validateFactsScope(current2, runSignal);
1204
+ assertRoot();
1205
+ this.directionalCheckpoint = checkpoint;
1206
+ try {
1207
+ return await current2.run(
1208
+ operation,
1209
+ retryCheckpoint === void 0 ? intent : { ...intent, retryCheckpoint },
1210
+ runSignal,
1211
+ onCommit,
1212
+ (id) => {
1213
+ checkpoint.job = id;
1214
+ diagnostics?.onSubmit(id);
1215
+ }
1216
+ );
1217
+ } finally {
1218
+ this.directionalCheckpoint = void 0;
1219
+ }
1220
+ },
1221
+ (owner, job, recoverySignal) => this.recoverDirectionalOwner(owner, job, recoverySignal, assertRoot),
1222
+ () => {
1223
+ this.cleanupRequired = true;
1224
+ }
1225
+ ) : await connection.run(operation, payload, runSignal, onCommit, diagnostics?.onSubmit);
1226
+ if (runSignal.aborted || reload?.signal.aborted) diagnostics?.rejected(void 0, true);
1227
+ else diagnostics?.returned(result);
926
1228
  if (request?.received && reload && !this.paused && !reload.signal.aborted && !signal?.aborted) {
927
1229
  this.validate();
928
1230
  this.pendingReload = reload;
@@ -930,7 +1232,7 @@ var PiDaemonClient = class {
930
1232
  }
931
1233
  return result;
932
1234
  } catch (error) {
933
- if (error instanceof DaemonError) {
1235
+ if (error instanceof DaemonError2) {
934
1236
  const prototype = error.name === "RemoteSelectionMismatchError" ? RemoteSelectionMismatchError.prototype : error.name === "SyncDecisionRequiredError" ? SyncDecisionRequiredError.prototype : void 0;
935
1237
  if (prototype) {
936
1238
  const restored = Object.create(prototype);
@@ -956,9 +1258,75 @@ var PiDaemonClient = class {
956
1258
  releaseReload(owner) {
957
1259
  if (this.pendingReload === owner) this.pendingReload = void 0;
958
1260
  }
1261
+ async readStartupSettings(signal) {
1262
+ this.validate();
1263
+ await settingsQueue;
1264
+ this.validate();
1265
+ signal.throwIfAborted();
1266
+ const document = await peekLocalConfigDocument();
1267
+ this.validate();
1268
+ signal.throwIfAborted();
1269
+ if (document && document.bytes.length > MAX_SETTINGS_BYTES)
1270
+ throw new Error("Settings exceed the local API byte limit; the source document is unchanged.");
1271
+ return { document, settings: document && validateSettingsDocument(document.parsed) };
1272
+ }
1273
+ tryStartupBootstrap(document, debug, signal) {
1274
+ const ownedSignal = AbortSignal.any([signal, this.signal]);
1275
+ let retirement;
1276
+ const operation = this.work.then(async () => {
1277
+ const verify = (connection2) => {
1278
+ this.validateFactsScope(connection2, ownedSignal);
1279
+ if (this.pendingReload) throw new Error("Pi Sync is paused for a session change.");
1280
+ };
1281
+ verify();
1282
+ const connection = await this.connect(void 0, ownedSignal);
1283
+ return this.queueFacts(async () => {
1284
+ verify(connection);
1285
+ if (connection.contactState !== "active" || connection.contactResumeState !== "idle") return false;
1286
+ const settingsFingerprint = fingerprint(document);
1287
+ let mayHavePublished = true;
1288
+ try {
1289
+ const ready = await requestStartupBootstrap(connection, settingsFingerprint, debug, ownedSignal);
1290
+ mayHavePublished = ready;
1291
+ verify(connection);
1292
+ if (!ready) return false;
1293
+ if (connection.contactState === "active") this.confirmContact(connection);
1294
+ this.startupDebug = debug;
1295
+ this.initialized = true;
1296
+ Object.assign(connection.facts, { ready: true, startupDebug: debug });
1297
+ return true;
1298
+ } catch (error) {
1299
+ if (mayHavePublished) {
1300
+ retirement = this.dispose();
1301
+ void retirement.catch(() => {
1302
+ });
1303
+ }
1304
+ throw error;
1305
+ }
1306
+ });
1307
+ });
1308
+ this.work = operation.then(
1309
+ () => {
1310
+ },
1311
+ () => {
1312
+ }
1313
+ );
1314
+ return operation.catch(async (error) => {
1315
+ try {
1316
+ await retirement;
1317
+ } catch (cause) {
1318
+ throw new AggregateError(
1319
+ [error, cause],
1320
+ "Startup readiness is uncertain; reconcile the daemon before reconnecting."
1321
+ );
1322
+ }
1323
+ throw error;
1324
+ });
1325
+ }
959
1326
  async markReady(debug) {
960
1327
  this.validate();
961
1328
  this.startupDebug = debug;
1329
+ this.setDebugPreference(debug);
962
1330
  this.initialized = true;
963
1331
  await this.update();
964
1332
  this.validate();
@@ -973,10 +1341,35 @@ var PiDaemonClient = class {
973
1341
  this.validate();
974
1342
  }
975
1343
  async update() {
976
- if (this.connection && !this.paused && !this.disposed && !this.signal.aborted)
1344
+ if (this.connection && !this.recoveringDirectionalOwner && !this.paused && !this.disposed && !this.signal.aborted)
977
1345
  await this.publishFacts(this.connection);
978
1346
  }
979
- async callback(callback, signal, protectionOnly) {
1347
+ async pagedMergeReview(connection, callback, loadDetails, signal) {
1348
+ const ctx = this.uiContext;
1349
+ const generation = this.generation;
1350
+ const combined = AbortSignal.any([signal, this.signal]);
1351
+ const isCurrent = () => !combined.aborted && this.ownsContactUI() && this.uiContext === ctx && this.generation === generation && (this.connection ?? this.partialConnection) === connection;
1352
+ if (!isCurrent()) return false;
1353
+ this.validate();
1354
+ if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) throw new Error("This client cannot present safety reviews.");
1355
+ const { title, confirmationLabel, summaryLines } = callback.payload;
1356
+ const { confirmMergeReview } = await import("./merge-review-AAC674C6.ts");
1357
+ if (!isCurrent()) return false;
1358
+ this.validate();
1359
+ const result = await confirmMergeReview(
1360
+ ctx,
1361
+ title,
1362
+ loadDetails,
1363
+ combined,
1364
+ isCurrent,
1365
+ confirmationLabel,
1366
+ summaryLines
1367
+ );
1368
+ if (!isCurrent()) return false;
1369
+ this.validate();
1370
+ return result;
1371
+ }
1372
+ async callback(connection, callback, signal, protectionOnly) {
980
1373
  const payload = callback.payload;
981
1374
  if (callback.kind === "queue-release") {
982
1375
  if (typeof payload?.reservation !== "string") throw new Error("Invalid queue release.");
@@ -986,6 +1379,10 @@ var PiDaemonClient = class {
986
1379
  this.validate();
987
1380
  signal.throwIfAborted();
988
1381
  if (this.paused) throw new Error("Pi session is changing; no new work is authorized.");
1382
+ if (callback.kind === "directional-checkpoint") {
1383
+ this.validateFactsScope(connection, this.runSignal);
1384
+ return !protectionOnly && this.directionalCheckpoint?.accept(connection, callback.job, payload?.fingerprint) === true;
1385
+ }
989
1386
  if (callback.kind === "queue-acquire") {
990
1387
  if (this.pendingReload) throw new Error("Pi resources are about to reload.");
991
1388
  if (payload.background && !this.facts().idle) throw new Error("Pi is busy; background apply was not granted.");
@@ -997,13 +1394,16 @@ var PiDaemonClient = class {
997
1394
  const combined = AbortSignal.any([signal, this.signal]);
998
1395
  if (callback.kind === "model-binding") {
999
1396
  if (protectionOnly) return null;
1000
- const facts = this.facts();
1001
- const connection = this.connection ?? this.partialConnection;
1002
- if (connection && JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model)) {
1003
- await connection.update(facts);
1004
- this.validate();
1005
- }
1006
- return payload.background && !facts.idle ? null : facts.model ?? null;
1397
+ return this.queueFactsWithAbortableWait(combined, async () => {
1398
+ this.validateFactsScope(connection, combined);
1399
+ let facts = this.facts();
1400
+ if (JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model)) {
1401
+ await connection.update(facts);
1402
+ this.validateFactsScope(connection, combined);
1403
+ facts = this.facts();
1404
+ }
1405
+ return payload.background && !facts.idle || JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model) ? null : facts.model ?? null;
1406
+ });
1007
1407
  }
1008
1408
  if (callback.kind === "reload") {
1009
1409
  if (!this.reloadRequest) throw new Error("No active Pi command can reload resources.");
@@ -1013,7 +1413,7 @@ var PiDaemonClient = class {
1013
1413
  if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) throw new Error("This client cannot present safety reviews.");
1014
1414
  let result;
1015
1415
  if (callback.kind === "merge-review" && typeof payload.title === "string" && typeof payload.content === "string") {
1016
- const { confirmMergeReview } = await import("./merge-review-OQDXNTJU.ts");
1416
+ const { confirmMergeReview } = await import("./merge-review-AAC674C6.ts");
1017
1417
  this.validate();
1018
1418
  combined.throwIfAborted();
1019
1419
  result = await confirmMergeReview(
@@ -1060,6 +1460,9 @@ var PiDaemonClient = class {
1060
1460
  try {
1061
1461
  await connection?.dispose(handoff);
1062
1462
  confirmed = Boolean(connection);
1463
+ } catch (error) {
1464
+ if (!connection || connection.identity.root !== this.recoveredOwner?.root || connection.identity.instance !== this.recoveredOwner.instance || connection.identity.pid !== this.recoveredOwner.pid)
1465
+ throw error;
1063
1466
  } finally {
1064
1467
  this.disposed = true;
1065
1468
  if (clients.get(this.manager) === this) clients.delete(this.manager);
@@ -1069,7 +1472,7 @@ var PiDaemonClient = class {
1069
1472
  if (confirmed) await gate.releaseAfterDrain();
1070
1473
  else quarantineClient(gate, connection.paths.root, connection.identity, connection.facts);
1071
1474
  }
1072
- await this.work;
1475
+ await Promise.all([this.work, this.factsQueue]);
1073
1476
  }
1074
1477
  })();
1075
1478
  return this.disposing;
@@ -1077,6 +1480,7 @@ var PiDaemonClient = class {
1077
1480
  };
1078
1481
 
1079
1482
  export {
1483
+ CompletedDirectionalRecoveryError,
1080
1484
  currentPiDaemonClient,
1081
1485
  installPiDaemonHost,
1082
1486
  bindPiDaemonClient,
@@ -1084,4 +1488,4 @@ export {
1084
1488
  withPiDaemonClient,
1085
1489
  remoteOperation
1086
1490
  };
1087
- //# sourceMappingURL=chunk-B5F3JLD3.ts.map
1491
+ //# sourceMappingURL=chunk-JQ5BAWW2.ts.map