@narumitw/pi-sync 0.65.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 (70) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +4 -4
  3. package/dist/chunks/{chunk-OWEOZZZE.ts → chunk-5YOLQKNZ.ts} +38 -2
  4. package/dist/chunks/chunk-5YOLQKNZ.ts.map +7 -0
  5. package/dist/chunks/{chunk-OBVJTKVY.ts → chunk-ASU3GZPW.ts} +10 -92
  6. package/dist/chunks/chunk-ASU3GZPW.ts.map +7 -0
  7. package/dist/chunks/{chunk-IOM6E5FW.ts → chunk-BESRBKVO.ts} +2 -2
  8. package/dist/chunks/{chunk-TZMVSTAM.ts → chunk-BYVHABNR.ts} +4 -4
  9. package/dist/chunks/chunk-ECYCNZOE.ts +12 -0
  10. package/dist/chunks/chunk-ECYCNZOE.ts.map +7 -0
  11. package/dist/chunks/{chunk-MANNB4WZ.ts → chunk-KNEUL4XN.ts} +1 -7
  12. package/dist/chunks/chunk-KNEUL4XN.ts.map +7 -0
  13. package/dist/chunks/chunk-Z5JMOXJM.ts +106 -0
  14. package/dist/chunks/chunk-Z5JMOXJM.ts.map +7 -0
  15. package/dist/chunks/{command-handler-YZ4DXQ7N.ts → command-handler-44EFGPWH.ts} +9 -7
  16. package/dist/chunks/{command-handler-YZ4DXQ7N.ts.map → command-handler-44EFGPWH.ts.map} +1 -1
  17. package/dist/chunks/{file-selection-DDQN4LVD.ts → file-selection-XWACUTAH.ts} +8 -8
  18. package/dist/chunks/ignore-file-ui-OHFISFVC.ts +21 -0
  19. package/dist/chunks/{manager-result-dispatcher-XB75YLEG.ts → manager-result-dispatcher-WXE2BAQO.ts} +3 -3
  20. package/dist/chunks/{manager-ui-RGA26Z6G.ts → manager-ui-CVZLMXJ5.ts} +57 -45
  21. package/dist/chunks/manager-ui-CVZLMXJ5.ts.map +7 -0
  22. package/dist/chunks/{remote-selection-ui-WVMET5RI.ts → remote-selection-ui-E4XZCQ7A.ts} +2 -2
  23. package/dist/chunks/remote-selection-ui-E4XZCQ7A.ts.map +7 -0
  24. package/dist/chunks/{setup-wizard-YP2KF2WQ.ts → setup-wizard-IEW56AZE.ts} +7 -5
  25. package/dist/chunks/{setup-wizard-YP2KF2WQ.ts.map → setup-wizard-IEW56AZE.ts.map} +1 -1
  26. package/dist/daemon/dist/consent.js +14 -2
  27. package/dist/daemon/dist/engine/backends/git/git-backend.js +5 -3
  28. package/dist/daemon/dist/engine/backends/git/git-storage.js +15 -3
  29. package/dist/daemon/dist/engine/ignore/adoption-journal.js +143 -0
  30. package/dist/daemon/dist/engine/ignore/snapshot-ignore-rules.js +39 -0
  31. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +2 -2
  32. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +6 -6
  33. package/dist/daemon/dist/engine/snapshot/snapshot-types.js +5 -1
  34. package/dist/daemon/dist/engine/snapshot/snapshot.js +5 -2
  35. package/dist/daemon/dist/engine/sync/conflict-review.js +2 -0
  36. package/dist/daemon/dist/engine/sync/continuous-watch.js +3 -2
  37. package/dist/daemon/dist/engine/sync/directional-action.js +3 -8
  38. package/dist/daemon/dist/engine/sync/ignore-adoption-recovery.js +50 -0
  39. package/dist/daemon/dist/engine/sync/ignore-adoption.js +401 -0
  40. package/dist/daemon/dist/engine/sync/ignore-publication.js +23 -0
  41. package/dist/daemon/dist/engine/sync/initialization.js +12 -0
  42. package/dist/daemon/dist/engine/sync/local-fields.js +6 -3
  43. package/dist/daemon/dist/engine/sync/merge-journal.js +2 -2
  44. package/dist/daemon/dist/engine/sync/merged-sync.js +14 -3
  45. package/dist/daemon/dist/engine/sync/sync-local.js +2 -1
  46. package/dist/daemon/dist/engine/sync/sync-mutations.js +82 -19
  47. package/dist/daemon/dist/engine/sync/sync-policy.js +5 -5
  48. package/dist/daemon/dist/engine/sync/sync-queries.js +1 -1
  49. package/dist/daemon/dist/engine/sync/sync-rollback.js +9 -3
  50. package/dist/daemon/dist/engine/ui/ignore-rule-preview.js +18 -0
  51. package/dist/daemon/dist/engine-service.js +1 -1
  52. package/dist/daemon/package.json +1 -1
  53. package/dist/index.ts +1 -1
  54. package/docs/tui-contract.md +3 -3
  55. package/package.json +2 -2
  56. package/skills/configure-pi-sync/references/configuration.md +10 -8
  57. package/src/ui/ignore-file-ui.ts +13 -5
  58. package/src/ui/manager-state.ts +15 -8
  59. package/src/ui/manager-ui.ts +1 -1
  60. package/src/ui/remote-selection-ui.ts +43 -2
  61. package/src/ui/settings-ui.ts +30 -30
  62. package/dist/chunks/chunk-MANNB4WZ.ts.map +0 -7
  63. package/dist/chunks/chunk-OBVJTKVY.ts.map +0 -7
  64. package/dist/chunks/chunk-OWEOZZZE.ts.map +0 -7
  65. package/dist/chunks/manager-ui-RGA26Z6G.ts.map +0 -7
  66. /package/dist/chunks/{chunk-IOM6E5FW.ts.map → chunk-BESRBKVO.ts.map} +0 -0
  67. /package/dist/chunks/{chunk-TZMVSTAM.ts.map → chunk-BYVHABNR.ts.map} +0 -0
  68. /package/dist/chunks/{file-selection-DDQN4LVD.ts.map → file-selection-XWACUTAH.ts.map} +0 -0
  69. /package/dist/chunks/{manager-result-dispatcher-XB75YLEG.ts.map → ignore-file-ui-OHFISFVC.ts.map} +0 -0
  70. /package/dist/chunks/{remote-selection-ui-WVMET5RI.ts.map → manager-result-dispatcher-WXE2BAQO.ts.map} +0 -0
@@ -1,5 +1,6 @@
1
1
  import { createSyncBackend } from "../backends/backend-factory.js";
2
2
  import { expectedRemoteHead, SyncBackendConflictError, } from "../backends/sync-backend.js";
3
+ import { loadAdoptionJournal, requireNoPendingAdoption } from "../ignore/adoption-journal.js";
3
4
  import { loadConfig, loadConfigForCheck, syncCheckConfigFingerprint } from "../settings/config.js";
4
5
  import { effectiveSessionRoot, requireStableMergeSessionRoot, resolvedSnapshotOptionsForContext, sessionDirForApply, } from "../snapshot/session-paths.js";
5
6
  import { createSnapshot, filterSnapshotForConfigPolicy, scanSnapshot, snapshotIncludesSessions, } from "../snapshot/snapshot.js";
@@ -8,6 +9,7 @@ import { pendingTransactionEntries } from "../snapshot/snapshot-transaction-dire
8
9
  import { ignorePolicyValidator } from "../snapshot/snapshot-transaction-policy.js";
9
10
  import { pruneMergeBaselines } from "../state/merge-baseline-store.js";
10
11
  import { readStateForConfig, syncStateFingerprint, writeStateForConfig } from "../state/sync-state-store.js";
12
+ import { formatRuleChanges } from "../ui/ignore-rule-preview.js";
11
13
  import { countPreservedRemoteFiles, formatPullSummary, formatPushSummary, formatTransferReview, } from "../ui/sync-format.js";
12
14
  import { setSyncStatus } from "../ui/sync-status.js";
13
15
  import { confirmTransferReview } from "../ui/transfer-review.js";
@@ -15,6 +17,8 @@ import { startupTransferEnabled } from "./agent-policy.js";
15
17
  import { inspectCaseCleanup, revalidateCaseCleanup } from "./apply-review.js";
16
18
  import { checkpointDirectionalAction, foregroundDirectionalAction, keepProtectedRemoteSessions, localRestoreGuidance, notifyDirectionalSuccess, remoteRestoreGuidance, requireDirectionalPullBoundary, requireDirectionalSelection, validateDirectionalSettings, } from "./directional-action.js";
17
19
  import { confirmFieldMigration } from "./field-migration.js";
20
+ import { adoptionSettingsFingerprint, adoptRemoteRules, canReviewAdoption } from "./ignore-adoption.js";
21
+ import { ignorePublicationNotice, withPublishedIgnoreRules } from "./ignore-publication.js";
18
22
  import { overlayLocalFields, portableSnapshot, sameLocalFields, validatePortableSnapshot } from "./local-fields.js";
19
23
  import { readMergeJournal, requireNoMergeJournal, retireMergeJournal } from "./merge-journal.js";
20
24
  import { mergeSync } from "./merged-sync.js";
@@ -30,6 +34,7 @@ const VERSION = 1;
30
34
  export { PublicationStatePersistenceError, RollbackPublicationError } from "./sync-errors.js";
31
35
  export { rollback } from "./sync-rollback.js";
32
36
  export async function push(ctx, options, input, factory = createSyncBackend) {
37
+ requireNoPendingAdoption();
33
38
  const validateOwner = captureMutationOwner(ctx, options.signal);
34
39
  const validateCommittedOwner = captureMutationOwner(ctx);
35
40
  const action = foregroundDirectionalAction(ctx, options);
@@ -75,21 +80,22 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
75
80
  ? await readSnapshotForHead(backend, head, options.signal, config)
76
81
  : await readRemoteSnapshotForUpload(backend, config, head, state, options);
77
82
  validateMutation();
78
- if (config.ignorePolicy && remoteForUpload && options.force && (options.auto || options.yes || !ctx.hasUI)) {
79
- const comparison = inspectRemoteSelection(config.include, remoteForUpload, config.exclude, config);
80
- if (comparison.kind === "different")
81
- requireCompatibleRemoteSelection(config, remoteForUpload);
82
- }
83
- if (action)
83
+ const policyOverwrite = Boolean(config.ignorePolicy &&
84
+ remoteForUpload &&
85
+ inspectRemoteSelection(config.include, remoteForUpload, config.exclude, config).kind === "different");
86
+ if (policyOverwrite && remoteForUpload && (options.auto || options.background || options.yes || !ctx.hasUI))
87
+ requireCompatibleRemoteSelection(config, remoteForUpload);
88
+ if (action && !policyOverwrite)
84
89
  requireDirectionalSelection(config, state, localRaw, remoteForUpload, snapshotOptions.sessionDir);
85
90
  else
86
91
  requireIgnoreBaselineReview(ctx, config, state, options);
87
- if (!action && remoteForUpload && !options.force) {
92
+ if (!action && remoteForUpload && !options.force && !policyOverwrite) {
88
93
  requireCompatibleRemoteSelection(config, remoteForUpload);
89
94
  }
90
95
  if (!action &&
91
96
  remoteChangedSinceState(head, state, config, (left, right) => backend.sameRevision(left, right)) &&
92
- !options.force) {
97
+ !options.force &&
98
+ !policyOverwrite) {
93
99
  const remoteForConflict = remoteForUpload
94
100
  ? filterSnapshotForConfigPolicy(remoteForUpload, config, snapshotOptions)
95
101
  : undefined;
@@ -119,12 +125,18 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
119
125
  upload = keepProtectedRemoteSessions(config, upload, remoteForUpload, snapshotOptions.sessionDir, reviewedProtectedPaths);
120
126
  validatePortableSnapshot(upload);
121
127
  }
128
+ upload = await withPublishedIgnoreRules(upload, config, options.signal);
129
+ validateMutation();
122
130
  if (!config.skipSecretScan) {
123
- const secrets = scanSnapshot(local);
131
+ const secrets = scanSnapshot({ ...local, ...(upload.ignoreRules ? { ignoreRules: upload.ignoreRules } : {}) });
124
132
  if (secrets.length > 0) {
125
133
  throw new Error(`Refusing to push possible secrets:\n${secrets.map((s) => `- ${s}`).join("\n")}`);
126
134
  }
127
135
  }
136
+ if ((!action || policyOverwrite) &&
137
+ !(await confirmPush(ctx, options, config, backend, local, upload, head, remoteForUpload, validateMutation))) {
138
+ return "cancelled";
139
+ }
128
140
  if (action) {
129
141
  await checkpointDirectionalAction(options, {
130
142
  direction: "push",
@@ -138,9 +150,6 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
138
150
  });
139
151
  validateMutation();
140
152
  }
141
- else if (!(await confirmPush(ctx, options, config, backend, local, upload, head, remoteForUpload, validateMutation))) {
142
- return "cancelled";
143
- }
144
153
  if (options.force) {
145
154
  const refreshedHead = await backend.readHead(options.signal);
146
155
  validateMutation();
@@ -291,6 +300,10 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
291
300
  const action = foregroundDirectionalAction(ctx, options);
292
301
  if (action && initial)
293
302
  throw new Error("Single-action Pull cannot be used for initial-source selection.");
303
+ const adoptionReview = !initial && canReviewAdoption(ctx, options);
304
+ const journal = adoptionReview ? await loadAdoptionJournal() : undefined;
305
+ if (!adoptionReview)
306
+ requireNoPendingAdoption();
294
307
  const validateOwner = captureMutationOwner(ctx, options.signal);
295
308
  const validateCommittedOwner = captureMutationOwner(ctx);
296
309
  const config = action ? await loadConfigForCheck(undefined, options.signal) : await loadConfig(options.setup);
@@ -303,7 +316,7 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
303
316
  if (initial && initial.configIdentity !== configIdentity)
304
317
  throw new Error("Settings changed before initial pull; run sync again.");
305
318
  await requireNoMergeJournal(config, options);
306
- if (action && (await pendingTransactionEntries()).length)
319
+ if (action && !journal && (await pendingTransactionEntries()).length)
307
320
  throw new Error("A pending local transaction must be reconciled before Pull; its evidence was retained.");
308
321
  validateMutation();
309
322
  setSyncStatus(ctx, `pulling ${config.setupName}`, { activity: "pulling" });
@@ -317,6 +330,26 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
317
330
  if (action)
318
331
  snapshotOptions.sessionDir = await effectiveSessionRoot(ctx, config, options.signal);
319
332
  validateMutation();
333
+ if (journal) {
334
+ if (journal.setupName !== config.setupName ||
335
+ journal.setupFingerprint !== adoptionSettingsFingerprint(config) ||
336
+ config.pathPolicy !== "ignore-file")
337
+ throw new Error("Pending rule adoption belongs to a different setup. Preserve its journal and use the originating setup.");
338
+ const remote = await readSnapshotForHead(backend, journal.head, options.signal, config);
339
+ validateMutation();
340
+ return adoptRemoteRules({
341
+ ctx,
342
+ options,
343
+ config,
344
+ backend,
345
+ state,
346
+ head: journal.head,
347
+ remote,
348
+ snapshotOptions,
349
+ validateMutation,
350
+ journal,
351
+ });
352
+ }
320
353
  const validateIgnorePolicy = ignorePolicyValidator({ ...snapshotOptions, validateMutation });
321
354
  if (initial && initial.sessionDir !== snapshotOptions.sessionDir)
322
355
  throw new Error("Pi session storage changed before initial pull; run sync again.");
@@ -325,18 +358,40 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
325
358
  if (initial && !sameHashes(initial.localHashes, fileHashMap(local)))
326
359
  throw new Error("Local bytes changed before initial pull; run sync again.");
327
360
  let preimageRemote;
361
+ let adoption;
328
362
  const { head, snapshot: remote } = await readRemoteSnapshot(backend, config, options.signal, {
329
363
  ...snapshotOptions,
330
- ...(action
364
+ ...(action || (adoptionReview && config.ignorePolicy)
331
365
  ? {
332
366
  validateSelection: (raw) => {
333
- requireDirectionalSelection(config, state, local, raw, snapshotOptions.sessionDir);
334
- preimageRemote = raw;
367
+ const comparison = inspectRemoteSelection(config.include, raw, config.exclude, config).ignorePolicyComparison;
368
+ if (adoptionReview && comparison === "mismatch") {
369
+ adoption = raw;
370
+ }
371
+ else if (action) {
372
+ requireDirectionalSelection(config, state, local, raw, snapshotOptions.sessionDir);
373
+ preimageRemote = raw;
374
+ }
375
+ else {
376
+ requireCompatibleRemoteSelection(config, raw);
377
+ }
335
378
  },
336
379
  }
337
380
  : {}),
338
381
  });
339
382
  validateMutation();
383
+ if (adoption && head)
384
+ return adoptRemoteRules({
385
+ ctx,
386
+ options,
387
+ config,
388
+ backend,
389
+ state,
390
+ head,
391
+ remote: adoption,
392
+ snapshotOptions,
393
+ validateMutation,
394
+ });
340
395
  if (initial && !matchesInitialHead(initial, backend, head))
341
396
  throw new Error("Remote changed before initial pull; run sync again.");
342
397
  if (!action)
@@ -548,6 +603,7 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
548
603
  return "applied";
549
604
  }
550
605
  export async function syncBoth(ctx, options, factory = createSyncBackend) {
606
+ requireNoPendingAdoption();
551
607
  if (options.directionalAction)
552
608
  throw new Error("Single-action transfer cannot authorize bidirectional Sync.");
553
609
  const validateMutation = captureMutationOwner(ctx, options.signal);
@@ -710,9 +766,16 @@ async function confirmPush(ctx, options, config, backend, local, upload, head, r
710
766
  const comparison = config.ignorePolicy && remote
711
767
  ? inspectRemoteSelection(config.include, remote, config.exclude, config).ignorePolicyComparison
712
768
  : undefined;
713
- const confirmed = await confirmTransferReview(ctx, title, comparison && comparison !== "match"
714
- ? formatTransferReview(formatIgnorePolicyComparison(comparison), "Only files selected by this device's rules are published. Remote rules are not adopted.", "", summary)
715
- : summary, options.signal, validateMutation);
769
+ const notice = ignorePublicationNotice(upload);
770
+ const overwrite = comparison !== undefined && comparison !== "match";
771
+ const confirmed = await confirmTransferReview(ctx, overwrite ? "Overwrite remote policy and push?" : title, formatTransferReview(...(overwrite
772
+ ? [
773
+ formatIgnorePolicyComparison(comparison),
774
+ "This replaces the remote policy with this device's rules. Remote rules are not adopted on this device.",
775
+ `Sessions opt-in: ${remote?.selection?.version === 4 ? (remote.selection.sessions ? "on" : "off") : "legacy"} → ${config.ignorePolicy?.sessions ? "on" : "off"}.`,
776
+ formatRuleChanges(remote?.ignoreRules?.text, upload.ignoreRules?.text),
777
+ ]
778
+ : []), ...(notice ? [notice, ""] : []), summary), options.signal, validateMutation);
716
779
  throwIfAborted(options.signal);
717
780
  if (confirmed)
718
781
  return true;
@@ -1,7 +1,7 @@
1
1
  import { createHash } from "node:crypto";
2
2
  import path from "node:path";
3
3
  import { DEBUG_LOG_FILENAME, isDebugLogPath, isDeniedPath, toPosix } from "../paths.js";
4
- import { IGNORE_SNAPSHOT_VERSION, } from "../snapshot/snapshot-types.js";
4
+ import { isIgnoreSnapshotVersion, } from "../snapshot/snapshot-types.js";
5
5
  import { compilePathRules, compileSyncExclude, normalizeSyncExclude, sameSyncExclude } from "./exclude-policy.js";
6
6
  export const BUILT_IN_SYNC_ROOTS = [
7
7
  "settings.json",
@@ -199,8 +199,8 @@ export function validateSnapshotSelection(snapshot) {
199
199
  throw new Error("Exclude policy requires snapshot version 4 and selection version 2.");
200
200
  if ((snapshot.version === 5) !== (selection?.version === 3))
201
201
  throw new Error("Agent-directory policy requires snapshot version 5 and selection version 3.");
202
- if ((snapshot.version === IGNORE_SNAPSHOT_VERSION) !== (selection?.version === 4))
203
- throw new Error("Ignore-file policy requires snapshot version 6 and selection version 4.");
202
+ if (isIgnoreSnapshotVersion(snapshot.version) !== (selection?.version === 4))
203
+ throw new Error("Ignore-file policy requires snapshot version 6 or 7 and selection version 4.");
204
204
  }
205
205
  export function assertSnapshotPathExcludesDebugLog(filePath) {
206
206
  if (typeof filePath === "string" && isDebugLogPath(filePath))
@@ -211,7 +211,7 @@ export function assertSnapshotExcludesDebugLog(snapshot) {
211
211
  assertSnapshotPathExcludesDebugLog(file?.path);
212
212
  }
213
213
  export function requireLegacyTransferPolicy(snapshot) {
214
- if (snapshot.version === IGNORE_SNAPSHOT_VERSION || snapshot.selection?.version === 4)
214
+ if (isIgnoreSnapshotVersion(snapshot.version) || snapshot.selection?.version === 4)
215
215
  throw new Error("This setup cannot transfer an ignore-file snapshot without a reviewed local ignore policy.");
216
216
  }
217
217
  export function sameSyncInclude(left, right) {
@@ -243,7 +243,7 @@ export function formatIgnorePolicyComparison(comparison) {
243
243
  case "match":
244
244
  return "Remote ignore-file policy matches this device.";
245
245
  case "mismatch":
246
- return "Remote ignore-file policy differs. Edit local rules to match, or review publishing this device's policy.";
246
+ return "Remote ignore-file policy differs. Review a directional Push or Pull; Pull needs the remote rule text.";
247
247
  case "local-ignore-remote-legacy":
248
248
  return "Remote uses a legacy content policy. Review publishing this device's ignore-file policy.";
249
249
  case "local-legacy-remote-ignore":
@@ -20,7 +20,7 @@ function contentLines(config) {
20
20
  config.scope === "agent-directory"
21
21
  ? "included content: eligible files in the Pi agent directory"
22
22
  : `included content: ${config.include.map(safeTerminalText).join(", ") || "none"}`,
23
- ...(config.ignorePolicy ? ["path policy: local ignore file (rule text is not published)"] : []),
23
+ ...(config.ignorePolicy ? ["path policy: local ignore file (published unless it excludes itself)"] : []),
24
24
  ...(config.exclude === undefined
25
25
  ? []
26
26
  : [`excluded paths: ${config.exclude.map(safeTerminalText).join(", ") || "none"}`]),
@@ -1,8 +1,9 @@
1
1
  import { createSyncBackend } from "../backends/backend-factory.js";
2
2
  import { expectedRemoteHead } from "../backends/sync-backend.js";
3
+ import { requireNoPendingAdoption } from "../ignore/adoption-journal.js";
3
4
  import { loadConfig, syncCheckConfigFingerprint } from "../settings/config.js";
4
5
  import { effectiveSessionRoot, requireStableMergeSessionRoot, resolvedSnapshotOptionsForContext, sessionDirForApply, } from "../snapshot/session-paths.js";
5
- import { createSnapshot, filterSnapshotForConfigPolicy, regenerateSnapshotIdentity, snapshotIncludesSessions, snapshotWithoutSessions, } from "../snapshot/snapshot.js";
6
+ import { createSnapshot, filterSnapshotForConfigPolicy, regenerateSnapshotIdentity, scanSnapshot, snapshotIncludesSessions, snapshotWithoutSessions, } from "../snapshot/snapshot.js";
6
7
  import { applySnapshot } from "../snapshot/snapshot-apply.js";
7
8
  import { ignorePolicyValidator } from "../snapshot/snapshot-transaction-policy.js";
8
9
  import { pruneMergeBaselines } from "../state/merge-baseline-store.js";
@@ -11,6 +12,7 @@ import { formatPublicationPreview, formatRollbackSummary, formatTransferReview }
11
12
  import { confirmTransferReview } from "../ui/transfer-review.js";
12
13
  import { inspectCaseCleanup, revalidateCaseCleanup } from "./apply-review.js";
13
14
  import { confirmFieldMigration } from "./field-migration.js";
15
+ import { ignorePublicationNotice, withPublishedIgnoreRules } from "./ignore-publication.js";
14
16
  import { overlayLocalFields, portableSnapshot, sameLocalFields, validatePortableSnapshot } from "./local-fields.js";
15
17
  import { requireNoMergeJournal, retireMergeJournal } from "./merge-journal.js";
16
18
  import { readSnapshotForHead, requireCompatibleRemoteSelection, sameRemoteHead, snapshotForUpload, } from "./remote-snapshot.js";
@@ -25,6 +27,7 @@ const POST_LOCAL_COMMIT_TIMEOUT_MS = 30_000;
25
27
  export async function rollback(ctx, options, factory = createSyncBackend, expectedSelection) {
26
28
  if (options.directionalAction)
27
29
  throw new Error("Single-action transfer cannot authorize rollback.");
30
+ requireNoPendingAdoption();
28
31
  const validateMutation = captureMutationOwner(ctx, options.signal);
29
32
  const validateCommittedOwner = captureMutationOwner(ctx);
30
33
  const target = options.args[0];
@@ -73,10 +76,13 @@ export async function rollback(ctx, options, factory = createSyncBackend, expect
73
76
  if (config.scope === "agent-directory")
74
77
  requireStableMergeSessionRoot(local, physical, config.scope);
75
78
  const upload = config.ignorePolicy
76
- ? remote
79
+ ? await withPublishedIgnoreRules(remote, config, options.signal)
77
80
  : await snapshotForUpload(backend, config, remote, expectedHead, currentRemote, snapshotOptions);
81
+ validateMutation();
78
82
  if (config.scope === "agent-directory")
79
83
  validatePortableSnapshot(upload);
84
+ if (upload.ignoreRules && !config.skipSecretScan && scanSnapshot({ ...upload, files: [] }).length)
85
+ throw new Error("Refusing to publish possible secrets in the ignore file.");
80
86
  const caseCleanup = options.yes ? [] : await inspectCaseCleanup(physical, snapshotOptions);
81
87
  validateMutation();
82
88
  const reviewedProtectedPaths = protectedSessionPaths(ctx, snapshotOptions.sessionDir);
@@ -84,7 +90,7 @@ export async function rollback(ctx, options, factory = createSyncBackend, expect
84
90
  const title = snapshotIncludesSessions(remote) ? "Rollback pi settings and sessions?" : "Rollback pi settings?";
85
91
  const summary = formatRollbackSummary(config, backend.destination, local, physical, target, reviewedProtectedPaths, caseCleanup.map((item) => item.path));
86
92
  const confirmed = config.ignorePolicy
87
- ? await confirmTransferReview(ctx, title, formatTransferReview("Historical files are projected through this device's current ignore rules. Historical rules are not adopted. Retained history is not erased.", "", summary, "", "Remote publication:", formatPublicationPreview(currentRemote, upload)), options.signal, validateMutation)
93
+ ? await confirmTransferReview(ctx, title, formatTransferReview("Historical files are projected through this device's current ignore rules. Historical rules are not adopted. Retained history is not erased.", ignorePublicationNotice(upload) ?? "", summary, "", "Remote publication:", formatPublicationPreview(currentRemote, upload)), options.signal, validateMutation)
88
94
  : await ctx.ui.confirm(title, summary.content, { signal: options.signal });
89
95
  validateMutation();
90
96
  if (!confirmed) {
@@ -0,0 +1,18 @@
1
+ import { snapshotPathLabel } from "./terminal-text.js";
2
+ export function formatRuleChanges(before, after) {
3
+ if (before === after) {
4
+ const message = before === undefined ? "Rule text is unavailable on both sides." : "Rule text is unchanged.";
5
+ return { lines: [message], content: message };
6
+ }
7
+ const lines = (text, prefix) => text === undefined
8
+ ? [`${prefix} (rule text not in snapshot)`]
9
+ : text.split(/(?<=\n)/u).map((line) => `${prefix} ${snapshotPathLabel(JSON.stringify(line))}`);
10
+ return {
11
+ lines: ["Rule text changes. View details for the exact lines."],
12
+ content: [
13
+ "Rule text (− before, + after; JSON quotes show whitespace):",
14
+ ...lines(before, "-"),
15
+ ...lines(after, "+"),
16
+ ].join("\n"),
17
+ };
18
+ }
@@ -49,7 +49,7 @@ export function createEngineService(root, ignoreFileSettingsAvailable = false) {
49
49
  const execute = (operation, payload, execution) => host.run(execution, async () => {
50
50
  if (operation === "ignore.capabilities") {
51
51
  execution.validate();
52
- return { available: ignoreFileSettingsAvailable };
52
+ return { available: ignoreFileSettingsAvailable, ...(ignoreFileSettingsAvailable ? { portableRules: 1 } : {}) };
53
53
  }
54
54
  if (operation === "ignore.migration-offer" || operation === "ignore.migration-defer") {
55
55
  execution.validate();
@@ -1,3 +1,3 @@
1
1
  {
2
- "version": "0.11.0"
2
+ "version": "0.12.0"
3
3
  }
package/dist/index.ts CHANGED
@@ -334,7 +334,7 @@ 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-YZ4DXQ7N.ts"))),
337
+ commands: cachedModuleLoader(dependencies.loadCommandHandler ?? (() => import("./chunks/command-handler-44EFGPWH.ts"))),
338
338
  inspection: cachedModuleLoader(dependencies.loadSyncInspection ?? (() => import("./chunks/sync-inspection-NBBTSMKR.ts"))),
339
339
  setupSwitch: cachedModuleLoader(dependencies.loadSetupSwitch ?? (() => import("./chunks/setup-switch-644T6KHG.ts"))),
340
340
  snapshot: cachedModuleLoader(dependencies.loadSnapshot ?? (() => import("./chunks/snapshot-ZUJJZCFW.ts"))),
@@ -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.65.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.11.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,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,
@@ -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)}`]
@@ -492,7 +492,7 @@ function syncMainMenuItem(
492
492
  push: "This device → remote; replaces conflicting remote files.",
493
493
  diff: "Inspect changes; no transfer.",
494
494
  status: "Check remote; no transfer.",
495
- settings: "Change sync settings.",
495
+ settings: "Edit settings, setups, and storage connections.",
496
496
  history: "Review snapshots and rollback.",
497
497
  doctor: "Review backend diagnostics.",
498
498
  switch: "Choose another sync setup.",