@narumitw/pi-sync 0.64.0 → 0.65.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +76 -7
  3. package/dist/chunks/{chunk-CKUGCBHP.ts → chunk-AYGMIMCV.ts} +2 -2
  4. package/dist/chunks/chunk-AYGMIMCV.ts.map +7 -0
  5. package/dist/chunks/{chunk-F3VODLVQ.ts → chunk-IOM6E5FW.ts} +3 -3
  6. package/dist/chunks/{chunk-RW44KNFD.ts → chunk-JQ5BAWW2.ts} +182 -12
  7. package/dist/chunks/chunk-JQ5BAWW2.ts.map +7 -0
  8. package/dist/chunks/{chunk-NDEZ52SS.ts → chunk-OBVJTKVY.ts} +5 -5
  9. package/dist/chunks/{chunk-TJ7YNITN.ts → chunk-OWEOZZZE.ts} +2 -2
  10. package/dist/chunks/{chunk-VPSC7BXM.ts → chunk-SZJOUVCL.ts} +2 -2
  11. package/dist/chunks/{chunk-YT6PDRMM.ts → chunk-WJQ4TGN5.ts} +17 -17
  12. package/dist/chunks/chunk-WJQ4TGN5.ts.map +7 -0
  13. package/dist/chunks/{chunk-4VKWHVUO.ts → chunk-XUZV4OGI.ts} +3 -2
  14. package/dist/chunks/{chunk-4VKWHVUO.ts.map → chunk-XUZV4OGI.ts.map} +2 -2
  15. package/dist/chunks/{command-handler-N45GY7AV.ts → command-handler-YZ4DXQ7N.ts} +49 -10
  16. package/dist/chunks/command-handler-YZ4DXQ7N.ts.map +7 -0
  17. package/dist/chunks/{conflict-review-5E4M44BA.ts → conflict-review-J7L7S4AR.ts} +2 -2
  18. package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts → manager-result-dispatcher-XB75YLEG.ts} +4 -4
  19. package/dist/chunks/{manager-ui-EV23DPZQ.ts → manager-ui-RGA26Z6G.ts} +40 -38
  20. package/dist/chunks/manager-ui-RGA26Z6G.ts.map +7 -0
  21. package/dist/chunks/{merge-review-6YSLSMGS.ts → merge-review-AAC674C6.ts} +3 -3
  22. package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts → remote-selection-ui-WVMET5RI.ts} +3 -3
  23. package/dist/chunks/{setup-switch-HY7K3442.ts → setup-switch-644T6KHG.ts} +3 -3
  24. package/dist/chunks/{setup-wizard-LEKDQ3HK.ts → setup-wizard-YP2KF2WQ.ts} +5 -5
  25. package/dist/chunks/{sync-inspection-OS2LVOLV.ts → sync-inspection-NBBTSMKR.ts} +2 -2
  26. package/dist/chunks/{sync-operations-D3MDJUQQ.ts → sync-operations-AIEM2KL2.ts} +2 -2
  27. package/dist/daemon/dist/client.js +125 -287
  28. package/dist/daemon/dist/daemon-recovery.js +85 -2
  29. package/dist/daemon/dist/daemon-startup.js +257 -0
  30. package/dist/daemon/dist/engine/backends/git/git-backend.js +10 -1
  31. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +20 -9
  32. package/dist/daemon/dist/engine/backends/sync-backend.js +16 -0
  33. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +19 -6
  34. package/dist/daemon/dist/engine/sync/directional-action.js +124 -0
  35. package/dist/daemon/dist/engine/sync/remote-snapshot.js +3 -1
  36. package/dist/daemon/dist/engine/sync/sync-errors.js +20 -0
  37. package/dist/daemon/dist/engine/sync/sync-local.js +56 -3
  38. package/dist/daemon/dist/engine/sync/sync-mutations.js +300 -334
  39. package/dist/daemon/dist/engine/sync/sync-queries.js +2 -1
  40. package/dist/daemon/dist/engine/sync/sync-rollback.js +198 -0
  41. package/dist/daemon/dist/engine/sync/transfer-freshness.js +11 -5
  42. package/dist/daemon/dist/engine-service.js +68 -0
  43. package/dist/daemon/dist/foreground-queue-outcome.js +9 -0
  44. package/dist/daemon/dist/monitor.js +1 -0
  45. package/dist/daemon/dist/server.js +76 -11
  46. package/dist/daemon/dist/service-host.js +56 -8
  47. package/dist/daemon/package.json +1 -1
  48. package/dist/index.ts +6 -6
  49. package/docs/daemon-migration.md +3 -6
  50. package/package.json +2 -2
  51. package/src/commands/command-execution.ts +56 -2
  52. package/src/commands/command-handler.ts +2 -0
  53. package/src/commands/command.ts +2 -1
  54. package/src/daemon/directional-recovery.ts +103 -0
  55. package/src/daemon/pi-client.ts +112 -9
  56. package/src/ui/cancellable-operation.ts +5 -2
  57. package/src/ui/manager-state.ts +2 -2
  58. package/src/ui/manager-ui.ts +29 -24
  59. package/src/ui/merge-review.ts +8 -9
  60. package/src/ui/sync-confirmation.ts +7 -7
  61. package/dist/chunks/chunk-CKUGCBHP.ts.map +0 -7
  62. package/dist/chunks/chunk-RW44KNFD.ts.map +0 -7
  63. package/dist/chunks/chunk-YT6PDRMM.ts.map +0 -7
  64. package/dist/chunks/command-handler-N45GY7AV.ts.map +0 -7
  65. package/dist/chunks/manager-ui-EV23DPZQ.ts.map +0 -7
  66. /package/dist/chunks/{chunk-F3VODLVQ.ts.map → chunk-IOM6E5FW.ts.map} +0 -0
  67. /package/dist/chunks/{chunk-NDEZ52SS.ts.map → chunk-OBVJTKVY.ts.map} +0 -0
  68. /package/dist/chunks/{chunk-TJ7YNITN.ts.map → chunk-OWEOZZZE.ts.map} +0 -0
  69. /package/dist/chunks/{chunk-VPSC7BXM.ts.map → chunk-SZJOUVCL.ts.map} +0 -0
  70. /package/dist/chunks/{conflict-review-5E4M44BA.ts.map → conflict-review-J7L7S4AR.ts.map} +0 -0
  71. /package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts.map → manager-result-dispatcher-XB75YLEG.ts.map} +0 -0
  72. /package/dist/chunks/{merge-review-6YSLSMGS.ts.map → merge-review-AAC674C6.ts.map} +0 -0
  73. /package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts.map → remote-selection-ui-WVMET5RI.ts.map} +0 -0
  74. /package/dist/chunks/{setup-switch-HY7K3442.ts.map → setup-switch-644T6KHG.ts.map} +0 -0
  75. /package/dist/chunks/{setup-wizard-LEKDQ3HK.ts.map → setup-wizard-YP2KF2WQ.ts.map} +0 -0
  76. /package/dist/chunks/{sync-inspection-OS2LVOLV.ts.map → sync-inspection-NBBTSMKR.ts.map} +0 -0
  77. /package/dist/chunks/{sync-operations-D3MDJUQQ.ts.map → sync-operations-AIEM2KL2.ts.map} +0 -0
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.10.0"
2
+ "version": "0.11.0"
3
3
  }
package/dist/index.ts CHANGED
@@ -16,7 +16,7 @@ import {
16
16
  completeSyncArguments,
17
17
  setSyncSetupCompletions,
18
18
  splitArgs
19
- } from "./chunks/chunk-4VKWHVUO.ts";
19
+ } from "./chunks/chunk-XUZV4OGI.ts";
20
20
  import {
21
21
  withStateDirectoryAccess
22
22
  } from "./chunks/chunk-T3LABNHF.ts";
@@ -34,7 +34,7 @@ import {
34
34
  installPiDaemonHost,
35
35
  piDaemonClient,
36
36
  withPiDaemonClient
37
- } from "./chunks/chunk-RW44KNFD.ts";
37
+ } from "./chunks/chunk-JQ5BAWW2.ts";
38
38
  import {
39
39
  configureSyncStatus,
40
40
  createSyncStatusPublisher,
@@ -334,12 +334,12 @@ function createStartupCheck(loaders, attention, timeoutMs = 3e4, publish) {
334
334
  // src/sync/sync-loaders.ts
335
335
  function createSyncLoaders(dependencies) {
336
336
  const loaders = {
337
- commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-N45GY7AV.ts"))),
338
- inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-OS2LVOLV.ts"))),
339
- setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-HY7K3442.ts"))),
337
+ commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-YZ4DXQ7N.ts"))),
338
+ inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-NBBTSMKR.ts"))),
339
+ setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-644T6KHG.ts"))),
340
340
  snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import("./chunks/snapshot-ZUJJZCFW.ts"))),
341
341
  syncState: cachedModuleLoader(dependencies.loadSyncState ?? (() => import("./chunks/sync-state-QIT64TKV.ts"))),
342
- operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-D3MDJUQQ.ts")))
342
+ operations: cachedModuleLoader(dependencies.loadSyncOperations ?? (() => import("./chunks/sync-operations-AIEM2KL2.ts")))
343
343
  };
344
344
  return loaders;
345
345
  }
@@ -92,21 +92,18 @@ accepts the current participant's facts. An older daemon can stay reachable
92
92
  without supporting this repair; a healthy CLI status alone does not confirm Pi
93
93
  participation.
94
94
 
95
- Reconnect does not replay a submitted operation or restart startup transfers.
95
+ Ordinary reconnect does not replay a submitted operation or restart startup transfers.
96
96
  If Pi releases a file queue but the local acknowledgement is lost in transit,
97
97
  it retries that acknowledgement with the same daemon. Brief retries stay
98
98
  quiet; longer retries show `sync recovering` when sync status is enabled.
99
99
  If a background release remains unconfirmed during a command, Pi reports it
100
100
  after the command finishes.
101
101
  A release acknowledgement alone does not confirm that a transfer succeeded.
102
- If a write or file-queue release cannot be confirmed, preserve the journals and
103
- use the existing recovery path before retrying a transfer. Reconnect does not
104
- stop or restart the service, and it does not extend transfer or model permission.
102
+ For the manager's explicit **Push to remote** and **Pull from remote** actions, the client first resolves the original job with the same daemon. On an eligible file-queue failure it can then drain that exact owner and reconnect after verifying exit. It never repeats a verified result. It can resume after a proven pre-write failure only once and only when the original setup and source/destination evidence still match. It does not restart an owner that still has other live participating Pi clients, pending work, or unresolved consent or upgrade state. A missing result or conflicting evidence is not permission to replay. If recovery stops after a verified transfer, Pi Sync reports the restore point to the active session. If `/sync daemon status` is blocked by recovery, run it after recovery finishes. This path does not extend transfer or model permission.
105
103
 
106
104
  ## Recover from uncertain daemon cleanup
107
105
 
108
- **Stop daemon for recovery…** in `/sync` remains available when daemon cleanup
109
- blocks Pi Sync initialization. In TUI or RPC, `/sync daemon recover` opens the same
106
+ **Stop daemon for recovery…** in `/sync` remains a diagnostic fallback when automatic recovery cannot verify cleanup or daemon cleanup blocks initialization. In TUI or RPC, `/sync daemon recover` opens the same
110
107
  review without starting or upgrading the daemon. The review identifies the
111
108
  agent directory and PID before requesting permission to stop work for every
112
109
  Pi session attached to that daemon.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-sync",
3
- "version": "0.64.0",
3
+ "version": "0.65.0",
4
4
  "description": "Pi extension that syncs Pi configuration through Git, WebDAV, Cloudflare R2, or S3-compatible storage.",
5
5
  "type": "module",
6
6
  "license": "MIT",
@@ -57,7 +57,7 @@
57
57
  "devDependencies": {
58
58
  "@earendil-works/pi-coding-agent": "1.6.0",
59
59
  "@earendil-works/pi-tui": "1.6.0",
60
- "@narumitw/pi-sync-daemon": "^0.10.0",
60
+ "@narumitw/pi-sync-daemon": "^0.11.0",
61
61
  "@types/proper-lockfile": "^4.1.4",
62
62
  "@types/semver": "^7.8.0",
63
63
  "esbuild": "0.28.2",
@@ -1,12 +1,13 @@
1
1
  import type { ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import { piDaemonClient, remoteOperation } from "../daemon/pi-client.js";
2
+ import { CompletedDirectionalRecoveryError } from "../daemon/directional-recovery.js";
3
+ import { type PiDaemonClient, piDaemonClient, remoteOperation } from "../daemon/pi-client.js";
3
4
  import { loadSettingsConfig, sessionTokenWarnings, syncSessionsWarnings } from "../settings/config.js";
4
5
  import { activeLocalConfigPath, createLocalConfigDocument, localConfigPath } from "../settings/config-file.js";
5
6
  import { localConfigTemplate, readLocalConfigObject } from "../settings/settings-store.js";
6
7
  import type { AnySyncConfig } from "../settings/settings-types.js";
7
8
  import { throwIfAborted } from "../sync/signals.js";
8
9
  import { syncErrorGuidance } from "../sync/sync-error-guidance.js";
9
- import { isSyncDecisionRequiredError, SetupPullRequiresUiError } from "../sync/sync-errors.js";
10
+ import { errorMessage, isSyncDecisionRequiredError, SetupPullRequiresUiError } from "../sync/sync-errors.js";
10
11
  import type { SyncLoaders } from "../sync/sync-loaders.js";
11
12
  import { RemoteSelectionMismatchError, syncSessionsSelected } from "../sync/sync-policy.js";
12
13
  import { automaticSyncSummary } from "../ui/automatic-sync-summary.js";
@@ -74,12 +75,27 @@ export async function executeCommand(
74
75
  setup?: string,
75
76
  onDialog?: (active: boolean) => void,
76
77
  retryRefusal = false,
78
+ directionalFingerprint?: string,
77
79
  ): Promise<RunRouteResult> {
78
80
  ctx = trackOperationDialogs(ctx, onDialog);
79
81
  try {
82
+ const directionalClient = directionalFingerprint === undefined ? undefined : piDaemonClient(ctx);
80
83
  const command = await resolveSyncCommand(rawArgs, ctx);
81
84
  if (signal?.aborted || !command) return { kind: "completed" };
82
85
  const { subcommand, rest } = command;
86
+ if (directionalClient && directionalFingerprint !== undefined) {
87
+ if ((subcommand !== "push" && subcommand !== "pull") || rest.length || !setup || retryRefusal)
88
+ 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
+ }
83
99
  const options = parseOptions(rest);
84
100
  if (setup !== undefined) options.setup = setup;
85
101
  if (signal) options.signal = signal;
@@ -219,6 +235,10 @@ export async function executeCommand(
219
235
  } catch (error) {
220
236
  if (signal?.aborted) return { kind: "failed" };
221
237
  setSyncStatus(ctx, undefined);
238
+ if (directionalFingerprint !== undefined) {
239
+ ctx.ui.notify(safeTerminalText(errorMessage(error)).slice(0, 1200), "error");
240
+ return { kind: "failed" };
241
+ }
222
242
  if (error instanceof SetupPullRequiresUiError) throw error;
223
243
  if (error instanceof RemoteSelectionMismatchError) {
224
244
  return { kind: "remote-selection-required", decision: error.decision };
@@ -231,6 +251,40 @@ export async function executeCommand(
231
251
  }
232
252
  }
233
253
 
254
+ async function runDirectionalAction(
255
+ client: PiDaemonClient,
256
+ ctx: ExtensionCommandContext,
257
+ direction: "push" | "pull",
258
+ setup: string,
259
+ fingerprint: string,
260
+ signal: AbortSignal | undefined,
261
+ onCommit: (() => void) | undefined,
262
+ ): Promise<RunRouteResult> {
263
+ try {
264
+ const result = (await client.run(`${direction}.foreground`, { setup, fingerprint }, signal, ctx, onCommit)) as
265
+ | { outcome?: "applied" | "cancelled"; message?: string }
266
+ | undefined;
267
+ if (!client.canReportDirectionalResult() || (signal?.aborted && result?.outcome !== "applied"))
268
+ return { kind: "failed" };
269
+ if (
270
+ !result ||
271
+ (result.outcome !== "applied" && result.outcome !== "cancelled") ||
272
+ (result.message !== undefined && typeof result.message !== "string")
273
+ ) {
274
+ throw new Error("Invalid result from directional synchronization.");
275
+ }
276
+ if (result.message) ctx.ui.notify(safeTerminalText(result.message), "info");
277
+ return signal?.aborted ? { kind: "failed" } : { kind: "completed", outcome: result.outcome };
278
+ } catch (error) {
279
+ const completed = error instanceof CompletedDirectionalRecoveryError;
280
+ if (!client.canReportDirectionalResult() || (signal?.aborted && !completed)) return { kind: "failed" };
281
+ if (!signal?.aborted) setSyncStatus(ctx, undefined);
282
+ const message = safeTerminalText(errorMessage(error));
283
+ ctx.ui.notify(completed ? message : message.slice(0, 1200), "error");
284
+ return { kind: "failed" };
285
+ }
286
+ }
287
+
234
288
  async function migrateStateDirectory(ctx: ExtensionCommandContext, options: CommandOptions) {
235
289
  const result = (await remoteOperation(ctx, "migrate-state", options)) as
236
290
  | { status: string; message?: string }
@@ -39,6 +39,7 @@ export async function handleCommand(
39
39
  target?: string,
40
40
  onDialog?: (active: boolean) => void,
41
41
  retryRefusal = false,
42
+ directionalFingerprint?: string,
42
43
  ) => {
43
44
  const [command, ...args] = splitArgs(route);
44
45
  if (command === "sync" && !retryRefusal) {
@@ -59,6 +60,7 @@ export async function handleCommand(
59
60
  target,
60
61
  onDialog,
61
62
  retryRefusal,
63
+ directionalFingerprint,
62
64
  );
63
65
  };
64
66
  if (!rawArgs.trim()) {
@@ -255,7 +255,8 @@ export function usage() {
255
255
  return [
256
256
  "Usage: /sync <command>",
257
257
  `Commands: ${commands}`,
258
- "Daemon cleanup: /sync daemon recover reviews and stops the existing daemon. It does not start a replacement or retry a transfer.",
258
+ "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.",
259
260
  `Automatic sync: ${AUTOMATIC_SYNC_DESCRIPTION}`,
260
261
  `Startup transfer: ${STARTUP_TRANSFER_DESCRIPTION}`,
261
262
  "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.",
@@ -0,0 +1,103 @@
1
+ import type { DaemonConnection } from "@narumitw/pi-sync-daemon";
2
+ import { errorMessage } from "../sync/sync-errors.js";
3
+
4
+ export function isForegroundDirection(operation: string) {
5
+ return operation === "push.foreground" || operation === "pull.foreground";
6
+ }
7
+
8
+ export class DirectionalCheckpoint {
9
+ job?: string;
10
+ fingerprint?: string;
11
+
12
+ constructor(
13
+ readonly connection: DaemonConnection,
14
+ private readonly expected?: string,
15
+ ) {}
16
+
17
+ accept(connection: DaemonConnection, job: string, fingerprint: unknown) {
18
+ if (
19
+ connection !== this.connection ||
20
+ this.job !== job ||
21
+ typeof fingerprint !== "string" ||
22
+ !/^[a-f0-9]{64}$/u.test(fingerprint) ||
23
+ (this.expected !== undefined && fingerprint !== this.expected) ||
24
+ (this.fingerprint !== undefined && fingerprint !== this.fingerprint)
25
+ )
26
+ return false;
27
+ this.fingerprint = fingerprint;
28
+ return true;
29
+ }
30
+ }
31
+
32
+ function recoveryOutcome(value: unknown) {
33
+ if (!value || typeof value !== "object" || !("foregroundQueueCleanup" in value)) return;
34
+ if (value.foregroundQueueCleanup === "before-mutation") return { phase: "unchanged" as const };
35
+ if (value.foregroundQueueCleanup === "verified-result" && "result" in value)
36
+ return { phase: "completed" as const, result: value.result };
37
+ }
38
+
39
+ function restoreMessage(value: unknown): string {
40
+ return value && typeof value === "object" && "message" in value && typeof value.message === "string"
41
+ ? ` ${value.message}`
42
+ : "";
43
+ }
44
+
45
+ export class CompletedDirectionalRecoveryError extends Error {}
46
+
47
+ function cancelledAfterCompletion(result: unknown, cause: unknown) {
48
+ const error = new CompletedDirectionalRecoveryError(
49
+ `The transfer finished, but file-queue recovery was cancelled.${restoreMessage(result)}`,
50
+ { cause },
51
+ );
52
+ error.name = "AbortError";
53
+ return error;
54
+ }
55
+
56
+ export async function runDirectionalRecovery(
57
+ connection: DaemonConnection,
58
+ signal: AbortSignal,
59
+ run: (checkpoint: DirectionalCheckpoint, retryCheckpoint?: string) => Promise<unknown>,
60
+ recover: (connection: DaemonConnection, job: string, signal: AbortSignal) => Promise<DaemonConnection>,
61
+ markCleanupRequired: () => void,
62
+ ) {
63
+ signal.throwIfAborted();
64
+ const attempt = new DirectionalCheckpoint(connection);
65
+ const result = await run(attempt);
66
+ const primary = recoveryOutcome(result);
67
+ if (!primary) return result;
68
+ markCleanupRequired();
69
+ let replacement: DaemonConnection;
70
+ const bounded = AbortSignal.any([signal, AbortSignal.timeout(45_000)]);
71
+ try {
72
+ bounded.throwIfAborted();
73
+ if (!attempt.job || (primary.phase === "unchanged" && !attempt.fingerprint))
74
+ throw new Error("The original transfer scope could not be verified.");
75
+ replacement = await recover(connection, attempt.job, bounded);
76
+ bounded.throwIfAborted();
77
+ } catch (error) {
78
+ if (signal.aborted) {
79
+ if (primary.phase === "completed") throw cancelledAfterCompletion(primary.result, signal.reason);
80
+ throw signal.reason;
81
+ }
82
+ const detail = bounded.aborted ? "The daemon did not recover in time." : errorMessage(error);
83
+ if (primary.phase === "completed")
84
+ throw new CompletedDirectionalRecoveryError(
85
+ `The transfer finished, but file-queue recovery stopped. ${detail}${restoreMessage(primary.result)}`,
86
+ { cause: error },
87
+ );
88
+ throw new Error(`No transfer was applied, but file-queue recovery stopped. ${detail}`, { cause: error });
89
+ }
90
+ if (primary.phase === "completed") return primary.result;
91
+ const retry = new DirectionalCheckpoint(replacement, attempt.fingerprint);
92
+ const retried = await run(retry, attempt.fingerprint);
93
+ const remaining = recoveryOutcome(retried);
94
+ if (!remaining) return retried;
95
+ markCleanupRequired();
96
+ if (remaining.phase === "completed") {
97
+ if (signal.aborted) throw cancelledAfterCompletion(remaining.result, signal.reason);
98
+ throw new CompletedDirectionalRecoveryError(
99
+ `Transfer finished, but file-queue cleanup is still uncertain after one recovery attempt.${restoreMessage(remaining.result)}`,
100
+ );
101
+ }
102
+ throw new Error("File-queue release could not be verified after one recovery attempt. No transfer was applied.");
103
+ }
@@ -1,6 +1,6 @@
1
1
  import { AsyncLocalStorage } from "node:async_hooks";
2
2
  import { randomUUID } from "node:crypto";
3
- import { realpathSync } from "node:fs";
3
+ import { lstatSync, realpathSync } from "node:fs";
4
4
  import fs from "node:fs/promises";
5
5
  import path from "node:path";
6
6
  import { type ExtensionContext, getAgentDir } from "@earendil-works/pi-coding-agent";
@@ -42,6 +42,7 @@ import {
42
42
  import { safeTerminalText } from "../ui/terminal-text.js";
43
43
  import { PiApplyGate } from "./apply-gate.js";
44
44
  import { observeDebugJob } from "./client-debug.js";
45
+ import { type DirectionalCheckpoint, isForegroundDirection, runDirectionalRecovery } from "./directional-recovery.js";
45
46
  import { createQueueReleaseUI, type QueueReleaseEvent } from "./queue-release-ui.js";
46
47
  import { quarantineClient, recoverDetachedClients } from "./recovery.js";
47
48
  import { requestStartupBootstrap } from "./startup-bootstrap-client.js";
@@ -266,6 +267,8 @@ export class PiDaemonClient {
266
267
  private uiContext: ExtensionContext;
267
268
  private reloadRequest?: { received: boolean };
268
269
  private pendingReload?: AbortController;
270
+ private directionalCheckpoint?: DirectionalCheckpoint;
271
+ private recoveringDirectionalOwner = false;
269
272
  private readonly busy = new Set<string>();
270
273
  private initialized = false;
271
274
  private startupDebug = false;
@@ -343,8 +346,8 @@ export class PiDaemonClient {
343
346
  cwd: this.ctx.cwd,
344
347
  mode: this.ctx.mode,
345
348
  hasUI: !protectionOnly && this.ctx.hasUI,
346
- idle: !protectionOnly && !this.paused && !this.busy.size && this.ctx.isIdle(),
347
- ready: !protectionOnly && this.initialized,
349
+ idle: !protectionOnly && !this.recoveringDirectionalOwner && !this.paused && !this.busy.size && this.ctx.isIdle(),
350
+ ready: !protectionOnly && !this.recoveringDirectionalOwner && this.initialized,
348
351
  startupDebug: this.startupDebug,
349
352
  sessionFile: canonicalPath(manager.getSessionFile?.()),
350
353
  sessionId: manager.getSessionId?.(),
@@ -378,12 +381,14 @@ export class PiDaemonClient {
378
381
  }
379
382
  async attachExisting({ allowUpgrade = false } = {}) {
380
383
  this.validate();
384
+ this.assertNoDirectionalRecovery();
381
385
  if (!allowUpgrade && !this.paused && this.connection?.contactState === "active") return !this.protectionOnly;
382
386
  const address = await findDaemon(this.root).catch((error: unknown) => {
383
387
  this.recordDebug({ event: "connection", outcome: "failed" });
384
388
  throw error;
385
389
  });
386
390
  this.validate();
391
+ this.assertNoDirectionalRecovery();
387
392
  if (!address) {
388
393
  this.recordDebug({ event: "connection", outcome: "skipped" });
389
394
  return false;
@@ -397,7 +402,7 @@ export class PiDaemonClient {
397
402
  return true;
398
403
  } catch (error) {
399
404
  this.validate();
400
- if (this.paused) throw error;
405
+ if (this.paused || this.recoveringDirectionalOwner) throw error;
401
406
  upgradeFailure = safeTerminalText(errorMessage(error));
402
407
  }
403
408
  }
@@ -429,7 +434,15 @@ export class PiDaemonClient {
429
434
  this.validateFactsScope(connection);
430
435
  });
431
436
  }
437
+ private assertNoDirectionalRecovery() {
438
+ if (this.recoveringDirectionalOwner)
439
+ throw new Error("Pi Sync is recovering the daemon for a transfer. Retry after recovery finishes.");
440
+ }
432
441
  async connect(existing?: Awaited<ReturnType<typeof ensureDaemon>>, requestSignal?: AbortSignal) {
442
+ this.assertNoDirectionalRecovery();
443
+ return this.attachConnection(existing, requestSignal);
444
+ }
445
+ private async attachConnection(existing?: Awaited<ReturnType<typeof ensureDaemon>>, requestSignal?: AbortSignal) {
433
446
  const startupSignal = requestSignal ? AbortSignal.any([this.signal, requestSignal]) : this.signal;
434
447
  const validateStartup = () => {
435
448
  this.validate();
@@ -495,7 +508,12 @@ export class PiDaemonClient {
495
508
  contact: (state) => this.observeContact(connection, state),
496
509
  queueRelease: (event) => this.observeQueueRelease(connection, event),
497
510
  error: () => {
498
- if (this.ownsContactUI() && connection.facts.hasUI && !this.releaseUI.retrying)
511
+ if (
512
+ !this.recoveringDirectionalOwner &&
513
+ this.ownsContactUI() &&
514
+ connection.facts.hasUI &&
515
+ !this.releaseUI.retrying
516
+ )
499
517
  this.showContactStatus("sync service unavailable", "blocked", true);
500
518
  },
501
519
  });
@@ -706,9 +724,11 @@ export class PiDaemonClient {
706
724
  }
707
725
  async verifyConnection(signal?: AbortSignal) {
708
726
  const connection = await this.connect(undefined, signal);
709
- signal?.throwIfAborted();
727
+ this.validateFactsScope(connection, signal);
728
+ this.assertNoDirectionalRecovery();
710
729
  await this.publishFacts(connection, signal);
711
- signal?.throwIfAborted();
730
+ this.validateFactsScope(connection, signal);
731
+ this.assertNoDirectionalRecovery();
712
732
  return connection;
713
733
  }
714
734
  async readSettings(repair = false) {
@@ -723,6 +743,14 @@ export class PiDaemonClient {
723
743
  }
724
744
  return decode(await this.run(repair ? "settings.repair-read" : "settings.read", {}));
725
745
  }
746
+ canReportDirectionalResult() {
747
+ try {
748
+ this.validateFactsScope();
749
+ return !this.pendingReload;
750
+ } catch {
751
+ return false;
752
+ }
753
+ }
726
754
  get ownershipCleanupRequired() {
727
755
  return this.cleanupRequired;
728
756
  }
@@ -764,6 +792,38 @@ export class PiDaemonClient {
764
792
  );
765
793
  return result;
766
794
  }
795
+ private async recoverDirectionalOwner(
796
+ connection: DaemonConnection,
797
+ job: string,
798
+ signal: AbortSignal,
799
+ assertRoot: () => void,
800
+ ) {
801
+ this.validateFactsScope(connection, signal);
802
+ this.recoveringDirectionalOwner = true;
803
+ try {
804
+ this.stopContactRepair(true);
805
+ await this.factsQueue;
806
+ this.validateFactsScope(connection, signal);
807
+ await connection.recoverForeground(job, signal);
808
+ if (this.connection !== connection) throw new Error("The Pi participant changed during daemon recovery.");
809
+ this.confirmRecoveryExit(connection.identity);
810
+ await this.gate.releaseAfterDrain();
811
+ this.connection = undefined;
812
+ this.connecting = undefined;
813
+ this.cleanupRequired = false;
814
+ this.validateFactsScope(undefined, signal);
815
+ assertRoot();
816
+ const replacement = await ensureDaemon(this.root, signal, { compatibleOnly: true });
817
+ this.validateFactsScope(undefined, signal);
818
+ assertRoot();
819
+ const attached = await this.attachConnection(replacement, signal);
820
+ this.validateFactsScope(attached, signal);
821
+ assertRoot();
822
+ return attached;
823
+ } finally {
824
+ this.recoveringDirectionalOwner = false;
825
+ }
826
+ }
767
827
  private async runCurrent(
768
828
  operation: string,
769
829
  payload: unknown,
@@ -801,7 +861,43 @@ export class PiDaemonClient {
801
861
  const clearForeground = () => this.releaseUI.finishForeground(Boolean(this.releaseContext()));
802
862
  runSignal.addEventListener("abort", clearForeground, { once: true });
803
863
  try {
804
- const result = await connection.run(operation, payload, runSignal, onCommit, diagnostics?.onSubmit);
864
+ const root = isForegroundDirection(operation) ? lstatSync(this.root) : undefined;
865
+ const assertRoot = () => {
866
+ const current = lstatSync(this.root);
867
+ if (!root || !current.isDirectory() || current.dev !== root.dev || current.ino !== root.ino)
868
+ throw new Error("The agent directory changed during the transfer.");
869
+ };
870
+ const intent = root ? structuredClone(payload) : payload;
871
+ const result = root
872
+ ? await runDirectionalRecovery(
873
+ connection,
874
+ runSignal,
875
+ async (checkpoint, retryCheckpoint) => {
876
+ const current = checkpoint.connection;
877
+ this.validateFactsScope(current, runSignal);
878
+ assertRoot();
879
+ this.directionalCheckpoint = checkpoint;
880
+ try {
881
+ return await current.run(
882
+ operation,
883
+ retryCheckpoint === undefined ? intent : { ...(intent as object), retryCheckpoint },
884
+ runSignal,
885
+ onCommit,
886
+ (id) => {
887
+ checkpoint.job = id;
888
+ diagnostics?.onSubmit(id);
889
+ },
890
+ );
891
+ } finally {
892
+ this.directionalCheckpoint = undefined;
893
+ }
894
+ },
895
+ (owner, job, recoverySignal) => this.recoverDirectionalOwner(owner, job, recoverySignal, assertRoot),
896
+ () => {
897
+ this.cleanupRequired = true;
898
+ },
899
+ )
900
+ : await connection.run(operation, payload, runSignal, onCommit, diagnostics?.onSubmit);
805
901
  if (runSignal.aborted || reload?.signal.aborted) diagnostics?.rejected(undefined, true);
806
902
  else diagnostics?.returned(result);
807
903
  if (request?.received && reload && !this.paused && !reload.signal.aborted && !signal?.aborted) {
@@ -924,7 +1020,7 @@ export class PiDaemonClient {
924
1020
  this.validate();
925
1021
  }
926
1022
  async update() {
927
- if (this.connection && !this.paused && !this.disposed && !this.signal.aborted)
1023
+ if (this.connection && !this.recoveringDirectionalOwner && !this.paused && !this.disposed && !this.signal.aborted)
928
1024
  await this.publishFacts(this.connection);
929
1025
  }
930
1026
  private async pagedMergeReview(
@@ -984,6 +1080,7 @@ export class PiDaemonClient {
984
1080
  items?: string[];
985
1081
  helpText?: string;
986
1082
  background?: boolean;
1083
+ fingerprint?: string;
987
1084
  };
988
1085
  if (callback.kind === "queue-release") {
989
1086
  if (typeof payload?.reservation !== "string") throw new Error("Invalid queue release.");
@@ -993,6 +1090,12 @@ export class PiDaemonClient {
993
1090
  this.validate();
994
1091
  signal.throwIfAborted();
995
1092
  if (this.paused) throw new Error("Pi session is changing; no new work is authorized.");
1093
+ if (callback.kind === "directional-checkpoint") {
1094
+ this.validateFactsScope(connection, this.runSignal);
1095
+ return (
1096
+ !protectionOnly && this.directionalCheckpoint?.accept(connection, callback.job, payload?.fingerprint) === true
1097
+ );
1098
+ }
996
1099
  if (callback.kind === "queue-acquire") {
997
1100
  if (this.pendingReload) throw new Error("Pi resources are about to reload.");
998
1101
  if (payload.background && !this.facts().idle) throw new Error("Pi is busy; background apply was not granted.");
@@ -18,6 +18,7 @@ export type RunRoute = (
18
18
  target?: string,
19
19
  onDialog?: (active: boolean) => void,
20
20
  retryRefusal?: boolean,
21
+ directionalFingerprint?: string,
21
22
  ) => Promise<RunRouteResult | undefined>;
22
23
 
23
24
  export type CancellableOperationResult = RunRouteResult | { kind: "closed" } | { kind: "cancelled" };
@@ -27,6 +28,7 @@ interface CancellableOperationOptions {
27
28
  cancelAcrossDialogs?: boolean;
28
29
  cancelledMessage?: string | null;
29
30
  target?: string;
31
+ directionalFingerprint?: string;
30
32
  signal?: AbortSignal;
31
33
  isCurrent?: () => boolean;
32
34
  }
@@ -41,7 +43,8 @@ export async function runCancellableOperation(
41
43
  const result = await runCancellableTask(
42
44
  ctx,
43
45
  message,
44
- (signal, onCommit, onDialog) => runRoute(route, signal, onCommit, options.target, onDialog),
46
+ (signal, onCommit, onDialog) =>
47
+ runRoute(route, signal, onCommit, options.target, onDialog, undefined, options.directionalFingerprint),
45
48
  options,
46
49
  );
47
50
  return result.kind === "completed" ? (result.value ?? { kind: "failed" }) : result;
@@ -61,7 +64,7 @@ export async function runCancellableTask<Value>(
61
64
  onCommit?: () => void,
62
65
  onDialog?: (active: boolean) => void,
63
66
  ) => Promise<Value>,
64
- options: Omit<CancellableOperationOptions, "target"> = {},
67
+ options: Omit<CancellableOperationOptions, "target" | "directionalFingerprint"> = {},
65
68
  ): Promise<CancellableTaskResult<Value>> {
66
69
  const {
67
70
  commitAware = false,
@@ -25,8 +25,8 @@ import { safeTerminalText } from "./terminal-text.js";
25
25
 
26
26
  export const MAIN_MENU_ACTIONS = [
27
27
  "Sync now",
28
- "Pull from remote…",
29
- "Push to remote…",
28
+ "Pull from remote",
29
+ "Push to remote",
30
30
  "View differences",
31
31
  "Check remote status",
32
32
  "Settings",