@narumitw/pi-sync 0.62.0 → 0.63.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 (110) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +29 -15
  3. package/dist/chunks/{chunk-MNYRU5U5.ts → chunk-27F5W7DX.ts} +3 -2
  4. package/dist/chunks/{chunk-MNYRU5U5.ts.map → chunk-27F5W7DX.ts.map} +2 -2
  5. package/dist/chunks/chunk-CKUGCBHP.ts +114 -0
  6. package/dist/chunks/chunk-CKUGCBHP.ts.map +7 -0
  7. package/dist/chunks/chunk-EJDDRS6O.ts +17 -0
  8. package/dist/chunks/chunk-EJDDRS6O.ts.map +7 -0
  9. package/dist/chunks/{chunk-6PFZUEUG.ts → chunk-EXDWEFIJ.ts} +52 -135
  10. package/dist/chunks/chunk-EXDWEFIJ.ts.map +7 -0
  11. package/dist/chunks/{chunk-NHFGAZEC.ts → chunk-HSCAFOT5.ts} +7 -7
  12. package/dist/chunks/chunk-HSCAFOT5.ts.map +7 -0
  13. package/dist/chunks/chunk-MANNB4WZ.ts +36 -0
  14. package/dist/chunks/chunk-MANNB4WZ.ts.map +7 -0
  15. package/dist/chunks/{chunk-ZB3GNX3P.ts → chunk-S6FUUWV5.ts} +139 -12
  16. package/dist/chunks/chunk-S6FUUWV5.ts.map +7 -0
  17. package/dist/chunks/{chunk-PWESMTH6.ts → chunk-SXCH4Q5O.ts} +38 -20
  18. package/dist/chunks/chunk-SXCH4Q5O.ts.map +7 -0
  19. package/dist/chunks/{chunk-INECVQNR.ts → chunk-UGS6RYDZ.ts} +5 -3
  20. package/dist/chunks/chunk-UGS6RYDZ.ts.map +7 -0
  21. package/dist/chunks/{chunk-3E3TR3JE.ts → chunk-V76KCWHO.ts} +6 -4
  22. package/dist/chunks/{chunk-3E3TR3JE.ts.map → chunk-V76KCWHO.ts.map} +1 -1
  23. package/dist/chunks/{chunk-GSCZ4VXV.ts → chunk-VQ47JBLF.ts} +2 -2
  24. package/dist/chunks/chunk-WFBHWYI6.ts +18 -0
  25. package/dist/chunks/chunk-WFBHWYI6.ts.map +7 -0
  26. package/dist/chunks/{command-handler-6ATREPG7.ts → command-handler-VINMQ7ZM.ts} +19 -36
  27. package/dist/chunks/command-handler-VINMQ7ZM.ts.map +7 -0
  28. package/dist/chunks/{conflict-review-MAOGTIAI.ts → conflict-review-PCDFRIVB.ts} +2 -2
  29. package/dist/chunks/{file-selection-QR2KZVGD.ts → file-selection-KID23GAD.ts} +15 -8
  30. package/dist/chunks/file-selection-KID23GAD.ts.map +7 -0
  31. package/dist/chunks/{manager-result-dispatcher-MC6EQOQY.ts → manager-result-dispatcher-GDB74IOP.ts} +6 -5
  32. package/dist/chunks/{manager-ui-AOFUNXAJ.ts → manager-ui-YHDECYKI.ts} +197 -322
  33. package/dist/chunks/manager-ui-YHDECYKI.ts.map +7 -0
  34. package/dist/chunks/{remote-selection-ui-4BTP2OJR.ts → remote-selection-ui-GPITNEBF.ts} +5 -4
  35. package/dist/chunks/{setup-switch-Y6AMFFNK.ts → setup-switch-L54X5U5I.ts} +4 -4
  36. package/dist/chunks/{setup-wizard-5G426MOZ.ts → setup-wizard-YO4MCPUF.ts} +7 -3
  37. package/dist/chunks/{setup-wizard-5G426MOZ.ts.map → setup-wizard-YO4MCPUF.ts.map} +1 -1
  38. package/dist/chunks/{sync-inspection-ITZ6Z4DE.ts → sync-inspection-H2WX5SUT.ts} +3 -3
  39. package/dist/chunks/{sync-operations-NMVKF7SE.ts → sync-operations-2MZAYHL2.ts} +2 -2
  40. package/dist/daemon/dist/cli.js +1 -1
  41. package/dist/daemon/dist/consent.js +134 -16
  42. package/dist/daemon/dist/engine/backends/git/git-backend.js +61 -30
  43. package/dist/daemon/dist/engine/ignore/ignore-initialization.js +93 -27
  44. package/dist/daemon/dist/engine/ignore/ignore-settings.js +85 -14
  45. package/dist/daemon/dist/engine/settings/config-file.js +1 -1
  46. package/dist/daemon/dist/engine/settings/config.js +71 -28
  47. package/dist/daemon/dist/engine/settings/settings-management.js +8 -2
  48. package/dist/daemon/dist/engine/snapshot/session-paths.js +7 -2
  49. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-policy.js +37 -17
  50. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +55 -13
  51. package/dist/daemon/dist/engine/sync/agent-plan.js +1 -0
  52. package/dist/daemon/dist/engine/sync/agent-sync.js +8 -1
  53. package/dist/daemon/dist/engine/sync/continuous-sync.js +32 -15
  54. package/dist/daemon/dist/engine/sync/merge-acceptance.js +29 -0
  55. package/dist/daemon/dist/engine/sync/merge-apply.js +7 -4
  56. package/dist/daemon/dist/engine/sync/merge-journal.js +33 -14
  57. package/dist/daemon/dist/engine/sync/merged-sync.js +31 -39
  58. package/dist/daemon/dist/engine/sync/remote-snapshot.js +17 -2
  59. package/dist/daemon/dist/engine/sync/session-push.js +20 -6
  60. package/dist/daemon/dist/engine/sync/sync-mutations.js +71 -50
  61. package/dist/daemon/dist/engine/sync/sync-policy.js +28 -3
  62. package/dist/daemon/dist/engine/sync/sync-state.js +3 -8
  63. package/dist/daemon/dist/engine/sync/transfer-freshness.js +82 -0
  64. package/dist/daemon/dist/engine-service.js +124 -27
  65. package/dist/daemon/dist/monitor.js +84 -32
  66. package/dist/daemon/dist/server.js +46 -5
  67. package/dist/daemon/dist/service-host.js +2 -1
  68. package/dist/daemon/package.json +1 -1
  69. package/dist/index.ts +28 -25
  70. package/dist/index.ts.map +4 -4
  71. package/package.json +3 -3
  72. package/skills/configure-pi-sync/SKILL.md +17 -64
  73. package/skills/configure-pi-sync/references/configuration.md +60 -20
  74. package/src/commands/command-execution.ts +12 -8
  75. package/src/commands/command-types.ts +1 -0
  76. package/src/daemon/pi-client.ts +4 -2
  77. package/src/settings/config.ts +1 -0
  78. package/src/sync/automatic-sync.ts +9 -2
  79. package/src/sync/setup-switch.ts +38 -15
  80. package/src/sync/startup-check.ts +7 -4
  81. package/src/ui/excluded-paths-ui.ts +2 -2
  82. package/src/ui/file-selection.ts +7 -2
  83. package/src/ui/ignore-file-guidance.ts +7 -0
  84. package/src/ui/ignore-file-ui.ts +28 -202
  85. package/src/ui/manager-state.ts +27 -15
  86. package/src/ui/manager-ui.ts +4 -1
  87. package/src/ui/remote-selection-ui.ts +51 -24
  88. package/src/ui/settings-ui.ts +132 -81
  89. package/src/ui/setup/setup-actions.ts +16 -4
  90. package/src/ui/setup/setup-prompts.ts +55 -9
  91. package/src/ui/setup/setup-switcher.ts +24 -11
  92. package/src/ui/storage-connections-ui.ts +33 -11
  93. package/src/ui/sync-setups-ui.ts +24 -7
  94. package/dist/chunks/chunk-6PFZUEUG.ts.map +0 -7
  95. package/dist/chunks/chunk-ECYCNZOE.ts +0 -12
  96. package/dist/chunks/chunk-ECYCNZOE.ts.map +0 -7
  97. package/dist/chunks/chunk-INECVQNR.ts.map +0 -7
  98. package/dist/chunks/chunk-NHFGAZEC.ts.map +0 -7
  99. package/dist/chunks/chunk-PWESMTH6.ts.map +0 -7
  100. package/dist/chunks/chunk-ZB3GNX3P.ts.map +0 -7
  101. package/dist/chunks/command-handler-6ATREPG7.ts.map +0 -7
  102. package/dist/chunks/file-selection-QR2KZVGD.ts.map +0 -7
  103. package/dist/chunks/manager-ui-AOFUNXAJ.ts.map +0 -7
  104. /package/dist/chunks/{chunk-GSCZ4VXV.ts.map → chunk-VQ47JBLF.ts.map} +0 -0
  105. /package/dist/chunks/{conflict-review-MAOGTIAI.ts.map → conflict-review-PCDFRIVB.ts.map} +0 -0
  106. /package/dist/chunks/{manager-result-dispatcher-MC6EQOQY.ts.map → manager-result-dispatcher-GDB74IOP.ts.map} +0 -0
  107. /package/dist/chunks/{remote-selection-ui-4BTP2OJR.ts.map → remote-selection-ui-GPITNEBF.ts.map} +0 -0
  108. /package/dist/chunks/{setup-switch-Y6AMFFNK.ts.map → setup-switch-L54X5U5I.ts.map} +0 -0
  109. /package/dist/chunks/{sync-inspection-ITZ6Z4DE.ts.map → sync-inspection-H2WX5SUT.ts.map} +0 -0
  110. /package/dist/chunks/{sync-operations-NMVKF7SE.ts.map → sync-operations-2MZAYHL2.ts.map} +0 -0
@@ -1,11 +1,11 @@
1
1
  import { createSyncBackend } from "../backends/backend-factory.js";
2
- import { expectedRemoteHead, SyncBackendConflictError, } from "../backends/sync-backend.js";
2
+ import { expectedRemoteHead, SyncBackendConflictError } from "../backends/sync-backend.js";
3
3
  import { loadConfig, syncCheckConfigFingerprint } from "../settings/config.js";
4
4
  import { effectiveSessionRoot, requireStableMergeSessionRoot, snapshotOptionsForContext, } from "../snapshot/session-paths.js";
5
5
  import { createSnapshot, filterSnapshotForConfigPolicy, mergeRemotePreservedFiles, regenerateSnapshotIdentity, scanSnapshot, } from "../snapshot/snapshot.js";
6
6
  import { ignorePolicyValidator } from "../snapshot/snapshot-transaction-policy.js";
7
- import { hasCurrentMergeBaseline, pruneMergeBaselines, readMergeAncestors, stageMergeBaseline, } from "../state/merge-baseline-store.js";
8
- import { readStateForConfig, statePathForConfig, syncStateFingerprint, writeStateForConfig, } from "../state/sync-state-store.js";
7
+ import { hasCurrentMergeBaseline, pruneMergeBaselines, readMergeAncestors } from "../state/merge-baseline-store.js";
8
+ import { readStateForConfig, statePathForConfig, syncStateFingerprint } from "../state/sync-state-store.js";
9
9
  import { confirmMergeReview } from "../ui/merge-review.js";
10
10
  import { mergedSyncSummary } from "../ui/merged-sync-summary.js";
11
11
  import { safeTerminalText } from "../ui/terminal-text.js";
@@ -18,18 +18,20 @@ import { resolveContentConflicts } from "./content-conflicts.js";
18
18
  import { ContinuousError } from "./continuous-errors.js";
19
19
  import { planFileMerge } from "./file-merge-planner.js";
20
20
  import { overlayLocalFields, portableSnapshot, sameLocalFields } from "./local-fields.js";
21
+ import { acceptedState, matchesAcceptedState, writeAcceptedState } from "./merge-acceptance.js";
21
22
  import { applyMergedSnapshot, preflightMergedTargets } from "./merge-apply.js";
22
23
  import { assertMergeJournalPolicy, clearMergeJournal, mergeJournalIdentity, mergeJournalPolicy, readMergeJournal, reviewInactiveIgnoreMerge, sameMergeRecoveryHead, writeMergeJournal, } from "./merge-journal.js";
23
24
  import { mergeTransferError } from "./merge-transfer-error.js";
24
- import { acceptedMergeFiles, progressState } from "./partial-progress.js";
25
+ import { acceptedMergeFiles } from "./partial-progress.js";
25
26
  import { formatRemoteSelectionStatus, readSnapshotForHead, requireCompatibleRemoteSelection, } from "./remote-snapshot.js";
26
27
  import { resolveSettingsConflicts } from "./settings-conflicts.js";
27
28
  import { createStartupTimings } from "./startup-timings.js";
28
29
  import { createSyncDecision } from "./sync-decision.js";
29
30
  import { backupLocal, captureMutationOwner, protectedSessionPaths } from "./sync-local.js";
30
31
  import { configuredSnapshotPathMatcher, inspectRemoteSelection, syncSessionsSelected } from "./sync-policy.js";
31
- import { acceptedSelection, fileHashMap, hasLocalChanges, hasRemoteChanges, sameHashes, syncPolicyChanged, } from "./sync-state.js";
32
+ import { fileHashMap, hasLocalChanges, hasRemoteChanges, sameHashes, syncPolicyChanged } from "./sync-state.js";
32
33
  import { TEXT_MERGE_WORK_LIMIT } from "./text-merge.js";
34
+ import { checkLiveProtection, validateMergeApplyReview, validateMergedPublication } from "./transfer-freshness.js";
33
35
  const MAX_ATTEMPTS = 3;
34
36
  /** Established-baseline sync only. First-source selection remains in the existing command flow. */
35
37
  export async function mergeSync(ctx, options, factory = createSyncBackend, resolution) {
@@ -418,7 +420,7 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
418
420
  await validate();
419
421
  const refreshedHead = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
420
422
  await validate();
421
- if (!refreshedHead || !backend.sameRevision(refreshedHead.revision, head.revision))
423
+ if (!sameMergeRecoveryHead(backend, refreshedHead, head))
422
424
  throw new ContinuousError("stale", "Remote changed during review; no merged transfer was performed.");
423
425
  await options.agentAcceptance?.commitCandidate?.();
424
426
  await validate();
@@ -469,7 +471,11 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
469
471
  const result = await timings.measure("transfer remote publication", () => backend.publishSnapshot(upload, expectedRemoteHead(head), {
470
472
  signal: options.signal,
471
473
  onCommit: options.onCommit,
472
- ...(validateIgnore ? { validateIgnorePolicy: validateFresh } : {}),
474
+ ...(validateIgnore
475
+ ? {
476
+ validateIgnorePolicy: () => validateMergedPublication(ctx, config, snapshotOptions, localRaw, after, journal.stateIdentity, validateFresh),
477
+ }
478
+ : {}),
473
479
  }));
474
480
  journal.committedHead = result.head;
475
481
  journal.warnings = result.warnings;
@@ -525,6 +531,7 @@ async function completeJournal(ctx, config, backend, journal, { validate, valida
525
531
  if (journal.identity !== mergeJournalIdentity(config, backend.identity) ||
526
532
  !sameLocalFields(journal.upload.localFields, config.localFields))
527
533
  throw new Error("Merge journal belongs to a different setup, selection or local-field policy; preserve it for reviewed recovery.");
534
+ assertMergeJournalPolicy(journal, config);
528
535
  await validateFresh();
529
536
  const sessionRoot = config.scope === "agent-directory" || syncSessionsSelected(config)
530
537
  ? await effectiveSessionRoot(ctx, config, signal)
@@ -545,6 +552,7 @@ async function completeJournal(ctx, config, backend, journal, { validate, valida
545
552
  validateMutation();
546
553
  if (!sameMergeRecoveryHead(backend, head, latest))
547
554
  throw new Error("Remote head changed during merge recovery; journal and backup retained.");
555
+ await validateFresh();
548
556
  return {
549
557
  sameBaseline: syncStateFingerprint(state) === journal.stateIdentity,
550
558
  sameLocal: sameHashes(fileHashMap(local), fileHashMap(journal.before)),
@@ -559,7 +567,7 @@ async function completeJournal(ctx, config, backend, journal, { validate, valida
559
567
  const state = await timings.measure("transfer state read", () => readStateForConfig(config));
560
568
  await validate();
561
569
  if (matchesAcceptedState(state, config, journal.committedHead, journal.accepted ?? journal.after, journal.progress)) {
562
- if (config.ignorePolicy)
570
+ if (journal.localPolicyKey)
563
571
  await validateFresh();
564
572
  await clearMergeJournal(config);
565
573
  await validate();
@@ -569,7 +577,7 @@ async function completeJournal(ctx, config, backend, journal, { validate, valida
569
577
  }
570
578
  }
571
579
  if (head &&
572
- (journal.version === 2 || head.selection?.version === 4) &&
580
+ (journal.ignoreSource || head.selection?.version === 4) &&
573
581
  inspectRemoteSelection(config.include, { selection: head.selection, files: [] }, config.exclude, config).kind !==
574
582
  "same")
575
583
  throw new Error("Remote ignore-file policy differs or is unavailable; preserve the pending merge for review.");
@@ -577,7 +585,7 @@ async function completeJournal(ctx, config, backend, journal, { validate, valida
577
585
  head &&
578
586
  (backend.sameRevision(head.revision, journal.expectedHead.revision) ||
579
587
  backend.matchesUncommittedRecoveryHead?.(head, journal.expectedHead))) {
580
- if (journal.version === 2 &&
588
+ if (journal.ignoreSource &&
581
589
  (head.snapshotId !== journal.expectedHead.snapshotId ||
582
590
  head.snapshotRef !== journal.expectedHead.snapshotRef ||
583
591
  head.snapshotId === journal.upload.id))
@@ -585,7 +593,7 @@ async function completeJournal(ctx, config, backend, journal, { validate, valida
585
593
  const { sameBaseline, sameLocal } = await readRetirementEvidence();
586
594
  validateMutation();
587
595
  if (!sameBaseline || !sameLocal) {
588
- if (journal.version === 2) {
596
+ if (journal.ignoreSource) {
589
597
  if (!sameBaseline)
590
598
  throw new Error("Sync baseline changed after uncertain publication; preserve the journal and backup for review.");
591
599
  return reviewInactiveIgnoreMerge(ctx, config, backend, journal, head, options, validateFresh, isCurrent);
@@ -630,12 +638,21 @@ async function completeJournal(ctx, config, backend, journal, { validate, valida
630
638
  throw new Error("Pending merge has unavailable remote selection metadata; preserve its journal and backup for review.");
631
639
  if (sessionRoot !== undefined)
632
640
  requireStableMergeSessionRoot(journal.before, journal.after, config.scope);
633
- await validate();
634
- await timings.measure("transfer local apply", () => applyMergedSnapshot(journal.before, journal.after, protectedSessionPaths(ctx, sessionRoot), { ...snapshotOptions, validateMutation }, validate, ctx.sessionManager.getSessionFile?.()));
641
+ await validateFresh();
642
+ const protectedPaths = protectedSessionPaths(ctx, sessionRoot);
643
+ const validateApply = () => {
644
+ validateMutation();
645
+ if (journal.localPolicyKey)
646
+ checkLiveProtection(ctx, sessionRoot, protectedPaths);
647
+ };
648
+ const validateApplyReview = journal.localPolicyKey
649
+ ? () => validateMergeApplyReview(backend, config, head, journal.stateIdentity, validateFresh, signal)
650
+ : undefined;
651
+ await timings.measure("transfer local apply", () => applyMergedSnapshot(journal.before, journal.after, protectedPaths, { ...snapshotOptions, validateMutation: validateApply, validateApplyReview }, validate, ctx.sessionManager.getSessionFile?.()));
635
652
  await validate();
636
653
  const headAtAcceptance = await timings.measure("transfer remote head", () => backend.readHead(signal));
637
654
  await validate();
638
- if (!headAtAcceptance || !backend.sameRevision(headAtAcceptance.revision, head.revision))
655
+ if (!sameMergeRecoveryHead(backend, headAtAcceptance, head))
639
656
  throw new Error("Remote changed during merged apply; journal and backup retained for review.");
640
657
  await timings.measure("transfer baseline write", () => writeAcceptedState(config, head, journal.accepted ?? journal.after, validateFresh, journal.progress));
641
658
  await validateFresh();
@@ -647,28 +664,3 @@ async function completeJournal(ctx, config, backend, journal, { validate, valida
647
664
  await validate();
648
665
  return true;
649
666
  }
650
- // Older valid journals may have accepted noncanonical JSON before projection normalization.
651
- function matchesAcceptedState(state, config, head, snapshot, progress) {
652
- return [true, false].some((canonical) => syncStateFingerprint(state) === syncStateFingerprint(acceptedState(config, head, snapshot, progress, canonical)));
653
- }
654
- function acceptedState(config, head, snapshot, progress, canonical = true) {
655
- if (progress)
656
- return progressState(config, head, snapshot, progress);
657
- return {
658
- version: 1,
659
- profile: config.snapshotIdentity,
660
- lastAppliedSnapshot: head.snapshotId,
661
- lastRemoteRevision: head.revision,
662
- lastFileHashes: fileHashMap(canonical ? portableSnapshot(snapshot, config.localFields) : snapshot),
663
- ...acceptedSelection(config),
664
- ...(config.localFields !== undefined ? { localFields: config.localFields } : {}),
665
- };
666
- }
667
- async function writeAcceptedState(config, head, snapshot, validate, progress) {
668
- const accepted = portableSnapshot(snapshot, config.localFields);
669
- const state = acceptedState(config, head, accepted, progress);
670
- await stageMergeBaseline(config, accepted, state, progress?.previous);
671
- await validate();
672
- await writeStateForConfig(config, state);
673
- await validate();
674
- }
@@ -1,5 +1,5 @@
1
1
  import { syncConfigReviewFingerprint } from "../settings/config.js";
2
- import { filterSnapshotForConfigPolicy } from "../snapshot/snapshot.js";
2
+ import { filterSnapshotForConfigPolicy, mergeRemotePreservedFiles } from "../snapshot/snapshot.js";
3
3
  import { safeTerminalText } from "../ui/terminal-text.js";
4
4
  import { sameLocalFields, validatePortableSnapshot } from "./local-fields.js";
5
5
  import { throwIfAborted } from "./signals.js";
@@ -43,10 +43,25 @@ export async function readRemoteSnapshotForUpload(backend, config, head, state,
43
43
  return readSnapshotForHead(backend, head, options.signal, config);
44
44
  return undefined;
45
45
  }
46
+ export async function snapshotForUpload(backend, config, local, head, remote, options) {
47
+ if (config.ignorePolicy)
48
+ return filterSnapshotForConfigPolicy(local, config, { ...options, regenerateId: true });
49
+ if (!head)
50
+ return config.reservedIgnoreNames === undefined ? local : filterSnapshotForConfigPolicy(local, config, options);
51
+ const snapshot = remote ?? (await readSnapshotForHead(backend, head, options.signal, config));
52
+ const remoteScoped = snapshot.selection?.version === 3;
53
+ if (remoteScoped !== (config.scope === "agent-directory")) {
54
+ throw new Error("Converting an existing remote between included paths and agent-directory scope is not supported. Use a separate storage location.");
55
+ }
56
+ return mergeRemotePreservedFiles(local, snapshot, config, options);
57
+ }
46
58
  export function sameRemoteHead(backend, left, right) {
47
59
  if (!left || !right)
48
60
  return left === right;
49
- return left.snapshotId === right.snapshotId && backend.sameRevision(left.revision, right.revision);
61
+ return (left.snapshotId === right.snapshotId &&
62
+ left.snapshotRef === right.snapshotRef &&
63
+ backend.sameRevision(left.revision, right.revision) &&
64
+ sameSnapshotSelection(left.selection, right.selection));
50
65
  }
51
66
  export function requireCompatibleRemoteSelection(config, snapshot) {
52
67
  const state = inspectRemoteSelection(config.include, snapshot, config.exclude, config);
@@ -1,4 +1,4 @@
1
- import { loadConfig } from "../settings/config.js";
1
+ import { loadConfigForCheck, syncCheckConfigFingerprint } from "../settings/config.js";
2
2
  import { resolvedSnapshotOptionsForContext } from "../snapshot/session-paths.js";
3
3
  import { createSnapshot } from "../snapshot/snapshot.js";
4
4
  import { withLock } from "../state/lock.js";
@@ -10,23 +10,37 @@ import { hasLocalChanges, syncPolicyChanged } from "./sync-state.js";
10
10
  /** Existing legacy policy; service ownership/consent is established by its caller. */
11
11
  export async function pushSessionsOnShutdown(ctx, options, loaders = { operations: () => import("./sync-operations.js") }) {
12
12
  const validate = captureMutationOwner(ctx, options.signal);
13
- const config = await loadConfig(options.setup);
13
+ const config = await loadConfigForCheck(undefined, options.signal);
14
14
  validate();
15
+ options.background?.validate(config);
16
+ if (options.setup !== undefined && options.setup !== config.setupName)
17
+ throw new Error("An automatic session push requires the current active sync setup.");
18
+ const fingerprint = syncCheckConfigFingerprint(config);
19
+ const refresh = async () => {
20
+ validate();
21
+ options.background?.validate();
22
+ const latest = await loadConfigForCheck(undefined, options.signal);
23
+ validate();
24
+ options.background?.validate(latest);
25
+ if (fingerprint !== syncCheckConfigFingerprint(latest))
26
+ throw new Error("Settings changed before automatic session push.");
27
+ };
15
28
  if (!config.automatic || !syncSessionsSelected(config))
16
29
  return;
17
30
  await withStateDirectoryAccess(() => withLock("auto-session-push", async () => {
31
+ await refresh();
18
32
  const state = await readStateForConfig(config);
19
- validate();
33
+ await refresh();
20
34
  if ((config.scope || state.scope) && (!state.lastAppliedSnapshot || syncPolicyChanged(state, config)))
21
35
  return;
22
36
  const snapshotOptions = await resolvedSnapshotOptionsForContext(ctx, config, options.signal);
23
- validate();
37
+ await refresh();
24
38
  const local = await createSnapshot(config.snapshotIdentity, snapshotOptions);
25
- validate();
39
+ await refresh();
26
40
  if (!hasLocalChanges(local, state, config))
27
41
  return;
28
42
  const operations = await loaders.operations();
29
- validate();
43
+ await refresh();
30
44
  await operations.push(ctx, { ...options, auto: true, yes: true, silent: true, reload: false }, { config, state, local });
31
45
  validate();
32
46
  }));
@@ -2,7 +2,7 @@ import { createSyncBackend } from "../backends/backend-factory.js";
2
2
  import { expectedRemoteHead, } from "../backends/sync-backend.js";
3
3
  import { loadConfig, syncCheckConfigFingerprint } from "../settings/config.js";
4
4
  import { effectiveSessionRoot, requireStableMergeSessionRoot, resolvedSnapshotOptionsForContext, sessionDirForApply, } from "../snapshot/session-paths.js";
5
- import { createSnapshot, filterSnapshotForConfigPolicy, mergeRemotePreservedFiles, regenerateSnapshotIdentity, scanSnapshot, snapshotIncludesSessions, snapshotWithoutSessions, } from "../snapshot/snapshot.js";
5
+ import { createSnapshot, filterSnapshotForConfigPolicy, regenerateSnapshotIdentity, scanSnapshot, snapshotIncludesSessions, snapshotWithoutSessions, } from "../snapshot/snapshot.js";
6
6
  import { applySnapshot } from "../snapshot/snapshot-apply.js";
7
7
  import { ignorePolicyValidator } from "../snapshot/snapshot-transaction-policy.js";
8
8
  import { pruneMergeBaselines } from "../state/merge-baseline-store.js";
@@ -16,28 +16,16 @@ import { confirmFieldMigration } from "./field-migration.js";
16
16
  import { overlayLocalFields, portableSnapshot, sameLocalFields, validatePortableSnapshot } from "./local-fields.js";
17
17
  import { readMergeJournal, requireNoMergeJournal, retireMergeJournal } from "./merge-journal.js";
18
18
  import { mergeSync } from "./merged-sync.js";
19
- import { readRemoteSnapshot, readRemoteSnapshotForUpload, readSnapshotForHead, requireCompatibleRemoteSelection, sameRemoteHead, } from "./remote-snapshot.js";
19
+ import { readRemoteSnapshot, readRemoteSnapshotForUpload, readSnapshotForHead, requireCompatibleRemoteSelection, sameRemoteHead, snapshotForUpload, } from "./remote-snapshot.js";
20
20
  import { throwIfAborted } from "./signals.js";
21
21
  import { createSyncDecision } from "./sync-decision.js";
22
22
  import { errorMessage } from "./sync-errors.js";
23
23
  import { backupLocal, captureMutationOwner, protectedSessionPaths } from "./sync-local.js";
24
24
  import { formatIgnorePolicyComparison, inspectRemoteSelection, requireLegacyTransferPolicy, syncSelectionHasContent, syncSessionsSelected, } from "./sync-policy.js";
25
25
  import { acceptedSelection, canPullRemoteSessionsOnFirstSync, canPullRemoteSettingsOnFirstSync, fileHashMap, hasLocalChanges, hasRemoteChanges, remoteChangedSinceState, sameHashes, shouldRefreshSyncedState, snapshotHashesMatchState, snapshotsMatch, syncPolicyChanged, } from "./sync-state.js";
26
+ import { directionalApplyGuards, requireIgnoreBaselineReview, requireResolvedDirectionalProgress, validateDirectionalPublication, } from "./transfer-freshness.js";
26
27
  const VERSION = 1;
27
28
  const POST_LOCAL_COMMIT_TIMEOUT_MS = 30_000;
28
- /** Whole-direction acceptance must never forget withheld state without an explicit recovery choice. */
29
- function requireResolvedDirectionalProgress(state, options, allowForce = true) {
30
- if (state.unresolved?.length && (options.auto || !options.force || !allowForce))
31
- throw new Error("Unresolved partial conflicts remain. Review /sync conflicts or explicitly choose push --force or pull --force; automatic transfer and rollback cannot accept unresolved groups.");
32
- }
33
- function requireIgnoreBaselineReview(ctx, config, state, options) {
34
- if (config.ignorePolicy &&
35
- state.lastAppliedSnapshot &&
36
- syncPolicyChanged(state, config) &&
37
- (options.auto || options.yes || !ctx.hasUI)) {
38
- throw new Error("Local ignore-file policy or source changed since the last accepted baseline. Review a foreground directional transfer.");
39
- }
40
- }
41
29
  export class PublicationStatePersistenceError extends Error {
42
30
  head;
43
31
  backupPath;
@@ -59,16 +47,23 @@ export class RollbackPublicationError extends Error {
59
47
  }
60
48
  }
61
49
  export async function push(ctx, options, input, factory = createSyncBackend) {
62
- const validateMutation = captureMutationOwner(ctx, options.signal);
50
+ const validateOwner = captureMutationOwner(ctx, options.signal);
63
51
  const validateCommittedOwner = captureMutationOwner(ctx);
64
- const config = input?.config ?? (await loadConfig(options.setup));
65
- throwIfAborted(options.signal);
52
+ const config = input?.config ?? (await loadConfig(options.setup, options.signal));
53
+ const validateMutation = () => {
54
+ validateOwner();
55
+ options.background?.validate(config);
56
+ };
57
+ validateMutation();
66
58
  await requireNoMergeJournal(config, options);
67
59
  const state = input?.state ?? (await readStateForConfig(config));
68
60
  validateMutation();
69
61
  requireResolvedDirectionalProgress(state, options);
70
62
  if (options.auto &&
71
- (config.scope === "agent-directory" || state.scope !== undefined) &&
63
+ (config.scope === "agent-directory" ||
64
+ state.scope !== undefined ||
65
+ config.reservedIgnoreNames !== undefined ||
66
+ state.ignorePolicyKey !== undefined) &&
72
67
  (options.force || !state.lastAppliedSnapshot || syncPolicyChanged(state, config))) {
73
68
  throw new Error("Automatic push requires an accepted baseline with matching content policy.");
74
69
  }
@@ -80,6 +75,8 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
80
75
  const validateIgnorePolicy = ignorePolicyValidator({ ...snapshotOptions, validateMutation });
81
76
  const localRaw = input?.local ?? (await createSnapshot(config.snapshotIdentity, snapshotOptions));
82
77
  const local = portableSnapshot(localRaw, config.localFields);
78
+ if (validateIgnorePolicy)
79
+ await validateIgnorePolicy();
83
80
  throwIfAborted(options.signal);
84
81
  let head = await backend.readHead(options.signal);
85
82
  let remoteForUpload = await readRemoteSnapshotForUpload(backend, config, head, state, options);
@@ -154,6 +151,7 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
154
151
  throw new Error("Settings changed during push review.");
155
152
  validateMutation();
156
153
  if (config.scope === "agent-directory" ||
154
+ validateIgnorePolicy ||
157
155
  !options.yes ||
158
156
  config.localFields !== undefined ||
159
157
  (await readMergeJournal(config))) {
@@ -162,7 +160,7 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
162
160
  throw new Error("Local content changed during push review; retry from current bytes.");
163
161
  }
164
162
  const currentState = await readStateForConfig(config);
165
- if ((config.ignorePolicy || !options.yes) && syncStateFingerprint(currentState) !== syncStateFingerprint(state))
163
+ if ((validateIgnorePolicy || !options.yes) && syncStateFingerprint(currentState) !== syncStateFingerprint(state))
166
164
  throw new Error("Baseline changed during push review.");
167
165
  requireResolvedDirectionalProgress(currentState, options);
168
166
  if (config.scope === "agent-directory" &&
@@ -172,6 +170,14 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
172
170
  if (configIdentity !== syncCheckConfigFingerprint(await loadConfig(options.setup)))
173
171
  throw new Error("Settings changed during push review.");
174
172
  validateMutation();
173
+ const validatePublication = validateIgnorePolicy || options.background
174
+ ? () => validateDirectionalPublication(ctx, config, snapshotOptions, state, fileHashMap(localRaw), validateIgnorePolicy ??
175
+ (async () => {
176
+ if (configIdentity !== syncCheckConfigFingerprint(await loadConfig(options.setup, options.signal)))
177
+ throw new Error("Settings changed before push publication.");
178
+ validateMutation();
179
+ }), "push")
180
+ : undefined;
175
181
  if (validateIgnorePolicy) {
176
182
  validatePortableSnapshot(upload);
177
183
  await validateIgnorePolicy();
@@ -179,7 +185,7 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
179
185
  const result = await backend.publishSnapshot(upload, expectedRemoteHead(head), {
180
186
  signal: options.signal,
181
187
  onCommit: options.onCommit,
182
- ...(validateIgnorePolicy ? { validateIgnorePolicy } : {}),
188
+ ...(validatePublication ? { validateIgnorePolicy: validatePublication } : {}),
183
189
  });
184
190
  try {
185
191
  await writeStateForConfig(config, {
@@ -316,7 +322,7 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
316
322
  await requireFreshRecovery();
317
323
  const currentState = await readStateForConfig(config);
318
324
  validateMutation();
319
- if ((config.ignorePolicy || initial || !options.yes) &&
325
+ if ((validateIgnorePolicy || initial || !options.yes) &&
320
326
  syncStateFingerprint(currentState) !== syncStateFingerprint(state))
321
327
  throw new Error("Baseline changed during pull review.");
322
328
  requireResolvedDirectionalProgress(currentState, options);
@@ -337,14 +343,27 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
337
343
  await validateIgnorePolicy();
338
344
  }
339
345
  const protectedPaths = protectedSessionPaths(ctx, snapshotOptions.sessionDir);
340
- if (validateIgnorePolicy && !samePaths(protectedPaths, reviewedProtectedPaths))
341
- throw new Error("Live session protection changed during pull review; reopen the review.");
342
- options.onCommit?.();
346
+ const applyGuards = directionalApplyGuards({
347
+ ctx,
348
+ config,
349
+ backend,
350
+ state,
351
+ sessionDir: snapshotOptions.sessionDir,
352
+ head,
353
+ protectedPaths: reviewedProtectedPaths,
354
+ signal: options.signal,
355
+ onCommit: options.onCommit,
356
+ validateMutation,
357
+ validateIgnorePolicy,
358
+ });
359
+ applyGuards.validateMutation();
360
+ if (!validateIgnorePolicy)
361
+ options.onCommit?.();
343
362
  const lastFileHashes = await applySnapshot(physical, protectedPaths, {
344
363
  ...snapshotOptions,
345
364
  sessionDir: applySessionDir,
346
- validateMutation,
347
- ...(config.scope === "agent-directory" ? { reviewedLocal: local } : {}),
365
+ ...applyGuards,
366
+ ...(config.scope === "agent-directory" || validateIgnorePolicy ? { reviewedLocal: local } : {}),
348
367
  expectedFileHashes: config.localFields?.length
349
368
  ? { "settings.json": fileHashMap(local)["settings.json"] ?? null }
350
369
  : undefined,
@@ -544,6 +563,7 @@ export async function rollback(ctx, options, factory = createSyncBackend, expect
544
563
  await requireNoMergeJournal(config);
545
564
  const state = await readStateForConfig(config);
546
565
  validateMutation();
566
+ requireIgnoreBaselineReview(ctx, config, state, options);
547
567
  requireResolvedDirectionalProgress(state, options, false);
548
568
  const decoded = await backend.readSnapshot(target, options.signal);
549
569
  validateMutation();
@@ -606,7 +626,7 @@ export async function rollback(ctx, options, factory = createSyncBackend, expect
606
626
  const backup = await backupLocal(config.snapshotIdentity, snapshotOptions, options.signal);
607
627
  const applySessionDir = await sessionDirForApply(ctx, config.scope ? physical : remote, snapshotOptions);
608
628
  const currentState = await readStateForConfig(config);
609
- if (!options.yes && syncStateFingerprint(currentState) !== syncStateFingerprint(state))
629
+ if ((validateIgnorePolicy || !options.yes) && syncStateFingerprint(currentState) !== syncStateFingerprint(state))
610
630
  throw new Error("Baseline changed during rollback review.");
611
631
  requireResolvedDirectionalProgress(currentState, options, false);
612
632
  if (!options.yes)
@@ -623,14 +643,27 @@ export async function rollback(ctx, options, factory = createSyncBackend, expect
623
643
  await validateIgnorePolicy();
624
644
  }
625
645
  const protectedPaths = protectedSessionPaths(ctx, snapshotOptions.sessionDir);
626
- if (validateIgnorePolicy && !samePaths(protectedPaths, reviewedProtectedPaths))
627
- throw new Error("Live session protection changed during rollback review; reopen the review.");
628
- options.onCommit?.();
646
+ const applyGuards = directionalApplyGuards({
647
+ ctx,
648
+ config,
649
+ backend,
650
+ state,
651
+ sessionDir: snapshotOptions.sessionDir,
652
+ head: expectedHead,
653
+ protectedPaths: reviewedProtectedPaths,
654
+ signal: options.signal,
655
+ onCommit: options.onCommit,
656
+ validateMutation,
657
+ validateIgnorePolicy,
658
+ });
659
+ applyGuards.validateMutation();
660
+ if (!validateIgnorePolicy)
661
+ options.onCommit?.();
629
662
  const lastFileHashes = await applySnapshot(physical, protectedPaths, {
630
663
  ...snapshotOptions,
631
664
  sessionDir: applySessionDir,
632
- validateMutation,
633
- ...(config.scope === "agent-directory" ? { reviewedLocal: local } : {}),
665
+ ...applyGuards,
666
+ ...(config.scope === "agent-directory" || validateIgnorePolicy ? { reviewedLocal: local } : {}),
634
667
  expectedFileHashes: config.localFields?.length
635
668
  ? { "settings.json": fileHashMap(local)["settings.json"] ?? null }
636
669
  : undefined,
@@ -640,14 +673,17 @@ export async function rollback(ctx, options, factory = createSyncBackend, expect
640
673
  let result;
641
674
  try {
642
675
  const signal = AbortSignal.timeout(POST_LOCAL_COMMIT_TIMEOUT_MS);
643
- const validateIgnorePolicy = ignorePolicyValidator({
676
+ const validatePolicy = ignorePolicyValidator({
644
677
  ...snapshotOptions,
645
678
  signal,
646
679
  validateMutation: validateCommittedOwner,
647
680
  });
681
+ const validatePublication = validatePolicy
682
+ ? () => validateDirectionalPublication(ctx, config, { ...snapshotOptions, sessionDir: applySessionDir, signal }, state, lastFileHashes, validatePolicy, "rollback")
683
+ : undefined;
648
684
  result = await backend.publishSnapshot(upload, expectedRemoteHead(expectedHead), {
649
685
  signal,
650
- ...(validateIgnorePolicy ? { validateIgnorePolicy } : {}),
686
+ ...(validatePublication ? { validateIgnorePolicy: validatePublication } : {}),
651
687
  });
652
688
  }
653
689
  catch (error) {
@@ -694,18 +730,6 @@ async function maybeReload(ctx, signal, validateMutation = captureMutationOwner(
694
730
  await ctx.reload();
695
731
  }
696
732
  }
697
- async function snapshotForUpload(backend, config, local, head, remote, options) {
698
- if (config.ignorePolicy)
699
- return filterSnapshotForConfigPolicy(local, config, { ...options, regenerateId: true });
700
- if (!head)
701
- return local;
702
- const snapshot = remote ?? (await readSnapshotForHead(backend, head, options.signal, config));
703
- const remoteScoped = snapshot.selection?.version === 3;
704
- if (remoteScoped !== (config.scope === "agent-directory")) {
705
- throw new Error("Converting an existing remote between included paths and agent-directory scope is not supported. Use a separate storage location.");
706
- }
707
- return mergeRemotePreservedFiles(local, snapshot, config, options);
708
- }
709
733
  async function confirmPush(ctx, options, config, backend, local, upload, head, remote, validateMutation, title = snapshotIncludesSessions(upload) ? "Push pi settings and sessions?" : "Push pi settings?") {
710
734
  validateMutation();
711
735
  if (options.yes)
@@ -727,7 +751,4 @@ async function confirmPush(ctx, options, config, backend, local, upload, head, r
727
751
  function matchesInitialHead(initial, backend, current) {
728
752
  return sameRemoteHead(backend, initial.head, current);
729
753
  }
730
- function samePaths(left, right) {
731
- return left.size === right.size && [...left].every((item) => right.has(item));
732
- }
733
754
  export { backupLocal } from "./sync-local.js";
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import path from "node:path";
2
3
  import { isDeniedPath, toPosix } from "../paths.js";
3
4
  import { IGNORE_SNAPSHOT_VERSION, } from "../snapshot/snapshot-types.js";
@@ -262,6 +263,23 @@ export function syncDirectoryPolicyKey(config) {
262
263
  normalizeDirectoryRules(config.reinclude).map((rule) => rule.toLowerCase()),
263
264
  ]);
264
265
  }
266
+ export function localIgnorePolicyKey(config) {
267
+ if (!config.ignorePolicy && config.reservedIgnoreNames === undefined)
268
+ return undefined;
269
+ const reserved = reservedIgnoreSnapshotNames(config);
270
+ return createHash("sha256")
271
+ .update(JSON.stringify([
272
+ config.setupName,
273
+ config.recoverySetupKey,
274
+ syncDirectoryPolicyKey(config) ?? [
275
+ includeFromSelectionConfig(config),
276
+ normalizeSyncExclude(config.exclude).map((rule) => rule.toLowerCase()),
277
+ ],
278
+ config.ignoreSourceIdentity,
279
+ [...(reserved ?? [])].sort(),
280
+ ]))
281
+ .digest("hex");
282
+ }
265
283
  export function inspectRemoteSelection(localInclude, snapshot, localExclude, directory) {
266
284
  const selection = snapshot.selection === undefined ? undefined : portableSnapshotSelection(snapshot.selection);
267
285
  const ignorePolicyComparison = compareIgnorePolicy(directory?.ignorePolicy, selection);
@@ -469,12 +487,19 @@ export function isIgnoreControlPath(relativePath, reservedNames) {
469
487
  function isIgnoreSnapshotSelection(config) {
470
488
  return config.version === 4 && config.fingerprint !== undefined;
471
489
  }
472
- function compileIgnoreControlPath(config) {
490
+ function reservedIgnoreSnapshotNames(config) {
473
491
  const local = config.ignorePolicy;
474
492
  if (!local && !config.reservedIgnoreNames && !isIgnoreSnapshotSelection(config))
475
493
  return undefined;
476
- const names = new Set([...(local ? [local.filename, ...local.reservedNames] : []), ...(config.reservedIgnoreNames ?? [])].map((name) => name.toLowerCase()));
477
- return (relativePath) => isIgnoreControlPath(relativePath, names);
494
+ return new Set([
495
+ ".syncignore",
496
+ ...(local ? [local.filename, ...local.reservedNames] : []),
497
+ ...(config.reservedIgnoreNames ?? []),
498
+ ].map((name) => name.toLowerCase()));
499
+ }
500
+ function compileIgnoreControlPath(config) {
501
+ const names = reservedIgnoreSnapshotNames(config);
502
+ return names ? (relativePath) => isIgnoreControlPath(relativePath, names) : undefined;
478
503
  }
479
504
  function compileDirectoryPolicy(config) {
480
505
  const localIgnore = config.ignorePolicy;
@@ -1,13 +1,8 @@
1
- import { createHash } from "node:crypto";
2
1
  import { toPosix } from "../paths.js";
3
2
  import { canonicalSnapshotPathForConfig, filterSnapshotForConfigPolicy, isSessionPath } from "../snapshot/snapshot.js";
4
3
  import { sameSyncExclude } from "./exclude-policy.js";
5
4
  import { portableSnapshot, sameLocalFields } from "./local-fields.js";
6
- import { compareIgnorePolicy, configuredSnapshotPathMatcher, customIncludePathsByLower, includeFromSelectionConfig, normalizeSyncInclude, syncDirectoryPolicyKey, syncSessionsSelected, } from "./sync-policy.js";
7
- function ignorePolicyKey(config) {
8
- const key = config.ignorePolicy && syncDirectoryPolicyKey(config);
9
- return key === undefined ? undefined : createHash("sha256").update(key).digest("hex");
10
- }
5
+ import { compareIgnorePolicy, configuredSnapshotPathMatcher, customIncludePathsByLower, includeFromSelectionConfig, localIgnorePolicyKey, normalizeSyncInclude, syncDirectoryPolicyKey, syncSessionsSelected, } from "./sync-policy.js";
11
6
  export function hasLocalChanges(local, state, config) {
12
7
  return ((Boolean(state.lastAppliedSnapshot) &&
13
8
  (state.scope !== config.scope ||
@@ -84,7 +79,7 @@ export function shouldRefreshSyncedState(remote, head, state, config, sameRevisi
84
79
  syncPolicyChanged(state, config));
85
80
  }
86
81
  export function acceptedSelection(config) {
87
- const key = ignorePolicyKey(config);
82
+ const key = localIgnorePolicyKey(config);
88
83
  return {
89
84
  include: config.ignorePolicy ? includeFromSelectionConfig(config) : [...config.include],
90
85
  ...(key === undefined ? {} : { ignorePolicyKey: key }),
@@ -94,7 +89,7 @@ export function acceptedSelection(config) {
94
89
  };
95
90
  }
96
91
  function sameSelectionRules(state, config) {
97
- const key = ignorePolicyKey(config);
92
+ const key = localIgnorePolicyKey(config);
98
93
  if (key !== undefined || state.ignorePolicyKey !== undefined)
99
94
  return key === state.ignorePolicyKey;
100
95
  return config.scope === "agent-directory" && state.scope === config.scope