@narumitw/pi-sync 0.63.1 → 0.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (140) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +86 -10
  3. package/dist/chunks/{chunk-CKUGCBHP.ts → chunk-AYGMIMCV.ts} +2 -2
  4. package/dist/chunks/chunk-AYGMIMCV.ts.map +7 -0
  5. package/dist/chunks/{chunk-27F5W7DX.ts → chunk-DAZZ5BEJ.ts} +3 -1
  6. package/dist/chunks/chunk-DAZZ5BEJ.ts.map +7 -0
  7. package/dist/chunks/{chunk-VQ47JBLF.ts → chunk-FI2F5JBS.ts} +2 -2
  8. package/dist/chunks/{chunk-V76KCWHO.ts → chunk-IOM6E5FW.ts} +4 -4
  9. package/dist/chunks/{chunk-B5F3JLD3.ts → chunk-JQ5BAWW2.ts} +482 -78
  10. package/dist/chunks/chunk-JQ5BAWW2.ts.map +7 -0
  11. package/dist/chunks/{chunk-LBNC5AOM.ts → chunk-OBVJTKVY.ts} +12 -12
  12. package/dist/chunks/{chunk-EXDWEFIJ.ts → chunk-OWEOZZZE.ts} +6 -6
  13. package/dist/chunks/{chunk-SXCH4Q5O.ts → chunk-SZJOUVCL.ts} +3 -3
  14. package/dist/chunks/{chunk-HSCAFOT5.ts → chunk-TZMVSTAM.ts} +5 -5
  15. package/dist/chunks/{chunk-POWOMJ7S.ts → chunk-WJQ4TGN5.ts} +58 -31
  16. package/dist/chunks/chunk-WJQ4TGN5.ts.map +7 -0
  17. package/dist/chunks/{chunk-HLCML3OW.ts → chunk-XUZV4OGI.ts} +5 -3
  18. package/dist/chunks/chunk-XUZV4OGI.ts.map +7 -0
  19. package/dist/chunks/{command-handler-GMRRFWOL.ts → command-handler-YZ4DXQ7N.ts} +81 -30
  20. package/dist/chunks/command-handler-YZ4DXQ7N.ts.map +7 -0
  21. package/dist/chunks/{conflict-review-JWEA7DPQ.ts → conflict-review-J7L7S4AR.ts} +2 -2
  22. package/dist/chunks/{file-selection-KID23GAD.ts → file-selection-DDQN4LVD.ts} +9 -9
  23. package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts → manager-result-dispatcher-XB75YLEG.ts} +5 -5
  24. package/dist/chunks/{manager-ui-T5J5WG7T.ts → manager-ui-RGA26Z6G.ts} +103 -83
  25. package/dist/chunks/manager-ui-RGA26Z6G.ts.map +7 -0
  26. package/dist/chunks/{merge-review-OQDXNTJU.ts → merge-review-AAC674C6.ts} +3 -2
  27. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts +59 -0
  28. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts.map +7 -0
  29. package/dist/chunks/{remote-selection-ui-GPITNEBF.ts → remote-selection-ui-WVMET5RI.ts} +4 -4
  30. package/dist/chunks/{setup-switch-L54X5U5I.ts → setup-switch-644T6KHG.ts} +4 -4
  31. package/dist/chunks/{setup-wizard-LL6YMGUR.ts → setup-wizard-YP2KF2WQ.ts} +9 -9
  32. package/dist/chunks/{sync-inspection-SRU6HGGK.ts → sync-inspection-NBBTSMKR.ts} +5 -5
  33. package/dist/chunks/{sync-operations-UGSCONZ7.ts → sync-operations-AIEM2KL2.ts} +2 -2
  34. package/dist/daemon/dist/cli.js +2 -0
  35. package/dist/daemon/dist/client-transport.js +66 -0
  36. package/dist/daemon/dist/client.js +222 -354
  37. package/dist/daemon/dist/consent.js +33 -11
  38. package/dist/daemon/dist/daemon-debug.js +33 -0
  39. package/dist/daemon/dist/daemon-recovery.js +158 -0
  40. package/dist/daemon/dist/daemon-startup.js +257 -0
  41. package/dist/daemon/dist/engine/backends/git/git-backend.js +49 -13
  42. package/dist/daemon/dist/engine/backends/git/git-runner.js +6 -1
  43. package/dist/daemon/dist/engine/backends/git/git-storage.js +5 -9
  44. package/dist/daemon/dist/engine/backends/publication-encoding.js +19 -0
  45. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +30 -21
  46. package/dist/daemon/dist/engine/backends/sync-backend.js +16 -0
  47. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +34 -32
  48. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +10 -0
  49. package/dist/daemon/dist/engine/debug-log.js +134 -0
  50. package/dist/daemon/dist/engine/paths.js +7 -1
  51. package/dist/daemon/dist/engine/settings/config-file.js +62 -17
  52. package/dist/daemon/dist/engine/settings/config.js +49 -14
  53. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +30 -8
  54. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +3 -1
  55. package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +32 -0
  56. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +34 -0
  57. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +50 -7
  58. package/dist/daemon/dist/engine/snapshot/snapshot.js +64 -25
  59. package/dist/daemon/dist/engine/state/lock.js +157 -17
  60. package/dist/daemon/dist/engine/sync/continuous-sync.js +35 -11
  61. package/dist/daemon/dist/engine/sync/directional-action.js +124 -0
  62. package/dist/daemon/dist/engine/sync/initialization.js +2 -2
  63. package/dist/daemon/dist/engine/sync/local-fields.js +42 -19
  64. package/dist/daemon/dist/engine/sync/merged-sync.js +13 -10
  65. package/dist/daemon/dist/engine/sync/remote-snapshot.js +21 -4
  66. package/dist/daemon/dist/engine/sync/session-push.js +13 -4
  67. package/dist/daemon/dist/engine/sync/startup-bootstrap.js +105 -0
  68. package/dist/daemon/dist/engine/sync/startup-recovery-evidence.js +37 -0
  69. package/dist/daemon/dist/engine/sync/startup-timings.js +80 -8
  70. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +6 -1
  71. package/dist/daemon/dist/engine/sync/sync-errors.js +20 -0
  72. package/dist/daemon/dist/engine/sync/sync-inspection.js +4 -7
  73. package/dist/daemon/dist/engine/sync/sync-local.js +59 -4
  74. package/dist/daemon/dist/engine/sync/sync-mutations.js +309 -337
  75. package/dist/daemon/dist/engine/sync/sync-policy.js +9 -1
  76. package/dist/daemon/dist/engine/sync/sync-queries.js +2 -1
  77. package/dist/daemon/dist/engine/sync/sync-rollback.js +198 -0
  78. package/dist/daemon/dist/engine/sync/sync-state.js +12 -4
  79. package/dist/daemon/dist/engine/sync/transfer-freshness.js +11 -5
  80. package/dist/daemon/dist/engine-service.js +122 -10
  81. package/dist/daemon/dist/foreground-queue-outcome.js +9 -0
  82. package/dist/daemon/dist/identity.js +36 -6
  83. package/dist/daemon/dist/index.js +2 -1
  84. package/dist/daemon/dist/monitor.js +21 -1
  85. package/dist/daemon/dist/paged-review.js +177 -0
  86. package/dist/daemon/dist/participant-ledger.js +149 -0
  87. package/dist/daemon/dist/protocol.js +4 -0
  88. package/dist/daemon/dist/server.js +340 -127
  89. package/dist/daemon/dist/service-host.js +83 -15
  90. package/dist/daemon/dist/state-wait-jobs.js +23 -0
  91. package/dist/daemon/dist/state-wait.js +34 -0
  92. package/dist/daemon/package.json +1 -1
  93. package/dist/index.ts +128 -48
  94. package/dist/index.ts.map +2 -2
  95. package/docs/continuous-sync-verification.md +2 -0
  96. package/docs/daemon-migration.md +31 -6
  97. package/docs/tui-contract.md +7 -1
  98. package/package.json +2 -2
  99. package/skills/configure-pi-sync/references/configuration.md +23 -13
  100. package/src/commands/command-execution.ts +67 -5
  101. package/src/commands/command-handler.ts +12 -3
  102. package/src/commands/command.ts +4 -2
  103. package/src/daemon/client-debug.ts +45 -0
  104. package/src/daemon/directional-recovery.ts +103 -0
  105. package/src/daemon/ownership-recovery.ts +50 -0
  106. package/src/daemon/pi-client.ts +399 -71
  107. package/src/daemon/startup-bootstrap-client.ts +26 -0
  108. package/src/settings/config.ts +1 -0
  109. package/src/sync/automatic-sync.ts +61 -18
  110. package/src/sync/startup-check.ts +13 -5
  111. package/src/sync-extension.ts +46 -8
  112. package/src/ui/cancellable-operation.ts +5 -2
  113. package/src/ui/manager-state.ts +31 -23
  114. package/src/ui/manager-ui.ts +45 -25
  115. package/src/ui/merge-review.ts +53 -18
  116. package/src/ui/settings-ui.ts +2 -2
  117. package/src/ui/sync-confirmation.ts +14 -17
  118. package/src/ui/sync-setups-ui.ts +15 -12
  119. package/dist/chunks/chunk-27F5W7DX.ts.map +0 -7
  120. package/dist/chunks/chunk-B5F3JLD3.ts.map +0 -7
  121. package/dist/chunks/chunk-CKUGCBHP.ts.map +0 -7
  122. package/dist/chunks/chunk-HLCML3OW.ts.map +0 -7
  123. package/dist/chunks/chunk-POWOMJ7S.ts.map +0 -7
  124. package/dist/chunks/command-handler-GMRRFWOL.ts.map +0 -7
  125. package/dist/chunks/manager-ui-T5J5WG7T.ts.map +0 -7
  126. /package/dist/chunks/{chunk-VQ47JBLF.ts.map → chunk-FI2F5JBS.ts.map} +0 -0
  127. /package/dist/chunks/{chunk-V76KCWHO.ts.map → chunk-IOM6E5FW.ts.map} +0 -0
  128. /package/dist/chunks/{chunk-LBNC5AOM.ts.map → chunk-OBVJTKVY.ts.map} +0 -0
  129. /package/dist/chunks/{chunk-EXDWEFIJ.ts.map → chunk-OWEOZZZE.ts.map} +0 -0
  130. /package/dist/chunks/{chunk-SXCH4Q5O.ts.map → chunk-SZJOUVCL.ts.map} +0 -0
  131. /package/dist/chunks/{chunk-HSCAFOT5.ts.map → chunk-TZMVSTAM.ts.map} +0 -0
  132. /package/dist/chunks/{conflict-review-JWEA7DPQ.ts.map → conflict-review-J7L7S4AR.ts.map} +0 -0
  133. /package/dist/chunks/{file-selection-KID23GAD.ts.map → file-selection-DDQN4LVD.ts.map} +0 -0
  134. /package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts.map → manager-result-dispatcher-XB75YLEG.ts.map} +0 -0
  135. /package/dist/chunks/{merge-review-OQDXNTJU.ts.map → merge-review-AAC674C6.ts.map} +0 -0
  136. /package/dist/chunks/{remote-selection-ui-GPITNEBF.ts.map → remote-selection-ui-WVMET5RI.ts.map} +0 -0
  137. /package/dist/chunks/{setup-switch-L54X5U5I.ts.map → setup-switch-644T6KHG.ts.map} +0 -0
  138. /package/dist/chunks/{setup-wizard-LL6YMGUR.ts.map → setup-wizard-YP2KF2WQ.ts.map} +0 -0
  139. /package/dist/chunks/{sync-inspection-SRU6HGGK.ts.map → sync-inspection-NBBTSMKR.ts.map} +0 -0
  140. /package/dist/chunks/{sync-operations-UGSCONZ7.ts.map → sync-operations-AIEM2KL2.ts.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { randomUUID } from "node:crypto";
3
- import { realpathSync } from "node:fs";
3
+ import { lstatSync, realpathSync } from "node:fs";
4
4
  import fs from "node:fs/promises";
5
5
  import path from "node:path";
6
6
  import { type ExtensionContext, getAgentDir } from "@earendil-works/pi-coding-agent";
@@ -11,14 +11,17 @@ import {
11
11
  type ContactState,
12
12
  DaemonConnection,
13
13
  DaemonError,
14
+ type DaemonRecoveryTarget,
14
15
  type DocumentView,
15
16
  documentFingerprint,
16
17
  ensureDaemon,
17
18
  findDaemon,
18
19
  MAX_SETTINGS_BYTES,
19
20
  modelSignature,
21
+ OWNERSHIP_CLEANUP_REQUIRED,
20
22
  waitForDaemonExit,
21
23
  } from "@narumitw/pi-sync-daemon";
24
+ import { appendDebugEvent, type DebugEvent } from "@narumitw/pi-sync-daemon/engine/debug-log";
22
25
  import { type ConfigAuthority, configureEngineHost } from "@narumitw/pi-sync-daemon/engine/host";
23
26
  import {
24
27
  type LocalConfigDocument,
@@ -38,8 +41,11 @@ import {
38
41
  } from "../ui/sync-status.js";
39
42
  import { safeTerminalText } from "../ui/terminal-text.js";
40
43
  import { PiApplyGate } from "./apply-gate.js";
44
+ import { observeDebugJob } from "./client-debug.js";
45
+ import { type DirectionalCheckpoint, isForegroundDirection, runDirectionalRecovery } from "./directional-recovery.js";
41
46
  import { createQueueReleaseUI, type QueueReleaseEvent } from "./queue-release-ui.js";
42
47
  import { quarantineClient, recoverDetachedClients } from "./recovery.js";
48
+ import { requestStartupBootstrap } from "./startup-bootstrap-client.js";
43
49
 
44
50
  const scope = new AsyncLocalStorage<{ client: PiDaemonClient; reload?: AbortController }>();
45
51
  const clients = new WeakMap<ExtensionContext["sessionManager"], PiDaemonClient>();
@@ -229,6 +235,7 @@ export class PiDaemonClient {
229
235
  private protectionOnly = false;
230
236
  private partialConnection?: DaemonConnection;
231
237
  private work = Promise.resolve();
238
+ private factsQueue = Promise.resolve();
232
239
  private closing = false;
233
240
  private paused = false;
234
241
  private pausing?: Promise<void>;
@@ -260,9 +267,12 @@ export class PiDaemonClient {
260
267
  private uiContext: ExtensionContext;
261
268
  private reloadRequest?: { received: boolean };
262
269
  private pendingReload?: AbortController;
270
+ private directionalCheckpoint?: DirectionalCheckpoint;
271
+ private recoveringDirectionalOwner = false;
263
272
  private readonly busy = new Set<string>();
264
273
  private initialized = false;
265
274
  private startupDebug = false;
275
+ private debug = false;
266
276
  private participantIdentity = { id: randomUUID(), generation: randomUUID() };
267
277
  get id() {
268
278
  return this.participantIdentity.id;
@@ -271,6 +281,8 @@ export class PiDaemonClient {
271
281
  return this.participantIdentity.generation;
272
282
  }
273
283
  readonly root: string;
284
+ private cleanupRequired = false;
285
+ private recoveredOwner?: DaemonRecoveryTarget;
274
286
  private readonly rawRoot: string;
275
287
  private readonly gate: PiApplyGate;
276
288
  private readonly manager: ExtensionContext["sessionManager"];
@@ -297,6 +309,19 @@ export class PiDaemonClient {
297
309
  if (getAgentDir() !== this.rawRoot || canonicalPath(path.resolve(this.rawRoot)) !== this.root)
298
310
  throw new Error("Agent directory changed; reload before synchronization.");
299
311
  }
312
+ get debugEnabled() {
313
+ return this.debug;
314
+ }
315
+ setDebugPreference(debug: boolean) {
316
+ this.debug = debug && this.ctx.hasUI && (this.ctx.mode === "tui" || this.ctx.mode === "rpc");
317
+ }
318
+ recordDebug(event: DebugEvent) {
319
+ if (!this.debug || this.protectionOnly || this.pendingReload || !this.ownsContactUI()) return;
320
+ try {
321
+ this.validate();
322
+ appendDebugEvent(this.root, "pi-sync", event);
323
+ } catch {}
324
+ }
300
325
  private modelBinding(): ClientFacts["model"] {
301
326
  const model = this.ctx.model;
302
327
  if (!model) return undefined;
@@ -321,8 +346,8 @@ export class PiDaemonClient {
321
346
  cwd: this.ctx.cwd,
322
347
  mode: this.ctx.mode,
323
348
  hasUI: !protectionOnly && this.ctx.hasUI,
324
- idle: !protectionOnly && !this.paused && !this.busy.size && this.ctx.isIdle(),
325
- ready: !protectionOnly && this.initialized,
349
+ idle: !protectionOnly && !this.recoveringDirectionalOwner && !this.paused && !this.busy.size && this.ctx.isIdle(),
350
+ ready: !protectionOnly && !this.recoveringDirectionalOwner && this.initialized,
326
351
  startupDebug: this.startupDebug,
327
352
  sessionFile: canonicalPath(manager.getSessionFile?.()),
328
353
  sessionId: manager.getSessionId?.(),
@@ -356,9 +381,18 @@ export class PiDaemonClient {
356
381
  }
357
382
  async attachExisting({ allowUpgrade = false } = {}) {
358
383
  this.validate();
359
- const address = await findDaemon(this.root);
384
+ this.assertNoDirectionalRecovery();
385
+ if (!allowUpgrade && !this.paused && this.connection?.contactState === "active") return !this.protectionOnly;
386
+ const address = await findDaemon(this.root).catch((error: unknown) => {
387
+ this.recordDebug({ event: "connection", outcome: "failed" });
388
+ throw error;
389
+ });
360
390
  this.validate();
361
- if (!address) return false;
391
+ this.assertNoDirectionalRecovery();
392
+ if (!address) {
393
+ this.recordDebug({ event: "connection", outcome: "skipped" });
394
+ return false;
395
+ }
362
396
  const upgrade = allowUpgrade && address.needsUpgrade && this.ctx.hasUI && ["tui", "rpc"].includes(this.ctx.mode);
363
397
  let upgradeFailure: string | undefined;
364
398
  if (upgrade) {
@@ -368,7 +402,7 @@ export class PiDaemonClient {
368
402
  return true;
369
403
  } catch (error) {
370
404
  this.validate();
371
- if (this.paused) throw error;
405
+ if (this.paused || this.recoveringDirectionalOwner) throw error;
372
406
  upgradeFailure = safeTerminalText(errorMessage(error));
373
407
  }
374
408
  }
@@ -391,14 +425,24 @@ export class PiDaemonClient {
391
425
  }
392
426
  async finishReattachment() {
393
427
  this.validate();
394
- if (this.connection) {
395
- await recoverDetachedClients({ paths: this.connection.paths, identity: this.connection.identity });
396
- this.validate();
397
- await this.connection.attach(this.signal);
398
- this.validate();
399
- }
428
+ const connection = this.connection;
429
+ if (!connection) return;
430
+ await recoverDetachedClients(connection);
431
+ await this.queueFacts(async () => {
432
+ this.validateFactsScope(connection);
433
+ await connection.attach(this.signal);
434
+ this.validateFactsScope(connection);
435
+ });
436
+ }
437
+ private assertNoDirectionalRecovery() {
438
+ if (this.recoveringDirectionalOwner)
439
+ throw new Error("Pi Sync is recovering the daemon for a transfer. Retry after recovery finishes.");
400
440
  }
401
441
  async connect(existing?: Awaited<ReturnType<typeof ensureDaemon>>, requestSignal?: AbortSignal) {
442
+ this.assertNoDirectionalRecovery();
443
+ return this.attachConnection(existing, requestSignal);
444
+ }
445
+ private async attachConnection(existing?: Awaited<ReturnType<typeof ensureDaemon>>, requestSignal?: AbortSignal) {
402
446
  const startupSignal = requestSignal ? AbortSignal.any([this.signal, requestSignal]) : this.signal;
403
447
  const validateStartup = () => {
404
448
  this.validate();
@@ -434,7 +478,11 @@ export class PiDaemonClient {
434
478
  if (daemon.paths.root !== this.root) throw new Error("Daemon root changed before attach.");
435
479
  const protectionOnly = daemon.needsUpgrade === true;
436
480
  const connection = new DaemonConnection(daemon.paths, daemon.identity, this.facts(protectionOnly), {
437
- callback: (callback, signal) => this.callback(callback, signal, protectionOnly),
481
+ callback: (callback, signal) => this.callback(connection, callback, signal, protectionOnly),
482
+ mergeReview:
483
+ !protectionOnly && this.ctx.hasUI
484
+ ? (callback, loadDetails, signal) => this.pagedMergeReview(connection, callback, loadDetails, signal)
485
+ : undefined,
438
486
  event: (event) => {
439
487
  if (event.kind === "commit") return;
440
488
  if (this.signal.aborted || this.disposed || this.closing || clients.get(this.manager) !== this) return;
@@ -460,7 +508,12 @@ export class PiDaemonClient {
460
508
  contact: (state) => this.observeContact(connection, state),
461
509
  queueRelease: (event) => this.observeQueueRelease(connection, event),
462
510
  error: () => {
463
- if (this.ownsContactUI() && connection.facts.hasUI && !this.releaseUI.retrying)
511
+ if (
512
+ !this.recoveringDirectionalOwner &&
513
+ this.ownsContactUI() &&
514
+ connection.facts.hasUI &&
515
+ !this.releaseUI.retrying
516
+ )
464
517
  this.showContactStatus("sync service unavailable", "blocked", true);
465
518
  },
466
519
  });
@@ -491,10 +544,22 @@ export class PiDaemonClient {
491
544
  this.partialConnection = undefined;
492
545
  return connection;
493
546
  }
494
- })().catch((error) => {
495
- this.connecting = undefined;
496
- throw error;
497
- });
547
+ })().then(
548
+ (connection) => {
549
+ this.recordDebug({ event: "connection", outcome: startupSignal.aborted ? "cancelled" : "completed" });
550
+ return connection;
551
+ },
552
+ (error: unknown) => {
553
+ this.connecting = undefined;
554
+ const outcome = startupSignal.aborted
555
+ ? "cancelled"
556
+ : existing && remoteErrorNamed(error, "DaemonStoppingError")
557
+ ? "skipped"
558
+ : "failed";
559
+ this.recordDebug({ event: "connection", outcome });
560
+ throw error;
561
+ },
562
+ );
498
563
  const connection = await this.connecting;
499
564
  validateStartup();
500
565
  if (!existing && this.protectionOnly)
@@ -558,71 +623,99 @@ export class PiDaemonClient {
558
623
  this.contactFactsUnpublished = false;
559
624
  this.clearConnectionStatus();
560
625
  }
561
- private async resumeContact(connection: DaemonConnection) {
626
+ private queueFacts<T>(publish: () => Promise<T>): Promise<T> {
627
+ const result = this.factsQueue.then(publish);
628
+ this.factsQueue = result.then(
629
+ () => {},
630
+ () => {},
631
+ );
632
+ return result;
633
+ }
634
+ private async queueFactsWithAbortableWait<T>(signal: AbortSignal, publish: () => Promise<T>): Promise<T> {
635
+ signal.throwIfAborted();
636
+ const cancelled = Promise.withResolvers<never>();
637
+ const abort = () => cancelled.reject(signal.reason);
638
+ signal.addEventListener("abort", abort, { once: true });
639
+ const queued = this.queueFacts(() => {
640
+ signal.removeEventListener("abort", abort);
641
+ signal.throwIfAborted();
642
+ return publish();
643
+ });
644
+ return Promise.race([queued, cancelled.promise]);
645
+ }
646
+ private validateFactsScope(connection?: DaemonConnection, signal?: AbortSignal) {
562
647
  this.validate();
563
- if (this.paused || this.connection !== connection) throw new Error("Pi Sync is paused for a session change.");
648
+ signal?.throwIfAborted();
649
+ if (this.paused) throw new Error("Pi Sync is paused for a session change.");
650
+ if (connection && connection !== (this.connection ?? this.partialConnection))
651
+ throw new Error("Synchronization session was replaced.");
652
+ }
653
+ private async resumeContact(connection: DaemonConnection) {
654
+ this.validateFactsScope(connection);
564
655
  if (this.contactRepair) return this.contactRepair.done;
565
- if (connection.contactState === "active" && connection.contactResumeState !== "uncertain") return;
566
- if (this.gate.size || connection.hasPendingWork || connection.contactResumeState === "uncertain") {
567
- throw new Error(
568
- "Pi Sync cannot reconnect while previous work is still running or uncertain. Check sync recovery before retrying.",
569
- );
570
- }
571
- const earlier = this.contactAttempt;
572
- if (connection.contactState !== "expired" || earlier) {
573
- throw new Error("Pi Sync could not restore contact. Review pending work before using /reload.", {
574
- cause: earlier?.error,
575
- });
576
- }
577
656
  const controller = new AbortController();
578
657
  const signal = AbortSignal.any([this.signal, controller.signal]);
579
- const attempt: { error?: unknown } = {};
580
- this.contactAttempt = attempt;
581
- const done = Promise.resolve().then(async () => {
658
+ const done = this.queueFacts(async () => {
659
+ this.validateFactsScope(connection, signal);
660
+ if (connection.contactState === "active" && connection.contactResumeState !== "uncertain") return;
661
+ if (this.gate.size || connection.hasPendingWork || connection.contactResumeState === "uncertain") {
662
+ throw new Error(
663
+ "Pi Sync cannot reconnect while previous work is still running or uncertain. Check sync recovery before retrying.",
664
+ );
665
+ }
666
+ const earlier = this.contactAttempt;
667
+ if (connection.contactState !== "expired" || earlier) {
668
+ throw new Error("Pi Sync could not restore contact. Review pending work before using /reload.", {
669
+ cause: earlier?.error,
670
+ });
671
+ }
672
+ const attempt: { error?: unknown } = {};
673
+ this.contactAttempt = attempt;
582
674
  try {
583
- this.validate();
584
- signal.throwIfAborted();
585
675
  this.showContactStatus("sync reconnecting", "retry");
586
676
  // Admission can wait behind an apply. Do not advertise readiness using
587
677
  // facts sampled before that wait; publish current facts after the ack.
588
678
  await connection.resumeContact({ ...this.facts(), idle: false, ready: false }, signal);
589
- this.validate();
590
- signal.throwIfAborted();
679
+ this.validateFactsScope(connection, signal);
591
680
  this.contactFactsUnpublished = true;
592
681
  this.contactAttempt = undefined;
593
- await connection.update(this.facts());
594
- this.validate();
595
- signal.throwIfAborted();
596
- this.confirmContact(connection);
682
+ await this.publishCurrentFacts(connection, signal);
683
+ this.recordDebug({ event: "connection", outcome: "completed" });
597
684
  } catch (error) {
685
+ this.recordDebug({ event: "connection", outcome: signal.aborted ? "cancelled" : "failed" });
598
686
  attempt.error = error;
599
- if (this.ownsContactUI() && !signal.aborted)
687
+ if (this.ownsContactUI() && !signal.aborted) {
688
+ this.validateFactsScope(connection, signal);
600
689
  this.showContactStatus("sync reconnect blocked; check /sync daemon status", "blocked");
690
+ }
601
691
  throw error;
602
- } finally {
603
- if (this.contactRepair?.controller === controller) this.contactRepair = undefined;
604
692
  }
693
+ }).finally(() => {
694
+ if (this.contactRepair?.controller === controller) this.contactRepair = undefined;
605
695
  });
606
696
  this.contactRepair = { controller, done };
607
697
  return done;
608
698
  }
609
- private async publishFacts(connection: DaemonConnection) {
610
- if (this.contactRepair) await this.contactRepair.done;
611
- this.validate();
612
- if (this.paused) throw new Error("Pi Sync is paused for a session change.");
699
+ private async publishCurrentFacts(connection: DaemonConnection, signal?: AbortSignal) {
700
+ this.validateFactsScope(connection, signal);
613
701
  if (connection.contactResumeState === "uncertain")
614
702
  throw new Error("Pi Sync cannot verify the previous reconnect. Review pending work before using /reload.");
703
+ await connection.update(this.facts());
704
+ this.validateFactsScope(connection, signal);
705
+ this.confirmContact(connection);
706
+ }
707
+ private async publishFacts(connection: DaemonConnection, signal?: AbortSignal) {
708
+ if (this.contactRepair) await this.contactRepair.done;
709
+ const publish = () => this.queueFacts(() => this.publishCurrentFacts(connection, signal));
615
710
  try {
616
- await connection.update(this.facts());
711
+ await publish();
617
712
  } catch (error) {
713
+ this.validateFactsScope(connection, signal);
618
714
  if (!connection.facts.hasUI || !remoteErrorNamed(error, "ClientContactExpiredError")) throw error;
619
715
  await this.resumeContact(connection);
620
- this.validate();
621
716
  // A shared repair might have started before these facts changed.
622
- await connection.update(this.facts());
717
+ await publish();
623
718
  }
624
- this.validate();
625
- this.confirmContact(connection);
626
719
  }
627
720
  private confirmContact(connection: DaemonConnection) {
628
721
  if (connection.contactState === "expired" || connection.contactState === "inactive")
@@ -631,9 +724,11 @@ export class PiDaemonClient {
631
724
  }
632
725
  async verifyConnection(signal?: AbortSignal) {
633
726
  const connection = await this.connect(undefined, signal);
634
- signal?.throwIfAborted();
635
- await this.publishFacts(connection);
636
- signal?.throwIfAborted();
727
+ this.validateFactsScope(connection, signal);
728
+ this.assertNoDirectionalRecovery();
729
+ await this.publishFacts(connection, signal);
730
+ this.validateFactsScope(connection, signal);
731
+ this.assertNoDirectionalRecovery();
637
732
  return connection;
638
733
  }
639
734
  async readSettings(repair = false) {
@@ -648,6 +743,33 @@ export class PiDaemonClient {
648
743
  }
649
744
  return decode(await this.run(repair ? "settings.repair-read" : "settings.read", {}));
650
745
  }
746
+ canReportDirectionalResult() {
747
+ try {
748
+ this.validateFactsScope();
749
+ return !this.pendingReload;
750
+ } catch {
751
+ return false;
752
+ }
753
+ }
754
+ get ownershipCleanupRequired() {
755
+ return this.cleanupRequired;
756
+ }
757
+ confirmRecoveryExit(owner: DaemonRecoveryTarget) {
758
+ this.cleanupRequired = true;
759
+ this.recoveredOwner = owner;
760
+ }
761
+ recordOwnershipFailure(error: unknown) {
762
+ if (
763
+ (error instanceof DaemonError && error.remote.properties?.code === OWNERSHIP_CLEANUP_REQUIRED) ||
764
+ (error instanceof Error &&
765
+ (("code" in error && error.code === OWNERSHIP_CLEANUP_REQUIRED) ||
766
+ error.message === "Daemon ownership cleanup is uncertain; stop and reconcile before restarting." ||
767
+ error.message === "Daemon ownership cleanup is uncertain; stop and reconcile before retrying." ||
768
+ error.message ===
769
+ "File-queue release is uncertain; stop the daemon and keep grants quarantined until owner exit."))
770
+ )
771
+ this.cleanupRequired = true;
772
+ }
651
773
  run(
652
774
  operation: string,
653
775
  payload: unknown,
@@ -656,13 +778,52 @@ export class PiDaemonClient {
656
778
  onCommit?: () => void,
657
779
  reload?: AbortController,
658
780
  ) {
659
- const result = this.work.then(() => this.runCurrent(operation, payload, signal, ctx, onCommit, reload));
781
+ const diagnostics = this.debug ? observeDebugJob(operation, (event) => this.recordDebug(event)) : undefined;
782
+ const result = this.work
783
+ .then(() => this.runCurrent(operation, payload, signal, ctx, onCommit, reload, diagnostics))
784
+ .catch((error: unknown) => {
785
+ diagnostics?.rejected(error, Boolean(signal?.aborted || reload?.signal.aborted));
786
+ this.recordOwnershipFailure(error);
787
+ throw error;
788
+ });
660
789
  this.work = result.then(
661
790
  () => {},
662
791
  () => {},
663
792
  );
664
793
  return result;
665
794
  }
795
+ private async recoverDirectionalOwner(
796
+ connection: DaemonConnection,
797
+ job: string,
798
+ signal: AbortSignal,
799
+ assertRoot: () => void,
800
+ ) {
801
+ this.validateFactsScope(connection, signal);
802
+ this.recoveringDirectionalOwner = true;
803
+ try {
804
+ this.stopContactRepair(true);
805
+ await this.factsQueue;
806
+ this.validateFactsScope(connection, signal);
807
+ await connection.recoverForeground(job, signal);
808
+ if (this.connection !== connection) throw new Error("The Pi participant changed during daemon recovery.");
809
+ this.confirmRecoveryExit(connection.identity);
810
+ await this.gate.releaseAfterDrain();
811
+ this.connection = undefined;
812
+ this.connecting = undefined;
813
+ this.cleanupRequired = false;
814
+ this.validateFactsScope(undefined, signal);
815
+ assertRoot();
816
+ const replacement = await ensureDaemon(this.root, signal, { compatibleOnly: true });
817
+ this.validateFactsScope(undefined, signal);
818
+ assertRoot();
819
+ const attached = await this.attachConnection(replacement, signal);
820
+ this.validateFactsScope(attached, signal);
821
+ assertRoot();
822
+ return attached;
823
+ } finally {
824
+ this.recoveringDirectionalOwner = false;
825
+ }
826
+ }
666
827
  private async runCurrent(
667
828
  operation: string,
668
829
  payload: unknown,
@@ -670,6 +831,7 @@ export class PiDaemonClient {
670
831
  ctx = this.ctx,
671
832
  onCommit?: () => void,
672
833
  reload?: AbortController,
834
+ diagnostics?: ReturnType<typeof observeDebugJob>,
673
835
  ) {
674
836
  this.validate();
675
837
  signal?.throwIfAborted();
@@ -687,7 +849,7 @@ export class PiDaemonClient {
687
849
  signal?.throwIfAborted();
688
850
  if (this.paused)
689
851
  await connection.update(this.facts()); // Existing, explicitly attached shutdown path.
690
- else await this.publishFacts(connection);
852
+ else await this.publishFacts(connection, signal);
691
853
  this.validate();
692
854
  signal?.throwIfAborted();
693
855
  this.uiContext = ctx;
@@ -699,7 +861,45 @@ export class PiDaemonClient {
699
861
  const clearForeground = () => this.releaseUI.finishForeground(Boolean(this.releaseContext()));
700
862
  runSignal.addEventListener("abort", clearForeground, { once: true });
701
863
  try {
702
- const result = await connection.run(operation, payload, runSignal, onCommit);
864
+ const root = isForegroundDirection(operation) ? lstatSync(this.root) : undefined;
865
+ const assertRoot = () => {
866
+ const current = lstatSync(this.root);
867
+ if (!root || !current.isDirectory() || current.dev !== root.dev || current.ino !== root.ino)
868
+ throw new Error("The agent directory changed during the transfer.");
869
+ };
870
+ const intent = root ? structuredClone(payload) : payload;
871
+ const result = root
872
+ ? await runDirectionalRecovery(
873
+ connection,
874
+ runSignal,
875
+ async (checkpoint, retryCheckpoint) => {
876
+ const current = checkpoint.connection;
877
+ this.validateFactsScope(current, runSignal);
878
+ assertRoot();
879
+ this.directionalCheckpoint = checkpoint;
880
+ try {
881
+ return await current.run(
882
+ operation,
883
+ retryCheckpoint === undefined ? intent : { ...(intent as object), retryCheckpoint },
884
+ runSignal,
885
+ onCommit,
886
+ (id) => {
887
+ checkpoint.job = id;
888
+ diagnostics?.onSubmit(id);
889
+ },
890
+ );
891
+ } finally {
892
+ this.directionalCheckpoint = undefined;
893
+ }
894
+ },
895
+ (owner, job, recoverySignal) => this.recoverDirectionalOwner(owner, job, recoverySignal, assertRoot),
896
+ () => {
897
+ this.cleanupRequired = true;
898
+ },
899
+ )
900
+ : await connection.run(operation, payload, runSignal, onCommit, diagnostics?.onSubmit);
901
+ if (runSignal.aborted || reload?.signal.aborted) diagnostics?.rejected(undefined, true);
902
+ else diagnostics?.returned(result);
703
903
  if (request?.received && reload && !this.paused && !reload.signal.aborted && !signal?.aborted) {
704
904
  this.validate();
705
905
  this.pendingReload = reload;
@@ -739,9 +939,72 @@ export class PiDaemonClient {
739
939
  releaseReload(owner: AbortController) {
740
940
  if (this.pendingReload === owner) this.pendingReload = undefined;
741
941
  }
942
+ async readStartupSettings(signal: AbortSignal) {
943
+ this.validate();
944
+ await settingsQueue;
945
+ this.validate();
946
+ signal.throwIfAborted();
947
+ const document = await peekLocalConfigDocument();
948
+ this.validate();
949
+ signal.throwIfAborted();
950
+ if (document && document.bytes.length > MAX_SETTINGS_BYTES)
951
+ throw new Error("Settings exceed the local API byte limit; the source document is unchanged.");
952
+ return { document, settings: document && validateSettingsDocument(document.parsed) };
953
+ }
954
+ tryStartupBootstrap(document: LocalConfigDocument, debug: boolean, signal: AbortSignal) {
955
+ const ownedSignal = AbortSignal.any([signal, this.signal]);
956
+ let retirement: Promise<void> | undefined;
957
+ const operation = this.work.then(async () => {
958
+ const verify = (connection?: DaemonConnection) => {
959
+ this.validateFactsScope(connection, ownedSignal);
960
+ if (this.pendingReload) throw new Error("Pi Sync is paused for a session change.");
961
+ };
962
+ verify();
963
+ const connection = await this.connect(undefined, ownedSignal);
964
+ return this.queueFacts(async () => {
965
+ verify(connection);
966
+ if (connection.contactState !== "active" || connection.contactResumeState !== "idle") return false;
967
+ const settingsFingerprint = fingerprint(document);
968
+ let mayHavePublished = true;
969
+ try {
970
+ const ready = await requestStartupBootstrap(connection, settingsFingerprint, debug, ownedSignal);
971
+ mayHavePublished = ready;
972
+ verify(connection);
973
+ if (!ready) return false;
974
+ if (connection.contactState === "active") this.confirmContact(connection);
975
+ this.startupDebug = debug;
976
+ this.initialized = true;
977
+ Object.assign(connection.facts, { ready: true, startupDebug: debug });
978
+ return true;
979
+ } catch (error) {
980
+ if (mayHavePublished) {
981
+ retirement = this.dispose();
982
+ void retirement.catch(() => {});
983
+ }
984
+ throw error;
985
+ }
986
+ });
987
+ });
988
+ this.work = operation.then(
989
+ () => {},
990
+ () => {},
991
+ );
992
+ return operation.catch(async (error: unknown) => {
993
+ try {
994
+ await retirement;
995
+ } catch (cause) {
996
+ throw new AggregateError(
997
+ [error, cause],
998
+ "Startup readiness is uncertain; reconcile the daemon before reconnecting.",
999
+ );
1000
+ }
1001
+ throw error;
1002
+ });
1003
+ }
742
1004
  async markReady(debug: boolean) {
743
1005
  this.validate();
744
1006
  this.startupDebug = debug;
1007
+ this.setDebugPreference(debug);
745
1008
  this.initialized = true;
746
1009
  await this.update();
747
1010
  this.validate();
@@ -757,10 +1020,54 @@ export class PiDaemonClient {
757
1020
  this.validate();
758
1021
  }
759
1022
  async update() {
760
- if (this.connection && !this.paused && !this.disposed && !this.signal.aborted)
1023
+ if (this.connection && !this.recoveringDirectionalOwner && !this.paused && !this.disposed && !this.signal.aborted)
761
1024
  await this.publishFacts(this.connection);
762
1025
  }
763
- private async callback(callback: Callback, signal: AbortSignal, protectionOnly: boolean) {
1026
+ private async pagedMergeReview(
1027
+ connection: DaemonConnection,
1028
+ callback: Callback,
1029
+ loadDetails: (signal?: AbortSignal) => Promise<string>,
1030
+ signal: AbortSignal,
1031
+ ) {
1032
+ const ctx = this.uiContext;
1033
+ const generation = this.generation;
1034
+ const combined = AbortSignal.any([signal, this.signal]);
1035
+ const isCurrent = () =>
1036
+ !combined.aborted &&
1037
+ this.ownsContactUI() &&
1038
+ this.uiContext === ctx &&
1039
+ this.generation === generation &&
1040
+ (this.connection ?? this.partialConnection) === connection;
1041
+ if (!isCurrent()) return false;
1042
+ this.validate();
1043
+ if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) throw new Error("This client cannot present safety reviews.");
1044
+ const { title, confirmationLabel, summaryLines } = callback.payload as {
1045
+ title: string;
1046
+ confirmationLabel?: string;
1047
+ summaryLines: readonly string[];
1048
+ };
1049
+ const { confirmMergeReview } = await import("../ui/merge-review.js");
1050
+ if (!isCurrent()) return false;
1051
+ this.validate();
1052
+ const result = await confirmMergeReview(
1053
+ ctx,
1054
+ title,
1055
+ loadDetails,
1056
+ combined,
1057
+ isCurrent,
1058
+ confirmationLabel,
1059
+ summaryLines,
1060
+ );
1061
+ if (!isCurrent()) return false;
1062
+ this.validate();
1063
+ return result;
1064
+ }
1065
+ private async callback(
1066
+ connection: DaemonConnection,
1067
+ callback: Callback,
1068
+ signal: AbortSignal,
1069
+ protectionOnly: boolean,
1070
+ ) {
764
1071
  const payload = callback.payload as {
765
1072
  reservation?: string;
766
1073
  targets?: string[];
@@ -773,6 +1080,7 @@ export class PiDaemonClient {
773
1080
  items?: string[];
774
1081
  helpText?: string;
775
1082
  background?: boolean;
1083
+ fingerprint?: string;
776
1084
  };
777
1085
  if (callback.kind === "queue-release") {
778
1086
  if (typeof payload?.reservation !== "string") throw new Error("Invalid queue release.");
@@ -782,6 +1090,12 @@ export class PiDaemonClient {
782
1090
  this.validate();
783
1091
  signal.throwIfAborted();
784
1092
  if (this.paused) throw new Error("Pi session is changing; no new work is authorized.");
1093
+ if (callback.kind === "directional-checkpoint") {
1094
+ this.validateFactsScope(connection, this.runSignal);
1095
+ return (
1096
+ !protectionOnly && this.directionalCheckpoint?.accept(connection, callback.job, payload?.fingerprint) === true
1097
+ );
1098
+ }
785
1099
  if (callback.kind === "queue-acquire") {
786
1100
  if (this.pendingReload) throw new Error("Pi resources are about to reload.");
787
1101
  if (payload.background && !this.facts().idle) throw new Error("Pi is busy; background apply was not granted.");
@@ -797,13 +1111,19 @@ export class PiDaemonClient {
797
1111
  const combined = AbortSignal.any([signal, this.signal]);
798
1112
  if (callback.kind === "model-binding") {
799
1113
  if (protectionOnly) return null;
800
- const facts = this.facts();
801
- const connection = this.connection ?? this.partialConnection;
802
- if (connection && JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model)) {
803
- await connection.update(facts);
804
- this.validate();
805
- }
806
- return payload.background && !facts.idle ? null : (facts.model ?? null);
1114
+ return this.queueFactsWithAbortableWait(combined, async () => {
1115
+ this.validateFactsScope(connection, combined);
1116
+ let facts = this.facts();
1117
+ if (JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model)) {
1118
+ await connection.update(facts);
1119
+ this.validateFactsScope(connection, combined);
1120
+ facts = this.facts();
1121
+ }
1122
+ return (payload.background && !facts.idle) ||
1123
+ JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model)
1124
+ ? null
1125
+ : (facts.model ?? null);
1126
+ });
807
1127
  }
808
1128
  if (callback.kind === "reload") {
809
1129
  if (!this.reloadRequest) throw new Error("No active Pi command can reload resources.");
@@ -873,6 +1193,14 @@ export class PiDaemonClient {
873
1193
  try {
874
1194
  await connection?.dispose(handoff);
875
1195
  confirmed = Boolean(connection);
1196
+ } catch (error) {
1197
+ if (
1198
+ !connection ||
1199
+ connection.identity.root !== this.recoveredOwner?.root ||
1200
+ connection.identity.instance !== this.recoveredOwner.instance ||
1201
+ connection.identity.pid !== this.recoveredOwner.pid
1202
+ )
1203
+ throw error;
876
1204
  } finally {
877
1205
  this.disposed = true;
878
1206
  if (clients.get(this.manager) === this) clients.delete(this.manager);
@@ -882,7 +1210,7 @@ export class PiDaemonClient {
882
1210
  if (confirmed) await gate.releaseAfterDrain();
883
1211
  else quarantineClient(gate, connection.paths.root, connection.identity, connection.facts);
884
1212
  }
885
- await this.work;
1213
+ await Promise.all([this.work, this.factsQueue]);
886
1214
  }
887
1215
  })();
888
1216
  return this.disposing;