@narumitw/pi-sync 0.68.1 → 0.69.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 (93) hide show
  1. package/CHANGELOG.md +15 -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/engine/backends/git/git-backend.js +1 -1
  34. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +2 -2
  35. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +67 -6
  36. package/dist/daemon/dist/engine/debug-check.js +59 -0
  37. package/dist/daemon/dist/engine/debug-log.js +100 -1
  38. package/dist/daemon/dist/engine/sync/directional-conflict.js +31 -0
  39. package/dist/daemon/dist/engine/sync/push-review.js +1 -1
  40. package/dist/daemon/dist/engine/sync/sync-error-guidance.js +6 -5
  41. package/dist/daemon/dist/engine/sync/sync-inspection.js +5 -1
  42. package/dist/daemon/dist/engine/sync/sync-mutations.js +40 -7
  43. package/dist/daemon/dist/engine/sync/sync-queries.js +99 -25
  44. package/dist/daemon/dist/engine/sync/sync-state.js +1 -1
  45. package/dist/daemon/dist/engine/ui/transfer-review.js +2 -3
  46. package/dist/daemon/dist/engine-service.js +100 -25
  47. package/dist/daemon/dist/foreground-transfer.js +10 -0
  48. package/dist/daemon/dist/index.js +1 -0
  49. package/dist/daemon/dist/server.js +2 -1
  50. package/dist/daemon/package.json +1 -1
  51. package/dist/index.ts +111 -10
  52. package/dist/index.ts.map +3 -3
  53. package/docs/daemon-migration.md +2 -2
  54. package/docs/tui-contract.md +7 -7
  55. package/package.json +7 -4
  56. package/skills/configure-pi-sync/SKILL.md +4 -7
  57. package/skills/configure-pi-sync/references/configuration.md +20 -19
  58. package/src/commands/command-execution.ts +36 -136
  59. package/src/commands/command-handler.ts +3 -3
  60. package/src/commands/command.ts +28 -26
  61. package/src/daemon/directional-recovery.ts +3 -1
  62. package/src/daemon/pi-client.ts +6 -0
  63. package/src/sync/debug-tool.ts +96 -0
  64. package/src/sync/startup-check.ts +1 -1
  65. package/src/sync/sync-operations.ts +0 -6
  66. package/src/sync-extension.ts +13 -1
  67. package/src/ui/cancellable-operation.ts +11 -4
  68. package/src/ui/manager-state.ts +13 -12
  69. package/src/ui/manager-ui.ts +96 -81
  70. package/src/ui/operation-dialogs.ts +1 -1
  71. package/src/ui/settings-ui.ts +2 -3
  72. package/src/ui/setup/webdav-ui.ts +1 -1
  73. package/dist/chunks/chunk-335XTMMZ.ts.map +0 -7
  74. package/dist/chunks/chunk-AYGMIMCV.ts.map +0 -7
  75. package/dist/chunks/chunk-ECYCNZOE.ts +0 -12
  76. package/dist/chunks/chunk-ECYCNZOE.ts.map +0 -7
  77. package/dist/chunks/chunk-FQKWGVMA.ts.map +0 -7
  78. package/dist/chunks/chunk-WQXUZSY5.ts.map +0 -7
  79. package/dist/chunks/command-handler-5LDTCUJE.ts.map +0 -7
  80. package/dist/chunks/manager-ui-KHMCSLLV.ts.map +0 -7
  81. /package/dist/chunks/{chunk-FR6A7ASZ.ts.map → chunk-EG6BUOUQ.ts.map} +0 -0
  82. /package/dist/chunks/{chunk-BCDBT4X3.ts.map → chunk-GXB74FYB.ts.map} +0 -0
  83. /package/dist/chunks/{chunk-J52GYZO6.ts.map → chunk-LNZRNXNQ.ts.map} +0 -0
  84. /package/dist/chunks/{chunk-WCGLU526.ts.map → chunk-RXZVLBPU.ts.map} +0 -0
  85. /package/dist/chunks/{chunk-KAIVTJIQ.ts.map → chunk-RZB2DPVU.ts.map} +0 -0
  86. /package/dist/chunks/{chunk-TLYT6HVI.ts.map → chunk-YX6DCQ7P.ts.map} +0 -0
  87. /package/dist/chunks/{conflict-review-SZ3AWTX6.ts.map → conflict-review-W5BCZIZG.ts.map} +0 -0
  88. /package/dist/chunks/{file-selection-4BOQBXS7.ts.map → file-selection-STCIRKF6.ts.map} +0 -0
  89. /package/dist/chunks/{manager-result-dispatcher-A4IWLS4J.ts.map → manager-result-dispatcher-MPLPDR2P.ts.map} +0 -0
  90. /package/dist/chunks/{merge-review-LWMUE5IW.ts.map → merge-review-KTIQBRLL.ts.map} +0 -0
  91. /package/dist/chunks/{remote-selection-ui-F6NJBQ3Y.ts.map → remote-selection-ui-CCHMCAHQ.ts.map} +0 -0
  92. /package/dist/chunks/{setup-switch-7LMIRMZ7.ts.map → setup-switch-J3YLBB6N.ts.map} +0 -0
  93. /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";
@@ -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
  },
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.14.1"
2
+ "version": "0.15.0"
3
3
  }
package/dist/index.ts CHANGED
@@ -4,16 +4,17 @@ import {
4
4
  createSyncAttentionController,
5
5
  readStateForConfig,
6
6
  syncStateFingerprint
7
- } from "./chunks/chunk-TLYT6HVI.ts";
7
+ } from "./chunks/chunk-YX6DCQ7P.ts";
8
8
  import {
9
9
  combineSignals,
10
10
  throwIfAborted
11
11
  } from "./chunks/chunk-UMPA5S7X.ts";
12
12
  import {
13
13
  completeSyncArguments,
14
+ retiredSyncCommandGuidance,
14
15
  setSyncSetupCompletions,
15
16
  splitArgs
16
- } from "./chunks/chunk-335XTMMZ.ts";
17
+ } from "./chunks/chunk-VQTYTUBU.ts";
17
18
  import {
18
19
  withStateDirectoryAccess
19
20
  } from "./chunks/chunk-T3LABNHF.ts";
@@ -24,14 +25,15 @@ import "./chunks/chunk-ZO52JM4H.ts";
24
25
  import {
25
26
  configFromSettings,
26
27
  loadConfigForCheck,
27
- syncCheckConfigFingerprint
28
- } from "./chunks/chunk-J52GYZO6.ts";
28
+ syncCheckConfigFingerprint,
29
+ syncConfigReviewFingerprint
30
+ } from "./chunks/chunk-LNZRNXNQ.ts";
29
31
  import {
30
32
  bindPiDaemonClient,
31
33
  installPiDaemonHost,
32
34
  piDaemonClient,
33
35
  withPiDaemonClient
34
- } from "./chunks/chunk-WQXUZSY5.ts";
36
+ } from "./chunks/chunk-EI2J5Z4Q.ts";
35
37
  import {
36
38
  configureSyncStatus,
37
39
  createSyncStatusPublisher,
@@ -168,6 +170,95 @@ async function autoPushSessions(ctx, signal, _loaders) {
168
170
  }
169
171
  }
170
172
 
173
+ // src/sync/debug-tool.ts
174
+ import { StringEnum } from "@earendil-works/pi-ai";
175
+ import { debugCheckFailure, summarizeDebugInspection } from "#pi-sync-daemon/engine/debug-check";
176
+ import { readLatestDebugCheck } from "#pi-sync-daemon/engine/debug-log";
177
+ import { Type } from "typebox";
178
+ var TOOL_NAME = "pi_sync_debug";
179
+ var RECHECK_TIMEOUT_MS = 3e4;
180
+ function toolResult(value) {
181
+ return { content: [{ type: "text", text: JSON.stringify(value) }], details: {} };
182
+ }
183
+ function registerPiSyncDebug(pi, getOwner) {
184
+ pi.registerTool({
185
+ name: TOOL_NAME,
186
+ label: "Pi Sync debug",
187
+ description: "Read the latest sanitized Pi Sync check from the local log (latest), or read configured remote storage without confirmation to return a fresh sanitized summary (recheck). Does not publish or apply files.",
188
+ parameters: Type.Object({ action: StringEnum(["latest", "recheck"]) }, { additionalProperties: false }),
189
+ defaultActive: false,
190
+ exposure: "direct",
191
+ executionMode: "sequential",
192
+ async execute(_id, { action }, toolSignal, _update, ctx) {
193
+ const owner = getOwner(ctx);
194
+ if (!owner || !ctx.hasUI || ctx.mode !== "tui" && ctx.mode !== "rpc")
195
+ throw new Error("Pi Sync debug requires an interactive session started with Debug mode on.");
196
+ const { client } = owner;
197
+ const signal = toolSignal ? AbortSignal.any([owner.signal, toolSignal]) : owner.signal;
198
+ const validate = () => {
199
+ signal.throwIfAborted();
200
+ if (getOwner(ctx)?.client !== client) throw new Error("Pi Sync session was replaced.");
201
+ try {
202
+ client.validateDebugTool();
203
+ } catch {
204
+ throw new Error("The Pi Sync debug session is no longer available.");
205
+ }
206
+ };
207
+ async function readSetup() {
208
+ validate();
209
+ try {
210
+ const { settings } = await client.readStartupSettings(signal);
211
+ validate();
212
+ if (settings) return configFromSettings(settings);
213
+ } catch {
214
+ validate();
215
+ }
216
+ throw new Error("The current Pi Sync setup is not available. Review /sync \u2192 Settings.");
217
+ }
218
+ const setup = await readSetup();
219
+ validate();
220
+ if (action === "latest") {
221
+ const last = readLatestDebugCheck(client.root, syncConfigReviewFingerprint(setup));
222
+ if (last.kind === "unavailable") throw new Error("The private Pi Sync debug log is unavailable.");
223
+ if (last.kind === "no-record") return toolResult({ kind: "no-record" });
224
+ return toolResult({ kind: "historical", ...last.check });
225
+ }
226
+ if (action !== "recheck") throw new Error("Choose latest or recheck.");
227
+ if (client.ownershipCleanupRequired) throw new Error("Pi Sync needs recovery. Open /sync daemon status.");
228
+ const fingerprint = syncCheckConfigFingerprint(setup);
229
+ const deadline = AbortSignal.timeout(RECHECK_TIMEOUT_MS);
230
+ const recheckSignal = AbortSignal.any([signal, deadline]);
231
+ let result;
232
+ try {
233
+ result = await client.run(
234
+ "inspect",
235
+ { setup: setup.setupName, fingerprint, origin: "recheck" },
236
+ recheckSignal,
237
+ ctx
238
+ );
239
+ } catch (error) {
240
+ validate();
241
+ const { reason } = debugCheckFailure(deadline.aborted ? deadline.reason : error);
242
+ throw new Error(`Pi Sync recheck failed: ${reason}.`);
243
+ }
244
+ validate();
245
+ if (deadline.aborted) throw new Error("Pi Sync recheck failed: timeout.");
246
+ const latest = await readSetup();
247
+ validate();
248
+ if (fingerprint !== syncCheckConfigFingerprint(latest))
249
+ throw new Error("Pi Sync setup changed during recheck. Ask to recheck the new setup.");
250
+ const summary = summarizeDebugInspection(result);
251
+ if (!summary) throw new Error("Pi Sync did not return a valid check result.");
252
+ return toolResult({ kind: "fresh", time: (/* @__PURE__ */ new Date()).toISOString(), origin: "recheck", summary });
253
+ }
254
+ });
255
+ return (enabled) => {
256
+ const active = pi.getActiveTools();
257
+ if (active.includes(TOOL_NAME) === enabled) return;
258
+ pi.setActiveTools(enabled ? [...active, TOOL_NAME] : active.filter((name) => name !== TOOL_NAME));
259
+ };
260
+ }
261
+
171
262
  // src/sync/startup-check.ts
172
263
  function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
173
264
  let active;
@@ -294,7 +385,7 @@ function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
294
385
  if (!latest || syncCheckConfigFingerprint(latest) !== syncCheckConfigFingerprint(config)) return;
295
386
  }
296
387
  ctx.ui.notify(
297
- config && startupTransferEnabled(config) ? `pi-sync automatic transfer stopped: ${safeTerminalText(errorMessage(error))}. Run /sync to review or reconcile retained recovery evidence. No resources were reloaded.` : `pi-sync startup check skipped: ${safeTerminalText(errorMessage(error))}. Run /sync status to retry. No startup transfer was performed.`,
388
+ config && startupTransferEnabled(config) ? `pi-sync automatic transfer stopped: ${safeTerminalText(errorMessage(error))}. Run /sync to review or reconcile retained recovery evidence. No resources were reloaded.` : `pi-sync startup check skipped: ${safeTerminalText(errorMessage(error))}. Use View differences in /sync, or ask Pi to recheck in Debug mode. No startup transfer was performed.`,
298
389
  "warning"
299
390
  );
300
391
  } finally {
@@ -342,12 +433,12 @@ function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
342
433
  // src/sync/sync-loaders.ts
343
434
  function createSyncLoaders(dependencies) {
344
435
  const loaders = {
345
- commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-5LDTCUJE.ts"))),
346
- inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-OTI4JDQ2.ts"))),
347
- setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-7LMIRMZ7.ts"))),
436
+ commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-ZR26OSBX.ts"))),
437
+ inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-7OADBR57.ts"))),
438
+ setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-J3YLBB6N.ts"))),
348
439
  snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import("./chunks/snapshot-ZUJJZCFW.ts"))),
349
440
  syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import("./chunks/sync-state-QIT64TKV.ts"))),
350
- operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-ZUYJLWUN.ts")))
441
+ operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-3K6WLPXY.ts")))
351
442
  };
352
443
  return loaders;
353
444
  }
@@ -400,11 +491,20 @@ function sync(pi, dependencies = {}) {
400
491
  let initialization = Promise.resolve(void 0);
401
492
  let owner;
402
493
  let ownerManager;
494
+ const exposeDebugTool = registerPiSyncDebug(
495
+ pi,
496
+ (ctx) => owner?.debugEnabled && !sessionAbort.signal.aborted && ownerManager === ctx.sessionManager ? { client: owner, signal: sessionAbort.signal } : void 0
497
+ );
403
498
  pi.registerCommand("sync", {
404
499
  description: "Sync Pi settings through Git, WebDAV, R2, or S3-compatible storage",
405
500
  getArgumentCompletions: completeSyncArguments,
406
501
  handler: async (args, ctx) => {
407
502
  if (!ctx.hasUI) throw new Error("/sync requires TUI or RPC mode so results and safety prompts are observable.");
503
+ const retired = retiredSyncCommandGuidance(splitArgs(args)[0]);
504
+ if (retired) {
505
+ ctx.ui.notify(retired, "warning");
506
+ return;
507
+ }
408
508
  status.bind(ctx);
409
509
  const signal = sessionAbort.signal;
410
510
  const client = owner;
@@ -550,6 +650,7 @@ function sync(pi, dependencies = {}) {
550
650
  });
551
651
  try {
552
652
  const ready = await initialization;
653
+ if (!signal.aborted && owner === client) exposeDebugTool(client.debugEnabled);
553
654
  if (ready === false) {
554
655
  client.disableQueueReleaseUI();
555
656
  releaseStatus();