@narumitw/pi-sync 0.65.0 → 0.67.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 (84) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +13 -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-SQC2L2FJ.ts} +9 -7
  16. package/dist/chunks/{command-handler-YZ4DXQ7N.ts.map → command-handler-SQC2L2FJ.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-DWOMAJKE.ts} +170 -45
  21. package/dist/chunks/manager-ui-DWOMAJKE.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/ignore-edit.js +2 -2
  31. package/dist/daemon/dist/engine/ignore/ignore-settings.js +2 -1
  32. package/dist/daemon/dist/engine/ignore/snapshot-ignore-rules.js +39 -0
  33. package/dist/daemon/dist/engine/settings/config-file.js +3 -0
  34. package/dist/daemon/dist/engine/settings/config.js +5 -5
  35. package/dist/daemon/dist/engine/settings/settings-management.js +6 -1
  36. package/dist/daemon/dist/engine/settings/settings-validation.js +21 -2
  37. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +2 -2
  38. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +6 -6
  39. package/dist/daemon/dist/engine/snapshot/snapshot-types.js +5 -1
  40. package/dist/daemon/dist/engine/snapshot/snapshot.js +5 -2
  41. package/dist/daemon/dist/engine/sync/conflict-review.js +2 -0
  42. package/dist/daemon/dist/engine/sync/continuous-errors.js +6 -0
  43. package/dist/daemon/dist/engine/sync/continuous-sync.js +4 -2
  44. package/dist/daemon/dist/engine/sync/continuous-watch.js +3 -2
  45. package/dist/daemon/dist/engine/sync/directional-action.js +3 -8
  46. package/dist/daemon/dist/engine/sync/ignore-adoption-recovery.js +50 -0
  47. package/dist/daemon/dist/engine/sync/ignore-adoption.js +410 -0
  48. package/dist/daemon/dist/engine/sync/ignore-publication.js +23 -0
  49. package/dist/daemon/dist/engine/sync/initialization.js +12 -0
  50. package/dist/daemon/dist/engine/sync/local-fields.js +6 -3
  51. package/dist/daemon/dist/engine/sync/merge-apply.js +18 -1
  52. package/dist/daemon/dist/engine/sync/merge-journal.js +2 -2
  53. package/dist/daemon/dist/engine/sync/merged-sync.js +50 -7
  54. package/dist/daemon/dist/engine/sync/push-review.js +33 -0
  55. package/dist/daemon/dist/engine/sync/sync-local.js +2 -1
  56. package/dist/daemon/dist/engine/sync/sync-mutations.js +108 -55
  57. package/dist/daemon/dist/engine/sync/sync-policy.js +5 -5
  58. package/dist/daemon/dist/engine/sync/sync-queries.js +1 -1
  59. package/dist/daemon/dist/engine/sync/sync-rollback.js +25 -5
  60. package/dist/daemon/dist/engine/sync/transfer-freshness.js +3 -2
  61. package/dist/daemon/dist/engine/sync/transfer-size-limits.js +92 -0
  62. package/dist/daemon/dist/engine/ui/ignore-rule-preview.js +18 -0
  63. package/dist/daemon/dist/engine-service.js +1 -1
  64. package/dist/daemon/package.json +1 -1
  65. package/dist/index.ts +1 -1
  66. package/docs/daemon-migration.md +6 -0
  67. package/docs/tui-contract.md +6 -5
  68. package/package.json +2 -2
  69. package/skills/configure-pi-sync/SKILL.md +1 -1
  70. package/skills/configure-pi-sync/references/configuration.md +43 -14
  71. package/src/ui/ignore-file-ui.ts +13 -5
  72. package/src/ui/manager-state.ts +15 -8
  73. package/src/ui/manager-ui.ts +1 -1
  74. package/src/ui/remote-selection-ui.ts +43 -2
  75. package/src/ui/settings-ui.ts +156 -32
  76. package/dist/chunks/chunk-MANNB4WZ.ts.map +0 -7
  77. package/dist/chunks/chunk-OBVJTKVY.ts.map +0 -7
  78. package/dist/chunks/chunk-OWEOZZZE.ts.map +0 -7
  79. package/dist/chunks/manager-ui-RGA26Z6G.ts.map +0 -7
  80. /package/dist/chunks/{chunk-IOM6E5FW.ts.map → chunk-BESRBKVO.ts.map} +0 -0
  81. /package/dist/chunks/{chunk-TZMVSTAM.ts.map → chunk-BYVHABNR.ts.map} +0 -0
  82. /package/dist/chunks/{file-selection-DDQN4LVD.ts.map → file-selection-XWACUTAH.ts.map} +0 -0
  83. /package/dist/chunks/{manager-result-dispatcher-XB75YLEG.ts.map → ignore-file-ui-OHFISFVC.ts.map} +0 -0
  84. /package/dist/chunks/{remote-selection-ui-WVMET5RI.ts.map → manager-result-dispatcher-WXE2BAQO.ts.map} +0 -0
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { assertRecoveryPolicy, BOUND_DIRECTORY_JOURNAL_VERSION, IGNORE_POLICY_JOURNAL_VERSION, ignorePolicyValidator, ignoreSourceBinding, recoveryPolicyKey, validateJournalPolicy, } from "../snapshot/snapshot-transaction-policy.js";
5
- import { IGNORE_SNAPSHOT_VERSION } from "../snapshot/snapshot-types.js";
5
+ import { isIgnoreSnapshotVersion } from "../snapshot/snapshot-types.js";
6
6
  import { readJsonIfExists, syncDirectory, writeJson } from "../state/json-file.js";
7
7
  import { readStateForConfig, statePathForConfig, syncStateFingerprint } from "../state/sync-state-store.js";
8
8
  import { confirmMergeReview } from "../ui/merge-review.js";
@@ -142,7 +142,7 @@ export async function readMergeJournal(config) {
142
142
  validateSnapshotFieldPolicy(snapshot);
143
143
  validateSnapshotSelection(snapshot);
144
144
  if ((journal.ignoreSource !== undefined
145
- ? snapshot.version !== IGNORE_SNAPSHOT_VERSION ||
145
+ ? !isIgnoreSnapshotVersion(snapshot.version) ||
146
146
  !sameSnapshotSelection(snapshot.selection, journal.upload.selection)
147
147
  : ![1, 2, 3, 4, 5].includes(snapshot.version)) ||
148
148
  typeof snapshot.id !== "string" ||
@@ -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 { requireNoPendingAdoption } from "../ignore/adoption-journal.js";
3
4
  import { loadConfig, syncCheckConfigFingerprint } from "../settings/config.js";
4
5
  import { effectiveSessionRoot, requireStableMergeSessionRoot, snapshotOptionsForContext, } from "../snapshot/session-paths.js";
5
6
  import { createSnapshot, filterSnapshotForConfigPolicy, mergeRemotePreservedFiles, observeSnapshot, regenerateSnapshotIdentity, scanSnapshot, snapshotWithObservedInventory, } from "../snapshot/snapshot.js";
@@ -15,8 +16,9 @@ import { conflictGroups, readConflictArtifact, saveConflictArtifact, } from "./c
15
16
  import { resolveReviewedGroup } from "./conflict-resolution.js";
16
17
  import { pruneCompletedConflicts } from "./conflict-retention.js";
17
18
  import { resolveContentConflicts } from "./content-conflicts.js";
18
- import { ContinuousError } from "./continuous-errors.js";
19
+ import { ContinuousError, TransferSizeError } from "./continuous-errors.js";
19
20
  import { planFileMerge } from "./file-merge-planner.js";
21
+ import { ignorePublicationNotice, withPublishedIgnoreRules } from "./ignore-publication.js";
20
22
  import { overlayLocalFields, portableSnapshot, sameLocalFields } from "./local-fields.js";
21
23
  import { acceptedState, matchesAcceptedState, writeAcceptedState } from "./merge-acceptance.js";
22
24
  import { applyMergedSnapshot, preflightMergedTargets } from "./merge-apply.js";
@@ -32,9 +34,11 @@ import { configuredSnapshotPathMatcher, inspectRemoteSelection, syncSessionsSele
32
34
  import { fileHashMap, hasLocalChanges, hasRemoteChanges, sameHashes, syncPolicyChanged } from "./sync-state.js";
33
35
  import { TEXT_MERGE_WORK_LIMIT } from "./text-merge.js";
34
36
  import { checkLiveProtection, validateMergeApplyReview, validateMergedPublication } from "./transfer-freshness.js";
37
+ import { requireTransferSize, selectedPublicationImage, transferSizeDetails, transferSizeLimitsEnabled, } from "./transfer-size-limits.js";
35
38
  const MAX_ATTEMPTS = 3;
36
39
  /** Established-baseline sync only. First-source selection remains in the existing command flow. */
37
40
  export async function mergeSync(ctx, options, factory = createSyncBackend, resolution) {
41
+ requireNoPendingAdoption();
38
42
  const timings = options.startupTimings ?? createStartupTimings();
39
43
  const sessionOwner = captureMutationOwner(ctx, options.signal);
40
44
  const validateOwner = (config) => {
@@ -185,7 +189,23 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
185
189
  const files = [...local.files, ...rawRemote.files];
186
190
  if (files.length > 16_384 ||
187
191
  files.reduce((bytes, file) => bytes + file.contentBase64.length * 0.75, 0) > 64 * 1024 * 1024) {
188
- throw new Error("Merged transfer exceeds the 64 MiB / 16,384 input-file bound; review an explicit push or pull instead.");
192
+ const message = "Merged transfer exceeds the 64 MiB / 16,384 input-file bound; review an explicit push or pull instead.";
193
+ if (!transferSizeLimitsEnabled(config))
194
+ throw new Error(message);
195
+ let details;
196
+ try {
197
+ const projected = portableSnapshot(filterSnapshotForConfigPolicy(rawRemote, config, { sessionDir: sessionRoot }), rawRemote.localFields);
198
+ details = transferSizeDetails(config, [
199
+ { side: "Local input", files: local.files },
200
+ { side: "Remote input", files: projected.files },
201
+ ]);
202
+ }
203
+ catch {
204
+ throw new ContinuousError("unsafe", message);
205
+ }
206
+ if (details)
207
+ throw new TransferSizeError(`${message} ${details}`);
208
+ throw new ContinuousError("unsafe", message);
189
209
  }
190
210
  }
191
211
  const remote = rawRemote
@@ -351,9 +371,12 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
351
371
  ...remote.files.filter((file) => withheld.has(file.path)),
352
372
  ],
353
373
  });
354
- const upload = mergeRemotePreservedFiles(publication, rawRemote, config, { sessionDir: sessionRoot });
355
374
  const publish = !sameHashes(fileHashMap(publication), fileHashMap(remote)) ||
356
375
  Boolean(config.partialSync && rawRemote.version < 3);
376
+ const candidate = mergeRemotePreservedFiles(publication, rawRemote, config, { sessionDir: sessionRoot });
377
+ const upload = publish ? await withPublishedIgnoreRules(candidate, config, options.signal) : candidate;
378
+ if (config.ignorePolicy && publish)
379
+ await validate();
357
380
  const apply = !sameHashes(fileHashMap(localRaw), fileHashMap(after));
358
381
  if (!publish && !apply) {
359
382
  const beforeEvidence = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
@@ -386,6 +409,8 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
386
409
  : "Pi Sync is already up to date.", progress ? "warning" : "info");
387
410
  return "applied";
388
411
  }
412
+ if (transferSizeLimitsEnabled(config))
413
+ requireTransferSize(config, ...(apply ? [{ side: "Local", files: accepted.files }] : []), ...(publish ? [selectedPublicationImage(upload, config, sessionRoot)] : []));
389
414
  await timings.measure("transfer preflight", () => preflightMergedTargets(localRaw, after, snapshotOptions, [
390
415
  ...(ctx.protectedSessionFiles ?? []),
391
416
  ...[ctx.sessionManager.getSessionFile?.()].filter((file) => Boolean(file)),
@@ -407,7 +432,8 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
407
432
  decisions: plan.decisions,
408
433
  capability: backend.capability,
409
434
  });
410
- if (!(await confirmMergeReview(ctx, summary.title, summary.content, options.signal, isCurrent, summary.confirmationLabel, summary.lines)))
435
+ const notice = ignorePublicationNotice(upload);
436
+ if (!(await confirmMergeReview(ctx, summary.title, notice ? `${notice}\n\n${summary.content}` : summary.content, options.signal, isCurrent, summary.confirmationLabel, notice ? [notice, "", ...summary.lines] : summary.lines)))
411
437
  return "cancelled";
412
438
  }
413
439
  await validate();
@@ -478,7 +504,7 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
478
504
  ? {
479
505
  validateIgnorePolicy: () => validateMergedPublication(ctx, config, snapshotOptions, localRaw, after, journal.stateIdentity, validateFresh),
480
506
  }
481
- : {}),
507
+ : { validateIgnorePolicy: validateFresh }),
482
508
  }));
483
509
  journal.committedHead = result.head;
484
510
  journal.warnings = result.warnings;
@@ -623,7 +649,11 @@ async function completeJournal(ctx, config, backend, journal, { validate, valida
623
649
  const observed = await timings.measure("transfer snapshot download", () => readSnapshotForHead(backend, head, signal, config));
624
650
  requireCompatibleRemoteSelection(config, observed);
625
651
  if (!sameHashes(fileHashMap(observed), fileHashMap(journal.upload)) ||
626
- JSON.stringify(observed.selection) !== JSON.stringify(journal.upload.selection))
652
+ JSON.stringify(observed.selection) !== JSON.stringify(journal.upload.selection) ||
653
+ observed.version !== journal.upload.version ||
654
+ (observed.ignoreRules === null) !== (journal.upload.ignoreRules === null) ||
655
+ observed.ignoreRules?.filename !== journal.upload.ignoreRules?.filename ||
656
+ observed.ignoreRules?.text !== journal.upload.ignoreRules?.text)
627
657
  throw new Error("Remote snapshot does not match the recorded merge publication.");
628
658
  const state = await timings.measure("transfer state read", () => readStateForConfig(config));
629
659
  if (matchesAcceptedState(state, config, head, journal.accepted ?? journal.after, journal.progress)) {
@@ -639,6 +669,19 @@ async function completeJournal(ctx, config, backend, journal, { validate, valida
639
669
  }
640
670
  if (inspectRemoteSelection(config.include, observed, config.exclude, config).kind !== "same")
641
671
  throw new Error("Pending merge has unavailable remote selection metadata; preserve its journal and backup for review.");
672
+ const requireReviewedApplyImage = journal.applyOnly && transferSizeLimitsEnabled(config);
673
+ if (requireReviewedApplyImage) {
674
+ const selected = journal.accepted ?? portableSnapshot(journal.after, config.localFields);
675
+ const details = transferSizeDetails(config, [{ side: "Local", files: selected.files }]);
676
+ if (details) {
677
+ const { sameBaseline, sameLocal } = await readRetirementEvidence();
678
+ if (sameBaseline && sameLocal) {
679
+ await clearMergeJournal(config);
680
+ throw new TransferSizeError(`Transfer blocked by size limits. ${details}`);
681
+ }
682
+ throw new TransferSizeError(`Transfer blocked by size limits. The local apply is not verified. Keep the journal and backup. Review the limits before retrying /sync sync. ${details}`);
683
+ }
684
+ }
642
685
  if (sessionRoot !== undefined)
643
686
  requireStableMergeSessionRoot(journal.before, journal.after, config.scope);
644
687
  await validateFresh();
@@ -651,7 +694,7 @@ async function completeJournal(ctx, config, backend, journal, { validate, valida
651
694
  const validateApplyReview = journal.localPolicyKey
652
695
  ? () => validateMergeApplyReview(backend, config, head, journal.stateIdentity, validateFresh, signal)
653
696
  : undefined;
654
- await timings.measure("transfer local apply", () => applyMergedSnapshot(journal.before, journal.after, protectedPaths, { ...snapshotOptions, validateMutation: validateApply, validateApplyReview }, validate, ctx.sessionManager.getSessionFile?.()));
697
+ await timings.measure("transfer local apply", () => applyMergedSnapshot(journal.before, journal.after, protectedPaths, { ...snapshotOptions, validateMutation: validateApply, validateApplyReview, requireReviewedApplyImage }, validate, ctx.sessionManager.getSessionFile?.()));
655
698
  await validate();
656
699
  const headAtAcceptance = await timings.measure("transfer remote head", () => backend.readHead(signal));
657
700
  await validate();
@@ -0,0 +1,33 @@
1
+ import { snapshotIncludesSessions } from "../snapshot/snapshot.js";
2
+ import { formatRuleChanges } from "../ui/ignore-rule-preview.js";
3
+ import { countPreservedRemoteFiles, formatPushSummary, formatTransferReview } from "../ui/sync-format.js";
4
+ import { setSyncStatus } from "../ui/sync-status.js";
5
+ import { confirmTransferReview } from "../ui/transfer-review.js";
6
+ import { ignorePublicationNotice } from "./ignore-publication.js";
7
+ import { throwIfAborted } from "./signals.js";
8
+ import { formatIgnorePolicyComparison, inspectRemoteSelection } from "./sync-policy.js";
9
+ export async function confirmPush(ctx, options, config, backend, local, upload, head, remote, validateMutation, title = snapshotIncludesSessions(upload) ? "Push pi settings and sessions?" : "Push pi settings?") {
10
+ validateMutation();
11
+ if (options.yes)
12
+ return true;
13
+ const summary = formatPushSummary(config, backend.destination, upload, head, countPreservedRemoteFiles(local, upload), remote);
14
+ const comparison = config.ignorePolicy && remote
15
+ ? inspectRemoteSelection(config.include, remote, config.exclude, config).ignorePolicyComparison
16
+ : undefined;
17
+ const notice = ignorePublicationNotice(upload);
18
+ const overwrite = comparison !== undefined && comparison !== "match";
19
+ const confirmed = await confirmTransferReview(ctx, overwrite ? "Overwrite remote policy and push?" : title, formatTransferReview(...(overwrite
20
+ ? [
21
+ formatIgnorePolicyComparison(comparison),
22
+ "This replaces the remote policy with this device's rules. Remote rules are not adopted on this device.",
23
+ `Sessions opt-in: ${remote?.selection?.version === 4 ? (remote.selection.sessions ? "on" : "off") : "legacy"} → ${config.ignorePolicy?.sessions ? "on" : "off"}.`,
24
+ formatRuleChanges(remote?.ignoreRules?.text, upload.ignoreRules?.text),
25
+ ]
26
+ : []), ...(notice ? [notice, ""] : []), summary), options.signal, validateMutation);
27
+ throwIfAborted(options.signal);
28
+ if (confirmed)
29
+ return true;
30
+ setSyncStatus(ctx, undefined);
31
+ ctx.ui.notify("Push cancelled.", "info");
32
+ return false;
33
+ }
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { constants } from "node:fs";
2
3
  import fs from "node:fs/promises";
3
4
  import path from "node:path";
@@ -65,7 +66,7 @@ export async function backupDirectionalSnapshot(snapshot, signal) {
65
66
  throwIfAborted(signal);
66
67
  };
67
68
  await validate();
68
- return { backupPath, validate };
69
+ return { backupPath, validate, digest: createHash("sha256").update(encoded).digest("hex") };
69
70
  }
70
71
  async function writeSnapshotBackup(snapshot, signal, durableParent = false) {
71
72
  throwIfAborted(signal);
@@ -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,28 +9,33 @@ 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";
11
- import { countPreservedRemoteFiles, formatPullSummary, formatPushSummary, formatTransferReview, } from "../ui/sync-format.js";
12
+ import { formatPullSummary } from "../ui/sync-format.js";
12
13
  import { setSyncStatus } from "../ui/sync-status.js";
13
14
  import { confirmTransferReview } from "../ui/transfer-review.js";
14
15
  import { startupTransferEnabled } from "./agent-policy.js";
15
16
  import { inspectCaseCleanup, revalidateCaseCleanup } from "./apply-review.js";
16
17
  import { checkpointDirectionalAction, foregroundDirectionalAction, keepProtectedRemoteSessions, localRestoreGuidance, notifyDirectionalSuccess, remoteRestoreGuidance, requireDirectionalPullBoundary, requireDirectionalSelection, validateDirectionalSettings, } from "./directional-action.js";
17
18
  import { confirmFieldMigration } from "./field-migration.js";
19
+ import { adoptionSettingsFingerprint, adoptRemoteRules, canReviewAdoption } from "./ignore-adoption.js";
20
+ import { withPublishedIgnoreRules } from "./ignore-publication.js";
18
21
  import { overlayLocalFields, portableSnapshot, sameLocalFields, validatePortableSnapshot } from "./local-fields.js";
19
22
  import { readMergeJournal, requireNoMergeJournal, retireMergeJournal } from "./merge-journal.js";
20
23
  import { mergeSync } from "./merged-sync.js";
24
+ import { confirmPush } from "./push-review.js";
21
25
  import { readRemoteSnapshot, readRemoteSnapshotForUpload, readSnapshotForHead, requireCompatibleRemoteSelection, sameRemoteHead, snapshotForUpload, } from "./remote-snapshot.js";
22
26
  import { throwIfAborted } from "./signals.js";
23
27
  import { createSyncDecision } from "./sync-decision.js";
24
28
  import { errorMessage, PublicationStatePersistenceError } from "./sync-errors.js";
25
29
  import { backupDirectionalSnapshot, backupLocal, captureMutationOwner, LocalBackupVerificationError, maybeReload, protectedSessionPaths, } from "./sync-local.js";
26
- import { formatIgnorePolicyComparison, inspectRemoteSelection, syncSelectionHasContent, syncSessionsSelected, } from "./sync-policy.js";
30
+ import { inspectRemoteSelection, syncSelectionHasContent, syncSessionsSelected } from "./sync-policy.js";
27
31
  import { acceptedSelection, canPullRemoteSessionsOnFirstSync, canPullRemoteSettingsOnFirstSync, fileHashMap, hasLocalChanges, hasRemoteChanges, remoteChangedSinceState, sameHashes, shouldRefreshSyncedState, snapshotHashesMatchState, snapshotsMatch, syncPolicyChanged, } from "./sync-state.js";
28
32
  import { checkLiveProtection, directionalApplyGuards, requireIgnoreBaselineReview, requireResolvedDirectionalProgress, validateDirectionalPublication, } from "./transfer-freshness.js";
33
+ import { requireTransferSize, selectedPublicationImage, selectedPullImage, transferSizeLimitsEnabled, } from "./transfer-size-limits.js";
29
34
  const VERSION = 1;
30
35
  export { PublicationStatePersistenceError, RollbackPublicationError } from "./sync-errors.js";
31
36
  export { rollback } from "./sync-rollback.js";
32
37
  export async function push(ctx, options, input, factory = createSyncBackend) {
38
+ requireNoPendingAdoption();
33
39
  const validateOwner = captureMutationOwner(ctx, options.signal);
34
40
  const validateCommittedOwner = captureMutationOwner(ctx);
35
41
  const action = foregroundDirectionalAction(ctx, options);
@@ -75,21 +81,22 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
75
81
  ? await readSnapshotForHead(backend, head, options.signal, config)
76
82
  : await readRemoteSnapshotForUpload(backend, config, head, state, options);
77
83
  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)
84
+ const policyOverwrite = Boolean(config.ignorePolicy &&
85
+ remoteForUpload &&
86
+ inspectRemoteSelection(config.include, remoteForUpload, config.exclude, config).kind === "different");
87
+ if (policyOverwrite && remoteForUpload && (options.auto || options.background || options.yes || !ctx.hasUI))
88
+ requireCompatibleRemoteSelection(config, remoteForUpload);
89
+ if (action && !policyOverwrite)
84
90
  requireDirectionalSelection(config, state, localRaw, remoteForUpload, snapshotOptions.sessionDir);
85
91
  else
86
92
  requireIgnoreBaselineReview(ctx, config, state, options);
87
- if (!action && remoteForUpload && !options.force) {
93
+ if (!action && remoteForUpload && !options.force && !policyOverwrite) {
88
94
  requireCompatibleRemoteSelection(config, remoteForUpload);
89
95
  }
90
96
  if (!action &&
91
97
  remoteChangedSinceState(head, state, config, (left, right) => backend.sameRevision(left, right)) &&
92
- !options.force) {
98
+ !options.force &&
99
+ !policyOverwrite) {
93
100
  const remoteForConflict = remoteForUpload
94
101
  ? filterSnapshotForConfigPolicy(remoteForUpload, config, snapshotOptions)
95
102
  : undefined;
@@ -114,17 +121,35 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
114
121
  return "cancelled";
115
122
  }
116
123
  const configIdentity = syncCheckConfigFingerprint(config);
124
+ const validateSettings = async () => {
125
+ if (action)
126
+ await validateDirectionalSettings(options, config, validateMutation);
127
+ else if (configIdentity !== syncCheckConfigFingerprint(await loadConfig(options.setup, options.signal)))
128
+ throw new Error("Settings changed during push review.");
129
+ validateMutation();
130
+ };
131
+ const checkUpload = (upload) => {
132
+ if (transferSizeLimitsEnabled(config))
133
+ requireTransferSize(config, selectedPublicationImage(upload, config, snapshotOptions.sessionDir));
134
+ };
117
135
  let upload = await snapshotForUpload(backend, config, local, head, remoteForUpload, snapshotOptions);
118
136
  if (action) {
119
137
  upload = keepProtectedRemoteSessions(config, upload, remoteForUpload, snapshotOptions.sessionDir, reviewedProtectedPaths);
120
138
  validatePortableSnapshot(upload);
121
139
  }
140
+ upload = await withPublishedIgnoreRules(upload, config, options.signal);
141
+ validateMutation();
142
+ checkUpload(upload);
122
143
  if (!config.skipSecretScan) {
123
- const secrets = scanSnapshot(local);
144
+ const secrets = scanSnapshot({ ...local, ...(upload.ignoreRules ? { ignoreRules: upload.ignoreRules } : {}) });
124
145
  if (secrets.length > 0) {
125
146
  throw new Error(`Refusing to push possible secrets:\n${secrets.map((s) => `- ${s}`).join("\n")}`);
126
147
  }
127
148
  }
149
+ if ((!action || policyOverwrite) &&
150
+ !(await confirmPush(ctx, options, config, backend, local, upload, head, remoteForUpload, validateMutation))) {
151
+ return "cancelled";
152
+ }
128
153
  if (action) {
129
154
  await checkpointDirectionalAction(options, {
130
155
  direction: "push",
@@ -138,9 +163,6 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
138
163
  });
139
164
  validateMutation();
140
165
  }
141
- else if (!(await confirmPush(ctx, options, config, backend, local, upload, head, remoteForUpload, validateMutation))) {
142
- return "cancelled";
143
- }
144
166
  if (options.force) {
145
167
  const refreshedHead = await backend.readHead(options.signal);
146
168
  validateMutation();
@@ -156,17 +178,15 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
156
178
  }
157
179
  validateMutation();
158
180
  upload = await snapshotForUpload(backend, config, local, head, remoteForUpload, snapshotOptions);
181
+ validateMutation();
182
+ checkUpload(upload);
159
183
  if (!(await confirmPush(ctx, options, config, backend, local, upload, head, remoteForUpload, validateMutation, "Remote changed during review. Push the refreshed plan?"))) {
160
184
  return "cancelled";
161
185
  }
162
186
  }
163
187
  }
164
188
  validateMutation();
165
- if (action)
166
- await validateDirectionalSettings(options, config, validateMutation);
167
- else if (configIdentity !== syncCheckConfigFingerprint(await loadConfig(options.setup)))
168
- throw new Error("Settings changed during push review.");
169
- validateMutation();
189
+ await validateSettings();
170
190
  if (!action &&
171
191
  (config.scope === "agent-directory" ||
172
192
  validateIgnorePolicy ||
@@ -185,11 +205,7 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
185
205
  snapshotOptions.sessionDir !== (await effectiveSessionRoot(ctx, config, options.signal)))
186
206
  throw new Error("Pi session storage changed during push review.");
187
207
  validateMutation();
188
- if (action)
189
- await validateDirectionalSettings(options, config, validateMutation);
190
- else if (configIdentity !== syncCheckConfigFingerprint(await loadConfig(options.setup)))
191
- throw new Error("Settings changed during push review.");
192
- validateMutation();
208
+ await validateSettings();
193
209
  const validatePublication = validateIgnorePolicy || options.background || action
194
210
  ? async () => {
195
211
  if (action && !sameRemoteHead(backend, head, await backend.readHead(options.signal)))
@@ -201,14 +217,9 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
201
217
  await validateDirectionalSettings(options, config, validateMutation);
202
218
  checkLiveProtection(ctx, snapshotOptions.sessionDir, reviewedProtectedPaths);
203
219
  }
204
- : (validateIgnorePolicy ??
205
- (async () => {
206
- if (configIdentity !== syncCheckConfigFingerprint(await loadConfig(options.setup, options.signal)))
207
- throw new Error("Settings changed before push publication.");
208
- validateMutation();
209
- })), "push", Boolean(action));
220
+ : (validateIgnorePolicy ?? validateSettings), "push", Boolean(action));
210
221
  }
211
- : undefined;
222
+ : validateSettings;
212
223
  if (validateIgnorePolicy) {
213
224
  validatePortableSnapshot(upload);
214
225
  await validateIgnorePolicy();
@@ -231,7 +242,7 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
231
242
  startedPublication = true;
232
243
  }
233
244
  : options.onCommit,
234
- ...(validatePublication ? { validateIgnorePolicy: validatePublication } : {}),
245
+ validateIgnorePolicy: validatePublication,
235
246
  });
236
247
  }
237
248
  catch (error) {
@@ -291,6 +302,10 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
291
302
  const action = foregroundDirectionalAction(ctx, options);
292
303
  if (action && initial)
293
304
  throw new Error("Single-action Pull cannot be used for initial-source selection.");
305
+ const adoptionReview = !initial && canReviewAdoption(ctx, options);
306
+ const journal = adoptionReview ? await loadAdoptionJournal() : undefined;
307
+ if (!adoptionReview)
308
+ requireNoPendingAdoption();
294
309
  const validateOwner = captureMutationOwner(ctx, options.signal);
295
310
  const validateCommittedOwner = captureMutationOwner(ctx);
296
311
  const config = action ? await loadConfigForCheck(undefined, options.signal) : await loadConfig(options.setup);
@@ -303,7 +318,7 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
303
318
  if (initial && initial.configIdentity !== configIdentity)
304
319
  throw new Error("Settings changed before initial pull; run sync again.");
305
320
  await requireNoMergeJournal(config, options);
306
- if (action && (await pendingTransactionEntries()).length)
321
+ if (action && !journal && (await pendingTransactionEntries()).length)
307
322
  throw new Error("A pending local transaction must be reconciled before Pull; its evidence was retained.");
308
323
  validateMutation();
309
324
  setSyncStatus(ctx, `pulling ${config.setupName}`, { activity: "pulling" });
@@ -317,6 +332,26 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
317
332
  if (action)
318
333
  snapshotOptions.sessionDir = await effectiveSessionRoot(ctx, config, options.signal);
319
334
  validateMutation();
335
+ if (journal) {
336
+ if (journal.setupName !== config.setupName ||
337
+ journal.setupFingerprint !== adoptionSettingsFingerprint(config) ||
338
+ config.pathPolicy !== "ignore-file")
339
+ throw new Error("Pending rule adoption belongs to a different setup. Preserve its journal and use the originating setup.");
340
+ const remote = await readSnapshotForHead(backend, journal.head, options.signal, config);
341
+ validateMutation();
342
+ return adoptRemoteRules({
343
+ ctx,
344
+ options,
345
+ config,
346
+ backend,
347
+ state,
348
+ head: journal.head,
349
+ remote,
350
+ snapshotOptions,
351
+ validateMutation,
352
+ journal,
353
+ });
354
+ }
320
355
  const validateIgnorePolicy = ignorePolicyValidator({ ...snapshotOptions, validateMutation });
321
356
  if (initial && initial.sessionDir !== snapshotOptions.sessionDir)
322
357
  throw new Error("Pi session storage changed before initial pull; run sync again.");
@@ -325,18 +360,40 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
325
360
  if (initial && !sameHashes(initial.localHashes, fileHashMap(local)))
326
361
  throw new Error("Local bytes changed before initial pull; run sync again.");
327
362
  let preimageRemote;
363
+ let adoption;
328
364
  const { head, snapshot: remote } = await readRemoteSnapshot(backend, config, options.signal, {
329
365
  ...snapshotOptions,
330
- ...(action
366
+ ...(action || (adoptionReview && config.ignorePolicy)
331
367
  ? {
332
368
  validateSelection: (raw) => {
333
- requireDirectionalSelection(config, state, local, raw, snapshotOptions.sessionDir);
334
- preimageRemote = raw;
369
+ const comparison = inspectRemoteSelection(config.include, raw, config.exclude, config).ignorePolicyComparison;
370
+ if (adoptionReview && comparison === "mismatch") {
371
+ adoption = raw;
372
+ }
373
+ else if (action) {
374
+ requireDirectionalSelection(config, state, local, raw, snapshotOptions.sessionDir);
375
+ preimageRemote = raw;
376
+ }
377
+ else {
378
+ requireCompatibleRemoteSelection(config, raw);
379
+ }
335
380
  },
336
381
  }
337
382
  : {}),
338
383
  });
339
384
  validateMutation();
385
+ if (adoption && head)
386
+ return adoptRemoteRules({
387
+ ctx,
388
+ options,
389
+ config,
390
+ backend,
391
+ state,
392
+ head,
393
+ remote: adoption,
394
+ snapshotOptions,
395
+ validateMutation,
396
+ });
340
397
  if (initial && !matchesInitialHead(initial, backend, head))
341
398
  throw new Error("Remote changed before initial pull; run sync again.");
342
399
  if (!action)
@@ -366,6 +423,9 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
366
423
  if (action || config.scope === "agent-directory")
367
424
  requireStableMergeSessionRoot(local, physical, config.scope);
368
425
  const reviewedProtectedPaths = protectedSessionPaths(ctx, snapshotOptions.sessionDir);
426
+ const sizeLimited = transferSizeLimitsEnabled(config);
427
+ if (sizeLimited)
428
+ requireTransferSize(config, selectedPullImage(logical, local, reviewedProtectedPaths));
369
429
  const remoteChanged = hasRemoteChanges(remote, state, config, reviewedProtectedPaths);
370
430
  if (!action && localChanged && remoteChanged && state.lastAppliedSnapshot && !options.force) {
371
431
  throw createSyncDecision({
@@ -461,6 +521,13 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
461
521
  await validateIgnorePolicy();
462
522
  }
463
523
  const protectedPaths = protectedSessionPaths(ctx, snapshotOptions.sessionDir);
524
+ const validateApplySettings = async () => {
525
+ if (configIdentity !== syncCheckConfigFingerprint(await loadConfig(options.setup, options.signal)))
526
+ throw new Error("Settings changed before pull apply.");
527
+ validateMutation();
528
+ if (sizeLimited)
529
+ checkLiveProtection(ctx, snapshotOptions.sessionDir, reviewedProtectedPaths);
530
+ };
464
531
  const applyGuards = directionalApplyGuards({
465
532
  ctx,
466
533
  config,
@@ -484,6 +551,7 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
484
551
  await validateActionBoundary?.();
485
552
  }
486
553
  : validateIgnorePolicy,
554
+ validateSettings: action ? undefined : validateApplySettings,
487
555
  effectiveRoot: Boolean(action),
488
556
  });
489
557
  applyGuards.validateMutation();
@@ -493,7 +561,9 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
493
561
  ...snapshotOptions,
494
562
  sessionDir: applySessionDir,
495
563
  ...applyGuards,
496
- ...(action || config.scope === "agent-directory" || validateIgnorePolicy ? { reviewedLocal: local } : {}),
564
+ ...(action || config.scope === "agent-directory" || validateIgnorePolicy || sizeLimited
565
+ ? { reviewedLocal: local }
566
+ : {}),
497
567
  expectedFileHashes: config.localFields?.length
498
568
  ? { "settings.json": fileHashMap(local)["settings.json"] ?? null }
499
569
  : undefined,
@@ -548,6 +618,7 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
548
618
  return "applied";
549
619
  }
550
620
  export async function syncBoth(ctx, options, factory = createSyncBackend) {
621
+ requireNoPendingAdoption();
551
622
  if (options.directionalAction)
552
623
  throw new Error("Single-action transfer cannot authorize bidirectional Sync.");
553
624
  const validateMutation = captureMutationOwner(ctx, options.signal);
@@ -702,24 +773,6 @@ export async function syncBoth(ctx, options, factory = createSyncBackend) {
702
773
  if (!options.silent)
703
774
  ctx.ui.notify("pi-sync is already up to date.", "info");
704
775
  }
705
- async function confirmPush(ctx, options, config, backend, local, upload, head, remote, validateMutation, title = snapshotIncludesSessions(upload) ? "Push pi settings and sessions?" : "Push pi settings?") {
706
- validateMutation();
707
- if (options.yes)
708
- return true;
709
- const summary = formatPushSummary(config, backend.destination, upload, head, countPreservedRemoteFiles(local, upload), remote);
710
- const comparison = config.ignorePolicy && remote
711
- ? inspectRemoteSelection(config.include, remote, config.exclude, config).ignorePolicyComparison
712
- : 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);
716
- throwIfAborted(options.signal);
717
- if (confirmed)
718
- return true;
719
- setSyncStatus(ctx, undefined);
720
- ctx.ui.notify("Push cancelled.", "info");
721
- return false;
722
- }
723
776
  function matchesInitialHead(initial, backend, current) {
724
777
  return sameRemoteHead(backend, initial.head, current);
725
778
  }
@@ -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"}`]),