@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,23 +1,27 @@
1
1
  import type { ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import { isDestinationConflict } from "@narumitw/pi-sync-daemon";
2
3
  import { showDaemonStatus } from "../daemon/daemon-status-ui.js";
3
4
  import { CompletedDirectionalRecoveryError } from "../daemon/directional-recovery.js";
4
5
  import { type PiDaemonClient, piDaemonClient, remoteOperation } from "../daemon/pi-client.js";
5
- import { loadSettingsConfig, sessionTokenWarnings, syncSessionsWarnings } from "../settings/config.js";
6
6
  import { activeLocalConfigPath, createLocalConfigDocument, localConfigPath } from "../settings/config-file.js";
7
7
  import { localConfigTemplate, readLocalConfigObject } from "../settings/settings-store.js";
8
- import type { AnySyncConfig } from "../settings/settings-types.js";
9
8
  import { throwIfAborted } from "../sync/signals.js";
10
9
  import { syncErrorGuidance } from "../sync/sync-error-guidance.js";
11
10
  import { errorMessage, isSyncDecisionRequiredError, SetupPullRequiresUiError } from "../sync/sync-errors.js";
12
11
  import type { SyncLoaders } from "../sync/sync-loaders.js";
13
- import { RemoteSelectionMismatchError, syncSessionsSelected } from "../sync/sync-policy.js";
14
- import { automaticSyncSummary } from "../ui/automatic-sync-summary.js";
15
- import type { RunRouteResult } from "../ui/cancellable-operation.js";
12
+ import { RemoteSelectionMismatchError } from "../sync/sync-policy.js";
13
+ import type { DirectionalIntent, RunRouteResult } from "../ui/cancellable-operation.js";
16
14
  import { trackOperationDialogs } from "../ui/operation-dialogs.js";
17
- import { startupTransferSummary } from "../ui/sync-behavior.js";
18
15
  import { setSyncStatus } from "../ui/sync-status.js";
19
16
  import { safeTerminalText } from "../ui/terminal-text.js";
20
- import { parseOptions, resolveSyncCommand, splitArgs, usage, validateCommandOptions } from "./command.js";
17
+ import {
18
+ parseOptions,
19
+ resolveSyncCommand,
20
+ retiredSyncCommandGuidance,
21
+ splitArgs,
22
+ usage,
23
+ validateCommandOptions,
24
+ } from "./command.js";
21
25
  import type { CommandOptions } from "./command-types.js";
22
26
 
23
27
  export async function executeRecoveryCommand(
@@ -75,26 +79,23 @@ export async function executeCommand(
75
79
  setup?: string,
76
80
  onDialog?: (active: boolean) => void,
77
81
  retryRefusal = false,
78
- directionalFingerprint?: string,
82
+ directional?: DirectionalIntent,
79
83
  ): Promise<RunRouteResult> {
80
84
  ctx = trackOperationDialogs(ctx, onDialog);
81
85
  try {
82
- const directionalClient = directionalFingerprint === undefined ? undefined : piDaemonClient(ctx);
86
+ const directionalClient = directional === undefined ? undefined : piDaemonClient(ctx);
83
87
  const command = await resolveSyncCommand(rawArgs, ctx);
84
88
  if (signal?.aborted || !command) return { kind: "completed" };
85
89
  const { subcommand, rest } = command;
86
- if (directionalClient && directionalFingerprint !== undefined) {
90
+ const retired = retiredSyncCommandGuidance(subcommand);
91
+ if (retired) {
92
+ ctx.ui.notify(retired, "warning");
93
+ return { kind: "failed" };
94
+ }
95
+ if (directionalClient && directional) {
87
96
  if ((subcommand !== "push" && subcommand !== "pull") || rest.length || !setup || retryRefusal)
88
97
  throw new Error("Invalid directional action.");
89
- return await runDirectionalAction(
90
- directionalClient,
91
- ctx,
92
- subcommand,
93
- setup,
94
- directionalFingerprint,
95
- signal,
96
- onCommit,
97
- );
98
+ return await runDirectionalAction(directionalClient, ctx, subcommand, setup, directional, signal, onCommit);
98
99
  }
99
100
  const options = parseOptions(rest);
100
101
  if (setup !== undefined) options.setup = setup;
@@ -146,21 +147,12 @@ export async function executeCommand(
146
147
  case "init":
147
148
  await initConfig(ctx, signal);
148
149
  return { kind: "completed" };
149
- case "config":
150
- await showConfig(ctx, options);
151
- return { kind: "completed" };
152
150
  case "files": {
153
151
  const { showFileSelection } = await import("../ui/file-selection.js");
154
152
  throwIfAborted(options.signal);
155
153
  await showFileSelection(ctx, options.setup, options.signal);
156
154
  return { kind: "completed" };
157
155
  }
158
- case "status": {
159
- const operations = await loaders.operations();
160
- throwIfAborted(options.signal);
161
- await operations.status(ctx, options);
162
- return { kind: "completed" };
163
- }
164
156
  case "diff": {
165
157
  const operations = await loaders.operations();
166
158
  throwIfAborted(options.signal);
@@ -173,12 +165,6 @@ export async function executeCommand(
173
165
  await showConflicts(ctx, options);
174
166
  return { kind: "completed" };
175
167
  }
176
- case "doctor": {
177
- const operations = await loaders.operations();
178
- throwIfAborted(options.signal);
179
- await operations.doctor(ctx, options);
180
- return { kind: "completed" };
181
- }
182
168
  case "push": {
183
169
  const operations = await loaders.operations();
184
170
  throwIfAborted(options.signal);
@@ -222,7 +208,7 @@ export async function executeCommand(
222
208
  } catch (error) {
223
209
  if (signal?.aborted) return { kind: "failed" };
224
210
  setSyncStatus(ctx, undefined);
225
- if (directionalFingerprint !== undefined) {
211
+ if (directional) {
226
212
  ctx.ui.notify(safeTerminalText(errorMessage(error)).slice(0, 1200), "error");
227
213
  return { kind: "failed" };
228
214
  }
@@ -243,26 +229,32 @@ async function runDirectionalAction(
243
229
  ctx: ExtensionCommandContext,
244
230
  direction: "push" | "pull",
245
231
  setup: string,
246
- fingerprint: string,
232
+ directional: DirectionalIntent,
247
233
  signal: AbortSignal | undefined,
248
234
  onCommit: (() => void) | undefined,
249
235
  ): Promise<RunRouteResult> {
250
236
  try {
251
237
  const operation = `${direction}.foreground`;
252
- const intent = { setup, fingerprint };
253
- const result = (await client.run(operation, intent, signal, ctx, onCommit)) as
254
- | { outcome?: "applied" | "cancelled"; message?: string }
255
- | undefined;
256
- if (!client.canReportDirectionalResult() || (signal?.aborted && result?.outcome !== "applied"))
238
+ const result = await client.run(operation, { setup, ...directional }, signal, ctx, onCommit);
239
+ if (!client.canReportDirectionalResult()) return { kind: "failed" };
240
+ if (
241
+ signal?.aborted &&
242
+ !(result && typeof result === "object" && "outcome" in result && result.outcome === "applied")
243
+ )
257
244
  return { kind: "failed" };
245
+ if (directional.intent === "reject-conflicts" && isDestinationConflict(result))
246
+ return { kind: "destination-conflict" };
258
247
  if (
259
- !result ||
248
+ typeof result !== "object" ||
249
+ result === null ||
250
+ !("outcome" in result) ||
260
251
  (result.outcome !== "applied" && result.outcome !== "cancelled") ||
261
- (result.message !== undefined && typeof result.message !== "string")
252
+ ("message" in result && typeof result.message !== "string")
262
253
  ) {
263
254
  throw new Error("Invalid result from directional synchronization.");
264
255
  }
265
- if (result.message) ctx.ui.notify(safeTerminalText(result.message), "info");
256
+ if ("message" in result && typeof result.message === "string" && result.message)
257
+ ctx.ui.notify(safeTerminalText(result.message), "info");
266
258
  return signal?.aborted ? { kind: "failed" } : { kind: "completed", outcome: result.outcome };
267
259
  } catch (error) {
268
260
  const completed = error instanceof CompletedDirectionalRecoveryError;
@@ -306,95 +298,3 @@ async function initConfig(ctx: ExtensionCommandContext, signal?: AbortSignal) {
306
298
  throwIfAborted(signal);
307
299
  ctx.ui.notify(`Created ${configPath}. Add a storage connection and sync setup before syncing.`, "info");
308
300
  }
309
-
310
- async function showConfig(ctx: ExtensionCommandContext, options: CommandOptions) {
311
- const config = await loadSettingsConfig(options.setup);
312
- throwIfAborted(options.signal);
313
- const warnings = [
314
- ...(config.backend.type === "s3" ? sessionTokenWarnings(config.backend.profile) : []),
315
- ...syncSessionsWarnings(config),
316
- ];
317
- const storageLines = configStorageLines(config);
318
- ctx.ui.notify(
319
- [
320
- "pi-sync config:",
321
- `sync setup: ${config.setupName}`,
322
- `storage connection: ${config.connectionName}`,
323
- ...storageLines,
324
- `storage path: ${config.storagePath}`,
325
- `automatic sync: ${automaticSyncSummary(config.automatic)}`,
326
- `settings field merge: ${config.mergeSettings ? "On" : "Off"}`,
327
- `machine-local settings.json fields: ${(config.localFields ?? []).map(safeTerminalText).join(", ") || "none"}`,
328
- `startup transfer: ${startupTransferSummary(config)}`,
329
- "Autonomous sync and Continuous sync are retired. Saved legacy flags have no effect.",
330
- config.scope ? "sync scope: Pi agent directory" : `included content: ${config.include.join(", ") || "none"}`,
331
- ...(config.scope
332
- ? [
333
- `excluded paths: ${config.exclude?.map(safeTerminalText).join(", ") || "none"}`,
334
- `re-included paths: ${config.reinclude?.map(safeTerminalText).join(", ") || "none"}`,
335
- ]
336
- : []),
337
- `sessions: ${syncSessionsSelected(config) ? "included" : "not included"}`,
338
- `settings file: ${localConfigPath()}`,
339
- ...warnings,
340
- ].join("\n"),
341
- warnings.length > 0 ? "warning" : "info",
342
- );
343
- }
344
-
345
- function configStorageLines(config: AnySyncConfig) {
346
- switch (config.backend.type) {
347
- case "git":
348
- return [
349
- "kind: git",
350
- `remote: ${displayGitRemote(config.backend.profile.remote)}`,
351
- "authentication: existing Git/SSH credentials (not stored)",
352
- `branch: ${config.backend.destination.branch}`,
353
- ];
354
- case "webdav":
355
- return [
356
- "kind: webdav",
357
- `url: ${displayWebDavUrl(config.backend.profile.url, config.backend.profile.username)}`,
358
- "username: configured (value hidden)",
359
- "password: configured",
360
- ];
361
- case "s3":
362
- return [
363
- "kind: s3",
364
- `endpoint: ${config.backend.profile.endpoint}`,
365
- `bucket: ${config.backend.destination.bucket}`,
366
- `region: ${config.backend.profile.region}`,
367
- "access key id: configured",
368
- "secret access key: configured",
369
- `session token: ${config.backend.profile.sessionToken ? "configured" : "not configured"}`,
370
- ];
371
- }
372
- }
373
-
374
- function displayGitRemote(value: string | undefined) {
375
- if (!value) return "missing";
376
- try {
377
- const url = new URL(value);
378
- url.username = "";
379
- url.password = "";
380
- url.search = "";
381
- url.hash = "";
382
- return url.toString();
383
- } catch {
384
- return value.replace(/^(?:[^@\s]+@)?(?<host>[^:]+):.+$/u, "$<host>:…");
385
- }
386
- }
387
-
388
- function displayWebDavUrl(value: string | undefined, username: string | undefined) {
389
- if (!value) return "missing";
390
- try {
391
- const url = new URL(value);
392
- url.username = "";
393
- url.password = "";
394
- url.search = "";
395
- url.hash = "";
396
- return username ? `${url.origin}/…` : `${url.origin}${url.pathname}`;
397
- } catch {
398
- return "invalid (value hidden)";
399
- }
400
- }
@@ -5,7 +5,7 @@ import { combineSignals } from "../sync/signals.js";
5
5
  import { errorMessage } from "../sync/sync-errors.js";
6
6
  import type { SyncLoaders } from "../sync/sync-loaders.js";
7
7
  import { formatRemoteSelectionMismatch } from "../sync/sync-policy.js";
8
- import type { RunRouteResult } from "../ui/cancellable-operation.js";
8
+ import type { DirectionalIntent, RunRouteResult } from "../ui/cancellable-operation.js";
9
9
  import {
10
10
  observationMatchesConfig,
11
11
  type SyncAttentionController,
@@ -39,7 +39,7 @@ export async function handleCommand(
39
39
  target?: string,
40
40
  onDialog?: (active: boolean) => void,
41
41
  retryRefusal = false,
42
- directionalFingerprint?: string,
42
+ directional?: DirectionalIntent,
43
43
  ) => {
44
44
  const [command, ...args] = splitArgs(route);
45
45
  if (command === "sync" && !retryRefusal) {
@@ -60,7 +60,7 @@ export async function handleCommand(
60
60
  target,
61
61
  onDialog,
62
62
  retryRefusal,
63
- directionalFingerprint,
63
+ directional,
64
64
  );
65
65
  };
66
66
  if (!rawArgs.trim()) {
@@ -10,12 +10,9 @@ export const SYNC_COMMANDS = [
10
10
  { name: "help", description: "Show command usage" },
11
11
  { name: "use", description: "Switch the current sync setup", usageSuffix: " <setup>" },
12
12
  { name: "init", description: "Create local config template" },
13
- { name: "config", description: "Show resolved configuration" },
14
13
  { name: "files", description: "Choose included content" },
15
- { name: "status", description: "Show sync status" },
16
14
  { name: "diff", description: "Show local/remote diff" },
17
15
  { name: "conflicts", description: "Review private unresolved conflict groups" },
18
- { name: "doctor", description: "Check config, secrets, and lock state" },
19
16
  {
20
17
  name: "daemon",
21
18
  description: "Review service handover and unattended permission",
@@ -48,12 +45,9 @@ const SETUP_FLAG_COMPLETION = {
48
45
  description: "Address a sync setup without switching",
49
46
  } as const;
50
47
  const SYNC_FLAG_COMPLETIONS: Record<string, readonly CommandArgumentCompletion[]> = {
51
- config: [SETUP_FLAG_COMPLETION],
52
48
  files: [SETUP_FLAG_COMPLETION],
53
- status: [SETUP_FLAG_COMPLETION],
54
49
  diff: [SETUP_FLAG_COMPLETION],
55
50
  conflicts: [SETUP_FLAG_COMPLETION],
56
- doctor: [SETUP_FLAG_COMPLETION],
57
51
  push: [
58
52
  ...YES_FLAG_COMPLETIONS,
59
53
  { value: "--force", label: "--force", description: "Overwrite visible remote changes" },
@@ -75,6 +69,10 @@ const SYNC_FLAG_COMPLETIONS: Record<string, readonly CommandArgumentCompletion[]
75
69
  unlock: [{ value: "--stale", label: "--stale", description: "Remove only a stale lock" }],
76
70
  };
77
71
 
72
+ function syncFlagCompletions(command: string) {
73
+ return Object.hasOwn(SYNC_FLAG_COMPLETIONS, command) ? SYNC_FLAG_COMPLETIONS[command] : undefined;
74
+ }
75
+
78
76
  export function splitArgs(input: string) {
79
77
  return input.match(/(?:[^\s"']+|"[^"]*"|'[^']*')+/g)?.map((arg) => arg.replace(/^['"]|['"]$/g, "")) ?? [];
80
78
  }
@@ -112,21 +110,21 @@ export function parseOptions(args: string[]): CommandOptions {
112
110
  };
113
111
  }
114
112
 
113
+ export function retiredSyncCommandGuidance(command: string | undefined): string | undefined {
114
+ if (command === "status") {
115
+ return "/sync status was retired. Use /sync diff to view file differences, or ask Pi to recheck the current setup in Debug mode.";
116
+ }
117
+ if (command === "doctor") {
118
+ return "/sync doctor was retired. Open /sync → Settings to review the setup, use /sync diff to check file differences, or open /sync → History for WebDAV history recovery.";
119
+ }
120
+ if (command === "config") {
121
+ return "/sync config was retired. Open /sync → Settings to review sync setups and storage connections.";
122
+ }
123
+ return undefined;
124
+ }
125
+
115
126
  export function validateCommandOptions(command: string, options: CommandOptions) {
116
- const setupAllowed = new Set([
117
- "config",
118
- "files",
119
- "status",
120
- "diff",
121
- "conflicts",
122
- "doctor",
123
- "push",
124
- "pull",
125
- "sync",
126
- "history",
127
- "rollback",
128
- ]);
129
- if (options.setup && !setupAllowed.has(command)) {
127
+ if (options.setup && !syncFlagCompletions(command)?.includes(SETUP_FLAG_COMPLETION)) {
130
128
  throw new Error(`--setup is not supported by /sync ${command}.`);
131
129
  }
132
130
  if (options.yes && !["push", "pull", "sync", "rollback", "migrate-state"].includes(command)) {
@@ -182,15 +180,18 @@ export function completeSyncArguments(argumentPrefix: string): CommandArgumentCo
182
180
  ? matches.map((action) => ({ value: `${base}${action}`, label: action, description: "Daemon control" }))
183
181
  : null;
184
182
  }
183
+ const flagCompletions = syncFlagCompletions(command);
184
+ if (!flagCompletions) return null;
185
185
  const setupFlagIndex = args.lastIndexOf("--setup");
186
- if (setupFlagIndex >= 0 && setupFlagIndex === args.length - (trailingSpace ? 1 : 2)) {
186
+ if (
187
+ flagCompletions.includes(SETUP_FLAG_COMPLETION) &&
188
+ setupFlagIndex >= 0 &&
189
+ setupFlagIndex === args.length - (trailingSpace ? 1 : 2)
190
+ ) {
187
191
  const currentSetup = trailingSpace ? "" : (args.at(-1) ?? "");
188
192
  if (!currentSetup.startsWith("-")) return completeSetupValue(prefix, currentSetup);
189
193
  }
190
194
 
191
- const flagCompletions = SYNC_FLAG_COMPLETIONS[command];
192
- if (!flagCompletions) return null;
193
-
194
195
  const completedArgs = trailingSpace ? args : args.slice(0, -1);
195
196
  const completedValues = completedArgs.filter((arg) => !arg.startsWith("-"));
196
197
  if (command === "rollback" ? completedValues.length > 1 : completedValues.length > 0) {
@@ -256,12 +257,13 @@ export function usage() {
256
257
  "Usage: /sync <command>",
257
258
  `Commands: ${commands}`,
258
259
  "In the /sync manager, Push to remote and Pull from remote use the chosen source and preserve a restore point without a second confirmation. Direct commands retain their existing review and flags.",
259
- "Daemon diagnostics: /sync daemon recover reviews and stops the existing daemon. It does not start a replacement or retry a transfer.",
260
+ "To review file differences without transferring files, use /sync diff. For check summaries or a fresh read-only recheck, start or /reload Pi with Debug mode enabled and ask Pi to use pi_sync_debug.",
261
+ "Daemon diagnostics: /sync daemon status shows service status. /sync daemon recover reviews and stops the existing daemon without starting a replacement or retrying a transfer.",
260
262
  `Automatic sync: ${AUTOMATIC_SYNC_DESCRIPTION}`,
261
263
  `Startup transfer: ${STARTUP_TRANSFER_DESCRIPTION}`,
262
264
  "Automatic transfer at startup is a separate opt-in: one conflict-free established-baseline transfer at idle in TUI/RPC, with conditional/lease publication and no resource reload.",
263
265
  "Autonomous sync and Continuous sync are retired. Saved flags no longer transfer files or call a model. Use Sync now to review a transfer or enable Startup transfer for one eligible startup sync.",
264
266
  "New after-exit grants are not supported. Use /sync daemon revoke-after-exit to clear a retained grant.",
265
- "Settings: use /sync init or edit storage connections and sync setups in ~/.pi/agent/pi-sync.json (or the configured Pi agent directory). Version 1 and version 2 settings are unsupported and are never rewritten.",
267
+ "Settings: open /sync → Settings to review sync setups and storage connections. Use /sync init or edit pi-sync.json in the Pi agent directory for manual setup. Version 1 and version 2 settings are unsupported and are never rewritten.",
266
268
  ].join("\n");
267
269
  }
@@ -59,6 +59,7 @@ export async function runDirectionalRecovery(
59
59
  run: (checkpoint: DirectionalCheckpoint, retryCheckpoint?: string) => Promise<unknown>,
60
60
  recover: (connection: DaemonConnection, job: string, signal: AbortSignal) => Promise<DaemonConnection>,
61
61
  markCleanupRequired: () => void,
62
+ allowRetry = true,
62
63
  ) {
63
64
  signal.throwIfAborted();
64
65
  const attempt = new DirectionalCheckpoint(connection);
@@ -88,7 +89,8 @@ export async function runDirectionalRecovery(
88
89
  throw new Error(`No transfer was applied, but file-queue recovery stopped. ${detail}`, { cause: error });
89
90
  }
90
91
  if (primary.phase === "completed") return primary.result;
91
- const retryCheckpoint = primary.phase === "unchanged" ? attempt.fingerprint : undefined;
92
+ if (!allowRetry) throw new Error("No transfer was applied. Start a new review before forcing the transfer.");
93
+ const retryCheckpoint = attempt.fingerprint;
92
94
  const retry = new DirectionalCheckpoint(replacement, retryCheckpoint);
93
95
  const retried = await run(retry, retryCheckpoint);
94
96
  const remaining = recoveryOutcome(retried);
@@ -324,6 +324,11 @@ export class PiDaemonClient {
324
324
  get debugEnabled() {
325
325
  return this.debug;
326
326
  }
327
+ validateDebugTool() {
328
+ this.validate();
329
+ if (!this.debug || !this.ownsContactUI() || this.pendingReload)
330
+ throw new Error("Pi Sync debug is not available in this session.");
331
+ }
327
332
  setDebugPreference(debug: boolean) {
328
333
  this.debug = debug && this.ctx.hasUI && (this.ctx.mode === "tui" || this.ctx.mode === "rpc");
329
334
  }
@@ -965,6 +970,7 @@ export class PiDaemonClient {
965
970
  () => {
966
971
  this.cleanupRequired = true;
967
972
  },
973
+ !(intent && typeof intent === "object" && "intent" in intent && intent.intent === "review-force"),
968
974
  )
969
975
  : await connection.run(operation, payload, runSignal, onCommit, diagnostics?.onSubmit);
970
976
  diagnostics?.returned(result, runSignal.aborted || reload?.signal.aborted);
@@ -0,0 +1,96 @@
1
+ import { StringEnum } from "@earendil-works/pi-ai";
2
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
3
+ import { debugCheckFailure, summarizeDebugInspection } from "@narumitw/pi-sync-daemon/engine/debug-check";
4
+ import { readLatestDebugCheck } from "@narumitw/pi-sync-daemon/engine/debug-log";
5
+ import { Type } from "typebox";
6
+ import type { PiDaemonClient } from "../daemon/pi-client.js";
7
+ import { configFromSettings, syncCheckConfigFingerprint, syncConfigReviewFingerprint } from "../settings/config.js";
8
+
9
+ const TOOL_NAME = "pi_sync_debug";
10
+ const RECHECK_TIMEOUT_MS = 30_000;
11
+ type DebugOwner = { client: PiDaemonClient; signal: AbortSignal };
12
+
13
+ function toolResult(value: unknown) {
14
+ return { content: [{ type: "text" as const, text: JSON.stringify(value) }], details: {} };
15
+ }
16
+
17
+ export function registerPiSyncDebug(pi: ExtensionAPI, getOwner: (ctx: ExtensionContext) => DebugOwner | undefined) {
18
+ pi.registerTool({
19
+ name: TOOL_NAME,
20
+ label: "Pi Sync debug",
21
+ description:
22
+ "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.",
23
+ parameters: Type.Object({ action: StringEnum(["latest", "recheck"]) }, { additionalProperties: false }),
24
+ defaultActive: false,
25
+ exposure: "direct",
26
+ executionMode: "sequential",
27
+ async execute(_id, { action }, toolSignal, _update, ctx) {
28
+ const owner = getOwner(ctx);
29
+ if (!owner || !ctx.hasUI || (ctx.mode !== "tui" && ctx.mode !== "rpc"))
30
+ throw new Error("Pi Sync debug requires an interactive session started with Debug mode on.");
31
+ const { client } = owner;
32
+ const signal = toolSignal ? AbortSignal.any([owner.signal, toolSignal]) : owner.signal;
33
+ const validate = () => {
34
+ signal.throwIfAborted();
35
+ if (getOwner(ctx)?.client !== client) throw new Error("Pi Sync session was replaced.");
36
+ try {
37
+ client.validateDebugTool();
38
+ } catch {
39
+ throw new Error("The Pi Sync debug session is no longer available.");
40
+ }
41
+ };
42
+ async function readSetup() {
43
+ validate();
44
+ try {
45
+ const { settings } = await client.readStartupSettings(signal);
46
+ validate();
47
+ if (settings) return configFromSettings(settings);
48
+ } catch {
49
+ validate();
50
+ }
51
+ throw new Error("The current Pi Sync setup is not available. Review /sync → Settings.");
52
+ }
53
+ const setup = await readSetup();
54
+ validate();
55
+ if (action === "latest") {
56
+ const last = readLatestDebugCheck(client.root, syncConfigReviewFingerprint(setup));
57
+ if (last.kind === "unavailable") throw new Error("The private Pi Sync debug log is unavailable.");
58
+ if (last.kind === "no-record") return toolResult({ kind: "no-record" });
59
+ return toolResult({ kind: "historical", ...last.check });
60
+ }
61
+ if (action !== "recheck") throw new Error("Choose latest or recheck.");
62
+ if (client.ownershipCleanupRequired) throw new Error("Pi Sync needs recovery. Open /sync daemon status.");
63
+ const fingerprint = syncCheckConfigFingerprint(setup);
64
+ const deadline = AbortSignal.timeout(RECHECK_TIMEOUT_MS);
65
+ const recheckSignal = AbortSignal.any([signal, deadline]);
66
+ let result: unknown;
67
+ try {
68
+ result = await client.run(
69
+ "inspect",
70
+ { setup: setup.setupName, fingerprint, origin: "recheck" },
71
+ recheckSignal,
72
+ ctx,
73
+ );
74
+ } catch (error) {
75
+ validate();
76
+ const { reason } = debugCheckFailure(deadline.aborted ? deadline.reason : error);
77
+ throw new Error(`Pi Sync recheck failed: ${reason}.`);
78
+ }
79
+ validate();
80
+ if (deadline.aborted) throw new Error("Pi Sync recheck failed: timeout.");
81
+ const latest = await readSetup();
82
+ validate();
83
+ if (fingerprint !== syncCheckConfigFingerprint(latest))
84
+ throw new Error("Pi Sync setup changed during recheck. Ask to recheck the new setup.");
85
+ const summary = summarizeDebugInspection(result);
86
+ if (!summary) throw new Error("Pi Sync did not return a valid check result.");
87
+ return toolResult({ kind: "fresh", time: new Date().toISOString(), origin: "recheck", summary });
88
+ },
89
+ });
90
+
91
+ return (enabled: boolean) => {
92
+ const active = pi.getActiveTools();
93
+ if (active.includes(TOOL_NAME) === enabled) return;
94
+ pi.setActiveTools(enabled ? [...active, TOOL_NAME] : active.filter((name) => name !== TOOL_NAME));
95
+ };
96
+ }
@@ -170,7 +170,7 @@ export function createStartupCheck(
170
170
  ctx.ui.notify(
171
171
  config && startupTransferEnabled(config)
172
172
  ? `pi-sync automatic transfer stopped: ${safeTerminalText(errorMessage(error))}. Run /sync to review or reconcile retained recovery evidence. No resources were reloaded.`
173
- : `pi-sync startup check skipped: ${safeTerminalText(errorMessage(error))}. Run /sync status to retry. No startup transfer was performed.`,
173
+ : `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.`,
174
174
  "warning",
175
175
  );
176
176
  } finally {
@@ -27,15 +27,9 @@ export async function syncBoth(ctx: ExtensionContext, options: CommandOptions) {
27
27
  export async function rollback(ctx: ExtensionContext, options: CommandOptions) {
28
28
  await remoteOperation(ctx, "rollback", options);
29
29
  }
30
- export async function status(ctx: ExtensionContext, options: CommandOptions) {
31
- await remoteOperation(ctx, "status", options);
32
- }
33
30
  export async function diff(ctx: ExtensionContext, options: CommandOptions) {
34
31
  await remoteOperation(ctx, "diff", options);
35
32
  }
36
- export async function doctor(ctx: ExtensionContext, options: CommandOptions) {
37
- await remoteOperation(ctx, "doctor", options);
38
- }
39
33
  export async function history(ctx: ExtensionContext, options: CommandOptions) {
40
34
  await remoteOperation(ctx, "history", options);
41
35
  }
@@ -1,5 +1,5 @@
1
1
  import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { completeSyncArguments, splitArgs } from "./commands/command.js";
2
+ import { completeSyncArguments, retiredSyncCommandGuidance, splitArgs } from "./commands/command.js";
3
3
  import {
4
4
  bindPiDaemonClient,
5
5
  installPiDaemonHost,
@@ -9,6 +9,7 @@ import {
9
9
  import type { AnySyncConfig } from "./settings/settings-types.js";
10
10
  import { startupTransferEnabled } from "./sync/agent-policy.js";
11
11
  import { autoPushSessions, startSession } from "./sync/automatic-sync.js";
12
+ import { registerPiSyncDebug } from "./sync/debug-tool.js";
12
13
  import { combineSignals } from "./sync/signals.js";
13
14
  import { createStartupCheck } from "./sync/startup-check.js";
14
15
  import { errorMessage } from "./sync/sync-errors.js";
@@ -30,12 +31,22 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
30
31
  let initialization = Promise.resolve<AnySyncConfig | false | undefined>(undefined);
31
32
  let owner: PiDaemonClient | undefined;
32
33
  let ownerManager: ExtensionContext["sessionManager"] | undefined;
34
+ const exposeDebugTool = registerPiSyncDebug(pi, (ctx) =>
35
+ owner?.debugEnabled && !sessionAbort.signal.aborted && ownerManager === ctx.sessionManager
36
+ ? { client: owner, signal: sessionAbort.signal }
37
+ : undefined,
38
+ );
33
39
 
34
40
  pi.registerCommand("sync", {
35
41
  description: "Sync Pi settings through Git, WebDAV, R2, or S3-compatible storage",
36
42
  getArgumentCompletions: completeSyncArguments,
37
43
  handler: async (args, ctx) => {
38
44
  if (!ctx.hasUI) throw new Error("/sync requires TUI or RPC mode so results and safety prompts are observable.");
45
+ const retired = retiredSyncCommandGuidance(splitArgs(args)[0]);
46
+ if (retired) {
47
+ ctx.ui.notify(retired, "warning");
48
+ return;
49
+ }
39
50
  status.bind(ctx);
40
51
  const signal = sessionAbort.signal;
41
52
  const client = owner;
@@ -193,6 +204,7 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
193
204
  });
194
205
  try {
195
206
  const ready = await initialization;
207
+ if (!signal.aborted && owner === client) exposeDebugTool(client.debugEnabled);
196
208
  if (ready === false) {
197
209
  client.disableQueueReleaseUI();
198
210
  releaseStatus();
@@ -1,5 +1,6 @@
1
1
  import { BorderedLoader, type ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { isKeyRelease, Key, matchesKey, truncateToWidth } from "@earendil-works/pi-tui";
3
+ import type { ForegroundTransferIntent } from "@narumitw/pi-sync-daemon";
3
4
  import { formatInteractionHints, runCustomInteraction } from "@narumitw/pi-tui-kit";
4
5
  import type { SetupPullOutcome } from "../sync/setup-switch.js";
5
6
  import type { SyncDecision } from "../sync/sync-decision.js";
@@ -9,8 +10,14 @@ export type RunRouteResult =
9
10
  | { kind: "completed"; outcome?: SetupPullOutcome }
10
11
  | { kind: "decision-required"; decision: SyncDecision }
11
12
  | { kind: "remote-selection-required"; decision: RemoteSelectionDecision }
13
+ | { kind: "destination-conflict" }
12
14
  | { kind: "failed" };
13
15
 
16
+ export interface DirectionalIntent {
17
+ fingerprint: string;
18
+ intent: ForegroundTransferIntent;
19
+ }
20
+
14
21
  export type RunRoute = (
15
22
  route: string,
16
23
  signal?: AbortSignal,
@@ -18,7 +25,7 @@ export type RunRoute = (
18
25
  target?: string,
19
26
  onDialog?: (active: boolean) => void,
20
27
  retryRefusal?: boolean,
21
- directionalFingerprint?: string,
28
+ directional?: DirectionalIntent,
22
29
  ) => Promise<RunRouteResult | undefined>;
23
30
 
24
31
  export type CancellableOperationResult = RunRouteResult | { kind: "closed" } | { kind: "cancelled" };
@@ -28,7 +35,7 @@ interface CancellableOperationOptions {
28
35
  cancelAcrossDialogs?: boolean;
29
36
  cancelledMessage?: string | null;
30
37
  target?: string;
31
- directionalFingerprint?: string;
38
+ directional?: DirectionalIntent;
32
39
  signal?: AbortSignal;
33
40
  isCurrent?: () => boolean;
34
41
  }
@@ -44,7 +51,7 @@ export async function runCancellableOperation(
44
51
  ctx,
45
52
  message,
46
53
  (signal, onCommit, onDialog) =>
47
- runRoute(route, signal, onCommit, options.target, onDialog, undefined, options.directionalFingerprint),
54
+ runRoute(route, signal, onCommit, options.target, onDialog, undefined, options.directional),
48
55
  options,
49
56
  );
50
57
  return result.kind === "completed" ? (result.value ?? { kind: "failed" }) : result;
@@ -64,7 +71,7 @@ export async function runCancellableTask<Value>(
64
71
  onCommit?: () => void,
65
72
  onDialog?: (active: boolean) => void,
66
73
  ) => Promise<Value>,
67
- options: Omit<CancellableOperationOptions, "target" | "directionalFingerprint"> = {},
74
+ options: Omit<CancellableOperationOptions, "target" | "directional"> = {},
68
75
  ): Promise<CancellableTaskResult<Value>> {
69
76
  const {
70
77
  commitAware = false,