@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
@@ -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,
@@ -27,29 +27,66 @@ export async function startSession(
27
27
  return { debug: false };
28
28
  }
29
29
  const timings = createStartupTimings(publish);
30
- const document = await timings.measure("settings read", () => client.readSettings());
31
- throwIfAborted(signal);
32
- configureSyncStatus(ctx, (document?.parsed.showStatus as boolean | undefined) ?? true);
33
- const { stateDirectoryMigrationNotice } = await import("../state/state-directory.js");
34
- const notice = stateDirectoryMigrationNotice();
35
- const { pendingTransactionEntries } = await import("../snapshot/snapshot-transaction-directory.js");
36
- const recoveryNeeded = (await pendingTransactionEntries()).some((entry) => entry.isDirectory());
37
- throwIfAborted(signal);
38
- if (!(await client.configured()) && !recoveryNeeded) {
39
- if (notice) ctx.ui.notify(notice, "warning");
40
- setSyncSetupCompletions([]);
41
- const debug = document?.parsed.debug === true;
42
- await client.markReady(debug);
43
- timings.publish(ctx, debug, signal, "local initialization", "completed");
44
- return { debug };
30
+ let showLocalTimings = false;
31
+ let localStartupComplete = false;
32
+ try {
33
+ const { document, settings } = await timings.measure("settings read", () => client.readStartupSettings(signal));
34
+ client.validate();
35
+ throwIfAborted(signal);
36
+ const debug = settings?.debug ?? false;
37
+ client.setDebugPreference(debug);
38
+ configureSyncStatus(ctx, settings?.showStatus ?? true);
39
+ const { stateDirectoryMigrationNotice } = await import("../state/state-directory.js");
40
+ client.validate();
41
+ throwIfAborted(signal);
42
+ const notice = stateDirectoryMigrationNotice();
43
+ if (settings?.activeSyncSetup && document) {
44
+ const ready = !notice && (await client.tryStartupBootstrap(document, debug, signal));
45
+ client.validate();
46
+ throwIfAborted(signal);
47
+ if (ready) {
48
+ setSyncSetupCompletions(Object.keys(settings.syncSetups).sort((a, b) => a.localeCompare(b)));
49
+ showLocalTimings = debug;
50
+ localStartupComplete = true;
51
+ return { debug, config: configFromSettings(settings) };
52
+ }
53
+ } else {
54
+ const { pendingTransactionEntries } = await import("../snapshot/snapshot-transaction-directory.js");
55
+ const recoveryNeeded = (await pendingTransactionEntries()).length > 0;
56
+ client.validate();
57
+ throwIfAborted(signal);
58
+ if (!recoveryNeeded) {
59
+ if (notice) ctx.ui.notify(notice, "warning");
60
+ setSyncSetupCompletions([]);
61
+ await client.markReady(debug);
62
+ client.validate();
63
+ throwIfAborted(signal);
64
+ client.recordDebug({ event: "job", operation: "initialize", outcome: "skipped" });
65
+ showLocalTimings = debug;
66
+ localStartupComplete = true;
67
+ return { debug };
68
+ }
69
+ }
70
+ localStartupComplete = true;
71
+ } finally {
72
+ timings.publish(
73
+ ctx,
74
+ showLocalTimings,
75
+ signal,
76
+ "local initialization",
77
+ localStartupComplete ? "completed" : "stopped",
78
+ client.debugEnabled && !signal.aborted
79
+ ? (report) => client.recordDebug({ event: "startup-timings", report })
80
+ : undefined,
81
+ );
45
82
  }
46
- throwIfAborted(signal);
47
83
  const result = (await client.run("initialize", {}, signal)) as {
48
84
  debug: boolean;
49
85
  config?: AnySyncConfig;
50
86
  settings?: PiSyncSettingsV3;
51
87
  handoverRequired: boolean;
52
88
  };
89
+ client.validate();
53
90
  throwIfAborted(signal);
54
91
  configureSyncStatus(ctx, result.settings?.showStatus ?? true);
55
92
  setSyncSetupCompletions(Object.keys(result.settings?.syncSetups ?? {}).sort((a, b) => a.localeCompare(b)));
@@ -68,11 +105,17 @@ export async function autoPushSessions(ctx: ExtensionContext, signal: AbortSigna
68
105
  try {
69
106
  const client = piDaemonClient(ctx);
70
107
  const eligible = (config: AnySyncConfig) => config.automatic && syncSessionsSelected(config);
71
- if (!(await client.configured((settings) => eligible(configFromSettings(settings))))) return;
108
+ if (!(await client.configured((settings) => eligible(configFromSettings(settings))))) {
109
+ client.recordDebug({ event: "job", operation: "shutdown", outcome: "skipped" });
110
+ return;
111
+ }
72
112
  throwIfAborted(signal);
73
113
  const config = await loadConfigForCheck(undefined, signal);
74
114
  throwIfAborted(signal);
75
- if (!eligible(config)) return;
115
+ if (!eligible(config)) {
116
+ client.recordDebug({ event: "job", operation: "shutdown", outcome: "skipped" });
117
+ return;
118
+ }
76
119
  const automaticFingerprint = syncCheckConfigFingerprint(config);
77
120
  await client.run(
78
121
  "shutdown",
@@ -30,7 +30,9 @@ export function createStartupCheck(
30
30
  }
31
31
  | undefined;
32
32
 
33
- let pending: { ctx: ExtensionContext; signal: AbortSignal; config: AnySyncConfig } | undefined;
33
+ let pending:
34
+ | { ctx: ExtensionContext; signal: AbortSignal; config: AnySyncConfig; logTimings?: (report: string) => void }
35
+ | undefined;
34
36
 
35
37
  const controllerApi = {
36
38
  async interrupt(ctx: ExtensionContext) {
@@ -43,12 +45,17 @@ export function createStartupCheck(
43
45
  const queued = pending;
44
46
  if (!queued || queued.ctx.sessionManager !== ctx.sessionManager || queued.signal.aborted || !ctx.isIdle()) return;
45
47
  pending = undefined;
46
- controllerApi.start(ctx, queued.signal, queued.config);
48
+ controllerApi.start(ctx, queued.signal, queued.config, queued.logTimings);
47
49
  },
48
- start(ctx: ExtensionContext, sessionSignal: AbortSignal, initialConfig?: AnySyncConfig) {
50
+ start(
51
+ ctx: ExtensionContext,
52
+ sessionSignal: AbortSignal,
53
+ initialConfig?: AnySyncConfig,
54
+ logTimings?: (report: string) => void,
55
+ ) {
49
56
  if (!ctx.hasUI || sessionSignal.aborted) return;
50
57
  if (initialConfig && startupTransferEnabled(initialConfig) && !ctx.isIdle()) {
51
- pending = { ctx, signal: sessionSignal, config: initialConfig };
58
+ pending = { ctx, signal: sessionSignal, config: initialConfig, logTimings };
52
59
  return;
53
60
  }
54
61
  if (active) throw new Error("Previous startup check has not been drained.");
@@ -119,7 +126,7 @@ export function createStartupCheck(
119
126
  throwIfAborted(signal);
120
127
  if (!isCurrent() || syncCheckConfigFingerprint(transferConfig) !== identity) return;
121
128
  if (!ctx.isIdle()) {
122
- pending = { ctx, signal: sessionSignal, config: captured };
129
+ pending = { ctx, signal: sessionSignal, config: captured, logTimings };
123
130
  return;
124
131
  }
125
132
  await timings.measure("automatic transfer", () =>
@@ -191,6 +198,7 @@ export function createStartupCheck(
191
198
  sessionSignal,
192
199
  "background startup",
193
200
  signal.aborted || stopped ? "stopped" : "completed",
201
+ logTimings,
194
202
  );
195
203
  }
196
204
  if (active === task) active = undefined;
@@ -53,9 +53,29 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
53
53
  await withPiDaemonClient(
54
54
  ctx,
55
55
  async (ctx) => {
56
- const command = splitArgs(args)[0];
57
- const ready = await initialization;
56
+ const [command, action, ...extra] = splitArgs(args);
57
+ const recover = command === "daemon" && action === "recover";
58
+ const ready = recover ? undefined : await initialization;
58
59
  if (signal.aborted || owner !== client) return;
60
+ const needsDaemonRecovery = () => client.ownershipCleanupRequired;
61
+ if (recover || (!command && needsDaemonRecovery())) {
62
+ if (recover && extra.length) {
63
+ ctx.ui.notify("Usage: /sync daemon recover", "error");
64
+ return;
65
+ }
66
+ const commands = await loaders.commands();
67
+ if (signal.aborted || owner !== client) return;
68
+ await commands.handleCommand(
69
+ args,
70
+ ctx,
71
+ commandSignal,
72
+ loaders,
73
+ attention,
74
+ undefined,
75
+ needsDaemonRecovery,
76
+ );
77
+ return;
78
+ }
59
79
  const requiresContact = !["help", "unlock", "migrate-state"].includes(command ?? "");
60
80
  let busyPublished = false;
61
81
  try {
@@ -85,8 +105,17 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
85
105
  }
86
106
  const commands = await loaders.commands();
87
107
  if (signal.aborted || owner !== client) return;
88
- await commands.handleCommand(args, ctx, commandSignal, loaders, attention);
108
+ await commands.handleCommand(
109
+ args,
110
+ ctx,
111
+ commandSignal,
112
+ loaders,
113
+ attention,
114
+ undefined,
115
+ needsDaemonRecovery,
116
+ );
89
117
  } catch (error) {
118
+ client.recordOwnershipFailure(error);
90
119
  if (!commandSignal.aborted && owner === client) {
91
120
  ctx.ui.notify(`pi-sync command unavailable: ${safeTerminalText(errorMessage(error))}`, "error");
92
121
  if (command === "unlock" || command === "migrate-state") throw error;
@@ -96,7 +125,7 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
96
125
  // Recovery can publish busy facts after bypassing the initial contact check.
97
126
  const publish = busyPublished || command === "unlock" || command === "migrate-state";
98
127
  // Release local busy state even if contact failed; do not mask the command result.
99
- await client.setBusy("command", false, publish).catch(() => {});
128
+ await client.setBusy("command", false, publish && !needsDaemonRecovery()).catch(() => {});
100
129
  }
101
130
  }
102
131
  },
@@ -148,9 +177,12 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
148
177
  } catch (error) {
149
178
  if (!signal.aborted && owner === client) {
150
179
  try {
151
- client.validate();
152
- if (ctx.hasUI)
153
- ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}`, "error");
180
+ ctx.isIdle();
181
+ client.recordOwnershipFailure(error);
182
+ if (ctx.hasUI) {
183
+ const advice = client.ownershipCleanupRequired ? " Open /sync to recover the daemon." : "";
184
+ ctx.ui.notify(`pi-sync recovery required: ${safeTerminalText(errorMessage(error))}${advice}`, "error");
185
+ }
154
186
  } catch {
155
187
  /* SDK context was replaced. */
156
188
  }
@@ -172,7 +204,12 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
172
204
  (ready.automatic || startupTransferEnabled(ready))
173
205
  )
174
206
  await withPiDaemonClient(ctx, async () => {
175
- check.start(ctx, signal, ready);
207
+ check.start(
208
+ ctx,
209
+ signal,
210
+ ready,
211
+ client.debugEnabled ? (report) => client.recordDebug({ event: "startup-timings", report }) : undefined,
212
+ );
176
213
  });
177
214
  } catch (error) {
178
215
  client.disableQueueReleaseUI();
@@ -239,6 +276,7 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
239
276
  if (signal.aborted || owner !== client) return;
240
277
  if (reason !== "reload") {
241
278
  shutdownClient = bindPiDaemonClient(ctx, signal, publishTimings);
279
+ shutdownClient.setDebugPreference(client.debugEnabled);
242
280
  await shutdownClient.setBusy("shutdown", true);
243
281
  const attached = await shutdownClient.attachExisting();
244
282
  if (!signal.aborted && owner === client && attached)
@@ -18,6 +18,7 @@ export type RunRoute = (
18
18
  target?: string,
19
19
  onDialog?: (active: boolean) => void,
20
20
  retryRefusal?: boolean,
21
+ directionalFingerprint?: string,
21
22
  ) => Promise<RunRouteResult | undefined>;
22
23
 
23
24
  export type CancellableOperationResult = RunRouteResult | { kind: "closed" } | { kind: "cancelled" };
@@ -27,6 +28,7 @@ interface CancellableOperationOptions {
27
28
  cancelAcrossDialogs?: boolean;
28
29
  cancelledMessage?: string | null;
29
30
  target?: string;
31
+ directionalFingerprint?: string;
30
32
  signal?: AbortSignal;
31
33
  isCurrent?: () => boolean;
32
34
  }
@@ -41,7 +43,8 @@ export async function runCancellableOperation(
41
43
  const result = await runCancellableTask(
42
44
  ctx,
43
45
  message,
44
- (signal, onCommit, onDialog) => runRoute(route, signal, onCommit, options.target, onDialog),
46
+ (signal, onCommit, onDialog) =>
47
+ runRoute(route, signal, onCommit, options.target, onDialog, undefined, options.directionalFingerprint),
45
48
  options,
46
49
  );
47
50
  return result.kind === "completed" ? (result.value ?? { kind: "failed" }) : result;
@@ -61,7 +64,7 @@ export async function runCancellableTask<Value>(
61
64
  onCommit?: () => void,
62
65
  onDialog?: (active: boolean) => void,
63
66
  ) => Promise<Value>,
64
- options: Omit<CancellableOperationOptions, "target"> = {},
67
+ options: Omit<CancellableOperationOptions, "target" | "directionalFingerprint"> = {},
65
68
  ): Promise<CancellableTaskResult<Value>> {
66
69
  const {
67
70
  commitAware = false,
@@ -1,8 +1,8 @@
1
1
  import { truncateToWidth } from "@earendil-works/pi-tui";
2
- import { configFromSettings, loadConfig, syncCheckConfigFingerprint } from "../settings/config.js";
3
- import { activeLocalConfigPath, readActiveLocalConfigDocumentForRepair } from "../settings/config-file.js";
4
- import type { AnySyncConfig, PiSyncSettingsV3 } from "../settings/settings-types.js";
5
- import { isCloudflareR2Endpoint, validateSettingsDocument } from "../settings/settings-validation.js";
2
+ import { createSettingsConfigView, syncCheckConfigFingerprint } from "../settings/config.js";
3
+ import { type LocalConfigDocument, readActiveLocalConfigDocumentForRepair } from "../settings/config-file.js";
4
+ import type { AnySyncConfig } from "../settings/settings-types.js";
5
+ import { isCloudflareR2Endpoint } from "../settings/settings-validation.js";
6
6
  import {
7
7
  inspectOperationAvailability,
8
8
  type OperationAvailability,
@@ -20,13 +20,13 @@ import {
20
20
  type SyncAttentionState,
21
21
  syncAttentionMatchesConfig,
22
22
  } from "./sync-attention.js";
23
- import { countValidSyncSetups } from "./sync-setups-ui.js";
23
+ import { hasAnotherSwitchableSetup } from "./sync-setups-ui.js";
24
24
  import { safeTerminalText } from "./terminal-text.js";
25
25
 
26
26
  export const MAIN_MENU_ACTIONS = [
27
27
  "Sync now",
28
- "Pull from remote…",
29
- "Push to remote…",
28
+ "Pull from remote",
29
+ "Push to remote",
30
30
  "View differences",
31
31
  "Check remote status",
32
32
  "Settings",
@@ -53,34 +53,35 @@ export async function describeManagerState(
53
53
  observation?: StartupObservation,
54
54
  canUseIgnoreSettings?: () => Promise<boolean>,
55
55
  ): Promise<ManagerDescription> {
56
- let raw: PiSyncSettingsV3 | undefined;
56
+ signal?.throwIfAborted();
57
+ let document: LocalConfigDocument | undefined;
58
+ let view: ReturnType<typeof createSettingsConfigView> | undefined;
57
59
  try {
58
- const document = await readActiveLocalConfigDocumentForRepair();
60
+ document = await readActiveLocalConfigDocumentForRepair();
59
61
  signal?.throwIfAborted();
60
- if (document) raw = validateSettingsDocument(document.parsed);
62
+ if (document) view = createSettingsConfigView(document);
61
63
  } catch (error) {
62
- if (signal?.aborted) throw error;
64
+ signal?.throwIfAborted();
63
65
  return {
64
66
  title: [
65
67
  "Manage sync",
66
68
  "",
67
69
  "Settings file needs repair. Automatic sync and settings writes are paused.",
68
70
  `Error: ${safeTerminalText(errorMessage(error))}`,
69
- `File: ${safeTerminalText(await activeLocalConfigPath())}`,
71
+ ...(document ? [`File: ${safeTerminalText(document.path)}`] : []),
70
72
  "",
71
73
  "Repair the JSON file, then reopen /sync.",
72
74
  ].join("\n"),
73
75
  actions: ["Help"],
74
76
  };
75
77
  }
76
- if (!raw) {
78
+ if (!view || !document) {
77
79
  return {
78
80
  title: ["Manage sync", "", "Not set up.", "", "What do you want to do?"].join("\n"),
79
81
  actions: ["Set up sync", "Help"],
80
82
  };
81
83
  }
82
- const configuredTargets = raw.syncSetups;
83
- if (Object.keys(configuredTargets).length === 0) {
84
+ if (view.setupNames.length === 0) {
84
85
  return {
85
86
  title: [
86
87
  "Manage sync",
@@ -95,25 +96,30 @@ export async function describeManagerState(
95
96
  }
96
97
  let settingsConfig: AnySyncConfig | undefined;
97
98
  try {
98
- settingsConfig = configFromSettings(raw);
99
+ settingsConfig = view.metadata();
99
100
  if (settingsConfig.reservedIgnoreNames && canUseIgnoreSettings && !(await canUseIgnoreSettings())) {
100
101
  throw new Error("the connected daemon does not support ignore-file setups");
101
102
  }
102
103
  signal?.throwIfAborted();
103
- const config = await loadConfig();
104
+ const config = await view.observe(undefined, signal);
104
105
  signal?.throwIfAborted();
105
106
  const operation = await inspectOperation();
107
+ signal?.throwIfAborted();
106
108
  const changesBlocked = operationBlocksChanges(operation);
107
109
  let currentAttention: SyncAttentionState | undefined;
110
+ let alternateUsable = false;
108
111
  if (attention) {
109
112
  try {
110
113
  const attentionConfig =
111
- attention.decision.setupName === config.setupName ? config : await loadConfig(attention.decision.setupName);
114
+ attention.decision.setupName === config.setupName
115
+ ? config
116
+ : await view.observe(attention.decision.setupName, signal);
117
+ alternateUsable = attentionConfig.setupName !== config.setupName;
112
118
  if (syncAttentionMatchesConfig(attention, attentionConfig)) currentAttention = attention;
113
119
  } catch {
114
120
  currentAttention = undefined;
115
121
  }
116
- if (signal?.aborted) throw signal.reason;
122
+ signal?.throwIfAborted();
117
123
  }
118
124
  const attentionComparison = currentAttention
119
125
  ? compareSyncInclude(currentAttention.decision.localInclude, currentAttention.decision.remoteInclude)
@@ -125,6 +131,7 @@ export async function describeManagerState(
125
131
  currentAttention?.decision.localDirectory || currentAttention?.decision.remoteDirectory;
126
132
  const noSyncedContent = !syncSelectionHasContent(config);
127
133
  const syncState = changesBlocked ? undefined : await readStateForConfig(config).catch(() => undefined);
134
+ signal?.throwIfAborted();
128
135
  const currentObservation =
129
136
  observation &&
130
137
  observationMatchesConfig(observation, config) &&
@@ -139,7 +146,8 @@ export async function describeManagerState(
139
146
  : syncState
140
147
  ? "Never synced"
141
148
  : "Unavailable";
142
- const canSwitch = (await countValidSyncSetups(configuredTargets, signal)) > 1;
149
+ const canSwitch = !changesBlocked && (alternateUsable || (await hasAnotherSwitchableSetup(view, signal)));
150
+ signal?.throwIfAborted();
143
151
  const mainActions: string[] = [...MAIN_MENU_ACTIONS];
144
152
  if (config.agentMode && !noSyncedContent) mainActions.splice(1, 0, "Retry refused model result…");
145
153
  if (canSwitch) mainActions.push("Switch sync setup");
@@ -201,7 +209,7 @@ export async function describeManagerState(
201
209
  : {}),
202
210
  };
203
211
  } catch (error) {
204
- if (signal?.aborted) throw error;
212
+ signal?.throwIfAborted();
205
213
  if (settingsConfig?.reservedIgnoreNames !== undefined) {
206
214
  return {
207
215
  title: [
@@ -221,9 +229,9 @@ export async function describeManagerState(
221
229
  "Manage sync",
222
230
  "",
223
231
  "Settings need attention. Automatic sync is paused.",
224
- `Current sync setup: ${safeTerminalText(typeof raw.activeSyncSetup === "string" ? raw.activeSyncSetup : "none")}`,
232
+ `Current sync setup: ${safeTerminalText(view.activeSetupName ?? "none")}`,
225
233
  `Error: ${safeTerminalText(errorMessage(error))}`,
226
- `File: ${safeTerminalText(await activeLocalConfigPath())}`,
234
+ `File: ${safeTerminalText(document.path)}`,
227
235
  "",
228
236
  "What do you want to do?",
229
237
  ].join("\n"),
@@ -27,7 +27,7 @@ export async function showSyncManager(
27
27
  ctx: ExtensionCommandContext,
28
28
  runRoute: RunRoute,
29
29
  sessionSignal?: AbortSignal,
30
- options: SyncManagerAttentionOptions = {},
30
+ options: SyncManagerAttentionOptions & { needsDaemonRecovery?: () => boolean } = {},
31
31
  ): Promise<void> {
32
32
  if (!ctx.hasUI) {
33
33
  await runRoute("help");
@@ -60,12 +60,36 @@ export async function showSyncManager(
60
60
  | "conflicts"
61
61
  | "doctor"
62
62
  | "recover"
63
+ | "daemon-recovery"
63
64
  | "refresh"
64
65
  | "help"
65
66
  | "init";
66
67
  interface State {
67
68
  manager: Awaited<ReturnType<typeof describeManagerState>>;
68
69
  }
70
+ const directionalAction = async (direction: "push" | "pull", state: State, signal: AbortSignal) => {
71
+ const review = state.manager.configReview;
72
+ if (!review) return { kind: "stay" as const };
73
+ const result = await runCancellableOperation(
74
+ ctx,
75
+ direction === "push" ? "Pushing to remote…" : "Pulling from remote…",
76
+ direction,
77
+ runRoute,
78
+ {
79
+ commitAware: true,
80
+ cancelledMessage: direction === "push" ? "Push cancellation requested." : "Pull cancellation requested.",
81
+ target: review.setupName,
82
+ directionalFingerprint: review.fingerprint,
83
+ signal,
84
+ isCurrent,
85
+ },
86
+ );
87
+ const done =
88
+ result.kind === "closed" ||
89
+ (result.kind === "completed" && result.outcome === "applied") ||
90
+ (result.kind === "failed" && options.needsDaemonRecovery?.());
91
+ return done ? { kind: "close" as const } : { kind: "stay" as const };
92
+ };
69
93
  const menuItems = (manager: State["manager"]) => {
70
94
  const attentionItems = attentionMainMenuItems(manager);
71
95
  const managerItems = manager.actions.map((label) => blockedSyncMenuItem(label, manager) ?? syncMainMenuItem(label));
@@ -194,26 +218,8 @@ export async function showSyncManager(
194
218
  const result = await showSyncSettings(ctx, runRoute, signal, review?.setupName);
195
219
  return { kind: result === "exit" ? "close" : "stay" };
196
220
  },
197
- pull: async ({ state }) => {
198
- const result = await runCancellableOperation(ctx, "Checking remote changes…", "pull", runRoute, {
199
- commitAware: true,
200
- cancelledMessage: "Pull check cancelled; no local files were changed.",
201
- target: state.manager.configReview?.setupName,
202
- signal: sessionSignal,
203
- });
204
- const disposition = await dispatchManagerResult(ctx, result, "pull", runRoute, sessionSignal);
205
- return disposition.kind === "close" ? { kind: "close" } : { kind: "stay" };
206
- },
207
- push: async ({ state }) => {
208
- const result = await runCancellableOperation(ctx, "Preparing push preview…", "push", runRoute, {
209
- commitAware: true,
210
- cancelledMessage: "Push preparation cancelled; no remote files were changed.",
211
- target: state.manager.configReview?.setupName,
212
- signal: sessionSignal,
213
- });
214
- const disposition = await dispatchManagerResult(ctx, result, "push", runRoute, sessionSignal);
215
- return disposition.kind === "close" ? { kind: "close" } : { kind: "stay" };
216
- },
221
+ pull: ({ state, signal }) => directionalAction("pull", state, signal),
222
+ push: ({ state, signal }) => directionalAction("push", state, signal),
217
223
  setups: async () => {
218
224
  const result = await showSyncSetupManager(ctx, runRoute, sessionSignal);
219
225
  return result === "exit" ? { kind: "close" } : { kind: "stay" };
@@ -295,6 +301,10 @@ export async function showSyncManager(
295
301
  });
296
302
  return { kind: result.kind === "closed" ? "close" : "stay" };
297
303
  },
304
+ "daemon-recovery": async ({ signal }) => {
305
+ await runRoute("daemon recover", signal);
306
+ return { kind: "stay" };
307
+ },
298
308
  recover: async ({ state, signal: actionSignal }) => {
299
309
  const result = await recoverSyncAccess(ctx, state.manager, runRoute, sessionSignal, actionSignal);
300
310
  return { kind: result === "close" ? "close" : "stay" };
@@ -377,13 +387,20 @@ export async function showSyncManager(
377
387
  },
378
388
  };
379
389
  let firstOpen = true;
390
+ const recovery: State["manager"] = {
391
+ title:
392
+ "Pi Sync recovery required\nDaemon cleanup could not be confirmed. Stop the daemon before retrying a transfer.",
393
+ actions: ["Stop daemon for recovery…", "Help"],
394
+ };
380
395
  const describe = async (signal: AbortSignal) => {
396
+ if (options.needsDaemonRecovery?.()) return recovery;
381
397
  const pendingAttention = options.getAttention?.();
382
398
  const observation = options.getObservation?.();
383
399
  const manager = await describeManagerState(signal, pendingAttention, undefined, observation, () =>
384
400
  ignoreFileSettingsAvailable(ctx, signal),
385
401
  );
386
402
  if (signal.aborted || !isCurrent()) return manager;
403
+ if (options.needsDaemonRecovery?.()) return recovery;
387
404
  // A busy operation suppresses baseline reads, not the stored check-time hint.
388
405
  if (
389
406
  observation &&
@@ -436,6 +453,7 @@ function syncMainMenuItem(
436
453
  | "conflicts"
437
454
  | "doctor"
438
455
  | "recover"
456
+ | "daemon-recovery"
439
457
  | "refresh"
440
458
  | "help"
441
459
  | "init"
@@ -443,8 +461,8 @@ function syncMainMenuItem(
443
461
  const actions = {
444
462
  "Sync now": "sync",
445
463
  "Retry refused model result…": "retry-refusal",
446
- "Pull from remote…": "pull",
447
- "Push to remote…": "push",
464
+ "Pull from remote": "pull",
465
+ "Push to remote": "push",
448
466
  "View differences": "diff",
449
467
  "Check remote status": "status",
450
468
  "Switch sync setup": "switch",
@@ -453,6 +471,7 @@ function syncMainMenuItem(
453
471
  Diagnostics: "doctor",
454
472
  "Review unresolved conflicts": "conflicts",
455
473
  "Restore sync access… (recommended)": "recover",
474
+ "Stop daemon for recovery…": "daemon-recovery",
456
475
  "Refresh operation status": "refresh",
457
476
  "Sync setups…": "setups",
458
477
  "Storage connections…": "connections",
@@ -469,8 +488,8 @@ function syncMainMenuItem(
469
488
  description: {
470
489
  sync: "Merge changes on both sides.",
471
490
  "retry-refusal": "Retry model; may incur costs.",
472
- pull: "Remote → this device.",
473
- push: "This device → remote snapshot.",
491
+ pull: "Remote → this device; replaces conflicting local files.",
492
+ push: "This device → remote; replaces conflicting remote files.",
474
493
  diff: "Inspect changes; no transfer.",
475
494
  status: "Check remote; no transfer.",
476
495
  settings: "Change sync settings.",
@@ -479,6 +498,7 @@ function syncMainMenuItem(
479
498
  switch: "Choose another sync setup.",
480
499
  conflicts: "Review unresolved file groups.",
481
500
  recover: "Review local lock recovery.",
501
+ "daemon-recovery": "Review and stop the current daemon without starting another.",
482
502
  refresh: "Recheck the operation lock.",
483
503
  setups: "Manage sync setups.",
484
504
  connections: "Manage storage connections.",