@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
@@ -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,
@@ -1,4 +1,4 @@
1
- import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
1
+ import type { ExtensionCommandContext, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
2
  import { isKeyRelease, Key, matchesKey } from "@earendil-works/pi-tui";
3
3
  import { piDaemonClient } from "../daemon/pi-client.js";
4
4
  import { captureMutationOwner } from "../sync/sync-local.js";
@@ -8,18 +8,26 @@ import { safeTerminalText } from "./terminal-text.js";
8
8
 
9
9
  type IgnoreOperation = "switch" | "migrate";
10
10
 
11
- export async function ignoreFileSettingsAvailable(ctx: ExtensionCommandContext, signal?: AbortSignal) {
12
- if (signal?.aborted) return false;
11
+ async function ignoreCapabilities(ctx: ExtensionContext, signal?: AbortSignal) {
12
+ if (signal?.aborted) return;
13
13
  try {
14
14
  const client = piDaemonClient(ctx);
15
15
  const result = await client.run("ignore.capabilities", {}, signal, ctx);
16
16
  client.validate();
17
- return !signal?.aborted && (result as { available?: unknown } | undefined)?.available === true;
17
+ if (!signal?.aborted) return result as { available?: unknown; portableRules?: unknown } | undefined;
18
18
  } catch {
19
- return false;
19
+ return;
20
20
  }
21
21
  }
22
22
 
23
+ export async function ignoreFileSettingsAvailable(ctx: ExtensionCommandContext, signal?: AbortSignal) {
24
+ return (await ignoreCapabilities(ctx, signal))?.available === true;
25
+ }
26
+
27
+ export async function portableIgnoreRulesAvailable(ctx: ExtensionContext, signal?: AbortSignal) {
28
+ return (await ignoreCapabilities(ctx, signal))?.portableRules === 1;
29
+ }
30
+
23
31
  export async function showIgnoreFileAction(
24
32
  ctx: ExtensionCommandContext,
25
33
  setup: string,
@@ -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",
@@ -159,7 +159,12 @@ export async function describeManagerState(
159
159
  `Current sync setup: ${safeTerminalText(config.setupName)}`,
160
160
  `Storage: ${backendStorageDescription(config)}`,
161
161
  ...(config.pathPolicy === "ignore-file"
162
- ? [`Sync scope: Pi agent directory · ignore file: ${safeTerminalText(config.ignoreFile ?? ".syncignore")}`]
162
+ ? [
163
+ `Sync scope: Pi agent directory · ignore file: ${safeTerminalText(config.ignoreFile ?? ".syncignore")}`,
164
+ ...(config.ignorePolicy?.matches(config.ignorePolicy.filename) === false
165
+ ? ["New snapshots include this rule file and its comments in remote history."]
166
+ : []),
167
+ ]
163
168
  : config.scope
164
169
  ? ["Sync scope: Pi agent directory, with exclusions"]
165
170
  : []),
@@ -171,13 +176,15 @@ export async function describeManagerState(
171
176
  currentAttention.decision.setupName === config.setupName
172
177
  ? "Sync status: Review needed"
173
178
  : `Sync status: Review needed for setup ${safeTerminalText(currentAttention.decision.setupName)}`,
174
- attentionDirectoryPolicy
175
- ? "Sync scopes or directory rules differ."
176
- : attentionComparison?.remoteOnly.length === 0 && attentionComparison.localOnly.length === 0
177
- ? attentionExclusionsDiffer
178
- ? "Synced-content exclusion rules differ."
179
- : "Only the synced-content order differs."
180
- : `Remote-only paths: ${attentionComparison?.remoteOnly.length ?? 0} · Device-only paths: ${attentionComparison?.localOnly.length ?? 0}${attentionExclusionsDiffer ? " · Exclusion rules differ." : ""}`,
179
+ currentAttention.decision.ignorePolicyComparison
180
+ ? "Ignore-file policies differ."
181
+ : attentionDirectoryPolicy
182
+ ? "Sync scopes or directory rules differ."
183
+ : attentionComparison?.remoteOnly.length === 0 && attentionComparison.localOnly.length === 0
184
+ ? attentionExclusionsDiffer
185
+ ? "Synced-content exclusion rules differ."
186
+ : "Only the synced-content order differs."
187
+ : `Remote-only paths: ${attentionComparison?.remoteOnly.length ?? 0} · Device-only paths: ${attentionComparison?.localOnly.length ?? 0}${attentionExclusionsDiffer ? " · Exclusion rules differ." : ""}`,
181
188
  ]
182
189
  : currentObservation
183
190
  ? [`Observed ${safeTerminalText(currentObservation.checkedAt)}: ${observationSummary(currentObservation)}`]
@@ -67,6 +67,29 @@ export async function showSyncManager(
67
67
  interface State {
68
68
  manager: Awaited<ReturnType<typeof describeManagerState>>;
69
69
  }
70
+ const directionalAction = async (direction: "push" | "pull", state: State, signal: AbortSignal) => {
71
+ const review = state.manager.configReview;
72
+ if (!review) return { kind: "stay" as const };
73
+ const result = await runCancellableOperation(
74
+ ctx,
75
+ direction === "push" ? "Pushing to remote…" : "Pulling from remote…",
76
+ direction,
77
+ runRoute,
78
+ {
79
+ commitAware: true,
80
+ cancelledMessage: direction === "push" ? "Push cancellation requested." : "Pull cancellation requested.",
81
+ target: review.setupName,
82
+ directionalFingerprint: review.fingerprint,
83
+ signal,
84
+ isCurrent,
85
+ },
86
+ );
87
+ const done =
88
+ result.kind === "closed" ||
89
+ (result.kind === "completed" && result.outcome === "applied") ||
90
+ (result.kind === "failed" && options.needsDaemonRecovery?.());
91
+ return done ? { kind: "close" as const } : { kind: "stay" as const };
92
+ };
70
93
  const menuItems = (manager: State["manager"]) => {
71
94
  const attentionItems = attentionMainMenuItems(manager);
72
95
  const managerItems = manager.actions.map((label) => blockedSyncMenuItem(label, manager) ?? syncMainMenuItem(label));
@@ -195,26 +218,8 @@ export async function showSyncManager(
195
218
  const result = await showSyncSettings(ctx, runRoute, signal, review?.setupName);
196
219
  return { kind: result === "exit" ? "close" : "stay" };
197
220
  },
198
- pull: async ({ state }) => {
199
- const result = await runCancellableOperation(ctx, "Checking remote changes…", "pull", runRoute, {
200
- commitAware: true,
201
- cancelledMessage: "Pull check cancelled; no local files were changed.",
202
- target: state.manager.configReview?.setupName,
203
- signal: sessionSignal,
204
- });
205
- const disposition = await dispatchManagerResult(ctx, result, "pull", runRoute, sessionSignal);
206
- return disposition.kind === "close" ? { kind: "close" } : { kind: "stay" };
207
- },
208
- push: async ({ state }) => {
209
- const result = await runCancellableOperation(ctx, "Preparing push preview…", "push", runRoute, {
210
- commitAware: true,
211
- cancelledMessage: "Push preparation cancelled; no remote files were changed.",
212
- target: state.manager.configReview?.setupName,
213
- signal: sessionSignal,
214
- });
215
- const disposition = await dispatchManagerResult(ctx, result, "push", runRoute, sessionSignal);
216
- return disposition.kind === "close" ? { kind: "close" } : { kind: "stay" };
217
- },
221
+ pull: ({ state, signal }) => directionalAction("pull", state, signal),
222
+ push: ({ state, signal }) => directionalAction("push", state, signal),
218
223
  setups: async () => {
219
224
  const result = await showSyncSetupManager(ctx, runRoute, sessionSignal);
220
225
  return result === "exit" ? { kind: "close" } : { kind: "stay" };
@@ -456,8 +461,8 @@ function syncMainMenuItem(
456
461
  const actions = {
457
462
  "Sync now": "sync",
458
463
  "Retry refused model result…": "retry-refusal",
459
- "Pull from remote…": "pull",
460
- "Push to remote…": "push",
464
+ "Pull from remote": "pull",
465
+ "Push to remote": "push",
461
466
  "View differences": "diff",
462
467
  "Check remote status": "status",
463
468
  "Switch sync setup": "switch",
@@ -483,11 +488,11 @@ function syncMainMenuItem(
483
488
  description: {
484
489
  sync: "Merge changes on both sides.",
485
490
  "retry-refusal": "Retry model; may incur costs.",
486
- pull: "Remote → this device.",
487
- push: "This device → remote snapshot.",
491
+ pull: "Remote → this device; replaces conflicting local files.",
492
+ push: "This device → remote; replaces conflicting remote files.",
488
493
  diff: "Inspect changes; no transfer.",
489
494
  status: "Check remote; no transfer.",
490
- settings: "Change sync settings.",
495
+ settings: "Edit settings, setups, and storage connections.",
491
496
  history: "Review snapshots and rollback.",
492
497
  doctor: "Review backend diagnostics.",
493
498
  switch: "Choose another sync setup.",
@@ -37,9 +37,7 @@ export async function confirmMergeReview(
37
37
  ? compactLegacyTransferSummary(summary)
38
38
  : summary;
39
39
  while (isCurrent() && !signal?.aborted) {
40
- const allowApproval = content !== undefined;
41
- const lines = allowApproval ? summary : [...summary, "Open View details before approving."];
42
- const tuiLines = allowApproval ? tuiSummary : lines;
40
+ const allowApproval = ctx.mode === "tui" || content !== undefined;
43
41
  const choice: { value: "cancel" | "approve" | "details" } = { value: "cancel" };
44
42
  const menu = defineMenu<undefined, "confirm", "choose", ReviewContext>({
45
43
  start: "confirm",
@@ -47,7 +45,7 @@ export async function confirmMergeReview(
47
45
  confirm: () => ({
48
46
  kind: "choice",
49
47
  title,
50
- lines,
48
+ lines: allowApproval ? summary : [...summary, "Open View details before approving."],
51
49
  initialItemId: "cancel",
52
50
  items: [
53
51
  { id: "cancel", label: "No, cancel" },
@@ -71,9 +69,8 @@ export async function confirmMergeReview(
71
69
  create: ({ tui, theme, keybindings, complete }) =>
72
70
  createSyncConfirmation({
73
71
  title,
74
- lines: tuiLines,
72
+ lines: tuiSummary,
75
73
  confirmationLabel,
76
- allowApproval,
77
74
  tui,
78
75
  theme,
79
76
  keybindings,
@@ -91,11 +88,12 @@ export async function confirmMergeReview(
91
88
  if (result.kind === "completed") choice.value = result.value;
92
89
  else if (result.kind !== "closed") return false;
93
90
  // Keep authorization separate from UI termination in both adapters.
94
- if (choice.value === "approve") return allowApproval;
95
- if (choice.value !== "details") return false;
91
+ const approved = choice.value === "approve" && allowApproval;
92
+ if (!approved && choice.value !== "details") return false;
96
93
  if (content === undefined && typeof details === "function") {
97
94
  try {
98
- const loaded = await runCancellableTask(ctx, "Loading exact sync details…", details, {
95
+ const message = approved ? "Verifying sync transfer…" : "Loading exact sync details…";
96
+ const loaded = await runCancellableTask(ctx, message, details, {
99
97
  signal,
100
98
  isCurrent,
101
99
  cancelledMessage: null,
@@ -108,6 +106,7 @@ export async function confirmMergeReview(
108
106
  }
109
107
  }
110
108
  if (content === undefined) return false;
109
+ if (approved) return true;
111
110
  const detail = await runDocumentReview(ctx, {
112
111
  title: "Sync change details",
113
112
  content,
@@ -179,12 +179,19 @@ async function showSelectionDifference(
179
179
  validateOwner: () => void,
180
180
  ): Promise<DifferenceFlowResult> {
181
181
  type Screen = "choice" | "review" | "saved";
182
- type Action = "adopt" | "keep" | "cancel" | "continue" | "done";
182
+ type Action = "adopt" | "keep" | "pull-rules" | "cancel" | "continue" | "done";
183
183
  interface FlowState {
184
184
  decision: RemoteSelectionDecision;
185
185
  saved: boolean;
186
186
  }
187
187
  const isCurrent = () => isReviewOwnerCurrent(validateOwner);
188
+ const canReviewPull = Boolean(
189
+ runRoute &&
190
+ !options.readOnly &&
191
+ initialDecision.ignorePolicyComparison === "mismatch" &&
192
+ (await (await import("./ignore-file-ui.js")).portableIgnoreRulesAvailable(ctx, sessionSignal)),
193
+ );
194
+ if (!isCurrent()) return { kind: "stale" };
188
195
  let flowState: FlowState = { decision: initialDecision, saved: false };
189
196
  let continuationFingerprint: string | undefined;
190
197
  let nextResult: RemoteSelectionReviewResult | undefined;
@@ -218,6 +225,16 @@ async function showSelectionDifference(
218
225
  action: "adopt" as const,
219
226
  },
220
227
  ]),
228
+ ...(canReviewPull
229
+ ? [
230
+ {
231
+ id: "pull-rules",
232
+ label: "Review pulling the remote rules…",
233
+ description: "Preview overwriting this device's rules and files if the snapshot includes rules.",
234
+ action: "pull-rules" as const,
235
+ },
236
+ ]
237
+ : []),
221
238
  ...(options.readOnly || !canPublishLocalPolicy(state.decision)
222
239
  ? []
223
240
  : [
@@ -358,6 +375,30 @@ async function showSelectionDifference(
358
375
  return { kind: "stay" as const };
359
376
  }
360
377
  },
378
+ "pull-rules": async ({ state, signal: actionSignal }) => {
379
+ if (!canReviewPull || !runRoute) return { kind: "rejected" };
380
+ const signal = combineSignals(sessionSignal, actionSignal);
381
+ try {
382
+ const latest = await loadConfig(state.decision.setupName);
383
+ if (signal.aborted) return { kind: "close" };
384
+ validateOwner();
385
+ if (syncConfigReviewFingerprint(latest) !== state.decision.configIdentity) {
386
+ refreshRequested = true;
387
+ return { kind: "close" };
388
+ }
389
+ const result = await runCancellableOperation(ctx, "Preparing remote policy preview…", "pull", runRoute, {
390
+ commitAware: true,
391
+ cancelAcrossDialogs: true,
392
+ target: state.decision.setupName,
393
+ signal,
394
+ });
395
+ return handleNestedRouteResult(result, "pull");
396
+ } catch (error) {
397
+ if (signal.aborted || !isCurrent()) return { kind: "close" };
398
+ ctx.ui.notify(`Could not prepare the local update: ${errorMessage(error)}`, "error");
399
+ return { kind: "stay" };
400
+ }
401
+ },
361
402
  keep: async ({ state, signal: actionSignal }) => {
362
403
  if (options.readOnly) return { kind: "rejected" };
363
404
  if (!canPublishLocalPolicy(state.decision)) return { kind: "stay" as const };
@@ -681,7 +722,7 @@ function canPublishLocalPolicy(decision: RemoteSelectionDecision) {
681
722
 
682
723
  function adoptionUnavailable(decision: RemoteSelectionDecision) {
683
724
  if (decision.ignorePolicyComparison)
684
- return "Ignore files are local. Published metadata cannot reconstruct remote rules.";
725
+ return "A policy comparison does not apply rules. A reviewed Pull can use a snapshot that contains rule text.";
685
726
  if (scopesDiffer(decision))
686
727
  return "Scope differs. Configure a setup with the remote scope to join it; this location is not migrated in place.";
687
728
  if (