@narumitw/pi-sync 0.64.0 → 0.66.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 (116) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +80 -11
  3. package/dist/chunks/{chunk-TJ7YNITN.ts → chunk-5YOLQKNZ.ts} +39 -3
  4. package/dist/chunks/chunk-5YOLQKNZ.ts.map +7 -0
  5. package/dist/chunks/{chunk-NDEZ52SS.ts → chunk-ASU3GZPW.ts} +11 -93
  6. package/dist/chunks/chunk-ASU3GZPW.ts.map +7 -0
  7. package/dist/chunks/{chunk-CKUGCBHP.ts → chunk-AYGMIMCV.ts} +2 -2
  8. package/dist/chunks/chunk-AYGMIMCV.ts.map +7 -0
  9. package/dist/chunks/{chunk-F3VODLVQ.ts → chunk-BESRBKVO.ts} +3 -3
  10. package/dist/chunks/{chunk-TZMVSTAM.ts → chunk-BYVHABNR.ts} +4 -4
  11. package/dist/chunks/chunk-ECYCNZOE.ts +12 -0
  12. package/dist/chunks/chunk-ECYCNZOE.ts.map +7 -0
  13. package/dist/chunks/{chunk-RW44KNFD.ts → chunk-JQ5BAWW2.ts} +182 -12
  14. package/dist/chunks/chunk-JQ5BAWW2.ts.map +7 -0
  15. package/dist/chunks/{chunk-MANNB4WZ.ts → chunk-KNEUL4XN.ts} +1 -7
  16. package/dist/chunks/chunk-KNEUL4XN.ts.map +7 -0
  17. package/dist/chunks/{chunk-VPSC7BXM.ts → chunk-SZJOUVCL.ts} +2 -2
  18. package/dist/chunks/{chunk-YT6PDRMM.ts → chunk-WJQ4TGN5.ts} +17 -17
  19. package/dist/chunks/chunk-WJQ4TGN5.ts.map +7 -0
  20. package/dist/chunks/{chunk-4VKWHVUO.ts → chunk-XUZV4OGI.ts} +3 -2
  21. package/dist/chunks/{chunk-4VKWHVUO.ts.map → chunk-XUZV4OGI.ts.map} +2 -2
  22. package/dist/chunks/chunk-Z5JMOXJM.ts +106 -0
  23. package/dist/chunks/chunk-Z5JMOXJM.ts.map +7 -0
  24. package/dist/chunks/{command-handler-N45GY7AV.ts → command-handler-44EFGPWH.ts} +54 -13
  25. package/dist/chunks/command-handler-44EFGPWH.ts.map +7 -0
  26. package/dist/chunks/{conflict-review-5E4M44BA.ts → conflict-review-J7L7S4AR.ts} +2 -2
  27. package/dist/chunks/{file-selection-DDQN4LVD.ts → file-selection-XWACUTAH.ts} +8 -8
  28. package/dist/chunks/ignore-file-ui-OHFISFVC.ts +21 -0
  29. package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts → manager-result-dispatcher-WXE2BAQO.ts} +4 -4
  30. package/dist/chunks/{manager-ui-EV23DPZQ.ts → manager-ui-CVZLMXJ5.ts} +90 -76
  31. package/dist/chunks/manager-ui-CVZLMXJ5.ts.map +7 -0
  32. package/dist/chunks/{merge-review-6YSLSMGS.ts → merge-review-AAC674C6.ts} +3 -3
  33. package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts → remote-selection-ui-E4XZCQ7A.ts} +3 -3
  34. package/dist/chunks/{setup-switch-HY7K3442.ts → setup-switch-644T6KHG.ts} +3 -3
  35. package/dist/chunks/setup-switch-644T6KHG.ts.map +7 -0
  36. package/dist/chunks/{setup-wizard-LEKDQ3HK.ts → setup-wizard-IEW56AZE.ts} +10 -8
  37. package/dist/chunks/{setup-wizard-LEKDQ3HK.ts.map → setup-wizard-IEW56AZE.ts.map} +1 -1
  38. package/dist/chunks/{sync-inspection-OS2LVOLV.ts → sync-inspection-NBBTSMKR.ts} +2 -2
  39. package/dist/chunks/{sync-operations-D3MDJUQQ.ts → sync-operations-AIEM2KL2.ts} +2 -2
  40. package/dist/daemon/dist/client.js +125 -287
  41. package/dist/daemon/dist/consent.js +14 -2
  42. package/dist/daemon/dist/daemon-recovery.js +85 -2
  43. package/dist/daemon/dist/daemon-startup.js +257 -0
  44. package/dist/daemon/dist/engine/backends/git/git-backend.js +15 -4
  45. package/dist/daemon/dist/engine/backends/git/git-storage.js +15 -3
  46. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +20 -9
  47. package/dist/daemon/dist/engine/backends/sync-backend.js +16 -0
  48. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +19 -6
  49. package/dist/daemon/dist/engine/ignore/adoption-journal.js +143 -0
  50. package/dist/daemon/dist/engine/ignore/snapshot-ignore-rules.js +39 -0
  51. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +2 -2
  52. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +6 -6
  53. package/dist/daemon/dist/engine/snapshot/snapshot-types.js +5 -1
  54. package/dist/daemon/dist/engine/snapshot/snapshot.js +5 -2
  55. package/dist/daemon/dist/engine/sync/conflict-review.js +2 -0
  56. package/dist/daemon/dist/engine/sync/continuous-watch.js +3 -2
  57. package/dist/daemon/dist/engine/sync/directional-action.js +119 -0
  58. package/dist/daemon/dist/engine/sync/ignore-adoption-recovery.js +50 -0
  59. package/dist/daemon/dist/engine/sync/ignore-adoption.js +401 -0
  60. package/dist/daemon/dist/engine/sync/ignore-publication.js +23 -0
  61. package/dist/daemon/dist/engine/sync/initialization.js +12 -0
  62. package/dist/daemon/dist/engine/sync/local-fields.js +6 -3
  63. package/dist/daemon/dist/engine/sync/merge-journal.js +2 -2
  64. package/dist/daemon/dist/engine/sync/merged-sync.js +14 -3
  65. package/dist/daemon/dist/engine/sync/remote-snapshot.js +3 -1
  66. package/dist/daemon/dist/engine/sync/sync-errors.js +20 -0
  67. package/dist/daemon/dist/engine/sync/sync-local.js +57 -3
  68. package/dist/daemon/dist/engine/sync/sync-mutations.js +375 -346
  69. package/dist/daemon/dist/engine/sync/sync-policy.js +5 -5
  70. package/dist/daemon/dist/engine/sync/sync-queries.js +3 -2
  71. package/dist/daemon/dist/engine/sync/sync-rollback.js +204 -0
  72. package/dist/daemon/dist/engine/sync/transfer-freshness.js +11 -5
  73. package/dist/daemon/dist/engine/ui/ignore-rule-preview.js +18 -0
  74. package/dist/daemon/dist/engine-service.js +69 -1
  75. package/dist/daemon/dist/foreground-queue-outcome.js +9 -0
  76. package/dist/daemon/dist/monitor.js +1 -0
  77. package/dist/daemon/dist/server.js +76 -11
  78. package/dist/daemon/dist/service-host.js +56 -8
  79. package/dist/daemon/package.json +1 -1
  80. package/dist/index.ts +6 -6
  81. package/docs/daemon-migration.md +3 -6
  82. package/docs/tui-contract.md +3 -3
  83. package/package.json +2 -2
  84. package/skills/configure-pi-sync/references/configuration.md +10 -8
  85. package/src/commands/command-execution.ts +56 -2
  86. package/src/commands/command-handler.ts +2 -0
  87. package/src/commands/command.ts +2 -1
  88. package/src/daemon/directional-recovery.ts +103 -0
  89. package/src/daemon/pi-client.ts +112 -9
  90. package/src/ui/cancellable-operation.ts +5 -2
  91. package/src/ui/ignore-file-ui.ts +13 -5
  92. package/src/ui/manager-state.ts +17 -10
  93. package/src/ui/manager-ui.ts +30 -25
  94. package/src/ui/merge-review.ts +8 -9
  95. package/src/ui/remote-selection-ui.ts +43 -2
  96. package/src/ui/settings-ui.ts +30 -30
  97. package/src/ui/sync-confirmation.ts +7 -7
  98. package/dist/chunks/chunk-CKUGCBHP.ts.map +0 -7
  99. package/dist/chunks/chunk-MANNB4WZ.ts.map +0 -7
  100. package/dist/chunks/chunk-NDEZ52SS.ts.map +0 -7
  101. package/dist/chunks/chunk-RW44KNFD.ts.map +0 -7
  102. package/dist/chunks/chunk-TJ7YNITN.ts.map +0 -7
  103. package/dist/chunks/chunk-YT6PDRMM.ts.map +0 -7
  104. package/dist/chunks/command-handler-N45GY7AV.ts.map +0 -7
  105. package/dist/chunks/manager-ui-EV23DPZQ.ts.map +0 -7
  106. /package/dist/chunks/{chunk-F3VODLVQ.ts.map → chunk-BESRBKVO.ts.map} +0 -0
  107. /package/dist/chunks/{chunk-TZMVSTAM.ts.map → chunk-BYVHABNR.ts.map} +0 -0
  108. /package/dist/chunks/{chunk-VPSC7BXM.ts.map → chunk-SZJOUVCL.ts.map} +0 -0
  109. /package/dist/chunks/{conflict-review-5E4M44BA.ts.map → conflict-review-J7L7S4AR.ts.map} +0 -0
  110. /package/dist/chunks/{file-selection-DDQN4LVD.ts.map → file-selection-XWACUTAH.ts.map} +0 -0
  111. /package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts.map → ignore-file-ui-OHFISFVC.ts.map} +0 -0
  112. /package/dist/chunks/{merge-review-6YSLSMGS.ts.map → manager-result-dispatcher-WXE2BAQO.ts.map} +0 -0
  113. /package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts.map → merge-review-AAC674C6.ts.map} +0 -0
  114. /package/dist/chunks/{setup-switch-HY7K3442.ts.map → remote-selection-ui-E4XZCQ7A.ts.map} +0 -0
  115. /package/dist/chunks/{sync-inspection-OS2LVOLV.ts.map → sync-inspection-NBBTSMKR.ts.map} +0 -0
  116. /package/dist/chunks/{sync-operations-D3MDJUQQ.ts.map → sync-operations-AIEM2KL2.ts.map} +0 -0
@@ -14,7 +14,7 @@ class OwnershipCleanupError extends Error {
14
14
  const scope = new AsyncLocalStorage();
15
15
  /** One service process owns one root; tests must use a separate process per root. */
16
16
  export function installServiceHost(root, ignoreFileOperationsAvailable) {
17
- let poisoned = false;
17
+ let poisoned;
18
18
  const assertRoot = canonicalRootGuard(root);
19
19
  function current() {
20
20
  const value = scope.getStore();
@@ -42,17 +42,30 @@ export function installServiceHost(root, ignoreFileOperationsAvailable) {
42
42
  protectedTarget(target, owner.execution);
43
43
  const peers = owner.peers.toSorted((a, b) => a.id.localeCompare(b.id));
44
44
  const requested = [];
45
+ const foreground = owner.foreground;
46
+ let acquireFailed = false;
47
+ let completed = false;
45
48
  return withCleanup(async () => {
46
49
  for (const peer of peers) {
47
50
  owner.execution.validate();
48
51
  const reservation = randomUUID();
49
52
  requested.push({ client: peer.id, reservation });
50
- await owner.execution.request("queue-acquire", { reservation, targets: missing, generation: peer.generation, background: !owner.execution.clientId }, peer.id);
53
+ try {
54
+ await owner.execution.request("queue-acquire", { reservation, targets: missing, generation: peer.generation, background: !owner.execution.clientId }, peer.id);
55
+ }
56
+ catch (error) {
57
+ acquireFailed = true;
58
+ throw error;
59
+ }
51
60
  owner.execution.validate();
52
61
  }
53
62
  for (const target of missing)
54
63
  protectedTarget(target, owner.execution);
55
- return await scope.run({ ...owner, held: new Set([...owner.held, ...missing]) }, action);
64
+ if (foreground)
65
+ foreground.entered = true;
66
+ const result = await scope.run({ ...owner, held: new Set([...owner.held, ...missing]) }, action);
67
+ completed = true;
68
+ return result;
56
69
  }, async () => {
57
70
  // Release by request identity even when a grant response was lost. A cancelled
58
71
  // prompt is not evidence that a granted remote writer stopped.
@@ -65,8 +78,17 @@ export function installServiceHost(root, ignoreFileOperationsAvailable) {
65
78
  }));
66
79
  const failure = results.find((result) => result.status === "rejected");
67
80
  if (failure?.status === "rejected") {
68
- poisoned = true;
69
- throw new OwnershipCleanupError("File-queue release is uncertain; stop the daemon and keep grants quarantined until owner exit.", { cause: failure.reason });
81
+ poisoned ??= "queue";
82
+ const error = new OwnershipCleanupError("File-queue release is uncertain; stop the daemon and keep grants quarantined until owner exit.", { cause: failure.reason });
83
+ if (foreground && poisoned === "queue") {
84
+ if (completed) {
85
+ foreground.deferred = true;
86
+ return;
87
+ }
88
+ if (acquireFailed && !foreground.entered && !owner.execution.signal.aborted)
89
+ foreground.beforeMutation = error;
90
+ }
91
+ throw error;
70
92
  }
71
93
  });
72
94
  }
@@ -75,7 +97,7 @@ export function installServiceHost(root, ignoreFileOperationsAvailable) {
75
97
  allowConfigMigration: () => Boolean(readConsent(root)),
76
98
  root: () => {
77
99
  assertRoot();
78
- if (poisoned)
100
+ if (poisoned && !(poisoned === "queue" && scope.getStore()?.foreground?.deferred))
79
101
  throw new OwnershipCleanupError("Daemon ownership cleanup is uncertain; stop and reconcile before restarting.");
80
102
  return root;
81
103
  },
@@ -110,7 +132,7 @@ export function installServiceHost(root, ignoreFileOperationsAvailable) {
110
132
  await release?.();
111
133
  }
112
134
  catch (error) {
113
- poisoned = true;
135
+ poisoned = "other";
114
136
  throw new OwnershipCleanupError("Pi settings lock release failed; stop and reconcile before restarting.", {
115
137
  cause: error,
116
138
  });
@@ -127,7 +149,33 @@ export function installServiceHost(root, ignoreFileOperationsAvailable) {
127
149
  status: (_ctx, value, presentation) => current().execution.emit("status", { value, presentation }),
128
150
  });
129
151
  return {
130
- cleanupRequired: () => poisoned,
152
+ cleanupRequired: () => poisoned !== undefined,
153
+ async runForeground(execution, action) {
154
+ const owner = current();
155
+ if (owner.execution !== execution || !execution.clientId || owner.held.size || owner.foreground)
156
+ throw new Error("Foreground queue recovery requires one attached directional job.");
157
+ const foreground = { entered: false, deferred: false };
158
+ return scope.run({ ...owner, foreground }, async () => {
159
+ try {
160
+ const result = await action();
161
+ if (foreground.deferred && poisoned === "queue")
162
+ return { foregroundQueueCleanup: "verified-result", result };
163
+ return result;
164
+ }
165
+ catch (error) {
166
+ if (foreground.beforeMutation &&
167
+ !execution.signal.aborted &&
168
+ error instanceof AggregateError &&
169
+ error.errors.includes(foreground.beforeMutation))
170
+ return { foregroundQueueCleanup: "before-mutation" };
171
+ if (foreground.deferred && !(error instanceof OwnershipCleanupError)) {
172
+ const detail = error instanceof Error ? ` ${error.message}` : "";
173
+ throw new OwnershipCleanupError(`File-queue release was not confirmed.${detail}`, { cause: error });
174
+ }
175
+ throw error;
176
+ }
177
+ });
178
+ },
131
179
  run(execution, action) {
132
180
  return scope.run({ execution, held: new Set() }, async () => {
133
181
  try {
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.10.0"
2
+ "version": "0.12.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-44EFGPWH.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.
@@ -4,7 +4,7 @@ This reference records the setting and transfer contracts used by the TUI. It do
4
4
 
5
5
  ## Action palette
6
6
 
7
- The `/sync` TUI manager uses Kit's public searchable `ChoiceScreen` with at most five visible choices. Ordinary rows contain only labels; the selected action's short description appears below the list and is included in search. Search and selection survive a cancelled operation. Navigation, confirmation, cancellation, paste, focus, scrolling and constrained-height framing remain Kit-owned. RPC keeps an unfiltered list with the established **Sync now** label and a **Done** exit; TUI displays **Sync…** for that same action.
7
+ The `/sync` TUI manager uses Kit's public searchable `ChoiceScreen` with at most five visible choices. Ordinary rows contain only labels; the selected action's short description appears below the list and is included in search. Searching for `storage connections` finds **Settings** in the configured manager. Search and selection survive a cancelled operation. Navigation, confirmation, cancellation, paste, focus, scrolling and constrained-height framing remain Kit-owned. RPC keeps an unfiltered list with the established **Sync now** label and a **Done** exit; TUI displays **Sync…** for that same action.
8
8
 
9
9
  The homepage shows setup/storage, cached remote observations, last applied state and relevant automatic-transfer permissions. It does not render scheduler owners, leases, request accounting or candidate limits. Recorded background phases and successful background-transfer timestamps are explicitly historical; neither replaces a fresh remote check. Missing records show **not yet observed**, and unreadable or invalid records show **Unknown**. Last applied does not invent a timestamp or direction.
10
10
 
@@ -37,7 +37,7 @@ All settings are private to this device. There are no project overrides. Default
37
37
  | Show sync status | `showStatus`, true | All setups | Immediate save and immediate status visibility change; notifications/widgets remain |
38
38
  | Debug mode | `debug`, false | All setups | Immediate save; Pi logging and timing display use the next session start in TUI/RPC; daemon log uses the next owner, job, or Continuous sync cycle boundary |
39
39
 
40
- Opening foreground Settings cancels and drains startup work. Back does not undo successful saves; cancelling a draft or compatibility review leaves that change unsaved. A failed save retains the previous document and effective/displayed value. Completed transfers are never undone by changing a preference.
40
+ Opening foreground Settings cancels and drains startup work. Simple changes report saving, then one setting-specific confirmation or an error in Pi's notifications. Back does not undo successful saves; cancelling a draft or compatibility review leaves that change unsaved. A failed save retains the previous document and effective/displayed value. Completed transfers are never undone by changing a preference.
41
41
 
42
42
  Writers queue the complete read-modify-write operation, hold the cross-process lock through validation and same-directory atomic replacement, preserve unknown fields and private permissions, and refuse invalid existing files. UI changes do not replace those writers.
43
43
 
@@ -74,7 +74,7 @@ Startup transfer summaries report the preference and prerequisites, not a claim
74
74
  | Explicit `--yes` | Existing documented review bypass only | Mandatory migration and operation safety remain; existing route suites |
75
75
  | Automatic startup / shutdown | No new modal; existing opt-in, capability, idle, all-or-nothing conflict and secret policies | `automatic-transfer.test.ts`, `startup-check.test.ts`, `backend-orchestration.test.ts` |
76
76
 
77
- TUI Pull, Push, and ignore-file rollback show directional counts and safety notes in the confirmation. Exact path rows are available in the read-only **View details** document. Older daemons can send the complete file list as the directional summary; the TUI moves only recognized path groups with verified counts out of that summary, without changing the exact details or the approval requirement. The configured Up and Down actions always select an option; selection-page bindings and the mouse wheel scroll the summary independently. Approval still requires displaying every row of the compact summary; a resize restarts the review. On a terminal too short to show the summary, resize to continue or cancel. RPC and legacy History rollback retain full file lists in their existing confirmation protocols. All changed counts come from effective snapshot differences rather than raw merge decisions. Protected paths, preserved remote files, merged bytes, and withheld paths must be accounted for before rendering. Cancellation performs no transfer; pre-commit preparation may retain recovery evidence. After the commit boundary, existing completion/recovery rules apply instead of promising undo.
77
+ On an ignore-policy mismatch, Push and Pull both require explicit directional approval. The review names the affected side and offers the available rule text and exact file changes in details. Pull does not offer an overwrite when the snapshot omits rule text; it does not change the remote or the Sessions setting. An aborted review performs no transfer. TUI Pull, Push, and ignore-file rollback show directional counts and safety notes in the confirmation. Exact path rows are available in the read-only **View details** document. Older daemons can send the complete file list as the directional summary; the TUI moves only recognized path groups with verified counts out of that summary, without changing the exact details or the approval requirement. The configured Up and Down actions always select an option; selection-page bindings and the mouse wheel scroll the summary independently. Approval still requires displaying every row of the compact summary; a resize restarts the review. On a terminal too short to show the summary, resize to continue or cancel. RPC and legacy History rollback retain full file lists in their existing confirmation protocols. All changed counts come from effective snapshot differences rather than raw merge decisions. Protected paths, preserved remote files, merged bytes, and withheld paths must be accounted for before rendering. Cancellation performs no transfer; pre-commit preparation may retain recovery evidence. After the commit boundary, existing completion/recovery rules apply instead of promising undo.
78
78
 
79
79
  ## Resource reload after a transfer
80
80
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@narumitw/pi-sync",
3
- "version": "0.64.0",
3
+ "version": "0.66.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.12.0",
61
61
  "@types/proper-lockfile": "^4.1.4",
62
62
  "@types/semver": "^7.8.0",
63
63
  "esbuild": "0.28.2",
@@ -76,7 +76,7 @@ The screen uses a searchable flat list without category navigation. Compare cont
76
76
  Returning from catalog management refreshes the rows; switching or removing the owning setup closes its old Settings screen.
77
77
 
78
78
  Descriptions identify the owner: this setup, all setups on this device, or shared connections.
79
- Simple choices report Saving and the durable Saved or failed/rejected result, preserve the selected row and search during refresh, and restore their previous value if saving fails.
79
+ Simple choices report saving, then a setting-specific confirmation or an error in Pi's notifications. They preserve the selected row and search during refresh and restore the previous value if saving fails.
80
80
  Escape closes the screen without undoing successful saves.
81
81
  Complex values retain their input/review flows.
82
82
  This navigation change does not alter schema, defaults, automatic-sync behavior, or explicit opt-ins.
@@ -353,17 +353,19 @@ Use `/` as the separator; escaped `/` is not supported. A leading `/` anchors a
353
353
 
354
354
  Session sync requires both a separate opt-in and rules that allow sessions. The starter `/sessions/` still excludes them. Match sessions by their logical `sessions/` paths even if stored elsewhere. Loaded sessions stay protected during apply.
355
355
 
356
- Pi credentials and trust (`auth.json` and `trust.json`), private Pi Sync files (settings, state, and the [debug log](#shared-log)), and `.syncignore` or its configured alternatives stay local regardless of the rules. `truth.json` is a starter exclusion, not Pi's trust file. Transfers do not replace or remove ignored local files, and exclusions do not erase retained snapshots or backups.
356
+ Pi credentials and trust (`auth.json` and `trust.json`), private Pi Sync files (settings, state, and the [debug log](#shared-log)), and other setups' rule files stay local. `truth.json` is a starter exclusion, not Pi's trust file. A new snapshot includes the active rule text and filename unless the file excludes itself. Add `/.syncignore` to keep the default rule file out of future snapshots. A later `!/.syncignore` can include it again. This does not erase rules or comments from retained history.
357
357
 
358
358
  #### Transfer review and recovery
359
359
 
360
- Setup, migration, rule-file switching, and edits neither start nor authorize transfers. Upgrade all peers before publishing a version 6 snapshot. It stores a policy fingerprint, not the filename or rule text. Use the same rule text and session opt-in on peers: even comment or whitespace changes can change the fingerprint. Do not copy rules from the remote.
360
+ Setup, migration, rule-file switching, and edits neither start nor authorize transfers. Upgrade all peers before publishing a version 7 snapshot. A version 6 snapshot has only the policy fingerprint; an upgraded publisher with matching rules can publish again to include rule text. Comments, whitespace and session opt-in affect the fingerprint. Re-review automatic transfers after upgrading an ignore-file setup.
361
361
 
362
- A legacy or mismatched head requires separately reviewed directional policy publication. Neither `--yes` nor automatic work can authorize it. Inspect scope with `/sync diff` and review the direction in `/sync`. A pull cannot apply a foreign policy, and rollback requires compatible history. If the rules, setup, or head change, reopen the review.
362
+ When policies differ, a reviewed Push can replace the remote policy. Pull can preview and adopt verified remote rules without writing to the remote. Cancel to leave both sides unchanged. Neither `--force`, `--yes` nor background work approves a policy overwrite. If rule text is unavailable, match the publisher's rules manually. If Sessions opt-in differs, review that setting locally first. Select a dedicated rule file before adopting into a shared source. An omitted rule file is not a request to delete it. Rollback projects historical content through the current local rules; it does not adopt historical rules.
363
363
 
364
- If creation or transfer is blocked or interrupted, stop new work. Preserve the rule file, creation marker, journals, backups, and consent records. Use a compatible daemon to review recovery with the originating setup and exact source. If source or remote evidence differs, preserve it instead of forcing replay or deleting a marker. The old policy remains authoritative until settings commit; a verified starter or settings backup can remain after a failed save.
364
+ If adoption is interrupted, keep the local rules, backups and journals. Startup recovers an interrupted local file transaction before opening sync, without adopting rules or contacting the backend. If startup cannot verify the recovery evidence, do not edit the affected files; preserve the journals for review.
365
365
 
366
- After any version 6 publication, downgrading the package alone is not rollback. Close incompatible clients, verify daemon exit, and review compatible local and remote restoration before resuming transfers. Keep retained history intact.
366
+ Run `/sync pull` on the originating setup to review resumption. It uses the recorded, retained snapshot even if another device has since published a newer one. If that snapshot is missing or the local evidence no longer matches, preserve the journals and backups; do not replace them with the newer snapshot. After recovery, run `/sync status` to check the newer remote state. The successful transfer reports the backup path for the previous rule text.
367
+
368
+ After a version 6 or 7 publication, downgrading the package alone is not rollback. Close incompatible clients, verify daemon exit, and review compatible local and remote restoration before resuming transfers. Keep retained history intact.
367
369
 
368
370
  ### Agent-directory scope
369
371
 
@@ -785,7 +787,7 @@ Coupled fields must be excluded together.
785
787
  Selected-path setups with nonempty rules must include `settings.json` in `sync.include`. Directory-scope setups must omit `sync.include` and can configure local fields without it. Path rules still govern whether `settings.json` syncs, and nonempty field rules require that exact file spelling if it is synced. Absent or explicitly empty rules remain valid for either scope.
786
788
  Settings asks for confirmation before saving changes to these rules. An explicit array requires settings version 4 or later, and editing the rules does not downgrade an existing settings version.
787
789
  Absent rules keep a setup nonportable, including unrelated setups in a version-4 document.
788
- An explicit array opts that setup into at least snapshot version 2; exclusion-enabled selected-path setups retain version 4, legacy directory scope retains version 5, and ignore-file setups use version 6.
790
+ An explicit array opts that setup into at least snapshot version 2; exclusion-enabled selected-path setups retain version 4, legacy directory scope retains version 5, and ignore-file setups publish version 7.
789
791
  `[]` after rule removal retains this reviewed opt-in and differs from absence.
790
792
  Older clients must refuse portable data rather than replace local-only values.
791
793
 
@@ -825,7 +827,7 @@ Never reinterpret portable snapshots with an old binary.
825
827
  `sync.mergeContent` and `sync.partialSync` are independent opt-in booleans, both default `false`.
826
828
  The owning **Settings → Content merge / partial progress** setting offers Off, Merge only, Merge + partial, and Partial only and confirms an explicit upgrade to at least settings version 5.
827
829
  Use a supported settings version of at least 5 (at least 7 for legacy directory scope and 8 for ignore-file policy).
828
- Partial publications retain snapshot version 4 for exclusion-enabled selected paths, version 5 for legacy directory scope, and version 6 for ignore-file policy.
830
+ Partial publications retain snapshot version 4 for exclusion-enabled selected paths, version 5 for legacy directory scope, and version 7 for ignore-file policy.
829
831
  Settings version 5 retains the portable-policy behavior of version 4; moving from a legacy setup can require the existing separately confirmed directional policy migration.
830
832
  Disabling options retains the schema and recovery evidence.
831
833
 
@@ -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
+ }