@narumitw/pi-sync 0.63.0 → 0.64.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 (135) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +28 -18
  3. package/dist/chunks/{chunk-HLCML3OW.ts → chunk-4VKWHVUO.ts} +4 -3
  4. package/dist/chunks/chunk-4VKWHVUO.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-V76KCWHO.ts → chunk-F3VODLVQ.ts} +3 -3
  8. package/dist/chunks/{chunk-VQ47JBLF.ts → chunk-FI2F5JBS.ts} +2 -2
  9. package/dist/chunks/{chunk-S6FUUWV5.ts → chunk-NDEZ52SS.ts} +13 -13
  10. package/dist/chunks/{chunk-S6FUUWV5.ts.map → chunk-NDEZ52SS.ts.map} +1 -1
  11. package/dist/chunks/{chunk-UGS6RYDZ.ts → chunk-RW44KNFD.ts} +304 -70
  12. package/dist/chunks/chunk-RW44KNFD.ts.map +7 -0
  13. package/dist/chunks/{chunk-EXDWEFIJ.ts → chunk-TJ7YNITN.ts} +5 -5
  14. package/dist/chunks/{chunk-HSCAFOT5.ts → chunk-TZMVSTAM.ts} +5 -5
  15. package/dist/chunks/{chunk-SXCH4Q5O.ts → chunk-VPSC7BXM.ts} +3 -3
  16. package/dist/chunks/chunk-YT6PDRMM.ts +282 -0
  17. package/dist/chunks/chunk-YT6PDRMM.ts.map +7 -0
  18. package/dist/chunks/{command-handler-VINMQ7ZM.ts → command-handler-N45GY7AV.ts} +39 -27
  19. package/dist/chunks/command-handler-N45GY7AV.ts.map +7 -0
  20. package/dist/chunks/{conflict-review-PCDFRIVB.ts → conflict-review-5E4M44BA.ts} +2 -2
  21. package/dist/chunks/{file-selection-KID23GAD.ts → file-selection-DDQN4LVD.ts} +9 -9
  22. package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts → manager-result-dispatcher-FKW55L7I.ts} +5 -5
  23. package/dist/chunks/{manager-ui-YHDECYKI.ts → manager-ui-EV23DPZQ.ts} +104 -77
  24. package/dist/chunks/manager-ui-EV23DPZQ.ts.map +7 -0
  25. package/dist/chunks/{merge-review-SGDLMVS4.ts → merge-review-6YSLSMGS.ts} +3 -2
  26. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts +59 -0
  27. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts.map +7 -0
  28. package/dist/chunks/{remote-selection-ui-GPITNEBF.ts → remote-selection-ui-N4NMWFT2.ts} +4 -4
  29. package/dist/chunks/{setup-switch-L54X5U5I.ts → setup-switch-HY7K3442.ts} +4 -4
  30. package/dist/chunks/{setup-wizard-YO4MCPUF.ts → setup-wizard-LEKDQ3HK.ts} +9 -9
  31. package/dist/chunks/{sync-inspection-H2WX5SUT.ts → sync-inspection-OS2LVOLV.ts} +5 -5
  32. package/dist/chunks/{sync-operations-2MZAYHL2.ts → sync-operations-D3MDJUQQ.ts} +2 -2
  33. package/dist/daemon/dist/cli.js +2 -0
  34. package/dist/daemon/dist/client-transport.js +66 -0
  35. package/dist/daemon/dist/client.js +116 -86
  36. package/dist/daemon/dist/consent.js +33 -11
  37. package/dist/daemon/dist/daemon-debug.js +33 -0
  38. package/dist/daemon/dist/daemon-recovery.js +75 -0
  39. package/dist/daemon/dist/engine/backends/git/git-backend.js +39 -12
  40. package/dist/daemon/dist/engine/backends/git/git-runner.js +6 -1
  41. package/dist/daemon/dist/engine/backends/git/git-storage.js +5 -9
  42. package/dist/daemon/dist/engine/backends/publication-encoding.js +19 -0
  43. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +10 -12
  44. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +15 -26
  45. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +10 -0
  46. package/dist/daemon/dist/engine/debug-log.js +134 -0
  47. package/dist/daemon/dist/engine/ignore/ignore-initialization.js +50 -14
  48. package/dist/daemon/dist/engine/ignore/ignore-settings.js +11 -14
  49. package/dist/daemon/dist/engine/ignore/ignore-source.js +1 -1
  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/initialization.js +2 -2
  62. package/dist/daemon/dist/engine/sync/local-fields.js +42 -19
  63. package/dist/daemon/dist/engine/sync/merged-sync.js +13 -10
  64. package/dist/daemon/dist/engine/sync/remote-snapshot.js +18 -3
  65. package/dist/daemon/dist/engine/sync/session-push.js +13 -4
  66. package/dist/daemon/dist/engine/sync/startup-bootstrap.js +105 -0
  67. package/dist/daemon/dist/engine/sync/startup-recovery-evidence.js +37 -0
  68. package/dist/daemon/dist/engine/sync/startup-timings.js +80 -8
  69. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +22 -4
  70. package/dist/daemon/dist/engine/sync/sync-inspection.js +4 -7
  71. package/dist/daemon/dist/engine/sync/sync-local.js +3 -1
  72. package/dist/daemon/dist/engine/sync/sync-mutations.js +13 -7
  73. package/dist/daemon/dist/engine/sync/sync-policy.js +9 -1
  74. package/dist/daemon/dist/engine/sync/sync-state.js +12 -4
  75. package/dist/daemon/dist/engine/ui/sync-format.js +23 -55
  76. package/dist/daemon/dist/engine/ui/transfer-review.js +3 -3
  77. package/dist/daemon/dist/engine-service.js +54 -10
  78. package/dist/daemon/dist/identity.js +36 -6
  79. package/dist/daemon/dist/index.js +2 -1
  80. package/dist/daemon/dist/monitor.js +20 -1
  81. package/dist/daemon/dist/paged-review.js +177 -0
  82. package/dist/daemon/dist/participant-ledger.js +149 -0
  83. package/dist/daemon/dist/protocol.js +4 -0
  84. package/dist/daemon/dist/server.js +268 -120
  85. package/dist/daemon/dist/service-host.js +29 -9
  86. package/dist/daemon/dist/state-wait-jobs.js +23 -0
  87. package/dist/daemon/dist/state-wait.js +34 -0
  88. package/dist/daemon/package.json +1 -1
  89. package/dist/index.ts +128 -48
  90. package/dist/index.ts.map +2 -2
  91. package/docs/continuous-sync-verification.md +2 -0
  92. package/docs/daemon-migration.md +30 -2
  93. package/docs/tui-contract.md +8 -2
  94. package/package.json +2 -2
  95. package/skills/configure-pi-sync/SKILL.md +119 -18
  96. package/skills/configure-pi-sync/references/configuration.md +88 -48
  97. package/src/commands/command-execution.ts +11 -3
  98. package/src/commands/command-handler.ts +10 -3
  99. package/src/commands/command.ts +3 -2
  100. package/src/daemon/client-debug.ts +45 -0
  101. package/src/daemon/ownership-recovery.ts +50 -0
  102. package/src/daemon/pi-client.ts +288 -63
  103. package/src/daemon/startup-bootstrap-client.ts +26 -0
  104. package/src/settings/config.ts +1 -0
  105. package/src/sync/automatic-sync.ts +61 -18
  106. package/src/sync/startup-check.ts +13 -5
  107. package/src/sync-extension.ts +46 -8
  108. package/src/ui/manager-state.ts +35 -24
  109. package/src/ui/manager-ui.ts +39 -18
  110. package/src/ui/merge-review.ts +75 -12
  111. package/src/ui/settings-ui.ts +2 -2
  112. package/src/ui/setup/webdav-ui.ts +1 -1
  113. package/src/ui/sync-confirmation.ts +81 -65
  114. package/src/ui/sync-setups-ui.ts +15 -12
  115. package/dist/chunks/chunk-27F5W7DX.ts.map +0 -7
  116. package/dist/chunks/chunk-GSQGBVKG.ts +0 -218
  117. package/dist/chunks/chunk-GSQGBVKG.ts.map +0 -7
  118. package/dist/chunks/chunk-HLCML3OW.ts.map +0 -7
  119. package/dist/chunks/chunk-UGS6RYDZ.ts.map +0 -7
  120. package/dist/chunks/command-handler-VINMQ7ZM.ts.map +0 -7
  121. package/dist/chunks/manager-ui-YHDECYKI.ts.map +0 -7
  122. /package/dist/chunks/{chunk-V76KCWHO.ts.map → chunk-F3VODLVQ.ts.map} +0 -0
  123. /package/dist/chunks/{chunk-VQ47JBLF.ts.map → chunk-FI2F5JBS.ts.map} +0 -0
  124. /package/dist/chunks/{chunk-EXDWEFIJ.ts.map → chunk-TJ7YNITN.ts.map} +0 -0
  125. /package/dist/chunks/{chunk-HSCAFOT5.ts.map → chunk-TZMVSTAM.ts.map} +0 -0
  126. /package/dist/chunks/{chunk-SXCH4Q5O.ts.map → chunk-VPSC7BXM.ts.map} +0 -0
  127. /package/dist/chunks/{conflict-review-PCDFRIVB.ts.map → conflict-review-5E4M44BA.ts.map} +0 -0
  128. /package/dist/chunks/{file-selection-KID23GAD.ts.map → file-selection-DDQN4LVD.ts.map} +0 -0
  129. /package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts.map → manager-result-dispatcher-FKW55L7I.ts.map} +0 -0
  130. /package/dist/chunks/{merge-review-SGDLMVS4.ts.map → merge-review-6YSLSMGS.ts.map} +0 -0
  131. /package/dist/chunks/{remote-selection-ui-GPITNEBF.ts.map → remote-selection-ui-N4NMWFT2.ts.map} +0 -0
  132. /package/dist/chunks/{setup-switch-L54X5U5I.ts.map → setup-switch-HY7K3442.ts.map} +0 -0
  133. /package/dist/chunks/{setup-wizard-YO4MCPUF.ts.map → setup-wizard-LEKDQ3HK.ts.map} +0 -0
  134. /package/dist/chunks/{sync-inspection-H2WX5SUT.ts.map → sync-inspection-OS2LVOLV.ts.map} +0 -0
  135. /package/dist/chunks/{sync-operations-2MZAYHL2.ts.map → sync-operations-D3MDJUQQ.ts.map} +0 -0
@@ -25,14 +25,16 @@ 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,35 @@ 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
+
170
201
  // src/daemon/queue-release-ui.ts
171
202
  function createQueueReleaseUI(show, warn) {
172
203
  const retries = /* @__PURE__ */ new Map();
@@ -325,6 +356,28 @@ async function recoverDetachedClients(address) {
325
356
  );
326
357
  }
327
358
 
359
+ // src/daemon/startup-bootstrap-client.ts
360
+ import { DaemonError, requestDaemon } from "#pi-sync-daemon";
361
+ async function requestStartupBootstrap(connection, fingerprint2, debug, signal) {
362
+ let result;
363
+ try {
364
+ const { id: client, generation } = connection.facts;
365
+ result = await requestDaemon(
366
+ connection.paths,
367
+ connection.identity,
368
+ "startup.bootstrap",
369
+ { client, generation, fingerprint: fingerprint2, debug },
370
+ signal
371
+ );
372
+ } catch (error) {
373
+ if (error instanceof DaemonError && error.name === "Error" && error.message === "Unknown daemon method.")
374
+ return false;
375
+ throw error;
376
+ }
377
+ if (typeof result !== "boolean") throw new Error("Invalid startup bootstrap response.");
378
+ return result;
379
+ }
380
+
328
381
  // src/daemon/pi-client.ts
329
382
  var scope = new AsyncLocalStorage();
330
383
  var clients = /* @__PURE__ */ new WeakMap();
@@ -483,7 +536,7 @@ async function remoteOperation(ctx, operation, options) {
483
536
  return client.run(operation, payload, signal, ctx, onCommit, reload);
484
537
  }
485
538
  function remoteErrorNamed(error, name) {
486
- return error instanceof DaemonError && error.remote.name === name;
539
+ return error instanceof DaemonError2 && error.remote.name === name;
487
540
  }
488
541
  var PiDaemonClient = class {
489
542
  constructor(ctx, signal, publish) {
@@ -506,6 +559,7 @@ var PiDaemonClient = class {
506
559
  protectionOnly = false;
507
560
  partialConnection;
508
561
  work = Promise.resolve();
562
+ factsQueue = Promise.resolve();
509
563
  closing = false;
510
564
  paused = false;
511
565
  pausing;
@@ -538,6 +592,7 @@ var PiDaemonClient = class {
538
592
  busy = /* @__PURE__ */ new Set();
539
593
  initialized = false;
540
594
  startupDebug = false;
595
+ debug = false;
541
596
  participantIdentity = { id: randomUUID2(), generation: randomUUID2() };
542
597
  get id() {
543
598
  return this.participantIdentity.id;
@@ -546,6 +601,8 @@ var PiDaemonClient = class {
546
601
  return this.participantIdentity.generation;
547
602
  }
548
603
  root;
604
+ cleanupRequired = false;
605
+ recoveredOwner;
549
606
  rawRoot;
550
607
  gate;
551
608
  manager;
@@ -557,6 +614,20 @@ var PiDaemonClient = class {
557
614
  if (getAgentDir() !== this.rawRoot || canonicalPath(path2.resolve(this.rawRoot)) !== this.root)
558
615
  throw new Error("Agent directory changed; reload before synchronization.");
559
616
  }
617
+ get debugEnabled() {
618
+ return this.debug;
619
+ }
620
+ setDebugPreference(debug) {
621
+ this.debug = debug && this.ctx.hasUI && (this.ctx.mode === "tui" || this.ctx.mode === "rpc");
622
+ }
623
+ recordDebug(event) {
624
+ if (!this.debug || this.protectionOnly || this.pendingReload || !this.ownsContactUI()) return;
625
+ try {
626
+ this.validate();
627
+ appendDebugEvent(this.root, "pi-sync", event);
628
+ } catch {
629
+ }
630
+ }
560
631
  modelBinding() {
561
632
  const model = this.ctx.model;
562
633
  if (!model) return void 0;
@@ -611,9 +682,16 @@ var PiDaemonClient = class {
611
682
  }
612
683
  async attachExisting({ allowUpgrade = false } = {}) {
613
684
  this.validate();
614
- const address = await findDaemon2(this.root);
685
+ if (!allowUpgrade && !this.paused && this.connection?.contactState === "active") return !this.protectionOnly;
686
+ const address = await findDaemon2(this.root).catch((error) => {
687
+ this.recordDebug({ event: "connection", outcome: "failed" });
688
+ throw error;
689
+ });
615
690
  this.validate();
616
- if (!address) return false;
691
+ if (!address) {
692
+ this.recordDebug({ event: "connection", outcome: "skipped" });
693
+ return false;
694
+ }
617
695
  const upgrade = allowUpgrade && address.needsUpgrade && this.ctx.hasUI && ["tui", "rpc"].includes(this.ctx.mode);
618
696
  let upgradeFailure;
619
697
  if (upgrade) {
@@ -644,12 +722,14 @@ var PiDaemonClient = class {
644
722
  }
645
723
  async finishReattachment() {
646
724
  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
- }
725
+ const connection = this.connection;
726
+ if (!connection) return;
727
+ await recoverDetachedClients(connection);
728
+ await this.queueFacts(async () => {
729
+ this.validateFactsScope(connection);
730
+ await connection.attach(this.signal);
731
+ this.validateFactsScope(connection);
732
+ });
653
733
  }
654
734
  async connect(existing, requestSignal) {
655
735
  const startupSignal = requestSignal ? AbortSignal.any([this.signal, requestSignal]) : this.signal;
@@ -683,7 +763,8 @@ var PiDaemonClient = class {
683
763
  if (daemon.paths.root !== this.root) throw new Error("Daemon root changed before attach.");
684
764
  const protectionOnly = daemon.needsUpgrade === true;
685
765
  const connection2 = new DaemonConnection2(daemon.paths, daemon.identity, this.facts(protectionOnly), {
686
- callback: (callback, signal) => this.callback(callback, signal, protectionOnly),
766
+ callback: (callback, signal) => this.callback(connection2, callback, signal, protectionOnly),
767
+ mergeReview: !protectionOnly && this.ctx.hasUI ? (callback, loadDetails, signal) => this.pagedMergeReview(connection2, callback, loadDetails, signal) : void 0,
687
768
  event: (event) => {
688
769
  if (event.kind === "commit") return;
689
770
  if (this.signal.aborted || this.disposed || this.closing || clients.get(this.manager) !== this) return;
@@ -711,7 +792,7 @@ var PiDaemonClient = class {
711
792
  try {
712
793
  await connection2.attach(startupSignal);
713
794
  } catch (error) {
714
- if (!(error instanceof DaemonError) || error.remote.name !== "DaemonStoppingError") throw error;
795
+ if (!(error instanceof DaemonError2) || error.remote.name !== "DaemonStoppingError") throw error;
715
796
  await connection2.dispose().catch(() => {
716
797
  });
717
798
  this.partialConnection = void 0;
@@ -734,10 +815,18 @@ var PiDaemonClient = class {
734
815
  this.partialConnection = void 0;
735
816
  return connection2;
736
817
  }
737
- })().catch((error) => {
738
- this.connecting = void 0;
739
- throw error;
740
- });
818
+ })().then(
819
+ (connection2) => {
820
+ this.recordDebug({ event: "connection", outcome: startupSignal.aborted ? "cancelled" : "completed" });
821
+ return connection2;
822
+ },
823
+ (error) => {
824
+ this.connecting = void 0;
825
+ const outcome = startupSignal.aborted ? "cancelled" : existing && remoteErrorNamed(error, "DaemonStoppingError") ? "skipped" : "failed";
826
+ this.recordDebug({ event: "connection", outcome });
827
+ throw error;
828
+ }
829
+ );
741
830
  const connection = await this.connecting;
742
831
  validateStartup();
743
832
  if (!existing && this.protectionOnly)
@@ -797,68 +886,98 @@ var PiDaemonClient = class {
797
886
  this.contactFactsUnpublished = false;
798
887
  this.clearConnectionStatus();
799
888
  }
800
- async resumeContact(connection) {
889
+ queueFacts(publish) {
890
+ const result = this.factsQueue.then(publish);
891
+ this.factsQueue = result.then(
892
+ () => {
893
+ },
894
+ () => {
895
+ }
896
+ );
897
+ return result;
898
+ }
899
+ async queueFactsWithAbortableWait(signal, publish) {
900
+ signal.throwIfAborted();
901
+ const cancelled = Promise.withResolvers();
902
+ const abort = () => cancelled.reject(signal.reason);
903
+ signal.addEventListener("abort", abort, { once: true });
904
+ const queued = this.queueFacts(() => {
905
+ signal.removeEventListener("abort", abort);
906
+ signal.throwIfAborted();
907
+ return publish();
908
+ });
909
+ return Promise.race([queued, cancelled.promise]);
910
+ }
911
+ validateFactsScope(connection, signal) {
801
912
  this.validate();
802
- if (this.paused || this.connection !== connection) throw new Error("Pi Sync is paused for a session change.");
913
+ signal?.throwIfAborted();
914
+ if (this.paused) throw new Error("Pi Sync is paused for a session change.");
915
+ if (connection && connection !== (this.connection ?? this.partialConnection))
916
+ throw new Error("Synchronization session was replaced.");
917
+ }
918
+ async resumeContact(connection) {
919
+ this.validateFactsScope(connection);
803
920
  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
921
  const controller = new AbortController();
817
922
  const signal = AbortSignal.any([this.signal, controller.signal]);
818
- const attempt2 = {};
819
- this.contactAttempt = attempt2;
820
- const done = Promise.resolve().then(async () => {
923
+ const done = this.queueFacts(async () => {
924
+ this.validateFactsScope(connection, signal);
925
+ if (connection.contactState === "active" && connection.contactResumeState !== "uncertain") return;
926
+ if (this.gate.size || connection.hasPendingWork || connection.contactResumeState === "uncertain") {
927
+ throw new Error(
928
+ "Pi Sync cannot reconnect while previous work is still running or uncertain. Check sync recovery before retrying."
929
+ );
930
+ }
931
+ const earlier = this.contactAttempt;
932
+ if (connection.contactState !== "expired" || earlier) {
933
+ throw new Error("Pi Sync could not restore contact. Review pending work before using /reload.", {
934
+ cause: earlier?.error
935
+ });
936
+ }
937
+ const attempt2 = {};
938
+ this.contactAttempt = attempt2;
821
939
  try {
822
- this.validate();
823
- signal.throwIfAborted();
824
940
  this.showContactStatus("sync reconnecting", "retry");
825
941
  await connection.resumeContact({ ...this.facts(), idle: false, ready: false }, signal);
826
- this.validate();
827
- signal.throwIfAborted();
942
+ this.validateFactsScope(connection, signal);
828
943
  this.contactFactsUnpublished = true;
829
944
  this.contactAttempt = void 0;
830
- await connection.update(this.facts());
831
- this.validate();
832
- signal.throwIfAborted();
833
- this.confirmContact(connection);
945
+ await this.publishCurrentFacts(connection, signal);
946
+ this.recordDebug({ event: "connection", outcome: "completed" });
834
947
  } catch (error) {
948
+ this.recordDebug({ event: "connection", outcome: signal.aborted ? "cancelled" : "failed" });
835
949
  attempt2.error = error;
836
- if (this.ownsContactUI() && !signal.aborted)
950
+ if (this.ownsContactUI() && !signal.aborted) {
951
+ this.validateFactsScope(connection, signal);
837
952
  this.showContactStatus("sync reconnect blocked; check /sync daemon status", "blocked");
953
+ }
838
954
  throw error;
839
- } finally {
840
- if (this.contactRepair?.controller === controller) this.contactRepair = void 0;
841
955
  }
956
+ }).finally(() => {
957
+ if (this.contactRepair?.controller === controller) this.contactRepair = void 0;
842
958
  });
843
959
  this.contactRepair = { controller, done };
844
960
  return done;
845
961
  }
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.");
962
+ async publishCurrentFacts(connection, signal) {
963
+ this.validateFactsScope(connection, signal);
850
964
  if (connection.contactResumeState === "uncertain")
851
965
  throw new Error("Pi Sync cannot verify the previous reconnect. Review pending work before using /reload.");
966
+ await connection.update(this.facts());
967
+ this.validateFactsScope(connection, signal);
968
+ this.confirmContact(connection);
969
+ }
970
+ async publishFacts(connection, signal) {
971
+ if (this.contactRepair) await this.contactRepair.done;
972
+ const publish = () => this.queueFacts(() => this.publishCurrentFacts(connection, signal));
852
973
  try {
853
- await connection.update(this.facts());
974
+ await publish();
854
975
  } catch (error) {
976
+ this.validateFactsScope(connection, signal);
855
977
  if (!connection.facts.hasUI || !remoteErrorNamed(error, "ClientContactExpiredError")) throw error;
856
978
  await this.resumeContact(connection);
857
- this.validate();
858
- await connection.update(this.facts());
979
+ await publish();
859
980
  }
860
- this.validate();
861
- this.confirmContact(connection);
862
981
  }
863
982
  confirmContact(connection) {
864
983
  if (connection.contactState === "expired" || connection.contactState === "inactive")
@@ -868,7 +987,7 @@ var PiDaemonClient = class {
868
987
  async verifyConnection(signal) {
869
988
  const connection = await this.connect(void 0, signal);
870
989
  signal?.throwIfAborted();
871
- await this.publishFacts(connection);
990
+ await this.publishFacts(connection, signal);
872
991
  signal?.throwIfAborted();
873
992
  return connection;
874
993
  }
@@ -884,8 +1003,24 @@ var PiDaemonClient = class {
884
1003
  }
885
1004
  return decode(await this.run(repair ? "settings.repair-read" : "settings.read", {}));
886
1005
  }
1006
+ get ownershipCleanupRequired() {
1007
+ return this.cleanupRequired;
1008
+ }
1009
+ confirmRecoveryExit(owner) {
1010
+ this.cleanupRequired = true;
1011
+ this.recoveredOwner = owner;
1012
+ }
1013
+ recordOwnershipFailure(error) {
1014
+ 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."))
1015
+ this.cleanupRequired = true;
1016
+ }
887
1017
  run(operation, payload, signal, ctx = this.ctx, onCommit, reload) {
888
- const result = this.work.then(() => this.runCurrent(operation, payload, signal, ctx, onCommit, reload));
1018
+ const diagnostics = this.debug ? observeDebugJob(operation, (event) => this.recordDebug(event)) : void 0;
1019
+ const result = this.work.then(() => this.runCurrent(operation, payload, signal, ctx, onCommit, reload, diagnostics)).catch((error) => {
1020
+ diagnostics?.rejected(error, Boolean(signal?.aborted || reload?.signal.aborted));
1021
+ this.recordOwnershipFailure(error);
1022
+ throw error;
1023
+ });
889
1024
  this.work = result.then(
890
1025
  () => {
891
1026
  },
@@ -894,7 +1029,7 @@ var PiDaemonClient = class {
894
1029
  );
895
1030
  return result;
896
1031
  }
897
- async runCurrent(operation, payload, signal, ctx = this.ctx, onCommit, reload) {
1032
+ async runCurrent(operation, payload, signal, ctx = this.ctx, onCommit, reload, diagnostics) {
898
1033
  this.validate();
899
1034
  signal?.throwIfAborted();
900
1035
  reload?.signal.throwIfAborted();
@@ -911,7 +1046,7 @@ var PiDaemonClient = class {
911
1046
  signal?.throwIfAborted();
912
1047
  if (this.paused)
913
1048
  await connection.update(this.facts());
914
- else await this.publishFacts(connection);
1049
+ else await this.publishFacts(connection, signal);
915
1050
  this.validate();
916
1051
  signal?.throwIfAborted();
917
1052
  this.uiContext = ctx;
@@ -922,7 +1057,9 @@ var PiDaemonClient = class {
922
1057
  const clearForeground = () => this.releaseUI.finishForeground(Boolean(this.releaseContext()));
923
1058
  runSignal.addEventListener("abort", clearForeground, { once: true });
924
1059
  try {
925
- const result = await connection.run(operation, payload, runSignal, onCommit);
1060
+ const result = await connection.run(operation, payload, runSignal, onCommit, diagnostics?.onSubmit);
1061
+ if (runSignal.aborted || reload?.signal.aborted) diagnostics?.rejected(void 0, true);
1062
+ else diagnostics?.returned(result);
926
1063
  if (request?.received && reload && !this.paused && !reload.signal.aborted && !signal?.aborted) {
927
1064
  this.validate();
928
1065
  this.pendingReload = reload;
@@ -930,7 +1067,7 @@ var PiDaemonClient = class {
930
1067
  }
931
1068
  return result;
932
1069
  } catch (error) {
933
- if (error instanceof DaemonError) {
1070
+ if (error instanceof DaemonError2) {
934
1071
  const prototype = error.name === "RemoteSelectionMismatchError" ? RemoteSelectionMismatchError.prototype : error.name === "SyncDecisionRequiredError" ? SyncDecisionRequiredError.prototype : void 0;
935
1072
  if (prototype) {
936
1073
  const restored = Object.create(prototype);
@@ -956,9 +1093,75 @@ var PiDaemonClient = class {
956
1093
  releaseReload(owner) {
957
1094
  if (this.pendingReload === owner) this.pendingReload = void 0;
958
1095
  }
1096
+ async readStartupSettings(signal) {
1097
+ this.validate();
1098
+ await settingsQueue;
1099
+ this.validate();
1100
+ signal.throwIfAborted();
1101
+ const document = await peekLocalConfigDocument();
1102
+ this.validate();
1103
+ signal.throwIfAborted();
1104
+ if (document && document.bytes.length > MAX_SETTINGS_BYTES)
1105
+ throw new Error("Settings exceed the local API byte limit; the source document is unchanged.");
1106
+ return { document, settings: document && validateSettingsDocument(document.parsed) };
1107
+ }
1108
+ tryStartupBootstrap(document, debug, signal) {
1109
+ const ownedSignal = AbortSignal.any([signal, this.signal]);
1110
+ let retirement;
1111
+ const operation = this.work.then(async () => {
1112
+ const verify = (connection2) => {
1113
+ this.validateFactsScope(connection2, ownedSignal);
1114
+ if (this.pendingReload) throw new Error("Pi Sync is paused for a session change.");
1115
+ };
1116
+ verify();
1117
+ const connection = await this.connect(void 0, ownedSignal);
1118
+ return this.queueFacts(async () => {
1119
+ verify(connection);
1120
+ if (connection.contactState !== "active" || connection.contactResumeState !== "idle") return false;
1121
+ const settingsFingerprint = fingerprint(document);
1122
+ let mayHavePublished = true;
1123
+ try {
1124
+ const ready = await requestStartupBootstrap(connection, settingsFingerprint, debug, ownedSignal);
1125
+ mayHavePublished = ready;
1126
+ verify(connection);
1127
+ if (!ready) return false;
1128
+ if (connection.contactState === "active") this.confirmContact(connection);
1129
+ this.startupDebug = debug;
1130
+ this.initialized = true;
1131
+ Object.assign(connection.facts, { ready: true, startupDebug: debug });
1132
+ return true;
1133
+ } catch (error) {
1134
+ if (mayHavePublished) {
1135
+ retirement = this.dispose();
1136
+ void retirement.catch(() => {
1137
+ });
1138
+ }
1139
+ throw error;
1140
+ }
1141
+ });
1142
+ });
1143
+ this.work = operation.then(
1144
+ () => {
1145
+ },
1146
+ () => {
1147
+ }
1148
+ );
1149
+ return operation.catch(async (error) => {
1150
+ try {
1151
+ await retirement;
1152
+ } catch (cause) {
1153
+ throw new AggregateError(
1154
+ [error, cause],
1155
+ "Startup readiness is uncertain; reconcile the daemon before reconnecting."
1156
+ );
1157
+ }
1158
+ throw error;
1159
+ });
1160
+ }
959
1161
  async markReady(debug) {
960
1162
  this.validate();
961
1163
  this.startupDebug = debug;
1164
+ this.setDebugPreference(debug);
962
1165
  this.initialized = true;
963
1166
  await this.update();
964
1167
  this.validate();
@@ -976,7 +1179,32 @@ var PiDaemonClient = class {
976
1179
  if (this.connection && !this.paused && !this.disposed && !this.signal.aborted)
977
1180
  await this.publishFacts(this.connection);
978
1181
  }
979
- async callback(callback, signal, protectionOnly) {
1182
+ async pagedMergeReview(connection, callback, loadDetails, signal) {
1183
+ const ctx = this.uiContext;
1184
+ const generation = this.generation;
1185
+ const combined = AbortSignal.any([signal, this.signal]);
1186
+ const isCurrent = () => !combined.aborted && this.ownsContactUI() && this.uiContext === ctx && this.generation === generation && (this.connection ?? this.partialConnection) === connection;
1187
+ if (!isCurrent()) return false;
1188
+ this.validate();
1189
+ if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) throw new Error("This client cannot present safety reviews.");
1190
+ const { title, confirmationLabel, summaryLines } = callback.payload;
1191
+ const { confirmMergeReview } = await import("./merge-review-6YSLSMGS.ts");
1192
+ if (!isCurrent()) return false;
1193
+ this.validate();
1194
+ const result = await confirmMergeReview(
1195
+ ctx,
1196
+ title,
1197
+ loadDetails,
1198
+ combined,
1199
+ isCurrent,
1200
+ confirmationLabel,
1201
+ summaryLines
1202
+ );
1203
+ if (!isCurrent()) return false;
1204
+ this.validate();
1205
+ return result;
1206
+ }
1207
+ async callback(connection, callback, signal, protectionOnly) {
980
1208
  const payload = callback.payload;
981
1209
  if (callback.kind === "queue-release") {
982
1210
  if (typeof payload?.reservation !== "string") throw new Error("Invalid queue release.");
@@ -997,13 +1225,16 @@ var PiDaemonClient = class {
997
1225
  const combined = AbortSignal.any([signal, this.signal]);
998
1226
  if (callback.kind === "model-binding") {
999
1227
  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;
1228
+ return this.queueFactsWithAbortableWait(combined, async () => {
1229
+ this.validateFactsScope(connection, combined);
1230
+ let facts = this.facts();
1231
+ if (JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model)) {
1232
+ await connection.update(facts);
1233
+ this.validateFactsScope(connection, combined);
1234
+ facts = this.facts();
1235
+ }
1236
+ return payload.background && !facts.idle || JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model) ? null : facts.model ?? null;
1237
+ });
1007
1238
  }
1008
1239
  if (callback.kind === "reload") {
1009
1240
  if (!this.reloadRequest) throw new Error("No active Pi command can reload resources.");
@@ -1013,7 +1244,7 @@ var PiDaemonClient = class {
1013
1244
  if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) throw new Error("This client cannot present safety reviews.");
1014
1245
  let result;
1015
1246
  if (callback.kind === "merge-review" && typeof payload.title === "string" && typeof payload.content === "string") {
1016
- const { confirmMergeReview } = await import("./merge-review-SGDLMVS4.ts");
1247
+ const { confirmMergeReview } = await import("./merge-review-6YSLSMGS.ts");
1017
1248
  this.validate();
1018
1249
  combined.throwIfAborted();
1019
1250
  result = await confirmMergeReview(
@@ -1060,6 +1291,9 @@ var PiDaemonClient = class {
1060
1291
  try {
1061
1292
  await connection?.dispose(handoff);
1062
1293
  confirmed = Boolean(connection);
1294
+ } catch (error) {
1295
+ if (!connection || connection.identity.root !== this.recoveredOwner?.root || connection.identity.instance !== this.recoveredOwner.instance || connection.identity.pid !== this.recoveredOwner.pid)
1296
+ throw error;
1063
1297
  } finally {
1064
1298
  this.disposed = true;
1065
1299
  if (clients.get(this.manager) === this) clients.delete(this.manager);
@@ -1069,7 +1303,7 @@ var PiDaemonClient = class {
1069
1303
  if (confirmed) await gate.releaseAfterDrain();
1070
1304
  else quarantineClient(gate, connection.paths.root, connection.identity, connection.facts);
1071
1305
  }
1072
- await this.work;
1306
+ await Promise.all([this.work, this.factsQueue]);
1073
1307
  }
1074
1308
  })();
1075
1309
  return this.disposing;
@@ -1084,4 +1318,4 @@ export {
1084
1318
  withPiDaemonClient,
1085
1319
  remoteOperation
1086
1320
  };
1087
- //# sourceMappingURL=chunk-UGS6RYDZ.ts.map
1321
+ //# sourceMappingURL=chunk-RW44KNFD.ts.map