@narumitw/pi-sync 0.60.4 → 0.61.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 (88) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/README.md +14 -6
  3. package/dist/chunks/chunk-2JHAN3ZO.ts +139 -0
  4. package/dist/chunks/chunk-2JHAN3ZO.ts.map +7 -0
  5. package/dist/chunks/chunk-2ZGV5KNC.ts +274 -0
  6. package/dist/chunks/chunk-2ZGV5KNC.ts.map +7 -0
  7. package/dist/chunks/{chunk-LAXTCSX4.ts → chunk-4KTJLJSJ.ts} +117 -132
  8. package/dist/chunks/chunk-4KTJLJSJ.ts.map +7 -0
  9. package/dist/chunks/chunk-4SR3ZYHA.ts +14 -0
  10. package/dist/chunks/chunk-4SR3ZYHA.ts.map +7 -0
  11. package/dist/chunks/{chunk-VQRDL3SY.ts → chunk-E3YLRLJM.ts} +155 -27
  12. package/dist/chunks/chunk-E3YLRLJM.ts.map +7 -0
  13. package/dist/chunks/{chunk-KPWZNMKM.ts → chunk-ECYCNZOE.ts} +1 -5
  14. package/dist/chunks/chunk-ECYCNZOE.ts.map +7 -0
  15. package/dist/chunks/{chunk-IGDI5CIH.ts → chunk-EMVZL4PH.ts} +2 -2
  16. package/dist/chunks/{chunk-OVCP2SOB.ts → chunk-H7VOTY5N.ts} +21 -8
  17. package/dist/chunks/chunk-H7VOTY5N.ts.map +7 -0
  18. package/dist/chunks/{chunk-SE7HHBKH.ts → chunk-JVFCVPPD.ts} +105 -51
  19. package/dist/chunks/chunk-JVFCVPPD.ts.map +7 -0
  20. package/dist/chunks/{chunk-MCUZFUHY.ts → chunk-PJMM75W5.ts} +6 -6
  21. package/dist/chunks/{chunk-RJZIKZI3.ts → chunk-S7F4FOAS.ts} +11 -6
  22. package/dist/chunks/chunk-S7F4FOAS.ts.map +7 -0
  23. package/dist/chunks/{chunk-6W2SNZ5P.ts → chunk-YQSFJLJ3.ts} +6 -2
  24. package/dist/chunks/{chunk-6W2SNZ5P.ts.map → chunk-YQSFJLJ3.ts.map} +3 -3
  25. package/dist/chunks/{chunk-V4AMI3VL.ts → chunk-ZVGRZD4C.ts} +9 -1
  26. package/dist/chunks/chunk-ZVGRZD4C.ts.map +7 -0
  27. package/dist/chunks/{command-handler-TMH4US44.ts → command-handler-K4XJOGYC.ts} +41 -37
  28. package/dist/chunks/{command-handler-TMH4US44.ts.map → command-handler-K4XJOGYC.ts.map} +2 -2
  29. package/dist/chunks/{conflict-review-QGUCODDH.ts → conflict-review-IGKY2TOJ.ts} +4 -4
  30. package/dist/chunks/{file-selection-DD6X4J2K.ts → file-selection-MGGVOKM7.ts} +26 -13
  31. package/dist/chunks/file-selection-MGGVOKM7.ts.map +7 -0
  32. package/dist/chunks/{manager-result-dispatcher-YVVD44QD.ts → manager-result-dispatcher-4VJVDEUD.ts} +8 -7
  33. package/dist/chunks/{manager-ui-Q54OHOPR.ts → manager-ui-KYQ5AZJS.ts} +134 -203
  34. package/dist/chunks/manager-ui-KYQ5AZJS.ts.map +7 -0
  35. package/dist/chunks/{remote-selection-ui-ODSUHX5N.ts → remote-selection-ui-W3KOZM3W.ts} +7 -6
  36. package/dist/chunks/{setup-switch-SPZE7HIQ.ts → setup-switch-D6K6PBPC.ts} +3 -3
  37. package/dist/chunks/{setup-wizard-5JYKAEIT.ts → setup-wizard-4DYUDHJR.ts} +13 -11
  38. package/dist/chunks/setup-wizard-4DYUDHJR.ts.map +7 -0
  39. package/dist/chunks/{sync-inspection-ECUTWISE.ts → sync-inspection-J3CRBORL.ts} +6 -6
  40. package/dist/chunks/{sync-operations-REXODWZB.ts → sync-operations-BVWYYKH3.ts} +4 -4
  41. package/dist/index.ts +28 -24
  42. package/dist/index.ts.map +2 -2
  43. package/docs/daemon-migration.md +6 -0
  44. package/package.json +4 -4
  45. package/skills/configure-pi-sync/references/configuration.md +59 -32
  46. package/src/commands/command-execution.ts +7 -1
  47. package/src/daemon/pi-client.ts +79 -22
  48. package/src/daemon/queue-release-ui.ts +88 -0
  49. package/src/sync/sync-policy.ts +5 -0
  50. package/src/sync-extension.ts +6 -2
  51. package/src/ui/agent-mode-setting.ts +9 -1
  52. package/src/ui/excluded-paths-ui.ts +154 -2
  53. package/src/ui/file-selection.ts +12 -7
  54. package/src/ui/manager-state.ts +13 -8
  55. package/src/ui/remote-selection-ui.ts +120 -27
  56. package/src/ui/settings-frame.ts +2 -8
  57. package/src/ui/settings-ui.ts +51 -26
  58. package/src/ui/setup/directory-rules.ts +81 -0
  59. package/src/ui/setup/git-ui.ts +14 -24
  60. package/src/ui/setup/s3-ui.ts +13 -26
  61. package/src/ui/setup/setup-actions.ts +0 -4
  62. package/src/ui/setup/setup-prompts.ts +99 -17
  63. package/src/ui/setup/setup-switcher.ts +4 -2
  64. package/src/ui/setup/setup-wizard.ts +5 -4
  65. package/src/ui/setup/webdav-ui.ts +13 -27
  66. package/src/ui/storage-connections-ui.ts +2 -2
  67. package/src/ui/sync-attention.ts +8 -3
  68. package/src/ui/sync-format.ts +8 -1
  69. package/src/ui/sync-setups-ui.ts +5 -3
  70. package/src/ui/sync-status.ts +27 -7
  71. package/dist/chunks/chunk-KPWZNMKM.ts.map +0 -7
  72. package/dist/chunks/chunk-LAXTCSX4.ts.map +0 -7
  73. package/dist/chunks/chunk-OVCP2SOB.ts.map +0 -7
  74. package/dist/chunks/chunk-RJZIKZI3.ts.map +0 -7
  75. package/dist/chunks/chunk-SE7HHBKH.ts.map +0 -7
  76. package/dist/chunks/chunk-V4AMI3VL.ts.map +0 -7
  77. package/dist/chunks/chunk-VQRDL3SY.ts.map +0 -7
  78. package/dist/chunks/file-selection-DD6X4J2K.ts.map +0 -7
  79. package/dist/chunks/manager-ui-Q54OHOPR.ts.map +0 -7
  80. package/dist/chunks/setup-wizard-5JYKAEIT.ts.map +0 -7
  81. /package/dist/chunks/{chunk-IGDI5CIH.ts.map → chunk-EMVZL4PH.ts.map} +0 -0
  82. /package/dist/chunks/{chunk-MCUZFUHY.ts.map → chunk-PJMM75W5.ts.map} +0 -0
  83. /package/dist/chunks/{conflict-review-QGUCODDH.ts.map → conflict-review-IGKY2TOJ.ts.map} +0 -0
  84. /package/dist/chunks/{manager-result-dispatcher-YVVD44QD.ts.map → manager-result-dispatcher-4VJVDEUD.ts.map} +0 -0
  85. /package/dist/chunks/{remote-selection-ui-ODSUHX5N.ts.map → remote-selection-ui-W3KOZM3W.ts.map} +0 -0
  86. /package/dist/chunks/{setup-switch-SPZE7HIQ.ts.map → setup-switch-D6K6PBPC.ts.map} +0 -0
  87. /package/dist/chunks/{sync-inspection-ECUTWISE.ts.map → sync-inspection-J3CRBORL.ts.map} +0 -0
  88. /package/dist/chunks/{sync-operations-REXODWZB.ts.map → sync-operations-BVWYYKH3.ts.map} +0 -0
@@ -30,9 +30,15 @@ import type { CommandOptions } from "../commands/command-types.js";
30
30
  import type { StartupTimingPublisher } from "../sync/startup-timings.js";
31
31
  import { errorMessage, SyncDecisionRequiredError } from "../sync/sync-errors.js";
32
32
  import { RemoteSelectionMismatchError } from "../sync/sync-policy.js";
33
- import { type SyncStatusPresentation, setSyncStatus, showSyncConnectionStatus } from "../ui/sync-status.js";
33
+ import {
34
+ type SyncStatusPresentation,
35
+ setSyncStatus,
36
+ showSyncConnectionStatus,
37
+ showSyncQueueReleaseRecovery,
38
+ } from "../ui/sync-status.js";
34
39
  import { safeTerminalText } from "../ui/terminal-text.js";
35
40
  import { PiApplyGate } from "./apply-gate.js";
41
+ import { createQueueReleaseUI, type QueueReleaseEvent } from "./queue-release-ui.js";
36
42
  import { quarantineClient, recoverDetachedClients } from "./recovery.js";
37
43
 
38
44
  const scope = new AsyncLocalStorage<{ client: PiDaemonClient; reload?: AbortController }>();
@@ -104,6 +110,7 @@ const authority: ConfigAuthority = {
104
110
  const document = await client.readSettings(true);
105
111
  client.validate();
106
112
  signal?.throwIfAborted();
113
+ if (document) validate(document.parsed);
107
114
  const next = update(structuredClone(document?.parsed ?? fallback) as T);
108
115
  validate(next);
109
116
  await client.run("settings.cas", { expected: fingerprint(document), next }, signal);
@@ -228,7 +235,25 @@ export class PiDaemonClient {
228
235
  private contactRepair?: { controller: AbortController; done: Promise<void> };
229
236
  private contactAttempt?: { error?: unknown };
230
237
  private contactFactsUnpublished = false;
231
- private clearContactStatus?: (redraw?: boolean) => void;
238
+ private contactStatus?: { clear(redraw?: boolean): void; unavailable: boolean };
239
+ private releaseUIEnabled = true;
240
+ private runSignal?: AbortSignal;
241
+ private readonly releaseUI = createQueueReleaseUI(
242
+ () => {
243
+ const ctx = this.releaseContext();
244
+ if (ctx) return showSyncQueueReleaseRecovery(ctx);
245
+ },
246
+ () =>
247
+ this.releaseContext()?.ui.notify(
248
+ "Pi Sync could not confirm the file write queue release. Sync may be paused; check /sync daemon status before retrying.",
249
+ "warning",
250
+ ),
251
+ );
252
+ private readonly stopReleaseUI = () => {
253
+ // Withdraw while the SDK owner is still active, but never redraw through a replaced context.
254
+ this.releaseUIEnabled = false;
255
+ this.releaseUI.clear(Boolean(this.releaseContext(true)));
256
+ };
232
257
  private disposed = false;
233
258
  private disposing?: Promise<void>;
234
259
  private uiContext: ExtensionContext;
@@ -260,6 +285,7 @@ export class PiDaemonClient {
260
285
  if (!root) throw new Error("Agent directory is unavailable.");
261
286
  this.root = root;
262
287
  this.gate = new PiApplyGate(() => this.validate());
288
+ this.signal.addEventListener("abort", this.stopReleaseUI, { once: true });
263
289
  }
264
290
  validate() {
265
291
  this.signal.throwIfAborted();
@@ -314,6 +340,7 @@ export class PiDaemonClient {
314
340
  async pauseForSessionChange() {
315
341
  this.validate();
316
342
  this.paused = true;
343
+ this.stopReleaseUI();
317
344
  this.stopContactRepair(true);
318
345
  this.gate.cancelPending();
319
346
  this.pausing ??= (async () => {
@@ -429,8 +456,10 @@ export class PiDaemonClient {
429
456
  );
430
457
  },
431
458
  contact: (state) => this.observeContact(connection, state),
459
+ queueRelease: (event) => this.observeQueueRelease(connection, event),
432
460
  error: () => {
433
- if (this.ownsContactUI()) this.showContactStatus("sync service unavailable", "blocked");
461
+ if (this.ownsContactUI() && connection.facts.hasUI && !this.releaseUI.retrying)
462
+ this.showContactStatus("sync service unavailable", "blocked", true);
434
463
  },
435
464
  });
436
465
  this.partialConnection = connection;
@@ -475,18 +504,40 @@ export class PiDaemonClient {
475
504
  !this.signal.aborted && !this.disposed && !this.closing && !this.paused && clients.get(this.manager) === this
476
505
  );
477
506
  }
478
- private showContactStatus(text: string, activity: "retry" | "blocked") {
479
- const previous = this.clearContactStatus;
480
- this.clearContactStatus = showSyncConnectionStatus(this.ctx, text, {
481
- activity,
482
- reason: activity === "retry" ? "temp" : "repair",
483
- });
484
- previous?.();
507
+ private releaseContext(cleanup = false) {
508
+ if (clients.get(this.manager) !== this) return;
509
+ if (!cleanup && (!this.releaseUIEnabled || !this.ownsContactUI() || this.busy.has("shutdown"))) return;
510
+ try {
511
+ this.ctx.isIdle(); // Also verifies the SDK context has not been retired.
512
+ if (this.ctx.hasUI && (this.ctx.mode === "tui" || this.ctx.mode === "rpc")) return this.ctx;
513
+ } catch {
514
+ // Detached cleanup can outlive its UI.
515
+ }
516
+ }
517
+ disableQueueReleaseUI() {
518
+ this.stopReleaseUI();
519
+ }
520
+ private observeQueueRelease(connection: DaemonConnection, event: QueueReleaseEvent) {
521
+ if (connection !== this.connection || !connection.facts.hasUI || !this.releaseContext()) return;
522
+ if (event.state === "retrying" && this.contactStatus?.unavailable) this.clearConnectionStatus();
523
+ this.releaseUI.observe(event, this.busy.has("command"), !this.runSignal || this.runSignal.aborted);
524
+ }
525
+ private showContactStatus(text: string, activity: "retry" | "blocked", unavailable = false) {
526
+ const previous = this.contactStatus;
527
+ this.contactStatus = {
528
+ clear: showSyncConnectionStatus(this.ctx, text, { activity, reason: activity === "retry" ? "temp" : "repair" }),
529
+ unavailable,
530
+ };
531
+ previous?.clear();
532
+ }
533
+ private clearConnectionStatus(redraw = true) {
534
+ const status = this.contactStatus;
535
+ this.contactStatus = undefined;
536
+ status?.clear(redraw);
485
537
  }
486
538
  private stopContactRepair(redraw: boolean) {
487
539
  this.contactRepair?.controller.abort(new DOMException("Pi session is changing", "AbortError"));
488
- this.clearContactStatus?.(redraw);
489
- this.clearContactStatus = undefined;
540
+ this.clearConnectionStatus(redraw);
490
541
  }
491
542
  private observeContact(connection: DaemonConnection, state: ContactState) {
492
543
  if (connection !== this.connection || !this.ownsContactUI()) return;
@@ -494,7 +545,7 @@ export class PiDaemonClient {
494
545
  if (this.contactRepair || this.contactFactsUnpublished || connection.contactResumeState === "uncertain") return;
495
546
  this.clearRestoredContact();
496
547
  } else if (state === "expired" && connection.facts.hasUI && !this.contactAttempt && !this.contactRepair) {
497
- if (this.gate.size || connection.hasPendingWork) return;
548
+ if (this.gate.size || connection.hasPendingWork || this.releaseUI.retrying) return;
498
549
  void this.resumeContact(connection).catch(() => {
499
550
  // The owning repair updates the status; a later command reports the error.
500
551
  });
@@ -503,8 +554,7 @@ export class PiDaemonClient {
503
554
  private clearRestoredContact() {
504
555
  this.contactAttempt = undefined;
505
556
  this.contactFactsUnpublished = false;
506
- this.clearContactStatus?.();
507
- this.clearContactStatus = undefined;
557
+ this.clearConnectionStatus();
508
558
  }
509
559
  private async resumeContact(connection: DaemonConnection) {
510
560
  this.validate();
@@ -642,13 +692,12 @@ export class PiDaemonClient {
642
692
  // The daemon directs reload only to the submitting client, and run() serializes its jobs.
643
693
  const request = reload ? { received: false } : undefined;
644
694
  this.reloadRequest = request;
695
+ const runSignal = signal ? AbortSignal.any([signal, this.signal]) : this.signal;
696
+ this.runSignal = runSignal;
697
+ const clearForeground = () => this.releaseUI.finishForeground(Boolean(this.releaseContext()));
698
+ runSignal.addEventListener("abort", clearForeground, { once: true });
645
699
  try {
646
- const result = await connection.run(
647
- operation,
648
- payload,
649
- signal ? AbortSignal.any([signal, this.signal]) : this.signal,
650
- onCommit,
651
- );
700
+ const result = await connection.run(operation, payload, runSignal, onCommit);
652
701
  if (request?.received && reload && !this.paused && !reload.signal.aborted && !signal?.aborted) {
653
702
  this.validate();
654
703
  this.pendingReload = reload;
@@ -673,6 +722,9 @@ export class PiDaemonClient {
673
722
  }
674
723
  throw error;
675
724
  } finally {
725
+ runSignal.removeEventListener("abort", clearForeground);
726
+ clearForeground();
727
+ this.runSignal = undefined;
676
728
  this.uiContext = this.ctx;
677
729
  this.reloadRequest = undefined;
678
730
  }
@@ -695,7 +747,10 @@ export class PiDaemonClient {
695
747
  async setBusy(reason: string, busy: boolean, publish = true) {
696
748
  this.validate();
697
749
  if (busy) this.busy.add(reason);
698
- else this.busy.delete(reason);
750
+ else if (this.busy.delete(reason) && reason === "command") {
751
+ // Local command completion does not depend on publishing idle facts.
752
+ this.releaseUI.flushWarnings();
753
+ }
699
754
  if (publish) await this.update();
700
755
  this.validate();
701
756
  }
@@ -807,6 +862,8 @@ export class PiDaemonClient {
807
862
  async dispose(handoff?: ClientHandoff) {
808
863
  if (this.disposing) return this.disposing;
809
864
  this.closing = true;
865
+ this.signal.removeEventListener("abort", this.stopReleaseUI);
866
+ this.stopReleaseUI();
810
867
  this.stopContactRepair(false);
811
868
  this.disposing = (async () => {
812
869
  const connection = this.connection ?? this.partialConnection ?? (await this.connecting?.catch(() => undefined));
@@ -0,0 +1,88 @@
1
+ import type { ConnectionOptions } from "@narumitw/pi-sync-daemon";
2
+
3
+ export type QueueReleaseEvent = Parameters<NonNullable<ConnectionOptions["queueRelease"]>>[0];
4
+ type ClearStatus = (redraw?: boolean) => void;
5
+
6
+ /** Session-owned presentation only; it neither controls delivery nor infers a job's outcome. */
7
+ export function createQueueReleaseUI(show: () => ClearStatus | undefined, warn: () => void) {
8
+ const retries = new Map<string, { job: string; foreground: boolean }>();
9
+ const handledJobs = new Set<string>();
10
+ const deferredWarnings = new Set<string>();
11
+ let timer: ReturnType<typeof setTimeout> | undefined;
12
+ let clearStatus: ClearStatus | undefined;
13
+
14
+ function remember(job: string) {
15
+ deferredWarnings.delete(job);
16
+ if (handledJobs.has(job)) return false;
17
+ if (handledJobs.size >= 128) {
18
+ const oldest = handledJobs.values().next();
19
+ if (!oldest.done) handledJobs.delete(oldest.value);
20
+ }
21
+ handledJobs.add(job);
22
+ return true;
23
+ }
24
+ function clearPresentation(redraw: boolean) {
25
+ clearTimeout(timer);
26
+ timer = undefined;
27
+ const release = clearStatus;
28
+ clearStatus = undefined;
29
+ release?.(redraw);
30
+ }
31
+
32
+ return {
33
+ get retrying() {
34
+ return retries.size > 0;
35
+ },
36
+ observe({ id, job, state, foreground }: QueueReleaseEvent, commandBusy: boolean, cancelled: boolean) {
37
+ if (state === "retrying") {
38
+ if (foreground && cancelled) {
39
+ remember(job);
40
+ return;
41
+ }
42
+ if (retries.has(id)) return;
43
+ retries.set(id, { job, foreground });
44
+ if (retries.size !== 1) return;
45
+ timer = setTimeout(() => {
46
+ timer = undefined;
47
+ const release = show();
48
+ if (retries.size) clearStatus = release;
49
+ else release?.(false); // Presentation may have synchronously reentered lifecycle cleanup.
50
+ }, 2_000);
51
+ timer.unref?.();
52
+ return;
53
+ }
54
+ const retry = retries.get(id);
55
+ retries.delete(id);
56
+ if (!retries.size) clearPresentation(true);
57
+ if (state !== "unconfirmed") return;
58
+ const background = !foreground && !retry?.foreground;
59
+ if (background && commandBusy) {
60
+ if (!handledJobs.has(job)) deferredWarnings.add(job);
61
+ } else if (remember(job) && background) warn();
62
+ },
63
+ flushWarnings() {
64
+ if (!deferredWarnings.size) return;
65
+ // One warning covers the background releases deferred by this command.
66
+ for (const job of deferredWarnings) remember(job);
67
+ try {
68
+ warn();
69
+ } catch {
70
+ // Presentation must not interrupt publication of the new idle state.
71
+ }
72
+ },
73
+ finishForeground(redraw: boolean) {
74
+ for (const [id, { job, foreground }] of retries) {
75
+ if (!foreground) continue;
76
+ retries.delete(id);
77
+ remember(job); // Late observations of this job should not duplicate its command result.
78
+ }
79
+ if (!retries.size) clearPresentation(redraw);
80
+ },
81
+ clear(redraw: boolean) {
82
+ retries.clear();
83
+ handledJobs.clear();
84
+ deferredWarnings.clear();
85
+ clearPresentation(redraw);
86
+ },
87
+ };
88
+ }
@@ -3,6 +3,8 @@ export {
3
3
  BUILT_IN_SYNC_ROOTS,
4
4
  canonicalSnapshotPathForConfig,
5
5
  compareSyncInclude,
6
+ compileSyncPolicyExclude,
7
+ compileSyncPolicyTraversal,
6
8
  configuredSnapshotPathMatcher,
7
9
  customIncludePathsByLower,
8
10
  DEFAULT_SYNC_INCLUDE,
@@ -16,6 +18,7 @@ export {
16
18
  isPreservableUnmanagedSnapshotPath,
17
19
  isSafeCustomIncludePath,
18
20
  isSafeExtraFileName,
21
+ normalizeDirectoryRules,
19
22
  normalizeExtraFiles,
20
23
  normalizeSyncFiles,
21
24
  normalizeSyncInclude,
@@ -28,7 +31,9 @@ export {
28
31
  selectionForSnapshot,
29
32
  snapshotSelectionExclude,
30
33
  snapshotSelectionInclude,
34
+ syncDirectoryPolicyKey,
31
35
  syncIncludeSelection,
36
+ syncSelectionHasContent,
32
37
  syncSessionsSelected,
33
38
  validateSnapshotSelection,
34
39
  } from "@narumitw/pi-sync-daemon/engine/sync/sync-policy";
@@ -111,11 +111,11 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
111
111
  },
112
112
  });
113
113
  pi.on("session_start", async (_event, ctx) => {
114
- const releaseStatus = status.start(ctx);
115
114
  const previousClient = owner;
116
115
  shutdownAbort?.abort(new DOMException("Session replaced", "AbortError"));
117
116
  shutdownAbort = undefined;
118
117
  sessionAbort.abort(new DOMException("Session replaced", "AbortError"));
118
+ const releaseStatus = status.start(ctx);
119
119
  sessionAbort = new AbortController();
120
120
  const signal = sessionAbort.signal;
121
121
  const client = bindPiDaemonClient(ctx, signal, publishTimings);
@@ -160,7 +160,10 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
160
160
  });
161
161
  try {
162
162
  const ready = await initialization;
163
- if (ready === false) releaseStatus();
163
+ if (ready === false) {
164
+ client.disableQueueReleaseUI();
165
+ releaseStatus();
166
+ }
164
167
  if (
165
168
  ready &&
166
169
  !signal.aborted &&
@@ -172,6 +175,7 @@ export default function sync(pi: ExtensionAPI, dependencies: Partial<SyncDepende
172
175
  check.start(ctx, signal, ready);
173
176
  });
174
177
  } catch (error) {
178
+ client.disableQueueReleaseUI();
175
179
  releaseStatus();
176
180
  throw error;
177
181
  }
@@ -3,6 +3,7 @@ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
3
3
  import { requireSettings, updateLocalConfig } from "../settings/settings-store.js";
4
4
  import { captureMutationOwner } from "../sync/sync-local.js";
5
5
  import { confirmMergeReview } from "./merge-review.js";
6
+ import { directorySessionOptInLine } from "./setup/directory-rules.js";
6
7
  import { safeTerminalText } from "./terminal-text.js";
7
8
 
8
9
  export const AGENT_MODE_DESCRIPTION =
@@ -43,7 +44,14 @@ export async function saveAgentMode(
43
44
  `Storage path: ${safeTerminalText(setup.storage.path)}`,
44
45
  ...(setup.storage.bucket ? [`Bucket: ${safeTerminalText(String(setup.storage.bucket))}`] : []),
45
46
  ...(setup.storage.branch ? [`Branch: ${safeTerminalText(String(setup.storage.branch))}`] : []),
46
- `Included paths: ${setup.sync.include.map(safeTerminalText).join(", ")}`,
47
+ ...(setup.sync.scope
48
+ ? [
49
+ "Sync scope: all eligible files in the Pi agent directory.",
50
+ directorySessionOptInLine(setup.sync.sessions),
51
+ `Excluded paths: ${setup.sync.exclude?.map(safeTerminalText).join(", ") || "none"}`,
52
+ `Re-included paths: ${setup.sync.reinclude?.map(safeTerminalText).join(", ") || "none"}`,
53
+ ]
54
+ : [`Included paths: ${setup.sync.include.map(safeTerminalText).join(", ")}`]),
47
55
  continuous ? CONTINUOUS_DESCRIPTION : AGENT_MODE_DESCRIPTION,
48
56
  ...(continuous
49
57
  ? [
@@ -3,8 +3,18 @@ import { defineMenu, runMenu } from "@narumitw/pi-tui-kit";
3
3
  import { loadConfig, syncCheckConfigFingerprint } from "../settings/config.js";
4
4
  import { localConfigPath } from "../settings/config-file.js";
5
5
  import { updateSyncSetup } from "../settings/settings-management.js";
6
+ import type { AnySyncConfig } from "../settings/settings-types.js";
6
7
  import { normalizeSyncExclude, sameSyncExclude } from "../sync/exclude-policy.js";
7
8
  import { captureMutationOwner } from "../sync/sync-local.js";
9
+ import {
10
+ acknowledgeSessions,
11
+ type DirectoryRulesDraft,
12
+ directoryScopeLines,
13
+ formatDirectoryRules,
14
+ promptDirectoryRules,
15
+ summarizeDirectoryRules,
16
+ } from "./setup/directory-rules.js";
17
+ import { saveReviewedDraft } from "./setup/setup-review.js";
8
18
  import { safeTerminalText } from "./terminal-text.js";
9
19
 
10
20
  /** Transactional draft; Pi owns editor input/paste and Kit owns review/cancellation. */
@@ -21,12 +31,13 @@ export async function showExcludedPaths(ctx: ExtensionCommandContext, setupName:
21
31
  validate();
22
32
  const config = await loadConfig(setupName);
23
33
  validate();
34
+ if (config.scope === "agent-directory") return showDirectoryScope(ctx, config, signal);
24
35
  if (ctx.mode !== "tui") {
25
36
  if (ctx.hasUI)
26
37
  ctx.ui.notify(
27
38
  [
28
39
  `Excluded paths: ${(config.exclude ?? []).map(safeTerminalText).join(", ") || "none"}`,
29
- `Edit sync.exclude in ${safeTerminalText(localConfigPath())}; an explicit array requires settings version 6.`,
40
+ `Edit sync.exclude in ${safeTerminalText(localConfigPath())}; an explicit array requires settings version 6 or later.`,
30
41
  ].join("\n"),
31
42
  "info",
32
43
  );
@@ -57,7 +68,7 @@ export async function showExcludedPaths(ctx: ExtensionCommandContext, setupName:
57
68
  title: "Review excluded paths",
58
69
  lines: [
59
70
  `Setup: ${safeTerminalText(config.setupName)}`,
60
- "Draft only. Save opts into settings version 6 / snapshot version 4; older clients must refuse them.",
71
+ "Draft only. Save requires at least settings version 6 and uses snapshot version 4 for this allowlist setup.",
61
72
  "Excluded local files stay untouched. New snapshots omit matching remote files; old history is NOT erased.",
62
73
  "Removing rules can expose local content or allow pull to replace it. Review a force push to publish policy changes.",
63
74
  "Previously excluded:",
@@ -104,3 +115,144 @@ export async function showExcludedPaths(ctx: ExtensionCommandContext, setupName:
104
115
  return;
105
116
  }
106
117
  }
118
+
119
+ export function directoryScopeSummary(config: AnySyncConfig) {
120
+ return [
121
+ `Setup: ${safeTerminalText(config.setupName)} · Scope: Pi agent directory`,
122
+ `Excluded paths: ${summarizeDirectoryRules(config.exclude)}`,
123
+ `Re-included paths: ${summarizeDirectoryRules(config.reinclude)}`,
124
+ `Session opt-in: ${config.include.includes("sessions") ? "On (path rules still apply)" : "Off"}`,
125
+ "Pi credentials and project trust always stay local.",
126
+ ];
127
+ }
128
+
129
+ export async function showDirectoryScope(ctx: ExtensionCommandContext, config: AnySyncConfig, signal?: AbortSignal) {
130
+ const validate = captureMutationOwner(ctx, signal);
131
+ const isCurrent = () => {
132
+ try {
133
+ validate();
134
+ return true;
135
+ } catch {
136
+ return false;
137
+ }
138
+ };
139
+ if (!isCurrent()) return;
140
+ if (ctx.mode !== "tui") {
141
+ if (ctx.hasUI)
142
+ ctx.ui.notify(
143
+ [
144
+ ...directoryScopeSummary(config),
145
+ `Edit sync.exclude, sync.reinclude, and sync.sessions in ${safeTerminalText(localConfigPath())}.`,
146
+ ].join("\n"),
147
+ "info",
148
+ );
149
+ return;
150
+ }
151
+ const original: DirectoryRulesDraft = {
152
+ exclude: config.exclude ?? [],
153
+ reinclude: config.reinclude ?? [],
154
+ sessions: config.include.includes("sessions"),
155
+ };
156
+ const draft: DirectoryRulesDraft = { ...original };
157
+ const change = () => ({
158
+ exclude: !sameSyncExclude(draft.exclude, original.exclude),
159
+ reinclude: !sameSyncExclude(draft.reinclude, original.reinclude),
160
+ sessions: draft.sessions !== original.sessions,
161
+ });
162
+ const menu = defineMenu<undefined, "draft", "exclude" | "reinclude" | "sessions" | "review", ExtensionCommandContext>(
163
+ {
164
+ start: "draft",
165
+ screens: {
166
+ draft: () => ({
167
+ kind: "actions",
168
+ title: `Agent directory scope · ${safeTerminalText(config.setupName)}`,
169
+ lines: [
170
+ "Changes stay in this draft until you review and save. Back discards the draft.",
171
+ "Session opt-in does not change path rules. Edit the rules separately to select which sessions can sync.",
172
+ ],
173
+ items: [
174
+ { id: "exclude", label: `Edit excluded paths… (${draft.exclude.length})`, action: "exclude" },
175
+ { id: "reinclude", label: `Edit re-included paths… (${draft.reinclude.length})`, action: "reinclude" },
176
+ {
177
+ id: "sessions",
178
+ label: `Session opt-in: ${draft.sessions ? "On → Off" : "Off → On"}`,
179
+ action: "sessions",
180
+ },
181
+ { id: "review", label: "Review changes…", action: "review" },
182
+ ],
183
+ hint: "back",
184
+ }),
185
+ },
186
+ actions: {
187
+ exclude: async ({ signal: actionSignal }) => editRules("exclude", actionSignal),
188
+ reinclude: async ({ signal: actionSignal }) => editRules("reinclude", actionSignal),
189
+ sessions: async ({ signal: actionSignal }) => {
190
+ if (!draft.sessions && !(await acknowledgeSessions(ctx, actionSignal))) return { kind: "stay" };
191
+ if (actionSignal.aborted || !isCurrent()) return { kind: "close" };
192
+ draft.sessions = !draft.sessions;
193
+ return { kind: "stay" };
194
+ },
195
+ review: async ({ signal: actionSignal }) => {
196
+ const changed = change();
197
+ if (!changed.exclude && !changed.reinclude && !changed.sessions) return { kind: "close" };
198
+ try {
199
+ validate();
200
+ const saved = await saveReviewedDraft(
201
+ ctx,
202
+ "Review agent directory scope",
203
+ [
204
+ `Setup: ${safeTerminalText(config.setupName)}`,
205
+ "",
206
+ ...directoryScopeLines(draft),
207
+ "",
208
+ ...formatDirectoryRules("Previously excluded", original.exclude),
209
+ ...formatDirectoryRules("Previously re-included", original.reinclude),
210
+ `Previous session opt-in: ${original.sessions ? "On" : "Off"}`,
211
+ "Changing rules can expose or replace files. Existing remote history is not erased.",
212
+ "A remote policy mismatch blocks transfer until reviewed. Saving does not start a transfer.",
213
+ ],
214
+ "Save changes",
215
+ (saveSignal) =>
216
+ updateSyncSetup(
217
+ config.setupName,
218
+ (setup) => {
219
+ validate();
220
+ if (setup.sync.scope !== "agent-directory") throw new Error("Sync scope changed during review.");
221
+ return {
222
+ ...setup,
223
+ sync: {
224
+ ...setup.sync,
225
+ ...(changed.exclude ? { exclude: draft.exclude } : {}),
226
+ ...(changed.reinclude ? { reinclude: draft.reinclude } : {}),
227
+ ...(changed.sessions ? { sessions: draft.sessions } : {}),
228
+ },
229
+ };
230
+ },
231
+ { expectedConfigFingerprint: syncCheckConfigFingerprint(config), signal: saveSignal },
232
+ ),
233
+ actionSignal,
234
+ );
235
+ if (saved && !actionSignal.aborted && isCurrent())
236
+ ctx.ui.notify("Agent directory rules saved. Applies to subsequent sync; no transfer started.", "info");
237
+ } catch (error) {
238
+ if (!actionSignal.aborted && isCurrent())
239
+ ctx.ui.notify(
240
+ `Agent directory rules not saved: ${safeTerminalText(error instanceof Error ? error.message : String(error))}`,
241
+ "error",
242
+ );
243
+ }
244
+ return { kind: "close" };
245
+ },
246
+ },
247
+ },
248
+ );
249
+ const result = await runMenu(ctx, menu, { getState: () => undefined, signal, isCurrent });
250
+ if (result.kind === "error" && isCurrent()) throw result.error;
251
+
252
+ async function editRules(kind: "exclude" | "reinclude", actionSignal: AbortSignal) {
253
+ const rules = await promptDirectoryRules(ctx, kind, draft[kind], actionSignal, validate);
254
+ if (actionSignal.aborted || !isCurrent()) return { kind: "close" as const };
255
+ if (rules) draft[kind] = rules;
256
+ return { kind: "stay" as const };
257
+ }
258
+ }
@@ -5,12 +5,14 @@ import { loadConfig, syncCheckConfigFingerprint } from "../settings/config.js";
5
5
  import { localConfigPath } from "../settings/config-file.js";
6
6
  import { updateSyncSetup } from "../settings/settings-management.js";
7
7
  import { agentDir } from "../snapshot/session-paths.js";
8
+ import { captureMutationOwner } from "../sync/sync-local.js";
8
9
  import {
9
10
  BUILT_IN_SYNC_ROOTS,
10
11
  isSafeCustomIncludePath,
11
12
  normalizeSyncInclude,
12
13
  syncIncludeSelection,
13
14
  } from "../sync/sync-policy.js";
15
+ import { showDirectoryScope } from "./excluded-paths-ui.js";
14
16
 
15
17
  const BUILT_IN_PREFIX = "builtin:";
16
18
  const CUSTOM_PREFIX = "custom:";
@@ -24,18 +26,19 @@ interface SelectionDraft {
24
26
  }
25
27
 
26
28
  export async function showFileSelection(ctx: ExtensionCommandContext, setupName?: string, signal?: AbortSignal) {
29
+ const validate = captureMutationOwner(ctx, signal);
27
30
  const config = await loadConfig(setupName);
28
31
  if (signal?.aborted) return;
32
+ validate();
33
+ if (config.scope === "agent-directory") return showDirectoryScope(ctx, config, signal);
29
34
  const selection = syncIncludeSelection(config.include);
30
35
  const original: SelectionDraft = {
31
36
  builtIns: new Set(selection.builtIns),
32
37
  custom: new Set(selection.custom),
33
38
  sessions: selection.sessions,
34
39
  };
35
- const draft = cloneDraft(original);
36
- const customCandidates = await listCustomCandidates(draft.custom);
37
-
38
40
  if (ctx.mode !== "tui") {
41
+ if (!ctx.hasUI) return;
39
42
  ctx.ui.notify(
40
43
  [
41
44
  `pi-sync included content for sync setup ${safeTerminalText(config.setupName)}:`,
@@ -49,6 +52,8 @@ export async function showFileSelection(ctx: ExtensionCommandContext, setupName?
49
52
  );
50
53
  return;
51
54
  }
55
+ const draft = cloneDraft(original);
56
+ const customCandidates = await listCustomCandidates(draft.custom);
52
57
 
53
58
  while (!signal?.aborted) {
54
59
  await showDraftEditor(ctx, config.setupName, draft, customCandidates, signal);
@@ -81,10 +86,10 @@ export async function showFileSelection(ctx: ExtensionCommandContext, setupName?
81
86
  if (signal?.aborted) return;
82
87
  await updateSyncSetup(
83
88
  config.setupName,
84
- (setup) => ({
85
- ...setup,
86
- sync: { ...setup.sync, include },
87
- }),
89
+ (setup) => {
90
+ if (setup.sync.scope === "agent-directory") throw new Error("Sync scope changed during review.");
91
+ return { ...setup, sync: { ...setup.sync, include } };
92
+ },
88
93
  { expectedConfigFingerprint: syncCheckConfigFingerprint(config), expectedInclude: config.include, signal },
89
94
  );
90
95
  if (signal?.aborted) return;
@@ -14,7 +14,7 @@ import { readStateForConfig, syncStateFingerprint } from "../state/sync-state-st
14
14
  import { sameSyncExclude } from "../sync/exclude-policy.js";
15
15
  import { errorMessage } from "../sync/sync-errors.js";
16
16
  import type { StartupObservation } from "../sync/sync-inspection.js";
17
- import { compareSyncInclude, syncSessionsSelected } from "../sync/sync-policy.js";
17
+ import { compareSyncInclude, syncSelectionHasContent, syncSessionsSelected } from "../sync/sync-policy.js";
18
18
  import {
19
19
  observationMatchesConfig,
20
20
  observationSummary,
@@ -77,7 +77,7 @@ export async function describeManagerState(
77
77
  }
78
78
  const configuredTargets = ownRecord(raw.syncSetups);
79
79
  if (
80
- (raw.version === 3 || raw.version === 4 || raw.version === 5 || raw.version === 6) &&
80
+ (raw.version === 3 || raw.version === 4 || raw.version === 5 || raw.version === 6 || raw.version === 7) &&
81
81
  configuredTargets &&
82
82
  Object.keys(configuredTargets).length === 0
83
83
  ) {
@@ -114,7 +114,9 @@ export async function describeManagerState(
114
114
  const attentionExclusionsDiffer = currentAttention
115
115
  ? !sameSyncExclude(currentAttention.decision.localExclude, currentAttention.decision.remoteExclude)
116
116
  : false;
117
- const noSyncedContent = config.include.length === 0;
117
+ const attentionDirectoryPolicy =
118
+ currentAttention?.decision.localDirectory || currentAttention?.decision.remoteDirectory;
119
+ const noSyncedContent = !syncSelectionHasContent(config);
118
120
  const syncState = changesBlocked ? undefined : await readStateForConfig(config).catch(() => undefined);
119
121
  const currentObservation =
120
122
  observation &&
@@ -141,6 +143,7 @@ export async function describeManagerState(
141
143
  "Manage sync",
142
144
  `Current sync setup: ${safeTerminalText(config.setupName)}`,
143
145
  `Storage: ${backendStorageDescription(config)}`,
146
+ ...(config.scope ? ["Sync scope: Pi agent directory, with exclusions"] : []),
144
147
  ...(syncState?.unresolved?.length
145
148
  ? [`Unresolved: ${syncState.unresolved.length} dependency groups · review needed`]
146
149
  : []),
@@ -149,11 +152,13 @@ export async function describeManagerState(
149
152
  currentAttention.decision.setupName === config.setupName
150
153
  ? "Sync status: Review needed"
151
154
  : `Sync status: Review needed for setup ${safeTerminalText(currentAttention.decision.setupName)}`,
152
- attentionComparison?.remoteOnly.length === 0 && attentionComparison.localOnly.length === 0
153
- ? attentionExclusionsDiffer
154
- ? "Synced-content exclusion rules differ."
155
- : "Only the synced-content order differs."
156
- : `Remote-only paths: ${attentionComparison?.remoteOnly.length ?? 0} · Device-only paths: ${attentionComparison?.localOnly.length ?? 0}${attentionExclusionsDiffer ? " · Exclusion rules differ." : ""}`,
155
+ attentionDirectoryPolicy
156
+ ? "Sync scopes or directory rules differ."
157
+ : attentionComparison?.remoteOnly.length === 0 && attentionComparison.localOnly.length === 0
158
+ ? attentionExclusionsDiffer
159
+ ? "Synced-content exclusion rules differ."
160
+ : "Only the synced-content order differs."
161
+ : `Remote-only paths: ${attentionComparison?.remoteOnly.length ?? 0} · Device-only paths: ${attentionComparison?.localOnly.length ?? 0}${attentionExclusionsDiffer ? " · Exclusion rules differ." : ""}`,
157
162
  ]
158
163
  : currentObservation
159
164
  ? [`Observed ${safeTerminalText(currentObservation.checkedAt)}: ${observationSummary(currentObservation)}`]