@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
@@ -7,10 +7,14 @@ import { readConsent } from "./consent.js";
7
7
  import { configureEngineHost } from "./engine/host.js";
8
8
  import { canonicalRootGuard, processExists } from "./identity.js";
9
9
  import { withCleanup } from "./lifecycle.js";
10
+ import { OWNERSHIP_CLEANUP_REQUIRED } from "./protocol.js";
11
+ class OwnershipCleanupError extends Error {
12
+ code = OWNERSHIP_CLEANUP_REQUIRED;
13
+ }
10
14
  const scope = new AsyncLocalStorage();
11
15
  /** One service process owns one root; tests must use a separate process per root. */
12
16
  export function installServiceHost(root, ignoreFileOperationsAvailable) {
13
- let poisoned = false;
17
+ let poisoned;
14
18
  const assertRoot = canonicalRootGuard(root);
15
19
  function current() {
16
20
  const value = scope.getStore();
@@ -27,7 +31,7 @@ export function installServiceHost(root, ignoreFileOperationsAvailable) {
27
31
  const owner = current();
28
32
  assertRoot();
29
33
  if (poisoned)
30
- throw new Error("Daemon ownership cleanup is uncertain; stop and reconcile before retrying.");
34
+ throw new OwnershipCleanupError("Daemon ownership cleanup is uncertain; stop and reconcile before retrying.");
31
35
  const missing = [...new Set(targets)].filter((target) => !owner.held.has(target)).sort();
32
36
  if (!missing.length)
33
37
  return action();
@@ -38,30 +42,53 @@ export function installServiceHost(root, ignoreFileOperationsAvailable) {
38
42
  protectedTarget(target, owner.execution);
39
43
  const peers = owner.peers.toSorted((a, b) => a.id.localeCompare(b.id));
40
44
  const requested = [];
45
+ const foreground = owner.foreground;
46
+ let acquireFailed = false;
47
+ let completed = false;
41
48
  return withCleanup(async () => {
42
49
  for (const peer of peers) {
43
50
  owner.execution.validate();
44
51
  const reservation = randomUUID();
45
52
  requested.push({ client: peer.id, reservation });
46
- await owner.execution.request("queue-acquire", { reservation, targets: missing, generation: peer.generation, background: !owner.execution.clientId }, peer.id);
53
+ try {
54
+ await owner.execution.request("queue-acquire", { reservation, targets: missing, generation: peer.generation, background: !owner.execution.clientId }, peer.id);
55
+ }
56
+ catch (error) {
57
+ acquireFailed = true;
58
+ throw error;
59
+ }
47
60
  owner.execution.validate();
48
61
  }
49
62
  for (const target of missing)
50
63
  protectedTarget(target, owner.execution);
51
- return await scope.run({ ...owner, held: new Set([...owner.held, ...missing]) }, action);
64
+ if (foreground)
65
+ foreground.entered = true;
66
+ const result = await scope.run({ ...owner, held: new Set([...owner.held, ...missing]) }, action);
67
+ completed = true;
68
+ return result;
52
69
  }, async () => {
53
70
  // Release by request identity even when a grant response was lost. A cancelled
54
71
  // prompt is not evidence that a granted remote writer stopped.
55
- const results = await Promise.allSettled(requested.map(({ client, reservation }) => {
72
+ const results = await Promise.allSettled(requested.map(async ({ client, reservation }) => {
56
73
  const peer = peers.find((peer) => peer.id === client);
57
- return peer && !processExists(peer.pid)
58
- ? Promise.resolve(true)
59
- : owner.execution.request("queue-release", { reservation }, client);
74
+ if (peer && !processExists(peer.pid))
75
+ return;
76
+ if ((await owner.execution.request("queue-release", { reservation }, client)) !== true)
77
+ throw new Error("File-queue release was not acknowledged.");
60
78
  }));
61
79
  const failure = results.find((result) => result.status === "rejected");
62
80
  if (failure?.status === "rejected") {
63
- poisoned = true;
64
- throw new Error("File-queue release is uncertain; stop the daemon and keep grants quarantined until owner exit.", { cause: failure.reason });
81
+ poisoned ??= "queue";
82
+ const error = new OwnershipCleanupError("File-queue release is uncertain; stop the daemon and keep grants quarantined until owner exit.", { cause: failure.reason });
83
+ if (foreground && poisoned === "queue") {
84
+ if (completed) {
85
+ foreground.deferred = true;
86
+ return;
87
+ }
88
+ if (acquireFailed && !foreground.entered && !owner.execution.signal.aborted)
89
+ foreground.beforeMutation = error;
90
+ }
91
+ throw error;
65
92
  }
66
93
  });
67
94
  }
@@ -70,8 +97,8 @@ export function installServiceHost(root, ignoreFileOperationsAvailable) {
70
97
  allowConfigMigration: () => Boolean(readConsent(root)),
71
98
  root: () => {
72
99
  assertRoot();
73
- if (poisoned)
74
- throw new Error("Daemon ownership cleanup is uncertain; stop and reconcile before restarting.");
100
+ if (poisoned && !(poisoned === "queue" && scope.getStore()?.foreground?.deferred))
101
+ throw new OwnershipCleanupError("Daemon ownership cleanup is uncertain; stop and reconcile before restarting.");
75
102
  return root;
76
103
  },
77
104
  reserveTargets: reserve,
@@ -105,8 +132,10 @@ export function installServiceHost(root, ignoreFileOperationsAvailable) {
105
132
  await release?.();
106
133
  }
107
134
  catch (error) {
108
- poisoned = true;
109
- throw error;
135
+ poisoned = "other";
136
+ throw new OwnershipCleanupError("Pi settings lock release failed; stop and reconcile before restarting.", {
137
+ cause: error,
138
+ });
110
139
  }
111
140
  });
112
141
  });
@@ -120,8 +149,47 @@ export function installServiceHost(root, ignoreFileOperationsAvailable) {
120
149
  status: (_ctx, value, presentation) => current().execution.emit("status", { value, presentation }),
121
150
  });
122
151
  return {
152
+ cleanupRequired: () => poisoned !== undefined,
153
+ async runForeground(execution, action) {
154
+ const owner = current();
155
+ if (owner.execution !== execution || !execution.clientId || owner.held.size || owner.foreground)
156
+ throw new Error("Foreground queue recovery requires one attached directional job.");
157
+ const foreground = { entered: false, deferred: false };
158
+ return scope.run({ ...owner, foreground }, async () => {
159
+ try {
160
+ const result = await action();
161
+ if (foreground.deferred && poisoned === "queue")
162
+ return { foregroundQueueCleanup: "verified-result", result };
163
+ return result;
164
+ }
165
+ catch (error) {
166
+ if (foreground.beforeMutation &&
167
+ !execution.signal.aborted &&
168
+ error instanceof AggregateError &&
169
+ error.errors.includes(foreground.beforeMutation))
170
+ return { foregroundQueueCleanup: "before-mutation" };
171
+ if (foreground.deferred && !(error instanceof OwnershipCleanupError)) {
172
+ const detail = error instanceof Error ? ` ${error.message}` : "";
173
+ throw new OwnershipCleanupError(`File-queue release was not confirmed.${detail}`, { cause: error });
174
+ }
175
+ throw error;
176
+ }
177
+ });
178
+ },
123
179
  run(execution, action) {
124
- return scope.run({ execution, held: new Set() }, action);
180
+ return scope.run({ execution, held: new Set() }, async () => {
181
+ try {
182
+ return await action();
183
+ }
184
+ catch (error) {
185
+ if (error instanceof AggregateError) {
186
+ const cleanup = error.errors.find((entry) => entry instanceof OwnershipCleanupError);
187
+ if (cleanup)
188
+ throw new OwnershipCleanupError(`${error.message} ${cleanup.message}`, { cause: error });
189
+ }
190
+ throw error;
191
+ }
192
+ });
125
193
  },
126
194
  };
127
195
  }
@@ -0,0 +1,23 @@
1
+ import { DAEMON_JOB_CAPACITY, record, validId } from "./protocol.js";
2
+ export const STATE_WAIT_FAILURE_LIMIT = 3;
3
+ export function stateWaitResult(reply) {
4
+ if (!record(reply) ||
5
+ typeof reply.stateRevision !== "string" ||
6
+ !/^[0-9]{1,40}$/u.test(reply.stateRevision) ||
7
+ !Array.isArray(reply.finished) ||
8
+ !Array.isArray(reply.missing) ||
9
+ !reply.finished.every(validId) ||
10
+ !reply.missing.every(validId))
11
+ throw new Error("Invalid daemon state-wait response.");
12
+ return { reply, version: reply.stateRevision, finished: reply.finished, missing: reply.missing };
13
+ }
14
+ export function stateWaitJobs(waiters) {
15
+ if (waiters.size <= DAEMON_JOB_CAPACITY)
16
+ return [...waiters.keys()];
17
+ const batch = [...waiters.entries()].slice(0, DAEMON_JOB_CAPACITY);
18
+ return batch.map(([id, waiter]) => {
19
+ waiters.delete(id);
20
+ waiters.set(id, waiter);
21
+ return id;
22
+ });
23
+ }
@@ -0,0 +1,34 @@
1
+ import { STATE_WAIT_HEARTBEAT_MS } from "./protocol.js";
2
+ export class ParticipantStateWait {
3
+ revision = 0n;
4
+ wake;
5
+ get version() {
6
+ return this.revision.toString();
7
+ }
8
+ changed() {
9
+ this.revision++;
10
+ this.wake?.();
11
+ }
12
+ wait(version, signal) {
13
+ signal?.throwIfAborted();
14
+ this.wake?.();
15
+ if (version !== this.version)
16
+ return;
17
+ return new Promise((resolve, reject) => {
18
+ const finish = () => {
19
+ clearTimeout(timer);
20
+ signal?.removeEventListener("abort", abort);
21
+ this.wake = undefined;
22
+ resolve();
23
+ };
24
+ const abort = () => {
25
+ reject(signal?.reason);
26
+ finish();
27
+ };
28
+ const timer = setTimeout(finish, STATE_WAIT_HEARTBEAT_MS);
29
+ timer.unref();
30
+ this.wake = finish;
31
+ signal?.addEventListener("abort", abort, { once: true });
32
+ });
33
+ }
34
+ }
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.9.1"
2
+ "version": "0.11.0"
3
3
  }
package/dist/index.ts CHANGED
@@ -7,34 +7,34 @@ import {
7
7
  createSyncAttentionController,
8
8
  readStateForConfig,
9
9
  syncStateFingerprint
10
- } from "./chunks/chunk-VQ47JBLF.ts";
10
+ } from "./chunks/chunk-FI2F5JBS.ts";
11
+ import {
12
+ combineSignals,
13
+ throwIfAborted
14
+ } from "./chunks/chunk-UMPA5S7X.ts";
11
15
  import {
12
16
  completeSyncArguments,
13
17
  setSyncSetupCompletions,
14
18
  splitArgs
15
- } from "./chunks/chunk-HLCML3OW.ts";
19
+ } from "./chunks/chunk-XUZV4OGI.ts";
16
20
  import {
17
21
  withStateDirectoryAccess
18
22
  } from "./chunks/chunk-T3LABNHF.ts";
19
23
  import {
20
24
  snapshotOptionsForContext
21
25
  } from "./chunks/chunk-P4GI7LTT.ts";
22
- import {
23
- bindPiDaemonClient,
24
- installPiDaemonHost,
25
- piDaemonClient,
26
- withPiDaemonClient
27
- } from "./chunks/chunk-B5F3JLD3.ts";
28
- import {
29
- combineSignals,
30
- throwIfAborted
31
- } from "./chunks/chunk-UMPA5S7X.ts";
32
26
  import "./chunks/chunk-ZO52JM4H.ts";
33
27
  import {
34
28
  configFromSettings,
35
29
  loadConfigForCheck,
36
30
  syncCheckConfigFingerprint
37
- } from "./chunks/chunk-27F5W7DX.ts";
31
+ } from "./chunks/chunk-DAZZ5BEJ.ts";
32
+ import {
33
+ bindPiDaemonClient,
34
+ installPiDaemonHost,
35
+ piDaemonClient,
36
+ withPiDaemonClient
37
+ } from "./chunks/chunk-JQ5BAWW2.ts";
38
38
  import {
39
39
  configureSyncStatus,
40
40
  createSyncStatusPublisher,
@@ -66,24 +66,59 @@ async function startSession(ctx, signal, publish) {
66
66
  return { debug: false };
67
67
  }
68
68
  const timings = createStartupTimings(publish);
69
- const document = await timings.measure("settings read", () => client.readSettings());
70
- throwIfAborted(signal);
71
- configureSyncStatus(ctx, document?.parsed.showStatus ?? true);
72
- const { stateDirectoryMigrationNotice } = await import("./chunks/state-directory-CMAIF34J.ts");
73
- const notice = stateDirectoryMigrationNotice();
74
- const { pendingTransactionEntries } = await import("./chunks/snapshot-transaction-directory-F46JWRAU.ts");
75
- const recoveryNeeded = (await pendingTransactionEntries()).some((entry) => entry.isDirectory());
76
- throwIfAborted(signal);
77
- if (!await client.configured() && !recoveryNeeded) {
78
- if (notice) ctx.ui.notify(notice, "warning");
79
- setSyncSetupCompletions([]);
80
- const debug = document?.parsed.debug === true;
81
- await client.markReady(debug);
82
- timings.publish(ctx, debug, signal, "local initialization", "completed");
83
- return { debug };
69
+ let showLocalTimings = false;
70
+ let localStartupComplete = false;
71
+ try {
72
+ const { document, settings } = await timings.measure("settings read", () => client.readStartupSettings(signal));
73
+ client.validate();
74
+ throwIfAborted(signal);
75
+ const debug = settings?.debug ?? false;
76
+ client.setDebugPreference(debug);
77
+ configureSyncStatus(ctx, settings?.showStatus ?? true);
78
+ const { stateDirectoryMigrationNotice } = await import("./chunks/state-directory-CMAIF34J.ts");
79
+ client.validate();
80
+ throwIfAborted(signal);
81
+ const notice = stateDirectoryMigrationNotice();
82
+ if (settings?.activeSyncSetup && document) {
83
+ const ready = !notice && await client.tryStartupBootstrap(document, debug, signal);
84
+ client.validate();
85
+ throwIfAborted(signal);
86
+ if (ready) {
87
+ setSyncSetupCompletions(Object.keys(settings.syncSetups).sort((a, b) => a.localeCompare(b)));
88
+ showLocalTimings = debug;
89
+ localStartupComplete = true;
90
+ return { debug, config: configFromSettings(settings) };
91
+ }
92
+ } else {
93
+ const { pendingTransactionEntries } = await import("./chunks/snapshot-transaction-directory-F46JWRAU.ts");
94
+ const recoveryNeeded = (await pendingTransactionEntries()).length > 0;
95
+ client.validate();
96
+ throwIfAborted(signal);
97
+ if (!recoveryNeeded) {
98
+ if (notice) ctx.ui.notify(notice, "warning");
99
+ setSyncSetupCompletions([]);
100
+ await client.markReady(debug);
101
+ client.validate();
102
+ throwIfAborted(signal);
103
+ client.recordDebug({ event: "job", operation: "initialize", outcome: "skipped" });
104
+ showLocalTimings = debug;
105
+ localStartupComplete = true;
106
+ return { debug };
107
+ }
108
+ }
109
+ localStartupComplete = true;
110
+ } finally {
111
+ timings.publish(
112
+ ctx,
113
+ showLocalTimings,
114
+ signal,
115
+ "local initialization",
116
+ localStartupComplete ? "completed" : "stopped",
117
+ client.debugEnabled && !signal.aborted ? (report) => client.recordDebug({ event: "startup-timings", report }) : void 0
118
+ );
84
119
  }
85
- throwIfAborted(signal);
86
120
  const result = await client.run("initialize", {}, signal);
121
+ client.validate();
87
122
  throwIfAborted(signal);
88
123
  configureSyncStatus(ctx, result.settings?.showStatus ?? true);
89
124
  setSyncSetupCompletions(Object.keys(result.settings?.syncSetups ?? {}).sort((a, b) => a.localeCompare(b)));
@@ -102,11 +137,17 @@ async function autoPushSessions(ctx, signal, _loaders) {
102
137
  try {
103
138
  const client = piDaemonClient(ctx);
104
139
  const eligible = (config2) => config2.automatic && syncSessionsSelected(config2);
105
- if (!await client.configured((settings) => eligible(configFromSettings(settings)))) return;
140
+ if (!await client.configured((settings) => eligible(configFromSettings(settings)))) {
141
+ client.recordDebug({ event: "job", operation: "shutdown", outcome: "skipped" });
142
+ return;
143
+ }
106
144
  throwIfAborted(signal);
107
145
  const config = await loadConfigForCheck(void 0, signal);
108
146
  throwIfAborted(signal);
109
- if (!eligible(config)) return;
147
+ if (!eligible(config)) {
148
+ client.recordDebug({ event: "job", operation: "shutdown", outcome: "skipped" });
149
+ return;
150
+ }
110
151
  const automaticFingerprint = syncCheckConfigFingerprint(config);
111
152
  await client.run(
112
153
  "shutdown",
@@ -134,12 +175,12 @@ function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
134
175
  const queued = pending;
135
176
  if (!queued || queued.ctx.sessionManager !== ctx.sessionManager || queued.signal.aborted || !ctx.isIdle()) return;
136
177
  pending = void 0;
137
- controllerApi.start(ctx, queued.signal, queued.config);
178
+ controllerApi.start(ctx, queued.signal, queued.config, queued.logTimings);
138
179
  },
139
- start(ctx, sessionSignal, initialConfig) {
180
+ start(ctx, sessionSignal, initialConfig, logTimings) {
140
181
  if (!ctx.hasUI || sessionSignal.aborted) return;
141
182
  if (initialConfig && startupTransferEnabled(initialConfig) && !ctx.isIdle()) {
142
- pending = { ctx, signal: sessionSignal, config: initialConfig };
183
+ pending = { ctx, signal: sessionSignal, config: initialConfig, logTimings };
143
184
  return;
144
185
  }
145
186
  if (active) throw new Error("Previous startup check has not been drained.");
@@ -203,7 +244,7 @@ function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
203
244
  throwIfAborted(signal);
204
245
  if (!isCurrent() || syncCheckConfigFingerprint(transferConfig) !== identity) return;
205
246
  if (!ctx.isIdle()) {
206
- pending = { ctx, signal: sessionSignal, config: captured };
247
+ pending = { ctx, signal: sessionSignal, config: captured, logTimings };
207
248
  return;
208
249
  }
209
250
  await timings.measure(
@@ -268,7 +309,8 @@ function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
268
309
  config?.debug ?? false,
269
310
  sessionSignal,
270
311
  "background startup",
271
- signal.aborted || stopped ? "stopped" : "completed"
312
+ signal.aborted || stopped ? "stopped" : "completed",
313
+ logTimings
272
314
  );
273
315
  }
274
316
  if (active === task) active = void 0;
@@ -292,12 +334,12 @@ function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
292
334
  // src/sync/sync-loaders.ts
293
335
  function createSyncLoaders(dependencies) {
294
336
  const loaders = {
295
- commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-GMRRFWOL.ts"))),
296
- inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-SRU6HGGK.ts"))),
297
- setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-L54X5U5I.ts"))),
337
+ commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-YZ4DXQ7N.ts"))),
338
+ inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-NBBTSMKR.ts"))),
339
+ setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-644T6KHG.ts"))),
298
340
  snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import("./chunks/snapshot-ZUJJZCFW.ts"))),
299
341
  syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import("./chunks/sync-state-QIT64TKV.ts"))),
300
- operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-UGSCONZ7.ts")))
342
+ operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-AIEM2KL2.ts")))
301
343
  };
302
344
  return loaders;
303
345
  }
@@ -372,9 +414,29 @@ function sync(pi, dependencies = {}) {
372
414
  await withPiDaemonClient(
373
415
  ctx,
374
416
  async (ctx2) => {
375
- const command = splitArgs(args)[0];
376
- const ready = await initialization;
417
+ const [command, action, ...extra] = splitArgs(args);
418
+ const recover = command === "daemon" && action === "recover";
419
+ const ready = recover ? void 0 : await initialization;
377
420
  if (signal.aborted || owner !== client) return;
421
+ const needsDaemonRecovery = () => client.ownershipCleanupRequired;
422
+ if (recover || !command && needsDaemonRecovery()) {
423
+ if (recover && extra.length) {
424
+ ctx2.ui.notify("Usage: /sync daemon recover", "error");
425
+ return;
426
+ }
427
+ const commands = await loaders.commands();
428
+ if (signal.aborted || owner !== client) return;
429
+ await commands.handleCommand(
430
+ args,
431
+ ctx2,
432
+ commandSignal,
433
+ loaders,
434
+ attention,
435
+ void 0,
436
+ needsDaemonRecovery
437
+ );
438
+ return;
439
+ }
378
440
  const requiresContact = !["help", "unlock", "migrate-state"].includes(command ?? "");
379
441
  let busyPublished = false;
380
442
  try {
@@ -397,8 +459,17 @@ function sync(pi, dependencies = {}) {
397
459
  }
398
460
  const commands = await loaders.commands();
399
461
  if (signal.aborted || owner !== client) return;
400
- await commands.handleCommand(args, ctx2, commandSignal, loaders, attention);
462
+ await commands.handleCommand(
463
+ args,
464
+ ctx2,
465
+ commandSignal,
466
+ loaders,
467
+ attention,
468
+ void 0,
469
+ needsDaemonRecovery
470
+ );
401
471
  } catch (error) {
472
+ client.recordOwnershipFailure(error);
402
473
  if (!commandSignal.aborted && owner === client) {
403
474
  ctx2.ui.notify(`pi-sync command unavailable: ${safeTerminalText(errorMessage(error))}`, "error");
404
475
  if (command === "unlock" || command === "migrate-state") throw error;
@@ -406,7 +477,7 @@ function sync(pi, dependencies = {}) {
406
477
  } finally {
407
478
  if (!signal.aborted && owner === client) {
408
479
  const publish = busyPublished || command === "unlock" || command === "migrate-state";
409
- await client.setBusy("command", false, publish).catch(() => {
480
+ await client.setBusy("command", false, publish && !needsDaemonRecovery()).catch(() => {
410
481
  });
411
482
  }
412
483
  }
@@ -456,9 +527,12 @@ function sync(pi, dependencies = {}) {
456
527
  } catch (error) {
457
528
  if (!signal.aborted && owner === client) {
458
529
  try {
459
- client.validate();
460
- if (ctx.hasUI)
461
- ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}`, "error");
530
+ ctx.isIdle();
531
+ client.recordOwnershipFailure(error);
532
+ if (ctx.hasUI) {
533
+ const advice = client.ownershipCleanupRequired ? " Open /sync to recover the daemon." : "";
534
+ ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}${advice}`, "error");
535
+ }
462
536
  } catch {
463
537
  }
464
538
  }
@@ -473,7 +547,12 @@ function sync(pi, dependencies = {}) {
473
547
  }
474
548
  if (ready && !signal.aborted && owner === client && !(ready.continuous && ready.agentMode) && (ready.automatic || startupTransferEnabled(ready)))
475
549
  await withPiDaemonClient(ctx, async () => {
476
- check.start(ctx, signal, ready);
550
+ check.start(
551
+ ctx,
552
+ signal,
553
+ ready,
554
+ client.debugEnabled ? (report) => client.recordDebug({ event: "startup-timings", report }) : void 0
555
+ );
477
556
  });
478
557
  } catch (error) {
479
558
  client.disableQueueReleaseUI();
@@ -537,6 +616,7 @@ function sync(pi, dependencies = {}) {
537
616
  if (signal.aborted || owner !== client) return;
538
617
  if (reason !== "reload") {
539
618
  shutdownClient = bindPiDaemonClient(ctx, signal, publishTimings);
619
+ shutdownClient.setDebugPreference(client.debugEnabled);
540
620
  await shutdownClient.setBusy("shutdown", true);
541
621
  const attached = await shutdownClient.attachExisting();
542
622
  if (!signal.aborted && owner === client && attached)