@narumitw/pi-sync-daemon 0.8.0 → 0.9.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 (54) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/cli.js +1 -1
  3. package/dist/consent.d.ts +14 -2
  4. package/dist/consent.js +134 -16
  5. package/dist/engine/backends/git/git-backend.d.ts +1 -2
  6. package/dist/engine/backends/git/git-backend.js +61 -30
  7. package/dist/engine/commands/command-types.d.ts +2 -1
  8. package/dist/engine/host.d.ts +1 -0
  9. package/dist/engine/ignore/ignore-initialization.d.ts +3 -0
  10. package/dist/engine/ignore/ignore-initialization.js +93 -27
  11. package/dist/engine/ignore/ignore-settings.d.ts +16 -1
  12. package/dist/engine/ignore/ignore-settings.js +85 -14
  13. package/dist/engine/settings/config-file.js +1 -1
  14. package/dist/engine/settings/config.d.ts +3 -2
  15. package/dist/engine/settings/config.js +71 -28
  16. package/dist/engine/settings/settings-management.d.ts +3 -1
  17. package/dist/engine/settings/settings-management.js +8 -2
  18. package/dist/engine/settings/settings-types.d.ts +2 -0
  19. package/dist/engine/snapshot/session-paths.js +7 -2
  20. package/dist/engine/snapshot/snapshot-apply.d.ts +1 -1
  21. package/dist/engine/snapshot/snapshot-transaction-policy.d.ts +7 -2
  22. package/dist/engine/snapshot/snapshot-transaction-policy.js +37 -17
  23. package/dist/engine/snapshot/snapshot-transaction.js +55 -13
  24. package/dist/engine/snapshot/snapshot-types.d.ts +4 -0
  25. package/dist/engine/sync/agent-plan.js +1 -0
  26. package/dist/engine/sync/agent-sync.js +8 -1
  27. package/dist/engine/sync/continuous-sync.d.ts +3 -1
  28. package/dist/engine/sync/continuous-sync.js +32 -15
  29. package/dist/engine/sync/merge-acceptance.d.ts +8 -0
  30. package/dist/engine/sync/merge-acceptance.js +29 -0
  31. package/dist/engine/sync/merge-apply.js +7 -4
  32. package/dist/engine/sync/merge-journal.d.ts +6 -0
  33. package/dist/engine/sync/merge-journal.js +33 -14
  34. package/dist/engine/sync/merged-sync.js +31 -39
  35. package/dist/engine/sync/remote-snapshot.d.ts +2 -1
  36. package/dist/engine/sync/remote-snapshot.js +17 -2
  37. package/dist/engine/sync/session-push.js +20 -6
  38. package/dist/engine/sync/sync-mutations.js +71 -50
  39. package/dist/engine/sync/sync-policy.d.ts +5 -0
  40. package/dist/engine/sync/sync-policy.js +28 -3
  41. package/dist/engine/sync/sync-state.d.ts +2 -0
  42. package/dist/engine/sync/sync-state.js +3 -8
  43. package/dist/engine/sync/transfer-freshness.d.ts +31 -0
  44. package/dist/engine/sync/transfer-freshness.js +82 -0
  45. package/dist/engine-service.d.ts +1 -1
  46. package/dist/engine-service.js +124 -27
  47. package/dist/monitor.d.ts +4 -1
  48. package/dist/monitor.js +84 -32
  49. package/dist/server.d.ts +1 -0
  50. package/dist/server.js +46 -5
  51. package/dist/service-host.d.ts +1 -1
  52. package/dist/service-host.js +2 -1
  53. package/docs/architecture.md +13 -5
  54. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
- import { assertRecoveryPolicy, IGNORE_POLICY_JOURNAL_VERSION, ignorePolicyValidator, ignoreSourceBinding, validateJournalPolicy, } from "../snapshot/snapshot-transaction-policy.js";
4
+ import { assertRecoveryPolicy, BOUND_DIRECTORY_JOURNAL_VERSION, IGNORE_POLICY_JOURNAL_VERSION, ignorePolicyValidator, ignoreSourceBinding, recoveryPolicyKey, validateJournalPolicy, } from "../snapshot/snapshot-transaction-policy.js";
5
5
  import { IGNORE_SNAPSHOT_VERSION } 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";
@@ -10,24 +10,30 @@ import { safeTerminalText } from "../ui/terminal-text.js";
10
10
  import { normalizeSyncExclude } from "./exclude-policy.js";
11
11
  import { planFileMerge } from "./file-merge-planner.js";
12
12
  import { portableSnapshot, sameLocalFields, validatePortableSnapshot, validateSnapshotFieldPolicy, } from "./local-fields.js";
13
- import { configuredSnapshotPathMatcher, sameSnapshotSelection, syncDirectoryPolicyKey, validateSnapshotSelection, } from "./sync-policy.js";
13
+ import { compileSyncPolicyExclude, configuredSnapshotPathMatcher, sameSnapshotSelection, syncDirectoryPolicyKey, validateSnapshotSelection, } from "./sync-policy.js";
14
14
  import { fileHashMap, sameHashes } from "./sync-state.js";
15
15
  export function mergeJournalPolicy(config) {
16
- return config.ignorePolicy ? { version: 2, ignoreSource: ignoreSourceBinding(config.ignorePolicy) } : { version: 1 };
16
+ const localPolicyKey = recoveryPolicyKey(config);
17
+ const ignoreSource = config.ignorePolicy ? ignoreSourceBinding(config.ignorePolicy) : undefined;
18
+ if (localPolicyKey)
19
+ return { version: 3, localPolicyKey, ...(ignoreSource ? { ignoreSource } : {}) };
20
+ return ignoreSource ? { version: 2, ignoreSource } : { version: 1 };
17
21
  }
18
22
  function ignoreRecoveryPolicy(journal) {
19
23
  return {
20
- version: IGNORE_POLICY_JOURNAL_VERSION,
24
+ version: journal.version === 3 ? BOUND_DIRECTORY_JOURNAL_VERSION : IGNORE_POLICY_JOURNAL_VERSION,
21
25
  ignoreSource: journal.ignoreSource,
26
+ localPolicyKey: journal.localPolicyKey,
22
27
  selection: journal.upload.selection,
23
28
  };
24
29
  }
25
30
  export function assertMergeJournalPolicy(journal, config) {
31
+ if (journal.localPolicyKey !== recoveryPolicyKey(config))
32
+ throw new Error("Pending merge lacks matching setup or ignore-file policy evidence; preserve its journal for reviewed recovery.");
26
33
  if (journal.version === 1 && !config.ignorePolicy && config.pathPolicy !== "ignore-file")
27
34
  return;
28
- if (journal.version !== 2)
29
- throw new Error("Pending merge lacks ignore-file policy evidence; preserve its journal for reviewed recovery.");
30
- assertRecoveryPolicy(ignoreRecoveryPolicy(journal), config);
35
+ if (journal.ignoreSource || config.ignorePolicy || config.pathPolicy === "ignore-file")
36
+ assertRecoveryPolicy(ignoreRecoveryPolicy(journal), config);
31
37
  try {
32
38
  const identity = JSON.parse(journal.identity);
33
39
  if (!Array.isArray(identity) ||
@@ -39,17 +45,21 @@ export function assertMergeJournalPolicy(journal, config) {
39
45
  throw new Error("Pending merge belongs to a different setup or local policy; preserve its journal.");
40
46
  }
41
47
  const configured = configuredSnapshotPathMatcher(config);
48
+ const excluded = compileSyncPolicyExclude(config);
49
+ if (!journal.applyOnly && journal.upload.files.some((file) => excluded(file.path)))
50
+ throw new Error("Pending publication contains protected paths; preserve its journal.");
42
51
  for (const snapshot of [
43
52
  journal.before,
44
53
  journal.after,
45
54
  journal.accepted,
46
- journal.applyOnly ? undefined : journal.upload,
55
+ journal.ignoreSource && !journal.applyOnly ? journal.upload : undefined,
47
56
  ]) {
48
57
  if (snapshot?.files.some((file) => !configured(file.path)))
49
58
  throw new Error("Pending merge contains paths outside the current ignore-file policy; preserve its journal.");
50
59
  }
51
60
  }
52
61
  export function mergeJournalIdentity(config, backendIdentity) {
62
+ const localPolicyKey = recoveryPolicyKey(config);
53
63
  return JSON.stringify([
54
64
  config.setupName,
55
65
  backendIdentity,
@@ -60,6 +70,7 @@ export function mergeJournalIdentity(config, backendIdentity) {
60
70
  : config.exclude === undefined
61
71
  ? []
62
72
  : ["exclude", normalizeSyncExclude(config.exclude).map((rule) => rule.toLowerCase())]),
73
+ ...(localPolicyKey ? [localPolicyKey] : []),
63
74
  ]);
64
75
  }
65
76
  export function mergeJournalPath(config) {
@@ -82,8 +93,12 @@ export async function readMergeJournal(config) {
82
93
  if (journal === undefined)
83
94
  return;
84
95
  if (!journal ||
85
- (journal.version !== 1 && journal.version !== 2) ||
96
+ ![1, 2, 3].includes(journal.version) ||
86
97
  (journal.version === 1 && journal.ignoreSource !== undefined) ||
98
+ (journal.version === 2 && !journal.ignoreSource) ||
99
+ (journal.version === 3
100
+ ? typeof journal.localPolicyKey !== "string" || !/^[0-9a-f]{64}$/u.test(journal.localPolicyKey)
101
+ : journal.localPolicyKey !== undefined) ||
87
102
  typeof journal.identity !== "string" ||
88
103
  typeof journal.backup !== "string" ||
89
104
  typeof journal.stateIdentity !== "string" ||
@@ -112,7 +127,7 @@ export async function readMergeJournal(config) {
112
127
  throw new Error("Unsupported or damaged merge journal; preserve it and review recovery before syncing.");
113
128
  // Verify every path and byte, including the unmanaged remote files retained for publication.
114
129
  try {
115
- if (journal.version === 2) {
130
+ if (journal.ignoreSource !== undefined) {
116
131
  validateJournalPolicy(ignoreRecoveryPolicy(journal));
117
132
  if ([journal.expectedHead.selection, journal.committedHead?.selection].some((selection) => selection !== undefined && !sameSnapshotSelection(selection, journal.upload.selection)))
118
133
  throw new Error("Inconsistent merge head policy.");
@@ -126,7 +141,7 @@ export async function readMergeJournal(config) {
126
141
  ]) {
127
142
  validateSnapshotFieldPolicy(snapshot);
128
143
  validateSnapshotSelection(snapshot);
129
- if ((journal.version === 2
144
+ if ((journal.ignoreSource !== undefined
130
145
  ? snapshot.version !== IGNORE_SNAPSHOT_VERSION ||
131
146
  !sameSnapshotSelection(snapshot.selection, journal.upload.selection)
132
147
  : ![1, 2, 3, 4, 5].includes(snapshot.version)) ||
@@ -230,7 +245,7 @@ export async function retireMergeJournal(config) {
230
245
  const validateIgnore = ignorePolicyValidator(config);
231
246
  if (validateIgnore)
232
247
  await validateIgnore();
233
- if (journal.version === 2)
248
+ if (journal.ignoreSource)
234
249
  throw new Error(ignoreMergeRecoveryGuidance);
235
250
  await archiveMergeJournal(config);
236
251
  }
@@ -262,9 +277,13 @@ export async function reviewInactiveIgnoreMerge(ctx, config, backend, journal, h
262
277
  const latest = await backend.readHead(options.signal);
263
278
  if (!isCurrent())
264
279
  return "cancelled";
265
- if (!sameMergeRecoveryHead(backend, head, latest) || syncStateFingerprint(state) !== journal.stateIdentity) {
280
+ await validateFresh();
281
+ if (!sameMergeRecoveryHead(backend, head, latest) ||
282
+ syncStateFingerprint(state) !== journal.stateIdentity ||
283
+ syncStateFingerprint(await readStateForConfig(config)) !== journal.stateIdentity) {
266
284
  throw new Error("Remote head or sync baseline changed during recovery review; journal and backup retained.");
267
285
  }
286
+ await validateFresh();
268
287
  await archiveMergeJournal(config);
269
288
  if (!options.silent && isCurrent())
270
289
  ctx.ui.notify("Archived the inactive merge journal. Local files, remote files, baseline and backup were kept. Run Sync now again for a fresh plan.", "info");
@@ -287,7 +306,7 @@ export async function requireNoMergeJournal(config, options = {}) {
287
306
  const validateIgnore = ignorePolicyValidator(config);
288
307
  if (validateIgnore)
289
308
  await validateIgnore();
290
- if (journal.version === 2)
309
+ if (journal.ignoreSource)
291
310
  throw new Error(ignoreMergeRecoveryGuidance);
292
311
  if (!options.force) {
293
312
  throw new Error("A merged transfer needs recovery. Run /sync sync to reconcile it. If newer local edits or remote revisions prevent recovery, review /sync diff and explicitly choose push --force or pull --force; the selected directional result will archive the old journal, not restore old bytes. Keep its backup; do not downgrade while recovery is pending.");
@@ -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,6 +1,6 @@
1
1
  import type { RemoteHead, SyncBackend } from "../backends/sync-backend.js";
2
2
  import type { AnySyncConfig } from "../settings/settings-types.js";
3
- import type { Snapshot } from "../snapshot/snapshot-types.js";
3
+ import type { Snapshot, SnapshotOptions } from "../snapshot/snapshot-types.js";
4
4
  import type { SyncState } from "../state/state-types.js";
5
5
  import { type RemoteSelectionState } from "./sync-policy.js";
6
6
  export declare function readSnapshotForHead(backend: SyncBackend, head: RemoteHead, signal?: AbortSignal, config?: AnySyncConfig): Promise<Snapshot>;
@@ -8,6 +8,7 @@ export declare function readRemoteSnapshotForUpload(backend: SyncBackend, config
8
8
  force?: boolean;
9
9
  signal?: AbortSignal;
10
10
  }): Promise<Snapshot | undefined>;
11
+ export declare function snapshotForUpload(backend: SyncBackend, config: AnySyncConfig, local: Snapshot, head: RemoteHead | undefined, remote: Snapshot | undefined, options: SnapshotOptions): Promise<Snapshot>;
11
12
  export declare function sameRemoteHead(backend: SyncBackend, left: RemoteHead | undefined, right: RemoteHead | undefined): boolean;
12
13
  export declare function requireCompatibleRemoteSelection(config: AnySyncConfig, snapshot: Snapshot): void;
13
14
  export declare function inspectHeadSelection(backend: SyncBackend, config: AnySyncConfig, head: RemoteHead, signal?: AbortSignal): Promise<RemoteSelectionState>;
@@ -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
  }));