@narumitw/pi-sync 0.63.1 → 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 (127) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +12 -5
  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-LBNC5AOM.ts → chunk-NDEZ52SS.ts} +12 -12
  10. package/dist/chunks/{chunk-B5F3JLD3.ts → chunk-RW44KNFD.ts} +304 -70
  11. package/dist/chunks/chunk-RW44KNFD.ts.map +7 -0
  12. package/dist/chunks/{chunk-EXDWEFIJ.ts → chunk-TJ7YNITN.ts} +5 -5
  13. package/dist/chunks/{chunk-HSCAFOT5.ts → chunk-TZMVSTAM.ts} +5 -5
  14. package/dist/chunks/{chunk-SXCH4Q5O.ts → chunk-VPSC7BXM.ts} +3 -3
  15. package/dist/chunks/{chunk-POWOMJ7S.ts → chunk-YT6PDRMM.ts} +58 -31
  16. package/dist/chunks/chunk-YT6PDRMM.ts.map +7 -0
  17. package/dist/chunks/{command-handler-GMRRFWOL.ts → command-handler-N45GY7AV.ts} +39 -27
  18. package/dist/chunks/command-handler-N45GY7AV.ts.map +7 -0
  19. package/dist/chunks/{conflict-review-JWEA7DPQ.ts → conflict-review-5E4M44BA.ts} +2 -2
  20. package/dist/chunks/{file-selection-KID23GAD.ts → file-selection-DDQN4LVD.ts} +9 -9
  21. package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts → manager-result-dispatcher-FKW55L7I.ts} +5 -5
  22. package/dist/chunks/{manager-ui-T5J5WG7T.ts → manager-ui-EV23DPZQ.ts} +75 -57
  23. package/dist/chunks/manager-ui-EV23DPZQ.ts.map +7 -0
  24. package/dist/chunks/{merge-review-OQDXNTJU.ts → merge-review-6YSLSMGS.ts} +3 -2
  25. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts +59 -0
  26. package/dist/chunks/ownership-recovery-UDDHSDSZ.ts.map +7 -0
  27. package/dist/chunks/{remote-selection-ui-GPITNEBF.ts → remote-selection-ui-N4NMWFT2.ts} +4 -4
  28. package/dist/chunks/{setup-switch-L54X5U5I.ts → setup-switch-HY7K3442.ts} +4 -4
  29. package/dist/chunks/{setup-wizard-LL6YMGUR.ts → setup-wizard-LEKDQ3HK.ts} +9 -9
  30. package/dist/chunks/{sync-inspection-SRU6HGGK.ts → sync-inspection-OS2LVOLV.ts} +5 -5
  31. package/dist/chunks/{sync-operations-UGSCONZ7.ts → sync-operations-D3MDJUQQ.ts} +2 -2
  32. package/dist/daemon/dist/cli.js +2 -0
  33. package/dist/daemon/dist/client-transport.js +66 -0
  34. package/dist/daemon/dist/client.js +116 -86
  35. package/dist/daemon/dist/consent.js +33 -11
  36. package/dist/daemon/dist/daemon-debug.js +33 -0
  37. package/dist/daemon/dist/daemon-recovery.js +75 -0
  38. package/dist/daemon/dist/engine/backends/git/git-backend.js +39 -12
  39. package/dist/daemon/dist/engine/backends/git/git-runner.js +6 -1
  40. package/dist/daemon/dist/engine/backends/git/git-storage.js +5 -9
  41. package/dist/daemon/dist/engine/backends/publication-encoding.js +19 -0
  42. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +10 -12
  43. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +15 -26
  44. package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +10 -0
  45. package/dist/daemon/dist/engine/debug-log.js +134 -0
  46. package/dist/daemon/dist/engine/paths.js +7 -1
  47. package/dist/daemon/dist/engine/settings/config-file.js +62 -17
  48. package/dist/daemon/dist/engine/settings/config.js +49 -14
  49. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +30 -8
  50. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +3 -1
  51. package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +32 -0
  52. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +34 -0
  53. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +50 -7
  54. package/dist/daemon/dist/engine/snapshot/snapshot.js +64 -25
  55. package/dist/daemon/dist/engine/state/lock.js +157 -17
  56. package/dist/daemon/dist/engine/sync/continuous-sync.js +35 -11
  57. package/dist/daemon/dist/engine/sync/initialization.js +2 -2
  58. package/dist/daemon/dist/engine/sync/local-fields.js +42 -19
  59. package/dist/daemon/dist/engine/sync/merged-sync.js +13 -10
  60. package/dist/daemon/dist/engine/sync/remote-snapshot.js +18 -3
  61. package/dist/daemon/dist/engine/sync/session-push.js +13 -4
  62. package/dist/daemon/dist/engine/sync/startup-bootstrap.js +105 -0
  63. package/dist/daemon/dist/engine/sync/startup-recovery-evidence.js +37 -0
  64. package/dist/daemon/dist/engine/sync/startup-timings.js +80 -8
  65. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +6 -1
  66. package/dist/daemon/dist/engine/sync/sync-inspection.js +4 -7
  67. package/dist/daemon/dist/engine/sync/sync-local.js +3 -1
  68. package/dist/daemon/dist/engine/sync/sync-mutations.js +9 -3
  69. package/dist/daemon/dist/engine/sync/sync-policy.js +9 -1
  70. package/dist/daemon/dist/engine/sync/sync-state.js +12 -4
  71. package/dist/daemon/dist/engine-service.js +54 -10
  72. package/dist/daemon/dist/identity.js +36 -6
  73. package/dist/daemon/dist/index.js +2 -1
  74. package/dist/daemon/dist/monitor.js +20 -1
  75. package/dist/daemon/dist/paged-review.js +177 -0
  76. package/dist/daemon/dist/participant-ledger.js +149 -0
  77. package/dist/daemon/dist/protocol.js +4 -0
  78. package/dist/daemon/dist/server.js +268 -120
  79. package/dist/daemon/dist/service-host.js +29 -9
  80. package/dist/daemon/dist/state-wait-jobs.js +23 -0
  81. package/dist/daemon/dist/state-wait.js +34 -0
  82. package/dist/daemon/package.json +1 -1
  83. package/dist/index.ts +128 -48
  84. package/dist/index.ts.map +2 -2
  85. package/docs/continuous-sync-verification.md +2 -0
  86. package/docs/daemon-migration.md +30 -2
  87. package/docs/tui-contract.md +7 -1
  88. package/package.json +2 -2
  89. package/skills/configure-pi-sync/references/configuration.md +23 -13
  90. package/src/commands/command-execution.ts +11 -3
  91. package/src/commands/command-handler.ts +10 -3
  92. package/src/commands/command.ts +3 -2
  93. package/src/daemon/client-debug.ts +45 -0
  94. package/src/daemon/ownership-recovery.ts +50 -0
  95. package/src/daemon/pi-client.ts +288 -63
  96. package/src/daemon/startup-bootstrap-client.ts +26 -0
  97. package/src/settings/config.ts +1 -0
  98. package/src/sync/automatic-sync.ts +61 -18
  99. package/src/sync/startup-check.ts +13 -5
  100. package/src/sync-extension.ts +46 -8
  101. package/src/ui/manager-state.ts +29 -21
  102. package/src/ui/manager-ui.ts +16 -1
  103. package/src/ui/merge-review.ts +52 -16
  104. package/src/ui/settings-ui.ts +2 -2
  105. package/src/ui/sync-confirmation.ts +16 -19
  106. package/src/ui/sync-setups-ui.ts +15 -12
  107. package/dist/chunks/chunk-27F5W7DX.ts.map +0 -7
  108. package/dist/chunks/chunk-B5F3JLD3.ts.map +0 -7
  109. package/dist/chunks/chunk-HLCML3OW.ts.map +0 -7
  110. package/dist/chunks/chunk-POWOMJ7S.ts.map +0 -7
  111. package/dist/chunks/command-handler-GMRRFWOL.ts.map +0 -7
  112. package/dist/chunks/manager-ui-T5J5WG7T.ts.map +0 -7
  113. /package/dist/chunks/{chunk-V76KCWHO.ts.map → chunk-F3VODLVQ.ts.map} +0 -0
  114. /package/dist/chunks/{chunk-VQ47JBLF.ts.map → chunk-FI2F5JBS.ts.map} +0 -0
  115. /package/dist/chunks/{chunk-LBNC5AOM.ts.map → chunk-NDEZ52SS.ts.map} +0 -0
  116. /package/dist/chunks/{chunk-EXDWEFIJ.ts.map → chunk-TJ7YNITN.ts.map} +0 -0
  117. /package/dist/chunks/{chunk-HSCAFOT5.ts.map → chunk-TZMVSTAM.ts.map} +0 -0
  118. /package/dist/chunks/{chunk-SXCH4Q5O.ts.map → chunk-VPSC7BXM.ts.map} +0 -0
  119. /package/dist/chunks/{conflict-review-JWEA7DPQ.ts.map → conflict-review-5E4M44BA.ts.map} +0 -0
  120. /package/dist/chunks/{file-selection-KID23GAD.ts.map → file-selection-DDQN4LVD.ts.map} +0 -0
  121. /package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts.map → manager-result-dispatcher-FKW55L7I.ts.map} +0 -0
  122. /package/dist/chunks/{merge-review-OQDXNTJU.ts.map → merge-review-6YSLSMGS.ts.map} +0 -0
  123. /package/dist/chunks/{remote-selection-ui-GPITNEBF.ts.map → remote-selection-ui-N4NMWFT2.ts.map} +0 -0
  124. /package/dist/chunks/{setup-switch-L54X5U5I.ts.map → setup-switch-HY7K3442.ts.map} +0 -0
  125. /package/dist/chunks/{setup-wizard-LL6YMGUR.ts.map → setup-wizard-LEKDQ3HK.ts.map} +0 -0
  126. /package/dist/chunks/{sync-inspection-SRU6HGGK.ts.map → sync-inspection-OS2LVOLV.ts.map} +0 -0
  127. /package/dist/chunks/{sync-operations-UGSCONZ7.ts.map → sync-operations-D3MDJUQQ.ts.map} +0 -0
@@ -0,0 +1,50 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { inspectDaemonRecovery, stopDaemonForRecovery } from "@narumitw/pi-sync-daemon";
3
+ import { errorMessage } from "../sync/sync-errors.js";
4
+ import { safeTerminalText } from "../ui/terminal-text.js";
5
+ import type { PiDaemonClient } from "./pi-client.js";
6
+
7
+ export async function recoverDaemonOwnership(
8
+ ctx: ExtensionContext,
9
+ client: Pick<PiDaemonClient, "root" | "validate" | "confirmRecoveryExit">,
10
+ signal: AbortSignal | undefined,
11
+ ) {
12
+ function current() {
13
+ signal?.throwIfAborted();
14
+ client.validate();
15
+ }
16
+ try {
17
+ current();
18
+ if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) throw new Error("Daemon recovery requires TUI or RPC mode.");
19
+ const owner = await inspectDaemonRecovery(client.root, signal);
20
+ current();
21
+ if (!owner) {
22
+ ctx.ui.notify("No daemon is running for this agent directory. Use /reload before syncing.", "info");
23
+ return;
24
+ }
25
+ const approved = await ctx.ui.confirm(
26
+ "Stop Pi Sync daemon for recovery?",
27
+ `Agent directory: ${safeTerminalText(owner.root)}\nPID: ${owner.pid}\n\nStop sync work for all Pi sessions using this daemon. This does not start a replacement, remove sync evidence, or retry a transfer.`,
28
+ { signal },
29
+ );
30
+ current();
31
+ if (!approved) return;
32
+ await stopDaemonForRecovery(owner, signal);
33
+ current();
34
+ client.confirmRecoveryExit(owner);
35
+ ctx.ui.notify(
36
+ "Pi Sync daemon exited. Use /reload, then open /sync. If a stale lock remains, choose Restore sync access. Check the sync state before retrying any transfer.",
37
+ "info",
38
+ );
39
+ } catch (error) {
40
+ try {
41
+ current();
42
+ } catch {
43
+ return;
44
+ }
45
+ ctx.ui.notify(
46
+ `Pi Sync daemon recovery could not finish: ${safeTerminalText(errorMessage(error))}\nKeep recovery files. Use /sync daemon recover to review the owner again, or follow the daemon CLI recovery guide.`,
47
+ "error",
48
+ );
49
+ }
50
+ }
@@ -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,10 @@ 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";
41
45
  import { createQueueReleaseUI, type QueueReleaseEvent } from "./queue-release-ui.js";
42
46
  import { quarantineClient, recoverDetachedClients } from "./recovery.js";
47
+ import { requestStartupBootstrap } from "./startup-bootstrap-client.js";
43
48
 
44
49
  const scope = new AsyncLocalStorage<{ client: PiDaemonClient; reload?: AbortController }>();
45
50
  const clients = new WeakMap<ExtensionContext["sessionManager"], PiDaemonClient>();
@@ -229,6 +234,7 @@ export class PiDaemonClient {
229
234
  private protectionOnly = false;
230
235
  private partialConnection?: DaemonConnection;
231
236
  private work = Promise.resolve();
237
+ private factsQueue = Promise.resolve();
232
238
  private closing = false;
233
239
  private paused = false;
234
240
  private pausing?: Promise<void>;
@@ -263,6 +269,7 @@ export class PiDaemonClient {
263
269
  private readonly busy = new Set<string>();
264
270
  private initialized = false;
265
271
  private startupDebug = false;
272
+ private debug = false;
266
273
  private participantIdentity = { id: randomUUID(), generation: randomUUID() };
267
274
  get id() {
268
275
  return this.participantIdentity.id;
@@ -271,6 +278,8 @@ export class PiDaemonClient {
271
278
  return this.participantIdentity.generation;
272
279
  }
273
280
  readonly root: string;
281
+ private cleanupRequired = false;
282
+ private recoveredOwner?: DaemonRecoveryTarget;
274
283
  private readonly rawRoot: string;
275
284
  private readonly gate: PiApplyGate;
276
285
  private readonly manager: ExtensionContext["sessionManager"];
@@ -297,6 +306,19 @@ export class PiDaemonClient {
297
306
  if (getAgentDir() !== this.rawRoot || canonicalPath(path.resolve(this.rawRoot)) !== this.root)
298
307
  throw new Error("Agent directory changed; reload before synchronization.");
299
308
  }
309
+ get debugEnabled() {
310
+ return this.debug;
311
+ }
312
+ setDebugPreference(debug: boolean) {
313
+ this.debug = debug && this.ctx.hasUI && (this.ctx.mode === "tui" || this.ctx.mode === "rpc");
314
+ }
315
+ recordDebug(event: DebugEvent) {
316
+ if (!this.debug || this.protectionOnly || this.pendingReload || !this.ownsContactUI()) return;
317
+ try {
318
+ this.validate();
319
+ appendDebugEvent(this.root, "pi-sync", event);
320
+ } catch {}
321
+ }
300
322
  private modelBinding(): ClientFacts["model"] {
301
323
  const model = this.ctx.model;
302
324
  if (!model) return undefined;
@@ -356,9 +378,16 @@ export class PiDaemonClient {
356
378
  }
357
379
  async attachExisting({ allowUpgrade = false } = {}) {
358
380
  this.validate();
359
- const address = await findDaemon(this.root);
381
+ if (!allowUpgrade && !this.paused && this.connection?.contactState === "active") return !this.protectionOnly;
382
+ const address = await findDaemon(this.root).catch((error: unknown) => {
383
+ this.recordDebug({ event: "connection", outcome: "failed" });
384
+ throw error;
385
+ });
360
386
  this.validate();
361
- if (!address) return false;
387
+ if (!address) {
388
+ this.recordDebug({ event: "connection", outcome: "skipped" });
389
+ return false;
390
+ }
362
391
  const upgrade = allowUpgrade && address.needsUpgrade && this.ctx.hasUI && ["tui", "rpc"].includes(this.ctx.mode);
363
392
  let upgradeFailure: string | undefined;
364
393
  if (upgrade) {
@@ -391,12 +420,14 @@ export class PiDaemonClient {
391
420
  }
392
421
  async finishReattachment() {
393
422
  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
- }
423
+ const connection = this.connection;
424
+ if (!connection) return;
425
+ await recoverDetachedClients(connection);
426
+ await this.queueFacts(async () => {
427
+ this.validateFactsScope(connection);
428
+ await connection.attach(this.signal);
429
+ this.validateFactsScope(connection);
430
+ });
400
431
  }
401
432
  async connect(existing?: Awaited<ReturnType<typeof ensureDaemon>>, requestSignal?: AbortSignal) {
402
433
  const startupSignal = requestSignal ? AbortSignal.any([this.signal, requestSignal]) : this.signal;
@@ -434,7 +465,11 @@ export class PiDaemonClient {
434
465
  if (daemon.paths.root !== this.root) throw new Error("Daemon root changed before attach.");
435
466
  const protectionOnly = daemon.needsUpgrade === true;
436
467
  const connection = new DaemonConnection(daemon.paths, daemon.identity, this.facts(protectionOnly), {
437
- callback: (callback, signal) => this.callback(callback, signal, protectionOnly),
468
+ callback: (callback, signal) => this.callback(connection, callback, signal, protectionOnly),
469
+ mergeReview:
470
+ !protectionOnly && this.ctx.hasUI
471
+ ? (callback, loadDetails, signal) => this.pagedMergeReview(connection, callback, loadDetails, signal)
472
+ : undefined,
438
473
  event: (event) => {
439
474
  if (event.kind === "commit") return;
440
475
  if (this.signal.aborted || this.disposed || this.closing || clients.get(this.manager) !== this) return;
@@ -491,10 +526,22 @@ export class PiDaemonClient {
491
526
  this.partialConnection = undefined;
492
527
  return connection;
493
528
  }
494
- })().catch((error) => {
495
- this.connecting = undefined;
496
- throw error;
497
- });
529
+ })().then(
530
+ (connection) => {
531
+ this.recordDebug({ event: "connection", outcome: startupSignal.aborted ? "cancelled" : "completed" });
532
+ return connection;
533
+ },
534
+ (error: unknown) => {
535
+ this.connecting = undefined;
536
+ const outcome = startupSignal.aborted
537
+ ? "cancelled"
538
+ : existing && remoteErrorNamed(error, "DaemonStoppingError")
539
+ ? "skipped"
540
+ : "failed";
541
+ this.recordDebug({ event: "connection", outcome });
542
+ throw error;
543
+ },
544
+ );
498
545
  const connection = await this.connecting;
499
546
  validateStartup();
500
547
  if (!existing && this.protectionOnly)
@@ -558,71 +605,99 @@ export class PiDaemonClient {
558
605
  this.contactFactsUnpublished = false;
559
606
  this.clearConnectionStatus();
560
607
  }
561
- private async resumeContact(connection: DaemonConnection) {
608
+ private queueFacts<T>(publish: () => Promise<T>): Promise<T> {
609
+ const result = this.factsQueue.then(publish);
610
+ this.factsQueue = result.then(
611
+ () => {},
612
+ () => {},
613
+ );
614
+ return result;
615
+ }
616
+ private async queueFactsWithAbortableWait<T>(signal: AbortSignal, publish: () => Promise<T>): Promise<T> {
617
+ signal.throwIfAborted();
618
+ const cancelled = Promise.withResolvers<never>();
619
+ const abort = () => cancelled.reject(signal.reason);
620
+ signal.addEventListener("abort", abort, { once: true });
621
+ const queued = this.queueFacts(() => {
622
+ signal.removeEventListener("abort", abort);
623
+ signal.throwIfAborted();
624
+ return publish();
625
+ });
626
+ return Promise.race([queued, cancelled.promise]);
627
+ }
628
+ private validateFactsScope(connection?: DaemonConnection, signal?: AbortSignal) {
562
629
  this.validate();
563
- if (this.paused || this.connection !== connection) throw new Error("Pi Sync is paused for a session change.");
630
+ signal?.throwIfAborted();
631
+ if (this.paused) throw new Error("Pi Sync is paused for a session change.");
632
+ if (connection && connection !== (this.connection ?? this.partialConnection))
633
+ throw new Error("Synchronization session was replaced.");
634
+ }
635
+ private async resumeContact(connection: DaemonConnection) {
636
+ this.validateFactsScope(connection);
564
637
  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
638
  const controller = new AbortController();
578
639
  const signal = AbortSignal.any([this.signal, controller.signal]);
579
- const attempt: { error?: unknown } = {};
580
- this.contactAttempt = attempt;
581
- const done = Promise.resolve().then(async () => {
640
+ const done = this.queueFacts(async () => {
641
+ this.validateFactsScope(connection, signal);
642
+ if (connection.contactState === "active" && connection.contactResumeState !== "uncertain") return;
643
+ if (this.gate.size || connection.hasPendingWork || connection.contactResumeState === "uncertain") {
644
+ throw new Error(
645
+ "Pi Sync cannot reconnect while previous work is still running or uncertain. Check sync recovery before retrying.",
646
+ );
647
+ }
648
+ const earlier = this.contactAttempt;
649
+ if (connection.contactState !== "expired" || earlier) {
650
+ throw new Error("Pi Sync could not restore contact. Review pending work before using /reload.", {
651
+ cause: earlier?.error,
652
+ });
653
+ }
654
+ const attempt: { error?: unknown } = {};
655
+ this.contactAttempt = attempt;
582
656
  try {
583
- this.validate();
584
- signal.throwIfAborted();
585
657
  this.showContactStatus("sync reconnecting", "retry");
586
658
  // Admission can wait behind an apply. Do not advertise readiness using
587
659
  // facts sampled before that wait; publish current facts after the ack.
588
660
  await connection.resumeContact({ ...this.facts(), idle: false, ready: false }, signal);
589
- this.validate();
590
- signal.throwIfAborted();
661
+ this.validateFactsScope(connection, signal);
591
662
  this.contactFactsUnpublished = true;
592
663
  this.contactAttempt = undefined;
593
- await connection.update(this.facts());
594
- this.validate();
595
- signal.throwIfAborted();
596
- this.confirmContact(connection);
664
+ await this.publishCurrentFacts(connection, signal);
665
+ this.recordDebug({ event: "connection", outcome: "completed" });
597
666
  } catch (error) {
667
+ this.recordDebug({ event: "connection", outcome: signal.aborted ? "cancelled" : "failed" });
598
668
  attempt.error = error;
599
- if (this.ownsContactUI() && !signal.aborted)
669
+ if (this.ownsContactUI() && !signal.aborted) {
670
+ this.validateFactsScope(connection, signal);
600
671
  this.showContactStatus("sync reconnect blocked; check /sync daemon status", "blocked");
672
+ }
601
673
  throw error;
602
- } finally {
603
- if (this.contactRepair?.controller === controller) this.contactRepair = undefined;
604
674
  }
675
+ }).finally(() => {
676
+ if (this.contactRepair?.controller === controller) this.contactRepair = undefined;
605
677
  });
606
678
  this.contactRepair = { controller, done };
607
679
  return done;
608
680
  }
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.");
681
+ private async publishCurrentFacts(connection: DaemonConnection, signal?: AbortSignal) {
682
+ this.validateFactsScope(connection, signal);
613
683
  if (connection.contactResumeState === "uncertain")
614
684
  throw new Error("Pi Sync cannot verify the previous reconnect. Review pending work before using /reload.");
685
+ await connection.update(this.facts());
686
+ this.validateFactsScope(connection, signal);
687
+ this.confirmContact(connection);
688
+ }
689
+ private async publishFacts(connection: DaemonConnection, signal?: AbortSignal) {
690
+ if (this.contactRepair) await this.contactRepair.done;
691
+ const publish = () => this.queueFacts(() => this.publishCurrentFacts(connection, signal));
615
692
  try {
616
- await connection.update(this.facts());
693
+ await publish();
617
694
  } catch (error) {
695
+ this.validateFactsScope(connection, signal);
618
696
  if (!connection.facts.hasUI || !remoteErrorNamed(error, "ClientContactExpiredError")) throw error;
619
697
  await this.resumeContact(connection);
620
- this.validate();
621
698
  // A shared repair might have started before these facts changed.
622
- await connection.update(this.facts());
699
+ await publish();
623
700
  }
624
- this.validate();
625
- this.confirmContact(connection);
626
701
  }
627
702
  private confirmContact(connection: DaemonConnection) {
628
703
  if (connection.contactState === "expired" || connection.contactState === "inactive")
@@ -632,7 +707,7 @@ export class PiDaemonClient {
632
707
  async verifyConnection(signal?: AbortSignal) {
633
708
  const connection = await this.connect(undefined, signal);
634
709
  signal?.throwIfAborted();
635
- await this.publishFacts(connection);
710
+ await this.publishFacts(connection, signal);
636
711
  signal?.throwIfAborted();
637
712
  return connection;
638
713
  }
@@ -648,6 +723,25 @@ export class PiDaemonClient {
648
723
  }
649
724
  return decode(await this.run(repair ? "settings.repair-read" : "settings.read", {}));
650
725
  }
726
+ get ownershipCleanupRequired() {
727
+ return this.cleanupRequired;
728
+ }
729
+ confirmRecoveryExit(owner: DaemonRecoveryTarget) {
730
+ this.cleanupRequired = true;
731
+ this.recoveredOwner = owner;
732
+ }
733
+ recordOwnershipFailure(error: unknown) {
734
+ if (
735
+ (error instanceof DaemonError && error.remote.properties?.code === OWNERSHIP_CLEANUP_REQUIRED) ||
736
+ (error instanceof Error &&
737
+ (("code" in error && error.code === OWNERSHIP_CLEANUP_REQUIRED) ||
738
+ error.message === "Daemon ownership cleanup is uncertain; stop and reconcile before restarting." ||
739
+ error.message === "Daemon ownership cleanup is uncertain; stop and reconcile before retrying." ||
740
+ error.message ===
741
+ "File-queue release is uncertain; stop the daemon and keep grants quarantined until owner exit."))
742
+ )
743
+ this.cleanupRequired = true;
744
+ }
651
745
  run(
652
746
  operation: string,
653
747
  payload: unknown,
@@ -656,7 +750,14 @@ export class PiDaemonClient {
656
750
  onCommit?: () => void,
657
751
  reload?: AbortController,
658
752
  ) {
659
- const result = this.work.then(() => this.runCurrent(operation, payload, signal, ctx, onCommit, reload));
753
+ const diagnostics = this.debug ? observeDebugJob(operation, (event) => this.recordDebug(event)) : undefined;
754
+ const result = this.work
755
+ .then(() => this.runCurrent(operation, payload, signal, ctx, onCommit, reload, diagnostics))
756
+ .catch((error: unknown) => {
757
+ diagnostics?.rejected(error, Boolean(signal?.aborted || reload?.signal.aborted));
758
+ this.recordOwnershipFailure(error);
759
+ throw error;
760
+ });
660
761
  this.work = result.then(
661
762
  () => {},
662
763
  () => {},
@@ -670,6 +771,7 @@ export class PiDaemonClient {
670
771
  ctx = this.ctx,
671
772
  onCommit?: () => void,
672
773
  reload?: AbortController,
774
+ diagnostics?: ReturnType<typeof observeDebugJob>,
673
775
  ) {
674
776
  this.validate();
675
777
  signal?.throwIfAborted();
@@ -687,7 +789,7 @@ export class PiDaemonClient {
687
789
  signal?.throwIfAborted();
688
790
  if (this.paused)
689
791
  await connection.update(this.facts()); // Existing, explicitly attached shutdown path.
690
- else await this.publishFacts(connection);
792
+ else await this.publishFacts(connection, signal);
691
793
  this.validate();
692
794
  signal?.throwIfAborted();
693
795
  this.uiContext = ctx;
@@ -699,7 +801,9 @@ export class PiDaemonClient {
699
801
  const clearForeground = () => this.releaseUI.finishForeground(Boolean(this.releaseContext()));
700
802
  runSignal.addEventListener("abort", clearForeground, { once: true });
701
803
  try {
702
- const result = await connection.run(operation, payload, runSignal, onCommit);
804
+ const result = await connection.run(operation, payload, runSignal, onCommit, diagnostics?.onSubmit);
805
+ if (runSignal.aborted || reload?.signal.aborted) diagnostics?.rejected(undefined, true);
806
+ else diagnostics?.returned(result);
703
807
  if (request?.received && reload && !this.paused && !reload.signal.aborted && !signal?.aborted) {
704
808
  this.validate();
705
809
  this.pendingReload = reload;
@@ -739,9 +843,72 @@ export class PiDaemonClient {
739
843
  releaseReload(owner: AbortController) {
740
844
  if (this.pendingReload === owner) this.pendingReload = undefined;
741
845
  }
846
+ async readStartupSettings(signal: AbortSignal) {
847
+ this.validate();
848
+ await settingsQueue;
849
+ this.validate();
850
+ signal.throwIfAborted();
851
+ const document = await peekLocalConfigDocument();
852
+ this.validate();
853
+ signal.throwIfAborted();
854
+ if (document && document.bytes.length > MAX_SETTINGS_BYTES)
855
+ throw new Error("Settings exceed the local API byte limit; the source document is unchanged.");
856
+ return { document, settings: document && validateSettingsDocument(document.parsed) };
857
+ }
858
+ tryStartupBootstrap(document: LocalConfigDocument, debug: boolean, signal: AbortSignal) {
859
+ const ownedSignal = AbortSignal.any([signal, this.signal]);
860
+ let retirement: Promise<void> | undefined;
861
+ const operation = this.work.then(async () => {
862
+ const verify = (connection?: DaemonConnection) => {
863
+ this.validateFactsScope(connection, ownedSignal);
864
+ if (this.pendingReload) throw new Error("Pi Sync is paused for a session change.");
865
+ };
866
+ verify();
867
+ const connection = await this.connect(undefined, ownedSignal);
868
+ return this.queueFacts(async () => {
869
+ verify(connection);
870
+ if (connection.contactState !== "active" || connection.contactResumeState !== "idle") return false;
871
+ const settingsFingerprint = fingerprint(document);
872
+ let mayHavePublished = true;
873
+ try {
874
+ const ready = await requestStartupBootstrap(connection, settingsFingerprint, debug, ownedSignal);
875
+ mayHavePublished = ready;
876
+ verify(connection);
877
+ if (!ready) return false;
878
+ if (connection.contactState === "active") this.confirmContact(connection);
879
+ this.startupDebug = debug;
880
+ this.initialized = true;
881
+ Object.assign(connection.facts, { ready: true, startupDebug: debug });
882
+ return true;
883
+ } catch (error) {
884
+ if (mayHavePublished) {
885
+ retirement = this.dispose();
886
+ void retirement.catch(() => {});
887
+ }
888
+ throw error;
889
+ }
890
+ });
891
+ });
892
+ this.work = operation.then(
893
+ () => {},
894
+ () => {},
895
+ );
896
+ return operation.catch(async (error: unknown) => {
897
+ try {
898
+ await retirement;
899
+ } catch (cause) {
900
+ throw new AggregateError(
901
+ [error, cause],
902
+ "Startup readiness is uncertain; reconcile the daemon before reconnecting.",
903
+ );
904
+ }
905
+ throw error;
906
+ });
907
+ }
742
908
  async markReady(debug: boolean) {
743
909
  this.validate();
744
910
  this.startupDebug = debug;
911
+ this.setDebugPreference(debug);
745
912
  this.initialized = true;
746
913
  await this.update();
747
914
  this.validate();
@@ -760,7 +927,51 @@ export class PiDaemonClient {
760
927
  if (this.connection && !this.paused && !this.disposed && !this.signal.aborted)
761
928
  await this.publishFacts(this.connection);
762
929
  }
763
- private async callback(callback: Callback, signal: AbortSignal, protectionOnly: boolean) {
930
+ private async pagedMergeReview(
931
+ connection: DaemonConnection,
932
+ callback: Callback,
933
+ loadDetails: (signal?: AbortSignal) => Promise<string>,
934
+ signal: AbortSignal,
935
+ ) {
936
+ const ctx = this.uiContext;
937
+ const generation = this.generation;
938
+ const combined = AbortSignal.any([signal, this.signal]);
939
+ const isCurrent = () =>
940
+ !combined.aborted &&
941
+ this.ownsContactUI() &&
942
+ this.uiContext === ctx &&
943
+ this.generation === generation &&
944
+ (this.connection ?? this.partialConnection) === connection;
945
+ if (!isCurrent()) return false;
946
+ this.validate();
947
+ if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode)) throw new Error("This client cannot present safety reviews.");
948
+ const { title, confirmationLabel, summaryLines } = callback.payload as {
949
+ title: string;
950
+ confirmationLabel?: string;
951
+ summaryLines: readonly string[];
952
+ };
953
+ const { confirmMergeReview } = await import("../ui/merge-review.js");
954
+ if (!isCurrent()) return false;
955
+ this.validate();
956
+ const result = await confirmMergeReview(
957
+ ctx,
958
+ title,
959
+ loadDetails,
960
+ combined,
961
+ isCurrent,
962
+ confirmationLabel,
963
+ summaryLines,
964
+ );
965
+ if (!isCurrent()) return false;
966
+ this.validate();
967
+ return result;
968
+ }
969
+ private async callback(
970
+ connection: DaemonConnection,
971
+ callback: Callback,
972
+ signal: AbortSignal,
973
+ protectionOnly: boolean,
974
+ ) {
764
975
  const payload = callback.payload as {
765
976
  reservation?: string;
766
977
  targets?: string[];
@@ -797,13 +1008,19 @@ export class PiDaemonClient {
797
1008
  const combined = AbortSignal.any([signal, this.signal]);
798
1009
  if (callback.kind === "model-binding") {
799
1010
  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);
1011
+ return this.queueFactsWithAbortableWait(combined, async () => {
1012
+ this.validateFactsScope(connection, combined);
1013
+ let facts = this.facts();
1014
+ if (JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model)) {
1015
+ await connection.update(facts);
1016
+ this.validateFactsScope(connection, combined);
1017
+ facts = this.facts();
1018
+ }
1019
+ return (payload.background && !facts.idle) ||
1020
+ JSON.stringify(connection.facts.model) !== JSON.stringify(facts.model)
1021
+ ? null
1022
+ : (facts.model ?? null);
1023
+ });
807
1024
  }
808
1025
  if (callback.kind === "reload") {
809
1026
  if (!this.reloadRequest) throw new Error("No active Pi command can reload resources.");
@@ -873,6 +1090,14 @@ export class PiDaemonClient {
873
1090
  try {
874
1091
  await connection?.dispose(handoff);
875
1092
  confirmed = Boolean(connection);
1093
+ } catch (error) {
1094
+ if (
1095
+ !connection ||
1096
+ connection.identity.root !== this.recoveredOwner?.root ||
1097
+ connection.identity.instance !== this.recoveredOwner.instance ||
1098
+ connection.identity.pid !== this.recoveredOwner.pid
1099
+ )
1100
+ throw error;
876
1101
  } finally {
877
1102
  this.disposed = true;
878
1103
  if (clients.get(this.manager) === this) clients.delete(this.manager);
@@ -882,7 +1107,7 @@ export class PiDaemonClient {
882
1107
  if (confirmed) await gate.releaseAfterDrain();
883
1108
  else quarantineClient(gate, connection.paths.root, connection.identity, connection.facts);
884
1109
  }
885
- await this.work;
1110
+ await Promise.all([this.work, this.factsQueue]);
886
1111
  }
887
1112
  })();
888
1113
  return this.disposing;
@@ -0,0 +1,26 @@
1
+ import { type DaemonConnection, DaemonError, requestDaemon } from "@narumitw/pi-sync-daemon";
2
+
3
+ export async function requestStartupBootstrap(
4
+ connection: DaemonConnection,
5
+ fingerprint: string | null,
6
+ debug: boolean,
7
+ signal: AbortSignal,
8
+ ): Promise<boolean> {
9
+ let result: unknown;
10
+ try {
11
+ const { id: client, generation } = connection.facts;
12
+ result = await requestDaemon(
13
+ connection.paths,
14
+ connection.identity,
15
+ "startup.bootstrap",
16
+ { client, generation, fingerprint, debug },
17
+ signal,
18
+ );
19
+ } catch (error) {
20
+ if (error instanceof DaemonError && error.name === "Error" && error.message === "Unknown daemon method.")
21
+ return false;
22
+ throw error;
23
+ }
24
+ if (typeof result !== "boolean") throw new Error("Invalid startup bootstrap response.");
25
+ return result;
26
+ }
@@ -1,6 +1,7 @@
1
1
  export type * from "@narumitw/pi-sync-daemon/engine/settings/config";
2
2
  export {
3
3
  configFromSettings,
4
+ createSettingsConfigView,
4
5
  isEnabled,
5
6
  isExplicitlyEnabled,
6
7
  loadConfig,