@narumitw/pi-sync-daemon 0.7.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 (93) hide show
  1. package/CHANGELOG.md +21 -0
  2. package/README.md +16 -2
  3. package/dist/cli.js +1 -1
  4. package/dist/consent.d.ts +14 -2
  5. package/dist/consent.js +147 -14
  6. package/dist/engine/backends/git/git-backend.d.ts +2 -3
  7. package/dist/engine/backends/git/git-backend.js +71 -25
  8. package/dist/engine/backends/git/git-storage.d.ts +1 -1
  9. package/dist/engine/backends/git/git-storage.js +30 -9
  10. package/dist/engine/backends/s3/s3-backend.js +8 -0
  11. package/dist/engine/backends/sync-backend.d.ts +1 -0
  12. package/dist/engine/backends/webdav/webdav-backend.js +8 -0
  13. package/dist/engine/commands/command-types.d.ts +2 -1
  14. package/dist/engine/host.d.ts +1 -0
  15. package/dist/engine/ignore/effective-ignore-policy.d.ts +10 -0
  16. package/dist/engine/ignore/effective-ignore-policy.js +33 -0
  17. package/dist/engine/ignore/ignore-edit.d.ts +13 -0
  18. package/dist/engine/ignore/ignore-edit.js +102 -0
  19. package/dist/engine/ignore/ignore-initialization.d.ts +9 -0
  20. package/dist/engine/ignore/ignore-initialization.js +252 -0
  21. package/dist/engine/ignore/ignore-migration-prompt.d.ts +7 -0
  22. package/dist/engine/ignore/ignore-migration-prompt.js +139 -0
  23. package/dist/engine/ignore/ignore-settings.d.ts +30 -0
  24. package/dist/engine/ignore/ignore-settings.js +393 -0
  25. package/dist/engine/ignore/ignore-source.d.ts +27 -0
  26. package/dist/engine/ignore/ignore-source.js +250 -0
  27. package/dist/engine/settings/config-file.d.ts +9 -2
  28. package/dist/engine/settings/config-file.js +124 -28
  29. package/dist/engine/settings/config.d.ts +6 -2
  30. package/dist/engine/settings/config.js +140 -11
  31. package/dist/engine/settings/settings-management.d.ts +5 -3
  32. package/dist/engine/settings/settings-management.js +24 -10
  33. package/dist/engine/settings/settings-types.d.ts +25 -2
  34. package/dist/engine/settings/settings-validation.js +23 -5
  35. package/dist/engine/snapshot/session-paths.d.ts +1 -1
  36. package/dist/engine/snapshot/session-paths.js +41 -13
  37. package/dist/engine/snapshot/snapshot-apply.d.ts +3 -3
  38. package/dist/engine/snapshot/snapshot-apply.js +23 -4
  39. package/dist/engine/snapshot/snapshot-codec.d.ts +1 -1
  40. package/dist/engine/snapshot/snapshot-codec.js +14 -5
  41. package/dist/engine/snapshot/snapshot-exclude-safety.d.ts +4 -2
  42. package/dist/engine/snapshot/snapshot-exclude-safety.js +76 -19
  43. package/dist/engine/snapshot/snapshot-transaction-images.d.ts +3 -1
  44. package/dist/engine/snapshot/snapshot-transaction-images.js +33 -3
  45. package/dist/engine/snapshot/snapshot-transaction-policy.d.ts +30 -2
  46. package/dist/engine/snapshot/snapshot-transaction-policy.js +135 -11
  47. package/dist/engine/snapshot/snapshot-transaction-verification.d.ts +7 -0
  48. package/dist/engine/snapshot/snapshot-transaction-verification.js +78 -0
  49. package/dist/engine/snapshot/snapshot-transaction.d.ts +1 -12
  50. package/dist/engine/snapshot/snapshot-transaction.js +129 -109
  51. package/dist/engine/snapshot/snapshot-types.d.ts +27 -1
  52. package/dist/engine/snapshot/snapshot-types.js +9 -1
  53. package/dist/engine/snapshot/snapshot.d.ts +6 -4
  54. package/dist/engine/snapshot/snapshot.js +91 -34
  55. package/dist/engine/state/state-types.d.ts +1 -0
  56. package/dist/engine/sync/agent-plan.js +1 -0
  57. package/dist/engine/sync/agent-sync.js +8 -1
  58. package/dist/engine/sync/continuous-sync.d.ts +3 -1
  59. package/dist/engine/sync/continuous-sync.js +50 -18
  60. package/dist/engine/sync/continuous-watch.js +4 -1
  61. package/dist/engine/sync/initialization.js +3 -2
  62. package/dist/engine/sync/local-fields.d.ts +3 -1
  63. package/dist/engine/sync/local-fields.js +62 -1
  64. package/dist/engine/sync/merge-acceptance.d.ts +8 -0
  65. package/dist/engine/sync/merge-acceptance.js +29 -0
  66. package/dist/engine/sync/merge-apply.js +42 -11
  67. package/dist/engine/sync/merge-journal.d.ts +24 -4
  68. package/dist/engine/sync/merge-journal.js +134 -8
  69. package/dist/engine/sync/merged-sync.d.ts +1 -1
  70. package/dist/engine/sync/merged-sync.js +128 -83
  71. package/dist/engine/sync/remote-snapshot.d.ts +11 -3
  72. package/dist/engine/sync/remote-snapshot.js +72 -18
  73. package/dist/engine/sync/session-push.js +20 -6
  74. package/dist/engine/sync/sync-inspection.js +7 -5
  75. package/dist/engine/sync/sync-mutations.d.ts +2 -1
  76. package/dist/engine/sync/sync-mutations.js +157 -73
  77. package/dist/engine/sync/sync-policy.d.ts +29 -8
  78. package/dist/engine/sync/sync-policy.js +152 -16
  79. package/dist/engine/sync/sync-queries.js +8 -1
  80. package/dist/engine/sync/sync-state.d.ts +4 -2
  81. package/dist/engine/sync/sync-state.js +15 -2
  82. package/dist/engine/sync/transfer-freshness.d.ts +31 -0
  83. package/dist/engine/sync/transfer-freshness.js +82 -0
  84. package/dist/engine-service.d.ts +1 -1
  85. package/dist/engine-service.js +146 -27
  86. package/dist/monitor.d.ts +4 -1
  87. package/dist/monitor.js +84 -32
  88. package/dist/server.d.ts +1 -0
  89. package/dist/server.js +46 -5
  90. package/dist/service-host.d.ts +1 -1
  91. package/dist/service-host.js +2 -1
  92. package/docs/architecture.md +30 -0
  93. package/package.json +2 -1
@@ -1,10 +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
- import { hasCurrentMergeBaseline, pruneMergeBaselines, readMergeAncestors, stageMergeBaseline, } from "../state/merge-baseline-store.js";
7
- import { readStateForConfig, statePathForConfig, syncStateFingerprint, writeStateForConfig, } from "../state/sync-state-store.js";
6
+ import { ignorePolicyValidator } from "../snapshot/snapshot-transaction-policy.js";
7
+ import { hasCurrentMergeBaseline, pruneMergeBaselines, readMergeAncestors } from "../state/merge-baseline-store.js";
8
+ import { readStateForConfig, statePathForConfig, syncStateFingerprint } from "../state/sync-state-store.js";
8
9
  import { confirmMergeReview } from "../ui/merge-review.js";
9
10
  import { mergedSyncSummary } from "../ui/merged-sync-summary.js";
10
11
  import { safeTerminalText } from "../ui/terminal-text.js";
@@ -17,18 +18,20 @@ import { resolveContentConflicts } from "./content-conflicts.js";
17
18
  import { ContinuousError } from "./continuous-errors.js";
18
19
  import { planFileMerge } from "./file-merge-planner.js";
19
20
  import { overlayLocalFields, portableSnapshot, sameLocalFields } from "./local-fields.js";
21
+ import { acceptedState, matchesAcceptedState, writeAcceptedState } from "./merge-acceptance.js";
20
22
  import { applyMergedSnapshot, preflightMergedTargets } from "./merge-apply.js";
21
- import { clearMergeJournal, mergeJournalIdentity, readMergeJournal, writeMergeJournal, } from "./merge-journal.js";
23
+ import { assertMergeJournalPolicy, clearMergeJournal, mergeJournalIdentity, mergeJournalPolicy, readMergeJournal, reviewInactiveIgnoreMerge, sameMergeRecoveryHead, writeMergeJournal, } from "./merge-journal.js";
22
24
  import { mergeTransferError } from "./merge-transfer-error.js";
23
- import { acceptedMergeFiles, progressState } from "./partial-progress.js";
25
+ import { acceptedMergeFiles } from "./partial-progress.js";
24
26
  import { formatRemoteSelectionStatus, readSnapshotForHead, requireCompatibleRemoteSelection, } from "./remote-snapshot.js";
25
27
  import { resolveSettingsConflicts } from "./settings-conflicts.js";
26
28
  import { createStartupTimings } from "./startup-timings.js";
27
29
  import { createSyncDecision } from "./sync-decision.js";
28
30
  import { backupLocal, captureMutationOwner, protectedSessionPaths } from "./sync-local.js";
29
31
  import { configuredSnapshotPathMatcher, inspectRemoteSelection, syncSessionsSelected } from "./sync-policy.js";
30
- import { acceptedSelection, fileHashMap, hasLocalChanges, hasRemoteChanges, sameHashes, syncPolicyChanged, } from "./sync-state.js";
32
+ import { fileHashMap, hasLocalChanges, hasRemoteChanges, sameHashes, syncPolicyChanged } from "./sync-state.js";
31
33
  import { TEXT_MERGE_WORK_LIMIT } from "./text-merge.js";
34
+ import { checkLiveProtection, validateMergeApplyReview, validateMergedPublication } from "./transfer-freshness.js";
32
35
  const MAX_ATTEMPTS = 3;
33
36
  /** Established-baseline sync only. First-source selection remains in the existing command flow. */
34
37
  export async function mergeSync(ctx, options, factory = createSyncBackend, resolution) {
@@ -54,6 +57,8 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
54
57
  };
55
58
  const config = await loadConfig(options.setup);
56
59
  validateOwner(config);
60
+ if (config.pathPolicy === "ignore-file" && !config.ignorePolicy)
61
+ throw new Error("Merged sync requires the resolved local ignore-file policy.");
57
62
  validateRetryAuthorization(config);
58
63
  const configToken = syncCheckConfigFingerprint(config);
59
64
  const modelToken = JSON.stringify(ctx.model);
@@ -84,15 +89,34 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
84
89
  if (options.auto && (!startupTransferEnabled(latest) || !ctx.isIdle()))
85
90
  throw new Error("Automatic transfer is no longer authorized at this idle boundary.");
86
91
  });
87
- await validate();
88
- const backend = await timings.measure("transfer backend initialization", () => factory(config));
89
- await validate();
92
+ const validateIgnore = ignorePolicyValidator({
93
+ ...config,
94
+ signal: options.signal,
95
+ validateMutation: () => {
96
+ validateOwner();
97
+ if (options.auto && !ctx.isIdle())
98
+ throw new Error("Automatic transfer is no longer authorized at this idle boundary.");
99
+ },
100
+ });
101
+ const validateFresh = validateIgnore
102
+ ? async () => {
103
+ await validate();
104
+ await validateIgnore();
105
+ }
106
+ : validate;
107
+ await validateFresh();
90
108
  const pending = await timings.measure("transfer journal read", () => readMergeJournal(config));
91
109
  await validate();
92
110
  if (pending && options.agentRetryRefusal)
93
111
  throw new Error("A pending merge journal requires ordinary Sync now before retrying a refused candidate.");
112
+ if (pending)
113
+ assertMergeJournalPolicy(pending, config);
114
+ const backend = await timings.measure("transfer backend initialization", () => factory(config));
115
+ await validate();
94
116
  if (pending) {
95
- const recovered = await timings.measure("transfer journal recovery", () => completeJournal(ctx, config, backend, pending, validate, timings, options.signal, options.auto, options.background?.validate));
117
+ const recovered = await timings.measure("transfer journal recovery", () => completeJournal(ctx, config, backend, pending, { validate, validateFresh, validateOwner }, timings, options, resolution ? undefined : isCurrent));
118
+ if (recovered === "archived" || recovered === "cancelled")
119
+ return recovered;
96
120
  if (!recovered) {
97
121
  if ((options.auto || !options.silent) && !options.signal?.aborted)
98
122
  ctx.ui.notify("Interrupted candidate is not active; local content and baseline were unchanged. Evidence was reconciled without retrying publication. Run sync again for a fresh plan.", "warning");
@@ -153,10 +177,11 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
153
177
  }
154
178
  }
155
179
  const rawRemote = head
156
- ? await timings.measure("transfer snapshot download", () => readSnapshotForHead(backend, head, options.signal))
180
+ ? await timings.measure("transfer snapshot download", () => readSnapshotForHead(backend, head, options.signal, config))
157
181
  : undefined;
158
182
  await validate();
159
183
  if (rawRemote) {
184
+ requireCompatibleRemoteSelection(config, rawRemote);
160
185
  const files = [...local.files, ...rawRemote.files];
161
186
  if (files.length > 16_384 ||
162
187
  files.reduce((bytes, file) => bytes + file.contentBase64.length * 0.75, 0) > 64 * 1024 * 1024) {
@@ -167,7 +192,6 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
167
192
  ? portableSnapshot(filterSnapshotForConfigPolicy(rawRemote, config, { sessionDir: sessionRoot }), rawRemote.localFields)
168
193
  : undefined;
169
194
  if (rawRemote) {
170
- requireCompatibleRemoteSelection(config, rawRemote);
171
195
  const validation = await timings.measure("transfer merge planning", () => planFileMerge({
172
196
  baseline: state.lastFileHashes,
173
197
  local: local.files,
@@ -232,7 +256,7 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
232
256
  if (config.agentMode && !resolution) {
233
257
  const { resolveAgentPlan } = await import("./agent-plan.js");
234
258
  await validate();
235
- plan = await resolveAgentPlan(ctx, options, config, backend, state, local, localRaw, remote, head, plan, snapshotOptions, validate);
259
+ plan = await resolveAgentPlan(ctx, options, config, backend, state, local, localRaw, remote, head, plan, snapshotOptions, validateFresh);
236
260
  await validate();
237
261
  if (plan.kind !== "planned" || (plan.conflicts.length && !config.partialSync))
238
262
  throw new ContinuousError("unsafe", "Autonomous sync paused: unsupported or refused conflict groups remain; no transfer was performed.");
@@ -351,7 +375,7 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
351
375
  throw new ContinuousError("stale", "Remote changed before baseline acceptance; retry from a fresh observation.");
352
376
  await options.agentAcceptance?.commitCandidate?.();
353
377
  await validate();
354
- await timings.measure("transfer baseline write", () => writeAcceptedState(config, head, accepted, validate, progress));
378
+ await timings.measure("transfer baseline write", () => writeAcceptedState(config, head, accepted, validateFresh, progress));
355
379
  await timings.measure("transfer cleanup", () => pruneMergeBaselines(config, acceptedState(config, head, accepted, progress), captureMutationOwner(ctx, options.signal)));
356
380
  await validate();
357
381
  await timings.measure("transfer cleanup", () => pruneCompletedConflicts(config, backend.identity, acceptedState(config, head, accepted, progress), accepted, remote, captureMutationOwner(ctx, options.signal)));
@@ -396,16 +420,16 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
396
420
  await validate();
397
421
  const refreshedHead = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
398
422
  await validate();
399
- if (!refreshedHead || !backend.sameRevision(refreshedHead.revision, head.revision))
423
+ if (!sameMergeRecoveryHead(backend, refreshedHead, head))
400
424
  throw new ContinuousError("stale", "Remote changed during review; no merged transfer was performed.");
401
425
  await options.agentAcceptance?.commitCandidate?.();
402
426
  await validate();
403
427
  progress = await persistProgress();
404
428
  await validate();
405
429
  const backup = await timings.measure("transfer backup", () => backupLocal(config.snapshotIdentity, snapshotOptions, options.signal));
406
- await validate();
430
+ await validateFresh();
407
431
  const journal = {
408
- version: 1,
432
+ ...mergeJournalPolicy(config),
409
433
  identity: mergeJournalIdentity(config, backend.identity),
410
434
  before: localRaw,
411
435
  after,
@@ -425,7 +449,7 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
425
449
  const atCommit = await timings.measure("transfer local snapshot", () => createSnapshot(config.snapshotIdentity, snapshotOptions));
426
450
  await validate();
427
451
  if (!sameHashes(fileHashMap(atCommit), fileHashMap(localRaw)) || atCommitState !== journal.stateIdentity) {
428
- await validate();
452
+ await validateFresh();
429
453
  await clearMergeJournal(config);
430
454
  throw new ContinuousError("stale", "Local content or baseline changed before publication; candidate retired without transfer. Review a fresh sync.");
431
455
  }
@@ -435,18 +459,23 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
435
459
  ...(ctx.protectedSessionFiles ?? []),
436
460
  ...[ctx.sessionManager.getSessionFile?.()].filter((file) => Boolean(file)),
437
461
  ]));
438
- await validate();
439
462
  }
440
463
  catch (error) {
441
- await validate();
464
+ await validateFresh();
442
465
  await clearMergeJournal(config);
443
466
  throw error;
444
467
  }
468
+ await validateFresh();
445
469
  try {
446
470
  if (publish) {
447
471
  const result = await timings.measure("transfer remote publication", () => backend.publishSnapshot(upload, expectedRemoteHead(head), {
448
472
  signal: options.signal,
449
473
  onCommit: options.onCommit,
474
+ ...(validateIgnore
475
+ ? {
476
+ validateIgnorePolicy: () => validateMergedPublication(ctx, config, snapshotOptions, localRaw, after, journal.stateIdentity, validateFresh),
477
+ }
478
+ : {}),
450
479
  }));
451
480
  journal.committedHead = result.head;
452
481
  journal.warnings = result.warnings;
@@ -459,6 +488,7 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
459
488
  if (error instanceof SyncBackendConflictError &&
460
489
  error.phase === "before-commit" &&
461
490
  !error.candidateMayHaveBeenActive) {
491
+ await validateFresh();
462
492
  await clearMergeJournal(config);
463
493
  if (attempt + 1 < MAX_ATTEMPTS)
464
494
  continue;
@@ -468,7 +498,7 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
468
498
  // Every uncertain/after-commit outcome retains evidence and is never blindly retried.
469
499
  throw mergeTransferError(error, config.backend);
470
500
  }
471
- const completed = await timings.measure("transfer journal recovery", () => completeJournal(ctx, config, backend, journal, validate, timings, options.signal, options.auto, options.background?.validate));
501
+ const completed = await timings.measure("transfer journal recovery", () => completeJournal(ctx, config, backend, journal, { validate, validateFresh, validateOwner }, timings, options));
472
502
  if (!completed) {
473
503
  if (!options.signal?.aborted && (options.auto || !options.silent))
474
504
  ctx.ui.notify("Remote changed before local apply; candidate retired without transfer. Run sync again.", "warning");
@@ -491,41 +521,54 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
491
521
  await timings.measure("transfer cleanup", () => releaseConflictArtifacts(config, ownedStatePath, createdArtifacts));
492
522
  }
493
523
  }
494
- async function completeJournal(ctx, config, backend, journal, validate, timings, signal, auto = false, validateBackground) {
524
+ async function completeJournal(ctx, config, backend, journal, { validate, validateFresh, validateOwner, }, timings, options, isCurrent) {
525
+ const { auto, signal } = options;
526
+ const validateMutation = () => {
527
+ validateOwner();
528
+ if (auto && !ctx.isIdle())
529
+ throw new Error("Automatic file apply is no longer idle; evidence retained.");
530
+ };
495
531
  if (journal.identity !== mergeJournalIdentity(config, backend.identity) ||
496
532
  !sameLocalFields(journal.upload.localFields, config.localFields))
497
533
  throw new Error("Merge journal belongs to a different setup, selection or local-field policy; preserve it for reviewed recovery.");
498
- await validate();
534
+ assertMergeJournalPolicy(journal, config);
535
+ await validateFresh();
499
536
  const sessionRoot = config.scope === "agent-directory" || syncSessionsSelected(config)
500
537
  ? await effectiveSessionRoot(ctx, config, signal)
501
538
  : undefined;
502
539
  await validate();
503
540
  if (sessionRoot !== undefined && journal.sessionRoot !== sessionRoot) {
504
- throw new Error("Merge journal session root is missing or differs from this context; preserve evidence and use reviewed directional recovery.");
541
+ throw new Error("Merge journal session root is missing or differs from this context; preserve its journal and backup for review.");
505
542
  }
506
543
  const snapshotOptions = { ...snapshotOptionsForContext(ctx, config), sessionDir: sessionRoot, signal };
507
544
  const head = await timings.measure("transfer remote head", () => backend.readHead(signal));
508
- if (!journal.committedHead &&
509
- head &&
510
- (backend.sameRevision(head.revision, journal.expectedHead.revision) ||
511
- backend.matchesUncommittedRecoveryHead?.(head, journal.expectedHead))) {
512
- await validate();
513
- const local = await timings.measure("transfer local snapshot", () => createSnapshot(config.snapshotIdentity, snapshotOptions));
514
- if (!sameHashes(fileHashMap(local), fileHashMap(journal.before)) ||
515
- syncStateFingerprint(await timings.measure("transfer state read", () => readStateForConfig(config))) !==
516
- journal.stateIdentity) {
517
- throw new Error("Uncertain publication is not active, but local content or baseline changed; keep the journal for reviewed recovery.");
518
- }
519
- await clearMergeJournal(config);
520
- return false;
521
- }
522
545
  await validate();
546
+ const readRetirementEvidence = async () => {
547
+ const state = await timings.measure("transfer state read", () => readStateForConfig(config));
548
+ await validateFresh();
549
+ const local = await timings.measure("transfer local snapshot", () => createSnapshot(config.snapshotIdentity, snapshotOptions));
550
+ validateMutation();
551
+ const latest = await timings.measure("transfer remote head", () => backend.readHead(signal));
552
+ validateMutation();
553
+ if (!sameMergeRecoveryHead(backend, head, latest))
554
+ throw new Error("Remote head changed during merge recovery; journal and backup retained.");
555
+ await validateFresh();
556
+ return {
557
+ sameBaseline: syncStateFingerprint(state) === journal.stateIdentity,
558
+ sameLocal: sameHashes(fileHashMap(local), fileHashMap(journal.before)),
559
+ };
560
+ };
523
561
  // Baseline publication is the durable completion boundary. A later remote revision
524
562
  // cannot undo that acceptance; retire only the journal for the recorded commit.
525
- if (journal.committedHead && (!head || !backend.sameRevision(head.revision, journal.committedHead.revision))) {
563
+ if (journal.committedHead?.snapshotId === journal.upload.id &&
564
+ typeof journal.committedHead.revision === "string" &&
565
+ journal.committedHead.revision &&
566
+ (!head || !backend.sameRevision(head.revision, journal.committedHead.revision))) {
526
567
  const state = await timings.measure("transfer state read", () => readStateForConfig(config));
527
568
  await validate();
528
569
  if (matchesAcceptedState(state, config, journal.committedHead, journal.accepted ?? journal.after, journal.progress)) {
570
+ if (journal.localPolicyKey)
571
+ await validateFresh();
529
572
  await clearMergeJournal(config);
530
573
  await validate();
531
574
  await pruneMergeBaselines(config, state, captureMutationOwner(ctx, signal));
@@ -533,12 +576,37 @@ async function completeJournal(ctx, config, backend, journal, validate, timings,
533
576
  return true;
534
577
  }
535
578
  }
579
+ if (head &&
580
+ (journal.ignoreSource || head.selection?.version === 4) &&
581
+ inspectRemoteSelection(config.include, { selection: head.selection, files: [] }, config.exclude, config).kind !==
582
+ "same")
583
+ throw new Error("Remote ignore-file policy differs or is unavailable; preserve the pending merge for review.");
584
+ if (!journal.committedHead &&
585
+ head &&
586
+ (backend.sameRevision(head.revision, journal.expectedHead.revision) ||
587
+ backend.matchesUncommittedRecoveryHead?.(head, journal.expectedHead))) {
588
+ if (journal.ignoreSource &&
589
+ (head.snapshotId !== journal.expectedHead.snapshotId ||
590
+ head.snapshotRef !== journal.expectedHead.snapshotRef ||
591
+ head.snapshotId === journal.upload.id))
592
+ throw new Error("Cannot verify that the ignore-file candidate is inactive; preserve the journal and backup.");
593
+ const { sameBaseline, sameLocal } = await readRetirementEvidence();
594
+ validateMutation();
595
+ if (!sameBaseline || !sameLocal) {
596
+ if (journal.ignoreSource) {
597
+ if (!sameBaseline)
598
+ throw new Error("Sync baseline changed after uncertain publication; preserve the journal and backup for review.");
599
+ return reviewInactiveIgnoreMerge(ctx, config, backend, journal, head, options, validateFresh, isCurrent);
600
+ }
601
+ throw new Error("Uncertain publication is not active, but local content or baseline changed; keep the journal for reviewed recovery.");
602
+ }
603
+ await clearMergeJournal(config);
604
+ return false;
605
+ }
536
606
  if (journal.applyOnly && (!head || !backend.sameRevision(head.revision, journal.expectedHead.revision))) {
537
- const local = await timings.measure("transfer local snapshot", () => createSnapshot(config.snapshotIdentity, snapshotOptions));
538
- const state = await timings.measure("transfer state read", () => readStateForConfig(config));
539
- await validate();
540
- if (sameHashes(fileHashMap(local), fileHashMap(journal.before)) &&
541
- syncStateFingerprint(state) === journal.stateIdentity) {
607
+ const { sameBaseline, sameLocal } = await readRetirementEvidence();
608
+ validateMutation();
609
+ if (sameBaseline && sameLocal) {
542
610
  await clearMergeJournal(config);
543
611
  return false;
544
612
  }
@@ -549,14 +617,14 @@ async function completeJournal(ctx, config, backend, journal, validate, timings,
549
617
  (journal.committedHead && !backend.sameRevision(head.revision, journal.committedHead.revision))) {
550
618
  throw new Error("Publication outcome cannot be reconciled with the current remote head. Journal and backup retained; do not retry publication or restore old bytes blindly.");
551
619
  }
552
- const observed = await timings.measure("transfer snapshot download", () => readSnapshotForHead(backend, head, signal));
620
+ const observed = await timings.measure("transfer snapshot download", () => readSnapshotForHead(backend, head, signal, config));
553
621
  requireCompatibleRemoteSelection(config, observed);
554
622
  if (!sameHashes(fileHashMap(observed), fileHashMap(journal.upload)) ||
555
623
  JSON.stringify(observed.selection) !== JSON.stringify(journal.upload.selection))
556
624
  throw new Error("Remote snapshot does not match the recorded merge publication.");
557
625
  const state = await timings.measure("transfer state read", () => readStateForConfig(config));
558
626
  if (matchesAcceptedState(state, config, head, journal.accepted ?? journal.after, journal.progress)) {
559
- await validate();
627
+ await validateFresh();
560
628
  await clearMergeJournal(config);
561
629
  await validate();
562
630
  await pruneMergeBaselines(config, state, captureMutationOwner(ctx, signal));
@@ -567,25 +635,27 @@ async function completeJournal(ctx, config, backend, journal, validate, timings,
567
635
  throw new Error("Sync baseline changed after the interrupted merge; preserve its journal and review recovery.");
568
636
  }
569
637
  if (inspectRemoteSelection(config.include, observed, config.exclude, config).kind !== "same")
570
- throw new Error("Pending merge has unavailable remote selection metadata; preserve its journal and choose a reviewed explicit direction.");
638
+ throw new Error("Pending merge has unavailable remote selection metadata; preserve its journal and backup for review.");
571
639
  if (sessionRoot !== undefined)
572
640
  requireStableMergeSessionRoot(journal.before, journal.after, config.scope);
573
- await validate();
574
- const validateOwner = captureMutationOwner(ctx, signal);
575
- const validateMutation = () => {
576
- validateOwner();
577
- validateBackground?.();
578
- if (auto && !ctx.isIdle())
579
- throw new Error("Automatic file apply is no longer idle; evidence retained.");
641
+ await validateFresh();
642
+ const protectedPaths = protectedSessionPaths(ctx, sessionRoot);
643
+ const validateApply = () => {
644
+ validateMutation();
645
+ if (journal.localPolicyKey)
646
+ checkLiveProtection(ctx, sessionRoot, protectedPaths);
580
647
  };
581
- await timings.measure("transfer local apply", () => applyMergedSnapshot(journal.before, journal.after, protectedSessionPaths(ctx, sessionRoot), { ...snapshotOptions, validateMutation }, validate, ctx.sessionManager.getSessionFile?.()));
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?.()));
582
652
  await validate();
583
653
  const headAtAcceptance = await timings.measure("transfer remote head", () => backend.readHead(signal));
584
654
  await validate();
585
- if (!headAtAcceptance || !backend.sameRevision(headAtAcceptance.revision, head.revision))
655
+ if (!sameMergeRecoveryHead(backend, headAtAcceptance, head))
586
656
  throw new Error("Remote changed during merged apply; journal and backup retained for review.");
587
- await timings.measure("transfer baseline write", () => writeAcceptedState(config, head, journal.accepted ?? journal.after, validate, journal.progress));
588
- await validate();
657
+ await timings.measure("transfer baseline write", () => writeAcceptedState(config, head, journal.accepted ?? journal.after, validateFresh, journal.progress));
658
+ await validateFresh();
589
659
  await clearMergeJournal(config);
590
660
  await validate();
591
661
  await timings.measure("transfer cleanup", () => pruneMergeBaselines(config, acceptedState(config, head, journal.accepted ?? journal.after, journal.progress), captureMutationOwner(ctx, signal)));
@@ -594,28 +664,3 @@ async function completeJournal(ctx, config, backend, journal, validate, timings,
594
664
  await validate();
595
665
  return true;
596
666
  }
597
- // Older valid journals may have accepted noncanonical JSON before projection normalization.
598
- function matchesAcceptedState(state, config, head, snapshot, progress) {
599
- return [true, false].some((canonical) => syncStateFingerprint(state) === syncStateFingerprint(acceptedState(config, head, snapshot, progress, canonical)));
600
- }
601
- function acceptedState(config, head, snapshot, progress, canonical = true) {
602
- if (progress)
603
- return progressState(config, head, snapshot, progress);
604
- return {
605
- version: 1,
606
- profile: config.snapshotIdentity,
607
- lastAppliedSnapshot: head.snapshotId,
608
- lastRemoteRevision: head.revision,
609
- lastFileHashes: fileHashMap(canonical ? portableSnapshot(snapshot, config.localFields) : snapshot),
610
- ...acceptedSelection(config),
611
- ...(config.localFields !== undefined ? { localFields: config.localFields } : {}),
612
- };
613
- }
614
- async function writeAcceptedState(config, head, snapshot, validate, progress) {
615
- const accepted = portableSnapshot(snapshot, config.localFields);
616
- const state = acceptedState(config, head, accepted, progress);
617
- await stageMergeBaseline(config, accepted, state, progress?.previous);
618
- await validate();
619
- await writeStateForConfig(config, state);
620
- await validate();
621
- }
@@ -1,9 +1,17 @@
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
+ import type { SyncState } from "../state/state-types.js";
4
5
  import { type RemoteSelectionState } from "./sync-policy.js";
5
- export declare function readSnapshotForHead(backend: SyncBackend, head: RemoteHead, signal?: AbortSignal): Promise<Snapshot>;
6
+ export declare function readSnapshotForHead(backend: SyncBackend, head: RemoteHead, signal?: AbortSignal, config?: AnySyncConfig): Promise<Snapshot>;
7
+ export declare function readRemoteSnapshotForUpload(backend: SyncBackend, config: AnySyncConfig, head: RemoteHead | undefined, state: SyncState, options: {
8
+ force?: boolean;
9
+ signal?: AbortSignal;
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>;
12
+ export declare function sameRemoteHead(backend: SyncBackend, left: RemoteHead | undefined, right: RemoteHead | undefined): boolean;
6
13
  export declare function requireCompatibleRemoteSelection(config: AnySyncConfig, snapshot: Snapshot): void;
14
+ export declare function inspectHeadSelection(backend: SyncBackend, config: AnySyncConfig, head: RemoteHead, signal?: AbortSignal): Promise<RemoteSelectionState>;
7
15
  export declare function formatRemoteSelectionStatus(state: RemoteSelectionState | undefined): string;
8
16
  export declare function readRemoteSnapshot(backend: SyncBackend, config: AnySyncConfig, signal?: AbortSignal, options?: {
9
17
  allowSelectionDifference?: boolean;
@@ -24,6 +32,6 @@ export declare function readRemoteSnapshot(backend: SyncBackend, config: AnySync
24
32
  syncSessions: boolean | undefined;
25
33
  selection: import("../snapshot/snapshot-types.js").SnapshotSelection;
26
34
  files: import("../snapshot/snapshot-types.js").SnapshotFile[];
27
- };
35
+ } | undefined;
28
36
  selectionState: RemoteSelectionState;
29
37
  }>;
@@ -1,10 +1,11 @@
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";
6
- import { inspectRemoteSelection, remoteSelectionMismatch, sameSnapshotSelection, } from "./sync-policy.js";
7
- export async function readSnapshotForHead(backend, head, signal) {
6
+ import { formatIgnorePolicyComparison, inspectRemoteSelection, remoteSelectionMismatch, requireLegacyTransferPolicy, sameSnapshotSelection, } from "./sync-policy.js";
7
+ import { syncPolicyChanged } from "./sync-state.js";
8
+ async function readValidatedSnapshotForHead(backend, head, signal) {
8
9
  const snapshot = await backend.readSnapshot(head.snapshotRef, signal);
9
10
  throwIfAborted(signal);
10
11
  validatePortableSnapshot(snapshot);
@@ -18,17 +19,73 @@ export async function readSnapshotForHead(backend, head, signal) {
18
19
  }
19
20
  return snapshot;
20
21
  }
22
+ export async function readSnapshotForHead(backend, head, signal, config) {
23
+ const snapshot = await readValidatedSnapshotForHead(backend, head, signal);
24
+ if (!config)
25
+ requireLegacyTransferPolicy(snapshot);
26
+ else if (!config.ignorePolicy && snapshot.selection?.version === 4)
27
+ requireCompatibleRemoteSelection(config, snapshot);
28
+ return snapshot;
29
+ }
30
+ export async function readRemoteSnapshotForUpload(backend, config, head, state, options) {
31
+ if (!head)
32
+ return undefined;
33
+ if (config.ignorePolicy ||
34
+ head.selection?.version === 4 ||
35
+ head.snapshotId !== state.lastAppliedSnapshot ||
36
+ syncPolicyChanged(state, config) ||
37
+ (state.lastRemoteRevision && !backend.sameRevision(head.revision, state.lastRemoteRevision)) ||
38
+ (!options.force &&
39
+ (config.scope === "agent-directory" ||
40
+ (head.selection &&
41
+ inspectRemoteSelection(config.include, { selection: head.selection, files: [] }, config.exclude, config)
42
+ .kind === "different"))))
43
+ return readSnapshotForHead(backend, head, options.signal, config);
44
+ return undefined;
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
+ }
58
+ export function sameRemoteHead(backend, left, right) {
59
+ if (!left || !right)
60
+ return left === right;
61
+ return (left.snapshotId === right.snapshotId &&
62
+ left.snapshotRef === right.snapshotRef &&
63
+ backend.sameRevision(left.revision, right.revision) &&
64
+ sameSnapshotSelection(left.selection, right.selection));
65
+ }
21
66
  export function requireCompatibleRemoteSelection(config, snapshot) {
67
+ const state = inspectRemoteSelection(config.include, snapshot, config.exclude, config);
68
+ if (state.kind === "different" && state.ignorePolicyComparison)
69
+ throw selectionMismatch(config, state);
22
70
  if (!sameLocalFields(config.localFields, snapshot.localFields))
23
71
  throw new Error("Remote local-field policy differs; confirm a reviewed directional migration. Old history is not erased.");
24
- const state = inspectRemoteSelection(config.include, snapshot, config.exclude, config);
25
- if (state.kind === "different") {
26
- throw remoteSelectionMismatch(config, state.include, syncConfigReviewFingerprint(config), state.exclude, state);
27
- }
72
+ if (state.kind === "different")
73
+ throw selectionMismatch(config, state);
74
+ }
75
+ export async function inspectHeadSelection(backend, config, head, signal) {
76
+ const remote = !head.selection && config.ignorePolicy
77
+ ? await readValidatedSnapshotForHead(backend, head, signal)
78
+ : { selection: head.selection, files: [] };
79
+ return inspectRemoteSelection(config.include, remote, config.exclude, config);
80
+ }
81
+ function selectionMismatch(config, state) {
82
+ return remoteSelectionMismatch(config, state.include, syncConfigReviewFingerprint(config), state.exclude, state);
28
83
  }
29
84
  export function formatRemoteSelectionStatus(state) {
30
85
  if (!state)
31
86
  return "remote included content: unavailable (remote is empty)";
87
+ if (state.ignorePolicyComparison)
88
+ return formatIgnorePolicyComparison(state.ignorePolicyComparison);
32
89
  if (state.kind === "same")
33
90
  return "remote included content: matches this setup";
34
91
  if (state.kind === "legacy") {
@@ -51,15 +108,12 @@ export async function readRemoteSnapshot(backend, config, signal, options = {})
51
108
  const head = await backend.readHead(signal);
52
109
  if (!head)
53
110
  return { head: undefined, snapshot: undefined, selectionState: undefined };
54
- const snapshot = await readSnapshotForHead(backend, head, signal);
55
- const selectionState = inspectRemoteSelection(config.include, snapshot, config.exclude, config);
56
- if (!options.allowSelectionDifference && selectionState.kind === "different") {
57
- const configIdentity = syncConfigReviewFingerprint(config);
58
- throw remoteSelectionMismatch(config, selectionState.include, configIdentity, selectionState.exclude, selectionState);
59
- }
60
- return {
61
- head,
62
- snapshot: filterSnapshotForConfigPolicy(snapshot, config, { sessionDir: options.sessionDir }),
63
- selectionState,
64
- };
111
+ const rawSnapshot = await readValidatedSnapshotForHead(backend, head, signal);
112
+ const selectionState = inspectRemoteSelection(config.include, rawSnapshot, config.exclude, config);
113
+ if (!options.allowSelectionDifference && selectionState.kind === "different")
114
+ throw selectionMismatch(config, selectionState);
115
+ const snapshot = selectionState.ignorePolicyComparison === "local-legacy-remote-ignore"
116
+ ? undefined
117
+ : filterSnapshotForConfigPolicy(rawSnapshot, config, { sessionDir: options.sessionDir });
118
+ return { head, snapshot, selectionState };
65
119
  }
@@ -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,9 +2,10 @@ import { createHash } from "node:crypto";
2
2
  import { createSyncBackend } from "../backends/backend-factory.js";
3
3
  import { createSnapshot } from "../snapshot/snapshot.js";
4
4
  import { readStateForConfig, syncStateFingerprint } from "../state/sync-state-store.js";
5
+ import { inspectHeadSelection } from "./remote-snapshot.js";
5
6
  import { throwIfAborted } from "./signals.js";
6
7
  import { createStartupTimings } from "./startup-timings.js";
7
- import { inspectRemoteSelection, syncSelectionHasContent } from "./sync-policy.js";
8
+ import { syncSelectionHasContent } from "./sync-policy.js";
8
9
  import { fileHashMap, hasLocalChanges, remoteChangedSinceState } from "./sync-state.js";
9
10
  /** Advisory baseline-relative observation, never an authorization to transfer files. */
10
11
  export async function inspectSync(config, options, signal, factory = createSyncBackend, timings = createStartupTimings()) {
@@ -17,6 +18,8 @@ export async function inspectSync(config, options, signal, factory = createSyncB
17
18
  throwIfAborted(signal);
18
19
  const head = await timings.measure("remote head", () => backend.readHead(signal));
19
20
  throwIfAborted(signal);
21
+ const selectionState = head ? await inspectHeadSelection(backend, config, head, signal) : undefined;
22
+ throwIfAborted(signal);
20
23
  const freshness = {
21
24
  localIdentity: createHash("sha256")
22
25
  .update(JSON.stringify(fileHashMap(local)))
@@ -25,12 +28,11 @@ export async function inspectSync(config, options, signal, factory = createSyncB
25
28
  return {
26
29
  ...freshness,
27
30
  head,
28
- selectionState: head
29
- ? inspectRemoteSelection(config.include, { selection: head.selection, files: [] }, config.exclude, config)
30
- : undefined,
31
+ selectionState,
31
32
  localFiles: local.files.length,
32
33
  localChanged: hasLocalChanges(local, state, config),
33
- remoteChanged: remoteChangedSinceState(head, state, config, (left, right) => backend.sameRevision(left, right)),
34
+ remoteChanged: (selectionState?.kind === "different" && !!selectionState.ignorePolicyComparison) ||
35
+ remoteChangedSinceState(head, state, config, (left, right) => backend.sameRevision(left, right)),
34
36
  firstSync: !state.lastAppliedSnapshot,
35
37
  emptyInclude: !syncSelectionHasContent(config),
36
38
  stateIdentity: syncStateFingerprint(state),