@narumitw/pi-sync 0.68.1 → 0.69.1

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 (94) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.md +35 -21
  3. package/dist/chunks/{chunk-AYGMIMCV.ts → chunk-4KGDPLQ4.ts} +2 -2
  4. package/dist/chunks/chunk-4KGDPLQ4.ts.map +7 -0
  5. package/dist/chunks/{chunk-FR6A7ASZ.ts → chunk-EG6BUOUQ.ts} +3 -3
  6. package/dist/chunks/{chunk-WQXUZSY5.ts → chunk-EI2J5Z4Q.ts} +13 -6
  7. package/dist/chunks/chunk-EI2J5Z4Q.ts.map +7 -0
  8. package/dist/chunks/{chunk-BCDBT4X3.ts → chunk-GXB74FYB.ts} +4 -4
  9. package/dist/chunks/{chunk-J52GYZO6.ts → chunk-LNZRNXNQ.ts} +2 -4
  10. package/dist/chunks/{chunk-FQKWGVMA.ts → chunk-OWSKD5XG.ts} +10 -7
  11. package/dist/chunks/chunk-OWSKD5XG.ts.map +7 -0
  12. package/dist/chunks/{chunk-WCGLU526.ts → chunk-RXZVLBPU.ts} +3 -3
  13. package/dist/chunks/{chunk-KAIVTJIQ.ts → chunk-RZB2DPVU.ts} +2 -2
  14. package/dist/chunks/{chunk-335XTMMZ.ts → chunk-VQTYTUBU.ts} +24 -26
  15. package/dist/chunks/chunk-VQTYTUBU.ts.map +7 -0
  16. package/dist/chunks/{chunk-TLYT6HVI.ts → chunk-YX6DCQ7P.ts} +2 -2
  17. package/dist/chunks/{command-handler-5LDTCUJE.ts → command-handler-ZR26OSBX.ts} +39 -143
  18. package/dist/chunks/command-handler-ZR26OSBX.ts.map +7 -0
  19. package/dist/chunks/{conflict-review-SZ3AWTX6.ts → conflict-review-W5BCZIZG.ts} +2 -2
  20. package/dist/chunks/{file-selection-4BOQBXS7.ts → file-selection-STCIRKF6.ts} +3 -3
  21. package/dist/chunks/{manager-result-dispatcher-A4IWLS4J.ts → manager-result-dispatcher-MPLPDR2P.ts} +5 -5
  22. package/dist/chunks/{manager-ui-KHMCSLLV.ts → manager-ui-OMZOBGYT.ts} +99 -96
  23. package/dist/chunks/manager-ui-OMZOBGYT.ts.map +7 -0
  24. package/dist/chunks/{merge-review-LWMUE5IW.ts → merge-review-KTIQBRLL.ts} +2 -2
  25. package/dist/chunks/{remote-selection-ui-F6NJBQ3Y.ts → remote-selection-ui-CCHMCAHQ.ts} +4 -4
  26. package/dist/chunks/{setup-switch-7LMIRMZ7.ts → setup-switch-J3YLBB6N.ts} +4 -4
  27. package/dist/chunks/{setup-wizard-2NRPR433.ts → setup-wizard-J3YOR7BR.ts} +3 -4
  28. package/dist/chunks/{setup-wizard-2NRPR433.ts.map → setup-wizard-J3YOR7BR.ts.map} +1 -1
  29. package/dist/chunks/{sync-inspection-OTI4JDQ2.ts → sync-inspection-7OADBR57.ts} +3 -3
  30. package/dist/chunks/{sync-operations-ZUYJLWUN.ts → sync-operations-3K6WLPXY.ts} +2 -10
  31. package/dist/chunks/{sync-operations-ZUYJLWUN.ts.map → sync-operations-3K6WLPXY.ts.map} +2 -2
  32. package/dist/daemon/dist/build-id.json +1 -1
  33. package/dist/daemon/dist/daemon-debug.js +13 -6
  34. package/dist/daemon/dist/engine/backends/git/git-backend.js +1 -1
  35. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +2 -2
  36. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +67 -6
  37. package/dist/daemon/dist/engine/debug-check.js +59 -0
  38. package/dist/daemon/dist/engine/debug-log.js +100 -1
  39. package/dist/daemon/dist/engine/sync/directional-conflict.js +31 -0
  40. package/dist/daemon/dist/engine/sync/push-review.js +1 -1
  41. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +6 -5
  42. package/dist/daemon/dist/engine/sync/sync-inspection.js +5 -1
  43. package/dist/daemon/dist/engine/sync/sync-mutations.js +40 -7
  44. package/dist/daemon/dist/engine/sync/sync-queries.js +99 -25
  45. package/dist/daemon/dist/engine/sync/sync-state.js +1 -1
  46. package/dist/daemon/dist/engine/ui/transfer-review.js +2 -3
  47. package/dist/daemon/dist/engine-service.js +100 -25
  48. package/dist/daemon/dist/foreground-transfer.js +10 -0
  49. package/dist/daemon/dist/index.js +1 -0
  50. package/dist/daemon/dist/server.js +17 -9
  51. package/dist/daemon/package.json +1 -1
  52. package/dist/index.ts +111 -10
  53. package/dist/index.ts.map +3 -3
  54. package/docs/daemon-migration.md +2 -2
  55. package/docs/tui-contract.md +7 -7
  56. package/package.json +7 -4
  57. package/skills/configure-pi-sync/SKILL.md +4 -7
  58. package/skills/configure-pi-sync/references/configuration.md +20 -19
  59. package/src/commands/command-execution.ts +36 -136
  60. package/src/commands/command-handler.ts +3 -3
  61. package/src/commands/command.ts +28 -26
  62. package/src/daemon/directional-recovery.ts +3 -1
  63. package/src/daemon/pi-client.ts +6 -0
  64. package/src/sync/debug-tool.ts +96 -0
  65. package/src/sync/startup-check.ts +1 -1
  66. package/src/sync/sync-operations.ts +0 -6
  67. package/src/sync-extension.ts +13 -1
  68. package/src/ui/cancellable-operation.ts +11 -4
  69. package/src/ui/manager-state.ts +13 -12
  70. package/src/ui/manager-ui.ts +96 -81
  71. package/src/ui/operation-dialogs.ts +1 -1
  72. package/src/ui/settings-ui.ts +2 -3
  73. package/src/ui/setup/webdav-ui.ts +1 -1
  74. package/dist/chunks/chunk-335XTMMZ.ts.map +0 -7
  75. package/dist/chunks/chunk-AYGMIMCV.ts.map +0 -7
  76. package/dist/chunks/chunk-ECYCNZOE.ts +0 -12
  77. package/dist/chunks/chunk-ECYCNZOE.ts.map +0 -7
  78. package/dist/chunks/chunk-FQKWGVMA.ts.map +0 -7
  79. package/dist/chunks/chunk-WQXUZSY5.ts.map +0 -7
  80. package/dist/chunks/command-handler-5LDTCUJE.ts.map +0 -7
  81. package/dist/chunks/manager-ui-KHMCSLLV.ts.map +0 -7
  82. /package/dist/chunks/{chunk-FR6A7ASZ.ts.map → chunk-EG6BUOUQ.ts.map} +0 -0
  83. /package/dist/chunks/{chunk-BCDBT4X3.ts.map → chunk-GXB74FYB.ts.map} +0 -0
  84. /package/dist/chunks/{chunk-J52GYZO6.ts.map → chunk-LNZRNXNQ.ts.map} +0 -0
  85. /package/dist/chunks/{chunk-WCGLU526.ts.map → chunk-RXZVLBPU.ts.map} +0 -0
  86. /package/dist/chunks/{chunk-KAIVTJIQ.ts.map → chunk-RZB2DPVU.ts.map} +0 -0
  87. /package/dist/chunks/{chunk-TLYT6HVI.ts.map → chunk-YX6DCQ7P.ts.map} +0 -0
  88. /package/dist/chunks/{conflict-review-SZ3AWTX6.ts.map → conflict-review-W5BCZIZG.ts.map} +0 -0
  89. /package/dist/chunks/{file-selection-4BOQBXS7.ts.map → file-selection-STCIRKF6.ts.map} +0 -0
  90. /package/dist/chunks/{manager-result-dispatcher-A4IWLS4J.ts.map → manager-result-dispatcher-MPLPDR2P.ts.map} +0 -0
  91. /package/dist/chunks/{merge-review-LWMUE5IW.ts.map → merge-review-KTIQBRLL.ts.map} +0 -0
  92. /package/dist/chunks/{remote-selection-ui-F6NJBQ3Y.ts.map → remote-selection-ui-CCHMCAHQ.ts.map} +0 -0
  93. /package/dist/chunks/{setup-switch-7LMIRMZ7.ts.map → setup-switch-J3YLBB6N.ts.map} +0 -0
  94. /package/dist/chunks/{sync-inspection-OTI4JDQ2.ts.map → sync-inspection-7OADBR57.ts.map} +0 -0
@@ -1,6 +1,6 @@
1
1
  import { createSyncBackend } from "../backends/backend-factory.js";
2
2
  import { HISTORY_PREVIEW_LIMIT } from "../backends/sync-backend.js";
3
- import { loadConfig, syncSessionsWarnings } from "../settings/config.js";
3
+ import { loadConfig, loadConfigForCheck, syncCheckConfigFingerprint, syncSessionsWarnings, } from "../settings/config.js";
4
4
  import { resolvedSnapshotOptionsForContext } from "../snapshot/session-paths.js";
5
5
  import { createSnapshot, scanSnapshot } from "../snapshot/snapshot.js";
6
6
  import { inspectLock, isLockGuardHeld, isStaleLock, withLock } from "../state/lock.js";
@@ -9,6 +9,7 @@ import { formatDiff, formatSnapshotOnlyDiff, publicationCapabilityDescription }
9
9
  import { setSyncStatus } from "../ui/sync-status.js";
10
10
  import { safeTerminalText } from "../ui/terminal-text.js";
11
11
  import { portableSnapshot } from "./local-fields.js";
12
+ import { captureMutationOwner } from "./mutation-owner.js";
12
13
  import { formatRemoteSelectionStatus, readRemoteSnapshot } from "./remote-snapshot.js";
13
14
  import { throwIfAborted } from "./signals.js";
14
15
  import { errorMessage } from "./sync-errors.js";
@@ -188,42 +189,115 @@ export async function doctor(ctx, options, factory = createSyncBackend) {
188
189
  ...(config ? reportSection("Sync scope", contentLines(config)) : []),
189
190
  ].join("\n"), attention.length > 0 ? "warning" : "info", "report");
190
191
  }
191
- export async function history(ctx, options, factory = createSyncBackend) {
192
- const config = await loadConfig(options.setup);
193
- throwIfAborted(options.signal);
192
+ export async function history(ctx, options, factory = createSyncBackend, validateJob) {
193
+ const { signal } = options;
194
+ const validateSession = captureMutationOwner(ctx, signal);
195
+ const validateOwner = () => {
196
+ validateJob?.();
197
+ validateSession();
198
+ };
199
+ validateOwner();
200
+ const config = await loadConfig(options.setup, signal);
201
+ validateOwner();
194
202
  const backend = await factory(config);
195
- const snapshots = (await backend.listHistory(options.signal)).slice(-HISTORY_PREVIEW_LIMIT).reverse();
196
- throwIfAborted(options.signal);
203
+ validateOwner();
204
+ const entries = await backend.listHistory(signal);
205
+ validateOwner();
206
+ const interactive = ctx.hasUI && (ctx.mode === "tui" || ctx.mode === "rpc");
207
+ const repair = interactive && !options.auto && config.backend.type === "webdav"
208
+ ? backend.repairActiveHistory?.bind(backend)
209
+ : undefined;
210
+ const head = repair
211
+ ? await backend.readHead(signal).catch(() => {
212
+ validateOwner();
213
+ ctx.ui.notify("History repair is unavailable because the active WebDAV snapshot could not be read.", "warning");
214
+ return undefined;
215
+ })
216
+ : undefined;
217
+ validateOwner();
218
+ const repairHead = head && !entries.some((entry) => entry.snapshotRef === head.snapshotRef) ? head : undefined;
219
+ const snapshots = entries.slice(-HISTORY_PREVIEW_LIMIT).reverse();
197
220
  const lastApplied = await readStateForConfig(config)
198
221
  .then((state) => state.lastAppliedSnapshot)
199
222
  .catch(() => undefined);
200
- throwIfAborted(options.signal);
223
+ validateOwner();
201
224
  const appliedDetails = lastApplied
202
225
  ? `Last applied snapshot ID: ${safeTerminalText(lastApplied)}\nApplication time: unavailable. Snapshot dates are creation times.`
203
226
  : "Last applied snapshot ID: unavailable.";
204
- if (snapshots.length === 0) {
227
+ if (snapshots.length === 0 && !repairHead) {
205
228
  ctx.ui.notify(`No remote pi-sync history found.\n${appliedDetails}`, "info");
206
229
  return;
207
230
  }
208
- const currentSnapshot = snapshots[0]?.snapshotId;
209
- if (ctx.mode === "tui") {
210
- const labels = snapshots.map((item, index) => `${index + 1}. ${item.createdAt} · ${safeTerminalText(item.machine)} · ${item.snapshotId}${item.snapshotId === currentSnapshot ? " (current)" : ""}${item.syncSessions ? " · sessions" : ""}`);
211
- const selected = await ctx.ui.select(`History for sync setup “${safeTerminalText(config.setupName)}”\n\n${appliedDetails}\n\nChoose a snapshot to preview rollback.`, [...labels, "Back"], { signal: options.signal });
212
- if (!selected || selected === "Back")
231
+ const previewRollback = interactive && ctx.mode === "tui";
232
+ if (!previewRollback) {
233
+ ctx.ui.notify([
234
+ appliedDetails,
235
+ ...snapshots.map((item) => `${safeTerminalText(item.snapshotRef)} ${safeTerminalText(item.createdAt)} ${safeTerminalText(item.machine)}`),
236
+ ].join("\n"), "info");
237
+ if (!repairHead)
213
238
  return;
214
- throwIfAborted(options.signal);
215
- const index = labels.indexOf(selected);
216
- const snapshot = snapshots[index];
217
- if (!snapshot)
239
+ }
240
+ const currentSnapshot = repair ? head?.snapshotId : snapshots[0]?.snapshotId;
241
+ const labels = previewRollback
242
+ ? snapshots.map((item, index) => `${index + 1}. ${safeTerminalText(item.createdAt)} · ${safeTerminalText(item.machine)} · ${safeTerminalText(item.snapshotId)}${item.snapshotId === currentSnapshot ? " (current)" : ""}${item.syncSessions ? " · sessions" : ""}`)
243
+ : [];
244
+ const setupName = safeTerminalText(config.setupName);
245
+ const repairChoice = "Repair active snapshot history";
246
+ const selected = await ctx.ui.select([
247
+ `History for sync setup “${setupName}”`,
248
+ appliedDetails,
249
+ ...(labels.length > 0 ? ["Choose a snapshot to preview rollback."] : []),
250
+ ...(repairHead ? ["The active WebDAV snapshot is missing from History."] : []),
251
+ ].join("\n\n"), [...labels, ...(repairHead ? [repairChoice] : []), "Back"], { signal });
252
+ validateOwner();
253
+ if (!selected || selected === "Back")
254
+ return;
255
+ if (selected === repairChoice && repairHead && repair) {
256
+ const validateRepairOwner = () => {
257
+ validateOwner();
258
+ if (!ctx.hasUI || (ctx.mode !== "tui" && ctx.mode !== "rpc"))
259
+ throw new Error("History repair no longer has an observable TUI or RPC client.");
260
+ };
261
+ validateRepairOwner();
262
+ const fingerprint = syncCheckConfigFingerprint(config);
263
+ const confirmed = await ctx.ui.confirm("Repair active WebDAV snapshot history?", [
264
+ `Setup: ${setupName}`,
265
+ `Storage: ${safeTerminalText(backend.destination)}`,
266
+ `Active snapshot: ${safeTerminalText(repairHead.snapshotId)}`,
267
+ "This runs a temporary conditional write/delete probe, then adds this snapshot to remote History if it is still missing. If History is full, the oldest entry is dropped. The active snapshot and local files do not change.",
268
+ ].join("\n"), { signal });
269
+ validateRepairOwner();
270
+ if (!confirmed)
218
271
  return;
219
- await withLock("rollback", () => rollback(ctx, { ...options, args: [snapshot.snapshotRef], yes: false }, factory, {
220
- backendIdentity: backend.identity,
221
- setup: config.setupName,
222
- }));
272
+ const validateSettings = async () => {
273
+ validateRepairOwner();
274
+ const current = await loadConfigForCheck(options.setup, signal);
275
+ validateRepairOwner();
276
+ if (syncCheckConfigFingerprint(current) !== fingerprint)
277
+ throw new Error("The sync setup settings changed. Reopen History before repairing it.");
278
+ };
279
+ const repaired = await withLock("history repair", async () => {
280
+ await validateSettings();
281
+ validateRepairOwner();
282
+ return repair(repairHead, {
283
+ signal,
284
+ validateOwner: validateRepairOwner,
285
+ validateSettings,
286
+ onCommit: options.onCommit,
287
+ });
288
+ });
289
+ validateRepairOwner();
290
+ ctx.ui.notify(repaired ? "Active WebDAV snapshot added to History." : "The active WebDAV snapshot is already in History.", "info");
223
291
  return;
224
292
  }
225
- ctx.ui.notify([
226
- appliedDetails,
227
- ...snapshots.map((item) => `${item.snapshotRef} ${item.createdAt} ${safeTerminalText(item.machine)}`),
228
- ].join("\n"), "info");
293
+ const snapshot = snapshots[labels.indexOf(selected)];
294
+ if (!snapshot)
295
+ return;
296
+ await withLock("rollback", () => {
297
+ validateOwner();
298
+ return rollback(ctx, { ...options, args: [snapshot.snapshotRef], yes: false }, factory, {
299
+ backendIdentity: backend.identity,
300
+ setup: config.setupName,
301
+ });
302
+ });
229
303
  }
@@ -46,7 +46,7 @@ export function rawSnapshotHashIdentity(snapshot) {
46
46
  .update(JSON.stringify(fileHashMap(snapshot)))
47
47
  .digest("hex");
48
48
  }
49
- function stateHashMapForConfig(state, config) {
49
+ export function stateHashMapForConfig(state, config) {
50
50
  const includePaths = customIncludePathsByLower(includeFromSelectionConfig(config));
51
51
  const configured = configuredSnapshotPathMatcher(config);
52
52
  return Object.fromEntries(Object.entries(state.lastFileHashes)
@@ -1,6 +1,5 @@
1
1
  import { confirmMergeReview } from "./merge-review.js";
2
- /** Presentation is supplied by the host; RPC keeps its existing directional confirmation. */
3
- export async function confirmTransferReview(ctx, title, review, signal, validate) {
2
+ export async function confirmTransferReview(ctx, title, review, signal, validate, reviewInRpc = false) {
4
3
  validate();
5
4
  const isCurrent = () => {
6
5
  try {
@@ -11,7 +10,7 @@ export async function confirmTransferReview(ctx, title, review, signal, validate
11
10
  return false;
12
11
  }
13
12
  };
14
- const confirmed = ctx.mode === "tui" && ctx.hasUI
13
+ const confirmed = ctx.hasUI && (ctx.mode === "tui" || (reviewInRpc && ctx.mode === "rpc"))
15
14
  ? await confirmMergeReview(ctx, title, review.content, signal, isCurrent, "apply reviewed transfer", review.lines)
16
15
  : await ctx.ui.confirm(title, review.content, { signal });
17
16
  validate();
@@ -1,9 +1,11 @@
1
1
  import { authorizeAfterExit, captureAutomaticAuthorization, consentFingerprint, readConsent, requireHandover, } from "./consent.js";
2
2
  import { createDaemonDebug } from "./daemon-debug.js";
3
3
  import { documentFingerprint } from "./document.js";
4
+ import { debugCheckFailure, summarizeDebugInspection } from "./engine/debug-check.js";
4
5
  import { retiredIgnorePolicy } from "./engine/settings/retired-ignore-policy.js";
5
6
  import { assertNoRetiredRuleJournal } from "./engine/settings/retired-ignore-recovery.js";
6
7
  import { captureStartupReviewLock } from "./engine/state/lock.js";
8
+ import { isForegroundTransferIntent } from "./foreground-transfer.js";
7
9
  import { createLegacyConsentGuard } from "./legacy-consent-guard.js";
8
10
  import { MAX_SETTINGS_BYTES, record } from "./protocol.js";
9
11
  import { createServiceContext, installServiceHost } from "./service-host.js";
@@ -121,23 +123,8 @@ export function createEngineService(root) {
121
123
  const ctx = createServiceContext(execution);
122
124
  if (operation === "initialize")
123
125
  return initialize(ctx, execution);
124
- if (operation === "inspect") {
125
- if (!record(payload) || (payload.setup !== undefined && typeof payload.setup !== "string"))
126
- throw new Error("Invalid inspection request.");
127
- const { withStateDirectoryAccess } = await import("./engine/state/state-directory.js");
128
- const { withLock } = await import("./engine/state/lock.js");
129
- return withJobTimings(ctx, execution, "daemon inspection", (timings) => withStateDirectoryAccess(() => withLock("startup-check", async () => {
130
- const { loadConfigForCheck, syncCheckConfigFingerprint } = await import("./engine/settings/config.js");
131
- const config = await loadConfigForCheck(payload.setup, execution.signal);
132
- execution.validate();
133
- if (payload.fingerprint !== syncCheckConfigFingerprint(config))
134
- throw new Error("Settings changed before inspection.");
135
- const { snapshotOptionsForContext } = await import("./engine/snapshot/session-paths.js");
136
- const { inspectSync } = await import("./engine/sync/sync-inspection.js");
137
- execution.validate();
138
- return inspectSync(config, snapshotOptionsForContext(ctx, config), execution.signal, undefined, timings);
139
- })));
140
- }
126
+ if (operation === "inspect")
127
+ return inspectForClient(ctx, execution, payload);
141
128
  if (operation === "push.foreground" || operation === "pull.foreground") {
142
129
  const direction = operation === "push.foreground" ? "push" : "pull";
143
130
  return runForegroundDirectional(host, execution, ctx, direction, payload);
@@ -269,7 +256,9 @@ export function createEngineService(root) {
269
256
  }
270
257
  if (operation === "push" || operation === "pull" || operation === "rollback")
271
258
  return withLock(operation, () => operations[operation](ctx, options));
272
- if (operation === "status" || operation === "diff" || operation === "doctor" || operation === "history")
259
+ if (operation === "history")
260
+ return operations.history(ctx, options, undefined, execution.validate);
261
+ if (operation === "status" || operation === "diff" || operation === "doctor")
273
262
  return operations[operation](ctx, options);
274
263
  throw new Error("Unreachable operation.");
275
264
  });
@@ -305,7 +294,9 @@ async function runForegroundDirectional(host, execution, ctx, direction, payload
305
294
  !ctx.hasUI ||
306
295
  !["tui", "rpc"].includes(ctx.mode) ||
307
296
  !record(payload) ||
308
- Object.keys(payload).some((key) => !["setup", "fingerprint", "retryCheckpoint"].includes(key)) ||
297
+ Object.keys(payload).some((key) => !["setup", "fingerprint", "retryCheckpoint", "intent"].includes(key)) ||
298
+ (payload.intent !== undefined && !isForegroundTransferIntent(payload.intent)) ||
299
+ (payload.intent === "review-force" && payload.retryCheckpoint !== undefined) ||
309
300
  typeof payload.setup !== "string" ||
310
301
  !payload.setup ||
311
302
  payload.setup.length > 512 ||
@@ -315,11 +306,12 @@ async function runForegroundDirectional(host, execution, ctx, direction, payload
315
306
  (typeof payload.retryCheckpoint !== "string" || !fingerprintPattern.test(payload.retryCheckpoint)))) {
316
307
  throw new Error("Invalid foreground directional request.");
317
308
  }
318
- const { setup, fingerprint, retryCheckpoint } = payload;
309
+ const { setup, fingerprint, retryCheckpoint, intent } = payload;
319
310
  const { withStateDirectoryAccess } = await import("./engine/state/state-directory.js");
320
311
  const { withLock } = await import("./engine/state/lock.js");
321
312
  const { loadConfigForCheck, syncCheckConfigFingerprint } = await import("./engine/settings/config.js");
322
313
  const operations = await import("./engine/sync/sync-operations.js");
314
+ const { DirectionalDestinationConflict, DirectionalReviewChangedError } = await import("./engine/sync/directional-conflict.js");
323
315
  const validate = (config) => {
324
316
  execution.validate();
325
317
  if (config.setupName !== setup || syncCheckConfigFingerprint(config) !== fingerprint)
@@ -340,15 +332,17 @@ async function runForegroundDirectional(host, execution, ctx, direction, payload
340
332
  }
341
333
  return host.runForeground(execution, () => withLock(direction, async () => {
342
334
  validate(await loadConfigForCheck(undefined, execution.signal));
335
+ const changedDuringRecovery = () => new Error("The transfer source or destination changed during recovery. The transfer was not replayed.");
343
336
  let message;
344
- const outcome = await operations[direction](ctx, {
337
+ const options = {
345
338
  ...optionsFrom({ setup, args: [] }, execution, false),
346
339
  directionalAction: {
340
+ intent,
347
341
  validate,
348
342
  async checkpoint(current) {
349
343
  execution.validate();
350
344
  if (retryCheckpoint !== undefined && retryCheckpoint !== current)
351
- throw new Error("The transfer source or destination changed during recovery. The transfer was not replayed.");
345
+ throw changedDuringRecovery();
352
346
  const accepted = await execution.request("directional-checkpoint", { fingerprint: current });
353
347
  if (accepted !== true)
354
348
  throw new Error("The original transfer could not be retained for recovery. No transfer was started.");
@@ -358,11 +352,92 @@ async function runForegroundDirectional(host, execution, ctx, direction, payload
358
352
  message = value;
359
353
  },
360
354
  },
361
- });
362
- return { outcome, ...(message === undefined ? {} : { message }) };
355
+ };
356
+ const run = async () => {
357
+ try {
358
+ const outcome = await operations[direction](ctx, options);
359
+ return { outcome, ...(message === undefined ? {} : { message }) };
360
+ }
361
+ catch (error) {
362
+ if (intent !== "reject-conflicts" || !(error instanceof DirectionalDestinationConflict))
363
+ throw error;
364
+ execution.validate();
365
+ if (retryCheckpoint !== undefined)
366
+ throw changedDuringRecovery();
367
+ return { outcome: "destination-conflict" };
368
+ }
369
+ };
370
+ try {
371
+ return await run();
372
+ }
373
+ catch (error) {
374
+ if (intent !== "review-force" || !(error instanceof DirectionalReviewChangedError))
375
+ throw error;
376
+ validate(await loadConfigForCheck(undefined, execution.signal));
377
+ return run();
378
+ }
363
379
  }));
364
380
  });
365
381
  }
382
+ async function inspectForClient(ctx, execution, payload) {
383
+ if (!record(payload) ||
384
+ (payload.setup !== undefined && typeof payload.setup !== "string") ||
385
+ (payload.origin !== undefined && payload.origin !== "recheck"))
386
+ throw new Error("Invalid inspection request.");
387
+ const origin = payload.origin === "recheck" ? "recheck" : "startup";
388
+ const setup = typeof payload.setup === "string" ? payload.setup : undefined;
389
+ if (origin === "recheck" &&
390
+ (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode) || !execution.facts()?.startupDebug || !setup))
391
+ throw new Error("Recheck requires an interactive Debug mode session.");
392
+ const configChanged = () => Object.assign(new Error("Settings changed during inspection."), { code: "SYNC_INSPECTION_CHANGED" });
393
+ let setupKey;
394
+ const note = (summary) => {
395
+ if (setupKey && !execution.signal.aborted)
396
+ execution.debug?.({ event: "check", origin, setupKey, summary });
397
+ };
398
+ const { withStateDirectoryAccess } = await import("./engine/state/state-directory.js");
399
+ const { withLock } = await import("./engine/state/lock.js");
400
+ try {
401
+ const result = await withJobTimings(ctx, execution, "daemon inspection", (timings) => withStateDirectoryAccess(() => withLock("startup-check", async () => {
402
+ const [{ loadConfigForCheck, syncCheckConfigFingerprint, syncConfigReviewFingerprint }, { snapshotOptionsForContext }, { inspectSync },] = await Promise.all([
403
+ import("./engine/settings/config.js"),
404
+ import("./engine/snapshot/session-paths.js"),
405
+ import("./engine/sync/sync-inspection.js"),
406
+ ]);
407
+ const readReviewed = async () => {
408
+ execution.validate();
409
+ const config = await loadConfigForCheck(origin === "recheck" ? undefined : setup, execution.signal);
410
+ execution.validate();
411
+ if (payload.fingerprint !== syncCheckConfigFingerprint(config) ||
412
+ (origin === "recheck" && setup !== config.setupName))
413
+ throw configChanged();
414
+ return config;
415
+ };
416
+ const config = await readReviewed();
417
+ execution.validate();
418
+ setupKey = syncConfigReviewFingerprint(config);
419
+ const revalidate = origin === "recheck"
420
+ ? async () => {
421
+ await readReviewed();
422
+ }
423
+ : undefined;
424
+ const inspected = await inspectSync(config, snapshotOptionsForContext(ctx, config), execution.signal, undefined, timings, revalidate);
425
+ execution.validate();
426
+ if (revalidate)
427
+ await revalidate();
428
+ return inspected;
429
+ })));
430
+ execution.validate();
431
+ const summary = summarizeDebugInspection(result);
432
+ if (summary)
433
+ note(summary);
434
+ return result;
435
+ }
436
+ catch (error) {
437
+ note(debugCheckFailure(error));
438
+ throw error;
439
+ }
440
+ }
366
441
  async function withJobTimings(ctx, execution, label, action) {
367
442
  const { createStartupTimings } = await import("./engine/sync/startup-timings.js");
368
443
  const timings = createStartupTimings((_ctx, report) => execution.emit("timings", { report }));
@@ -382,7 +457,7 @@ async function requireStartupRecoveryCleared(execution) {
382
457
  const pending = await pendingTransactionEntries();
383
458
  execution.validate();
384
459
  if (pending.length)
385
- throw new Error("Pi Sync startup cannot confirm recovery is clear. Preserve recovery files and check /sync doctor before retrying.");
460
+ throw new Error("Pi Sync startup cannot confirm recovery is clear. Preserve recovery files and use /sync daemon status for recovery guidance before retrying.");
386
461
  }
387
462
  async function initialize(ctx, execution, diagnostics = true) {
388
463
  const { pendingTransactionEntries } = await import("./engine/snapshot/snapshot-transaction-directory.js");
@@ -0,0 +1,10 @@
1
+ export function isForegroundTransferIntent(value) {
2
+ return value === "reject-conflicts" || value === "review-force";
3
+ }
4
+ export function isDestinationConflict(value) {
5
+ return (typeof value === "object" &&
6
+ value !== null &&
7
+ "outcome" in value &&
8
+ value.outcome === "destination-conflict" &&
9
+ Object.keys(value).length === 1);
10
+ }
@@ -3,5 +3,6 @@ export { inspectDaemonRecovery, stopDaemonForRecovery, } from "./daemon-recovery
3
3
  export { DaemonUpgradeBlockedError } from "./daemon-startup.js";
4
4
  export { inspectDaemonStatus } from "./daemon-status.js";
5
5
  export { documentFingerprint } from "./document.js";
6
+ export { isDestinationConflict } from "./foreground-transfer.js";
6
7
  export { modelSignature } from "./model-signature.js";
7
8
  export { MAX_SETTINGS_BYTES, OWNERSHIP_CLEANUP_REQUIRED, PROTOCOL_VERSION } from "./protocol.js";
@@ -59,7 +59,7 @@ export async function startServer(root, execute, hooks = {}) {
59
59
  const debug = diagnostic
60
60
  ? (event, current) => {
61
61
  try {
62
- diagnostic(event, () => ownsLog() && (current?.() ?? true));
62
+ return diagnostic(event, () => ownsLog() && (current?.() ?? true))?.catch(() => { });
63
63
  }
64
64
  catch { }
65
65
  }
@@ -321,7 +321,8 @@ export async function startServer(root, execute, hooks = {}) {
321
321
  validate,
322
322
  request,
323
323
  emit: (kind, data, target = job.client) => emit(kind, data, target),
324
- debug,
324
+ debug: debug &&
325
+ ((event, current) => debug(event.event === "check" ? { ...event, operationId: job.view.id } : event, current)),
325
326
  noteDebugOutcome(outcome) {
326
327
  job.debugOutcome = outcome;
327
328
  },
@@ -383,9 +384,10 @@ export async function startServer(root, execute, hooks = {}) {
383
384
  job.controller.abort(new DOMException("Operation cancelled before dispatch", "AbortError"));
384
385
  const execution = makeExecution(job);
385
386
  const kind = debug && debugOperation(operation);
386
- const note = (outcome) => {
387
+ const waitForInspectionLog = kind === "inspect";
388
+ const note = (outcome, current) => {
387
389
  if (kind)
388
- debug?.({ event: "job", operation: kind, outcome, operationId: id });
390
+ return debug?.({ event: "job", operation: kind, outcome, operationId: id }, current);
389
391
  };
390
392
  job.promise = queue
391
393
  .then(async () => {
@@ -403,21 +405,27 @@ export async function startServer(root, execute, hooks = {}) {
403
405
  });
404
406
  foregroundRecoveryJob ??= job;
405
407
  }
408
+ const logged = note(debugJobResult(operation, result) ?? job.debugOutcome ?? "completed", waitForInspectionLog ? () => !execution.signal.aborted : undefined);
409
+ if (waitForInspectionLog && logged) {
410
+ await logged;
411
+ execution.validate();
412
+ }
406
413
  job.view.result = result;
407
414
  job.view.phase = "done";
408
- note(debugJobResult(operation, result) ?? job.debugOutcome ?? "completed");
409
415
  })
410
- .catch((error) => {
416
+ .catch(async (error) => {
411
417
  if (error instanceof ConsentPublicationError)
412
418
  consentPublicationFailed = true;
413
- job.view.phase = "failed";
414
- job.view.error = remoteError(error);
415
- note(!job.committed && (job.controller.signal.aborted || (error instanceof Error && error.name === "AbortError"))
419
+ const logged = note(!job.committed && (job.controller.signal.aborted || (error instanceof Error && error.name === "AbortError"))
416
420
  ? "cancelled"
417
421
  : (job.debugOutcome ??
418
422
  (error instanceof SyncDecisionRequiredError || error instanceof DaemonStoppingError
419
423
  ? "blocked"
420
424
  : "failed")));
425
+ if (waitForInspectionLog && logged)
426
+ await logged;
427
+ job.view.phase = "failed";
428
+ job.view.error = remoteError(error);
421
429
  if (job.committed)
422
430
  for (const id of new Set([client, ...job.peers])) {
423
431
  const affected = participants.get(id);
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.14.1"
2
+ "version": "0.15.1"
3
3
  }