@narumitw/pi-sync-daemon 0.6.2 → 0.8.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 (97) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +17 -3
  3. package/dist/consent.js +26 -1
  4. package/dist/engine/backends/git/git-backend.d.ts +1 -1
  5. package/dist/engine/backends/git/git-backend.js +17 -2
  6. package/dist/engine/backends/git/git-storage.d.ts +1 -1
  7. package/dist/engine/backends/git/git-storage.js +39 -13
  8. package/dist/engine/backends/s3/s3-backend.js +8 -0
  9. package/dist/engine/backends/sync-backend.d.ts +1 -0
  10. package/dist/engine/backends/webdav/webdav-backend.js +8 -0
  11. package/dist/engine/ignore/effective-ignore-policy.d.ts +10 -0
  12. package/dist/engine/ignore/effective-ignore-policy.js +33 -0
  13. package/dist/engine/ignore/ignore-edit.d.ts +13 -0
  14. package/dist/engine/ignore/ignore-edit.js +102 -0
  15. package/dist/engine/ignore/ignore-initialization.d.ts +6 -0
  16. package/dist/engine/ignore/ignore-initialization.js +186 -0
  17. package/dist/engine/ignore/ignore-migration-prompt.d.ts +7 -0
  18. package/dist/engine/ignore/ignore-migration-prompt.js +139 -0
  19. package/dist/engine/ignore/ignore-settings.d.ts +15 -0
  20. package/dist/engine/ignore/ignore-settings.js +322 -0
  21. package/dist/engine/ignore/ignore-source.d.ts +27 -0
  22. package/dist/engine/ignore/ignore-source.js +250 -0
  23. package/dist/engine/paths.js +1 -1
  24. package/dist/engine/settings/config-file.d.ts +9 -2
  25. package/dist/engine/settings/config-file.js +126 -28
  26. package/dist/engine/settings/config.d.ts +5 -4
  27. package/dist/engine/settings/config.js +114 -13
  28. package/dist/engine/settings/settings-management.js +34 -32
  29. package/dist/engine/settings/settings-types.d.ts +40 -5
  30. package/dist/engine/settings/settings-validation.js +52 -24
  31. package/dist/engine/snapshot/session-paths.d.ts +6 -4
  32. package/dist/engine/snapshot/session-paths.js +84 -15
  33. package/dist/engine/snapshot/snapshot-apply.d.ts +7 -8
  34. package/dist/engine/snapshot/snapshot-apply.js +107 -21
  35. package/dist/engine/snapshot/snapshot-bounds.d.ts +4 -0
  36. package/dist/engine/snapshot/snapshot-bounds.js +20 -0
  37. package/dist/engine/snapshot/snapshot-codec.d.ts +1 -1
  38. package/dist/engine/snapshot/snapshot-codec.js +15 -7
  39. package/dist/engine/snapshot/snapshot-entry-projection.d.ts +10 -0
  40. package/dist/engine/snapshot/snapshot-entry-projection.js +78 -0
  41. package/dist/engine/snapshot/snapshot-exclude-safety.d.ts +9 -2
  42. package/dist/engine/snapshot/snapshot-exclude-safety.js +239 -24
  43. package/dist/engine/snapshot/snapshot-payload.d.ts +2 -0
  44. package/dist/engine/snapshot/snapshot-payload.js +10 -0
  45. package/dist/engine/snapshot/snapshot-reviewed-preimages.d.ts +2 -0
  46. package/dist/engine/snapshot/snapshot-reviewed-preimages.js +60 -0
  47. package/dist/engine/snapshot/snapshot-root-transition.d.ts +4 -0
  48. package/dist/engine/snapshot/snapshot-root-transition.js +16 -0
  49. package/dist/engine/snapshot/snapshot-transaction-images.d.ts +39 -0
  50. package/dist/engine/snapshot/snapshot-transaction-images.js +387 -0
  51. package/dist/engine/snapshot/snapshot-transaction-policy.d.ts +73 -0
  52. package/dist/engine/snapshot/snapshot-transaction-policy.js +276 -0
  53. package/dist/engine/snapshot/snapshot-transaction-stage.d.ts +32 -0
  54. package/dist/engine/snapshot/snapshot-transaction-stage.js +303 -0
  55. package/dist/engine/snapshot/snapshot-transaction-verification.d.ts +7 -0
  56. package/dist/engine/snapshot/snapshot-transaction-verification.js +78 -0
  57. package/dist/engine/snapshot/snapshot-transaction.d.ts +1 -11
  58. package/dist/engine/snapshot/snapshot-transaction.js +390 -364
  59. package/dist/engine/snapshot/snapshot-types.d.ts +47 -2
  60. package/dist/engine/snapshot/snapshot-types.js +9 -1
  61. package/dist/engine/snapshot/snapshot.d.ts +22 -3
  62. package/dist/engine/snapshot/snapshot.js +357 -43
  63. package/dist/engine/state/merge-baseline-store.js +20 -9
  64. package/dist/engine/state/state-types.d.ts +3 -0
  65. package/dist/engine/sync/apply-review.d.ts +3 -3
  66. package/dist/engine/sync/apply-review.js +5 -4
  67. package/dist/engine/sync/continuous-sync.js +37 -12
  68. package/dist/engine/sync/continuous-watch.d.ts +4 -1
  69. package/dist/engine/sync/continuous-watch.js +90 -15
  70. package/dist/engine/sync/exclude-policy.d.ts +4 -0
  71. package/dist/engine/sync/exclude-policy.js +8 -1
  72. package/dist/engine/sync/initialization.js +9 -4
  73. package/dist/engine/sync/local-fields.d.ts +3 -1
  74. package/dist/engine/sync/local-fields.js +88 -8
  75. package/dist/engine/sync/merge-apply.js +190 -47
  76. package/dist/engine/sync/merge-journal.d.ts +18 -4
  77. package/dist/engine/sync/merge-journal.js +126 -10
  78. package/dist/engine/sync/merged-sync.d.ts +1 -1
  79. package/dist/engine/sync/merged-sync.js +124 -68
  80. package/dist/engine/sync/partial-progress.js +5 -3
  81. package/dist/engine/sync/remote-snapshot.d.ts +10 -2
  82. package/dist/engine/sync/remote-snapshot.js +59 -17
  83. package/dist/engine/sync/session-push.js +7 -6
  84. package/dist/engine/sync/sync-decision.d.ts +4 -0
  85. package/dist/engine/sync/sync-decision.js +17 -2
  86. package/dist/engine/sync/sync-inspection.js +8 -6
  87. package/dist/engine/sync/sync-mutations.d.ts +10 -2
  88. package/dist/engine/sync/sync-mutations.js +245 -101
  89. package/dist/engine/sync/sync-policy.d.ts +36 -10
  90. package/dist/engine/sync/sync-policy.js +285 -20
  91. package/dist/engine/sync/sync-queries.js +49 -32
  92. package/dist/engine/sync/sync-state.d.ts +11 -0
  93. package/dist/engine/sync/sync-state.js +42 -5
  94. package/dist/engine/ui/sync-format.js +22 -7
  95. package/dist/engine-service.js +24 -2
  96. package/docs/architecture.md +28 -0
  97. package/package.json +2 -1
@@ -3,6 +3,7 @@ import { expectedRemoteHead, SyncBackendConflictError, } from "../backends/sync-
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 { ignorePolicyValidator } from "../snapshot/snapshot-transaction-policy.js";
6
7
  import { hasCurrentMergeBaseline, pruneMergeBaselines, readMergeAncestors, stageMergeBaseline, } from "../state/merge-baseline-store.js";
7
8
  import { readStateForConfig, statePathForConfig, syncStateFingerprint, writeStateForConfig, } from "../state/sync-state-store.js";
8
9
  import { confirmMergeReview } from "../ui/merge-review.js";
@@ -18,7 +19,7 @@ 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";
20
21
  import { applyMergedSnapshot, preflightMergedTargets } from "./merge-apply.js";
21
- import { clearMergeJournal, mergeJournalIdentity, readMergeJournal, writeMergeJournal, } from "./merge-journal.js";
22
+ import { assertMergeJournalPolicy, clearMergeJournal, mergeJournalIdentity, mergeJournalPolicy, readMergeJournal, reviewInactiveIgnoreMerge, sameMergeRecoveryHead, writeMergeJournal, } from "./merge-journal.js";
22
23
  import { mergeTransferError } from "./merge-transfer-error.js";
23
24
  import { acceptedMergeFiles, progressState } from "./partial-progress.js";
24
25
  import { formatRemoteSelectionStatus, readSnapshotForHead, requireCompatibleRemoteSelection, } from "./remote-snapshot.js";
@@ -27,7 +28,7 @@ import { createStartupTimings } from "./startup-timings.js";
27
28
  import { createSyncDecision } from "./sync-decision.js";
28
29
  import { backupLocal, captureMutationOwner, protectedSessionPaths } from "./sync-local.js";
29
30
  import { configuredSnapshotPathMatcher, inspectRemoteSelection, syncSessionsSelected } from "./sync-policy.js";
30
- import { fileHashMap, hasLocalChanges, hasRemoteChanges, sameHashes, syncPolicyChanged } from "./sync-state.js";
31
+ import { acceptedSelection, fileHashMap, hasLocalChanges, hasRemoteChanges, sameHashes, syncPolicyChanged, } from "./sync-state.js";
31
32
  import { TEXT_MERGE_WORK_LIMIT } from "./text-merge.js";
32
33
  const MAX_ATTEMPTS = 3;
33
34
  /** Established-baseline sync only. First-source selection remains in the existing command flow. */
@@ -54,10 +55,14 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
54
55
  };
55
56
  const config = await loadConfig(options.setup);
56
57
  validateOwner(config);
58
+ if (config.pathPolicy === "ignore-file" && !config.ignorePolicy)
59
+ throw new Error("Merged sync requires the resolved local ignore-file policy.");
57
60
  validateRetryAuthorization(config);
58
61
  const configToken = syncCheckConfigFingerprint(config);
59
62
  const modelToken = JSON.stringify(ctx.model);
60
- const sessionRoot = syncSessionsSelected(config) ? await effectiveSessionRoot(ctx) : undefined;
63
+ const sessionRoot = config.scope === "agent-directory" || syncSessionsSelected(config)
64
+ ? await effectiveSessionRoot(ctx, config, options.signal)
65
+ : undefined;
61
66
  validateOwner();
62
67
  const snapshotOptions = {
63
68
  ...snapshotOptionsForContext(ctx, config),
@@ -72,7 +77,7 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
72
77
  if (configToken !== syncCheckConfigFingerprint(latest))
73
78
  throw new Error("Sync setup or settings changed during transfer; reopen sync.");
74
79
  if (sessionRoot !== undefined) {
75
- const currentRoot = await effectiveSessionRoot(ctx);
80
+ const currentRoot = await effectiveSessionRoot(ctx, latest, options.signal);
76
81
  validateOwner();
77
82
  if (currentRoot !== sessionRoot)
78
83
  throw new Error("Session storage root changed during transfer; evidence retained for review.");
@@ -82,15 +87,34 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
82
87
  if (options.auto && (!startupTransferEnabled(latest) || !ctx.isIdle()))
83
88
  throw new Error("Automatic transfer is no longer authorized at this idle boundary.");
84
89
  });
85
- await validate();
86
- const backend = await timings.measure("transfer backend initialization", () => factory(config));
87
- await validate();
90
+ const validateIgnore = ignorePolicyValidator({
91
+ ...config,
92
+ signal: options.signal,
93
+ validateMutation: () => {
94
+ validateOwner();
95
+ if (options.auto && !ctx.isIdle())
96
+ throw new Error("Automatic transfer is no longer authorized at this idle boundary.");
97
+ },
98
+ });
99
+ const validateFresh = validateIgnore
100
+ ? async () => {
101
+ await validate();
102
+ await validateIgnore();
103
+ }
104
+ : validate;
105
+ await validateFresh();
88
106
  const pending = await timings.measure("transfer journal read", () => readMergeJournal(config));
89
107
  await validate();
90
108
  if (pending && options.agentRetryRefusal)
91
109
  throw new Error("A pending merge journal requires ordinary Sync now before retrying a refused candidate.");
110
+ if (pending)
111
+ assertMergeJournalPolicy(pending, config);
112
+ const backend = await timings.measure("transfer backend initialization", () => factory(config));
113
+ await validate();
92
114
  if (pending) {
93
- const recovered = await timings.measure("transfer journal recovery", () => completeJournal(ctx, config, backend, pending, validate, timings, options.signal, options.auto, options.background?.validate));
115
+ const recovered = await timings.measure("transfer journal recovery", () => completeJournal(ctx, config, backend, pending, { validate, validateFresh, validateOwner }, timings, options, resolution ? undefined : isCurrent));
116
+ if (recovered === "archived" || recovered === "cancelled")
117
+ return recovered;
94
118
  if (!recovered) {
95
119
  if ((options.auto || !options.silent) && !options.signal?.aborted)
96
120
  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");
@@ -130,8 +154,8 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
130
154
  !state.unresolved?.length &&
131
155
  head.snapshotId === state.lastAppliedSnapshot &&
132
156
  backend.sameRevision(head.revision, state.lastRemoteRevision) &&
133
- inspectRemoteSelection(config.include, { selection: head.selection, files: [] }, config.exclude).kind ===
134
- "same" &&
157
+ inspectRemoteSelection(config.include, { selection: head.selection, files: [] }, config.exclude, config)
158
+ .kind === "same" &&
135
159
  matchesAcceptedState(state, config, head, local)) {
136
160
  const unchanged = await timings.measure("transfer unchanged verification", async () => {
137
161
  if (!(await hasCurrentMergeBaseline(config, local, state)))
@@ -151,10 +175,11 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
151
175
  }
152
176
  }
153
177
  const rawRemote = head
154
- ? await timings.measure("transfer snapshot download", () => readSnapshotForHead(backend, head, options.signal))
178
+ ? await timings.measure("transfer snapshot download", () => readSnapshotForHead(backend, head, options.signal, config))
155
179
  : undefined;
156
180
  await validate();
157
181
  if (rawRemote) {
182
+ requireCompatibleRemoteSelection(config, rawRemote);
158
183
  const files = [...local.files, ...rawRemote.files];
159
184
  if (files.length > 16_384 ||
160
185
  files.reduce((bytes, file) => bytes + file.contentBase64.length * 0.75, 0) > 64 * 1024 * 1024) {
@@ -162,10 +187,9 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
162
187
  }
163
188
  }
164
189
  const remote = rawRemote
165
- ? portableSnapshot(filterSnapshotForConfigPolicy(rawRemote, config), rawRemote.localFields)
190
+ ? portableSnapshot(filterSnapshotForConfigPolicy(rawRemote, config, { sessionDir: sessionRoot }), rawRemote.localFields)
166
191
  : undefined;
167
192
  if (rawRemote) {
168
- requireCompatibleRemoteSelection(config, rawRemote);
169
193
  const validation = await timings.measure("transfer merge planning", () => planFileMerge({
170
194
  baseline: state.lastFileHashes,
171
195
  local: local.files,
@@ -197,7 +221,7 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
197
221
  throw review("Included content changed; review the selection before merging.", "remote-or-policy-changed");
198
222
  if (!head || !remote || !rawRemote)
199
223
  throw review("The established remote is missing; choose an explicit recovery direction.", "remote-empty");
200
- const selectionState = inspectRemoteSelection(config.include, rawRemote, config.exclude);
224
+ const selectionState = inspectRemoteSelection(config.include, rawRemote, config.exclude, config);
201
225
  const selectionCompatible = selectionState.kind === "same";
202
226
  let plan = await timings.measure("transfer merge planning", () => planFileMerge({
203
227
  baseline: state.lastFileHashes,
@@ -230,7 +254,7 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
230
254
  if (config.agentMode && !resolution) {
231
255
  const { resolveAgentPlan } = await import("./agent-plan.js");
232
256
  await validate();
233
- plan = await resolveAgentPlan(ctx, options, config, backend, state, local, localRaw, remote, head, plan, snapshotOptions, validate);
257
+ plan = await resolveAgentPlan(ctx, options, config, backend, state, local, localRaw, remote, head, plan, snapshotOptions, validateFresh);
234
258
  await validate();
235
259
  if (plan.kind !== "planned" || (plan.conflicts.length && !config.partialSync))
236
260
  throw new ContinuousError("unsafe", "Autonomous sync paused: unsupported or refused conflict groups remain; no transfer was performed.");
@@ -315,19 +339,19 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
315
339
  files: acceptedMergeFiles(plan.decisions, local.files, withheld),
316
340
  });
317
341
  const after = overlayLocalFields(accepted, localRaw, config.localFields);
318
- if (syncSessionsSelected(config))
319
- requireStableMergeSessionRoot(localRaw, after);
342
+ if (sessionRoot !== undefined)
343
+ requireStableMergeSessionRoot(localRaw, after, config.scope);
320
344
  const publication = regenerateSnapshotIdentity({
321
345
  ...accepted,
322
- version: accepted.version === 4 ? 4 : config.partialSync ? 3 : accepted.version,
346
+ version: config.partialSync && accepted.version < 3 ? 3 : accepted.version,
323
347
  files: [
324
348
  ...accepted.files.filter((file) => !withheld.has(file.path)),
325
349
  ...remote.files.filter((file) => withheld.has(file.path)),
326
350
  ],
327
351
  });
328
- const upload = mergeRemotePreservedFiles(publication, rawRemote, config);
352
+ const upload = mergeRemotePreservedFiles(publication, rawRemote, config, { sessionDir: sessionRoot });
329
353
  const publish = !sameHashes(fileHashMap(publication), fileHashMap(remote)) ||
330
- Boolean(config.partialSync && rawRemote.version !== 3 && rawRemote.version !== 4);
354
+ Boolean(config.partialSync && rawRemote.version < 3);
331
355
  const apply = !sameHashes(fileHashMap(localRaw), fileHashMap(after));
332
356
  if (!publish && !apply) {
333
357
  const beforeEvidence = await timings.measure("transfer remote head", () => backend.readHead(options.signal));
@@ -349,7 +373,7 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
349
373
  throw new ContinuousError("stale", "Remote changed before baseline acceptance; retry from a fresh observation.");
350
374
  await options.agentAcceptance?.commitCandidate?.();
351
375
  await validate();
352
- await timings.measure("transfer baseline write", () => writeAcceptedState(config, head, accepted, validate, progress));
376
+ await timings.measure("transfer baseline write", () => writeAcceptedState(config, head, accepted, validateFresh, progress));
353
377
  await timings.measure("transfer cleanup", () => pruneMergeBaselines(config, acceptedState(config, head, accepted, progress), captureMutationOwner(ctx, options.signal)));
354
378
  await validate();
355
379
  await timings.measure("transfer cleanup", () => pruneCompletedConflicts(config, backend.identity, acceptedState(config, head, accepted, progress), accepted, remote, captureMutationOwner(ctx, options.signal)));
@@ -401,9 +425,9 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
401
425
  progress = await persistProgress();
402
426
  await validate();
403
427
  const backup = await timings.measure("transfer backup", () => backupLocal(config.snapshotIdentity, snapshotOptions, options.signal));
404
- await validate();
428
+ await validateFresh();
405
429
  const journal = {
406
- version: 1,
430
+ ...mergeJournalPolicy(config),
407
431
  identity: mergeJournalIdentity(config, backend.identity),
408
432
  before: localRaw,
409
433
  after,
@@ -423,7 +447,7 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
423
447
  const atCommit = await timings.measure("transfer local snapshot", () => createSnapshot(config.snapshotIdentity, snapshotOptions));
424
448
  await validate();
425
449
  if (!sameHashes(fileHashMap(atCommit), fileHashMap(localRaw)) || atCommitState !== journal.stateIdentity) {
426
- await validate();
450
+ await validateFresh();
427
451
  await clearMergeJournal(config);
428
452
  throw new ContinuousError("stale", "Local content or baseline changed before publication; candidate retired without transfer. Review a fresh sync.");
429
453
  }
@@ -433,18 +457,19 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
433
457
  ...(ctx.protectedSessionFiles ?? []),
434
458
  ...[ctx.sessionManager.getSessionFile?.()].filter((file) => Boolean(file)),
435
459
  ]));
436
- await validate();
437
460
  }
438
461
  catch (error) {
439
- await validate();
462
+ await validateFresh();
440
463
  await clearMergeJournal(config);
441
464
  throw error;
442
465
  }
466
+ await validateFresh();
443
467
  try {
444
468
  if (publish) {
445
469
  const result = await timings.measure("transfer remote publication", () => backend.publishSnapshot(upload, expectedRemoteHead(head), {
446
470
  signal: options.signal,
447
471
  onCommit: options.onCommit,
472
+ ...(validateIgnore ? { validateIgnorePolicy: validateFresh } : {}),
448
473
  }));
449
474
  journal.committedHead = result.head;
450
475
  journal.warnings = result.warnings;
@@ -457,6 +482,7 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
457
482
  if (error instanceof SyncBackendConflictError &&
458
483
  error.phase === "before-commit" &&
459
484
  !error.candidateMayHaveBeenActive) {
485
+ await validateFresh();
460
486
  await clearMergeJournal(config);
461
487
  if (attempt + 1 < MAX_ATTEMPTS)
462
488
  continue;
@@ -466,7 +492,7 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
466
492
  // Every uncertain/after-commit outcome retains evidence and is never blindly retried.
467
493
  throw mergeTransferError(error, config.backend);
468
494
  }
469
- const completed = await timings.measure("transfer journal recovery", () => completeJournal(ctx, config, backend, journal, validate, timings, options.signal, options.auto, options.background?.validate));
495
+ const completed = await timings.measure("transfer journal recovery", () => completeJournal(ctx, config, backend, journal, { validate, validateFresh, validateOwner }, timings, options));
470
496
  if (!completed) {
471
497
  if (!options.signal?.aborted && (options.auto || !options.silent))
472
498
  ctx.ui.notify("Remote changed before local apply; candidate retired without transfer. Run sync again.", "warning");
@@ -489,39 +515,52 @@ export async function mergeSync(ctx, options, factory = createSyncBackend, resol
489
515
  await timings.measure("transfer cleanup", () => releaseConflictArtifacts(config, ownedStatePath, createdArtifacts));
490
516
  }
491
517
  }
492
- async function completeJournal(ctx, config, backend, journal, validate, timings, signal, auto = false, validateBackground) {
518
+ async function completeJournal(ctx, config, backend, journal, { validate, validateFresh, validateOwner, }, timings, options, isCurrent) {
519
+ const { auto, signal } = options;
520
+ const validateMutation = () => {
521
+ validateOwner();
522
+ if (auto && !ctx.isIdle())
523
+ throw new Error("Automatic file apply is no longer idle; evidence retained.");
524
+ };
493
525
  if (journal.identity !== mergeJournalIdentity(config, backend.identity) ||
494
526
  !sameLocalFields(journal.upload.localFields, config.localFields))
495
527
  throw new Error("Merge journal belongs to a different setup, selection or local-field policy; preserve it for reviewed recovery.");
496
- await validate();
497
- const sessionRoot = syncSessionsSelected(config) ? await effectiveSessionRoot(ctx) : undefined;
528
+ await validateFresh();
529
+ const sessionRoot = config.scope === "agent-directory" || syncSessionsSelected(config)
530
+ ? await effectiveSessionRoot(ctx, config, signal)
531
+ : undefined;
498
532
  await validate();
499
533
  if (sessionRoot !== undefined && journal.sessionRoot !== sessionRoot) {
500
- throw new Error("Merge journal session root is missing or differs from this context; preserve evidence and use reviewed directional recovery.");
534
+ throw new Error("Merge journal session root is missing or differs from this context; preserve its journal and backup for review.");
501
535
  }
502
536
  const snapshotOptions = { ...snapshotOptionsForContext(ctx, config), sessionDir: sessionRoot, signal };
503
537
  const head = await timings.measure("transfer remote head", () => backend.readHead(signal));
504
- if (!journal.committedHead &&
505
- head &&
506
- (backend.sameRevision(head.revision, journal.expectedHead.revision) ||
507
- backend.matchesUncommittedRecoveryHead?.(head, journal.expectedHead))) {
508
- await validate();
509
- const local = await timings.measure("transfer local snapshot", () => createSnapshot(config.snapshotIdentity, snapshotOptions));
510
- if (!sameHashes(fileHashMap(local), fileHashMap(journal.before)) ||
511
- syncStateFingerprint(await timings.measure("transfer state read", () => readStateForConfig(config))) !==
512
- journal.stateIdentity) {
513
- throw new Error("Uncertain publication is not active, but local content or baseline changed; keep the journal for reviewed recovery.");
514
- }
515
- await clearMergeJournal(config);
516
- return false;
517
- }
518
538
  await validate();
539
+ const readRetirementEvidence = async () => {
540
+ const state = await timings.measure("transfer state read", () => readStateForConfig(config));
541
+ await validateFresh();
542
+ const local = await timings.measure("transfer local snapshot", () => createSnapshot(config.snapshotIdentity, snapshotOptions));
543
+ validateMutation();
544
+ const latest = await timings.measure("transfer remote head", () => backend.readHead(signal));
545
+ validateMutation();
546
+ if (!sameMergeRecoveryHead(backend, head, latest))
547
+ throw new Error("Remote head changed during merge recovery; journal and backup retained.");
548
+ return {
549
+ sameBaseline: syncStateFingerprint(state) === journal.stateIdentity,
550
+ sameLocal: sameHashes(fileHashMap(local), fileHashMap(journal.before)),
551
+ };
552
+ };
519
553
  // Baseline publication is the durable completion boundary. A later remote revision
520
554
  // cannot undo that acceptance; retire only the journal for the recorded commit.
521
- if (journal.committedHead && (!head || !backend.sameRevision(head.revision, journal.committedHead.revision))) {
555
+ if (journal.committedHead?.snapshotId === journal.upload.id &&
556
+ typeof journal.committedHead.revision === "string" &&
557
+ journal.committedHead.revision &&
558
+ (!head || !backend.sameRevision(head.revision, journal.committedHead.revision))) {
522
559
  const state = await timings.measure("transfer state read", () => readStateForConfig(config));
523
560
  await validate();
524
561
  if (matchesAcceptedState(state, config, journal.committedHead, journal.accepted ?? journal.after, journal.progress)) {
562
+ if (config.ignorePolicy)
563
+ await validateFresh();
525
564
  await clearMergeJournal(config);
526
565
  await validate();
527
566
  await pruneMergeBaselines(config, state, captureMutationOwner(ctx, signal));
@@ -529,12 +568,37 @@ async function completeJournal(ctx, config, backend, journal, validate, timings,
529
568
  return true;
530
569
  }
531
570
  }
571
+ if (head &&
572
+ (journal.version === 2 || head.selection?.version === 4) &&
573
+ inspectRemoteSelection(config.include, { selection: head.selection, files: [] }, config.exclude, config).kind !==
574
+ "same")
575
+ throw new Error("Remote ignore-file policy differs or is unavailable; preserve the pending merge for review.");
576
+ if (!journal.committedHead &&
577
+ head &&
578
+ (backend.sameRevision(head.revision, journal.expectedHead.revision) ||
579
+ backend.matchesUncommittedRecoveryHead?.(head, journal.expectedHead))) {
580
+ if (journal.version === 2 &&
581
+ (head.snapshotId !== journal.expectedHead.snapshotId ||
582
+ head.snapshotRef !== journal.expectedHead.snapshotRef ||
583
+ head.snapshotId === journal.upload.id))
584
+ throw new Error("Cannot verify that the ignore-file candidate is inactive; preserve the journal and backup.");
585
+ const { sameBaseline, sameLocal } = await readRetirementEvidence();
586
+ validateMutation();
587
+ if (!sameBaseline || !sameLocal) {
588
+ if (journal.version === 2) {
589
+ if (!sameBaseline)
590
+ throw new Error("Sync baseline changed after uncertain publication; preserve the journal and backup for review.");
591
+ return reviewInactiveIgnoreMerge(ctx, config, backend, journal, head, options, validateFresh, isCurrent);
592
+ }
593
+ throw new Error("Uncertain publication is not active, but local content or baseline changed; keep the journal for reviewed recovery.");
594
+ }
595
+ await clearMergeJournal(config);
596
+ return false;
597
+ }
532
598
  if (journal.applyOnly && (!head || !backend.sameRevision(head.revision, journal.expectedHead.revision))) {
533
- const local = await timings.measure("transfer local snapshot", () => createSnapshot(config.snapshotIdentity, snapshotOptions));
534
- const state = await timings.measure("transfer state read", () => readStateForConfig(config));
535
- await validate();
536
- if (sameHashes(fileHashMap(local), fileHashMap(journal.before)) &&
537
- syncStateFingerprint(state) === journal.stateIdentity) {
599
+ const { sameBaseline, sameLocal } = await readRetirementEvidence();
600
+ validateMutation();
601
+ if (sameBaseline && sameLocal) {
538
602
  await clearMergeJournal(config);
539
603
  return false;
540
604
  }
@@ -545,14 +609,14 @@ async function completeJournal(ctx, config, backend, journal, validate, timings,
545
609
  (journal.committedHead && !backend.sameRevision(head.revision, journal.committedHead.revision))) {
546
610
  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.");
547
611
  }
548
- const observed = await timings.measure("transfer snapshot download", () => readSnapshotForHead(backend, head, signal));
612
+ const observed = await timings.measure("transfer snapshot download", () => readSnapshotForHead(backend, head, signal, config));
549
613
  requireCompatibleRemoteSelection(config, observed);
550
614
  if (!sameHashes(fileHashMap(observed), fileHashMap(journal.upload)) ||
551
615
  JSON.stringify(observed.selection) !== JSON.stringify(journal.upload.selection))
552
616
  throw new Error("Remote snapshot does not match the recorded merge publication.");
553
617
  const state = await timings.measure("transfer state read", () => readStateForConfig(config));
554
618
  if (matchesAcceptedState(state, config, head, journal.accepted ?? journal.after, journal.progress)) {
555
- await validate();
619
+ await validateFresh();
556
620
  await clearMergeJournal(config);
557
621
  await validate();
558
622
  await pruneMergeBaselines(config, state, captureMutationOwner(ctx, signal));
@@ -562,26 +626,19 @@ async function completeJournal(ctx, config, backend, journal, validate, timings,
562
626
  if (syncStateFingerprint(state) !== journal.stateIdentity) {
563
627
  throw new Error("Sync baseline changed after the interrupted merge; preserve its journal and review recovery.");
564
628
  }
565
- if (inspectRemoteSelection(config.include, observed, config.exclude).kind !== "same")
566
- throw new Error("Pending merge has unavailable remote selection metadata; preserve its journal and choose a reviewed explicit direction.");
567
- if (syncSessionsSelected(config))
568
- requireStableMergeSessionRoot(journal.before, journal.after);
629
+ if (inspectRemoteSelection(config.include, observed, config.exclude, config).kind !== "same")
630
+ throw new Error("Pending merge has unavailable remote selection metadata; preserve its journal and backup for review.");
631
+ if (sessionRoot !== undefined)
632
+ requireStableMergeSessionRoot(journal.before, journal.after, config.scope);
569
633
  await validate();
570
- const validateOwner = captureMutationOwner(ctx, signal);
571
- const validateMutation = () => {
572
- validateOwner();
573
- validateBackground?.();
574
- if (auto && !ctx.isIdle())
575
- throw new Error("Automatic file apply is no longer idle; evidence retained.");
576
- };
577
634
  await timings.measure("transfer local apply", () => applyMergedSnapshot(journal.before, journal.after, protectedSessionPaths(ctx, sessionRoot), { ...snapshotOptions, validateMutation }, validate, ctx.sessionManager.getSessionFile?.()));
578
635
  await validate();
579
636
  const headAtAcceptance = await timings.measure("transfer remote head", () => backend.readHead(signal));
580
637
  await validate();
581
638
  if (!headAtAcceptance || !backend.sameRevision(headAtAcceptance.revision, head.revision))
582
639
  throw new Error("Remote changed during merged apply; journal and backup retained for review.");
583
- await timings.measure("transfer baseline write", () => writeAcceptedState(config, head, journal.accepted ?? journal.after, validate, journal.progress));
584
- await validate();
640
+ await timings.measure("transfer baseline write", () => writeAcceptedState(config, head, journal.accepted ?? journal.after, validateFresh, journal.progress));
641
+ await validateFresh();
585
642
  await clearMergeJournal(config);
586
643
  await validate();
587
644
  await timings.measure("transfer cleanup", () => pruneMergeBaselines(config, acceptedState(config, head, journal.accepted ?? journal.after, journal.progress), captureMutationOwner(ctx, signal)));
@@ -603,8 +660,7 @@ function acceptedState(config, head, snapshot, progress, canonical = true) {
603
660
  lastAppliedSnapshot: head.snapshotId,
604
661
  lastRemoteRevision: head.revision,
605
662
  lastFileHashes: fileHashMap(canonical ? portableSnapshot(snapshot, config.localFields) : snapshot),
606
- include: [...config.include],
607
- ...(config.exclude === undefined ? {} : { exclude: [...config.exclude] }),
663
+ ...acceptedSelection(config),
608
664
  ...(config.localFields !== undefined ? { localFields: config.localFields } : {}),
609
665
  };
610
666
  }
@@ -1,4 +1,4 @@
1
- import { fileHashMap } from "./sync-state.js";
1
+ import { acceptedSelection, fileHashMap } from "./sync-state.js";
2
2
  /** Withholding preserves the complete local version, including explicit absence. */
3
3
  export function acceptedMergeFiles(decisions, localFiles, withheld) {
4
4
  const localByPath = new Map(localFiles.map((file) => [file.path, file]));
@@ -29,8 +29,10 @@ export function progressState(config, head, snapshot, progress) {
29
29
  version: 3,
30
30
  profile: config.snapshotIdentity,
31
31
  lastFileHashes: hashes,
32
- include: [...config.include],
33
- exclude: config.exclude === undefined ? undefined : [...config.exclude],
32
+ ...acceptedSelection(config),
33
+ ...(config.exclude === undefined ? { exclude: undefined } : {}),
34
+ ...(config.scope === undefined ? { scope: undefined } : {}),
35
+ ...(config.reinclude === undefined ? { reinclude: undefined } : {}),
34
36
  localFields: config.localFields,
35
37
  lastObservedSnapshot: head.snapshotId,
36
38
  lastObservedRevision: head.revision,
@@ -1,12 +1,20 @@
1
1
  import type { RemoteHead, SyncBackend } from "../backends/sync-backend.js";
2
2
  import type { AnySyncConfig } from "../settings/settings-types.js";
3
3
  import type { Snapshot } 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 sameRemoteHead(backend: SyncBackend, left: RemoteHead | undefined, right: RemoteHead | undefined): boolean;
6
12
  export declare function requireCompatibleRemoteSelection(config: AnySyncConfig, snapshot: Snapshot): void;
13
+ export declare function inspectHeadSelection(backend: SyncBackend, config: AnySyncConfig, head: RemoteHead, signal?: AbortSignal): Promise<RemoteSelectionState>;
7
14
  export declare function formatRemoteSelectionStatus(state: RemoteSelectionState | undefined): string;
8
15
  export declare function readRemoteSnapshot(backend: SyncBackend, config: AnySyncConfig, signal?: AbortSignal, options?: {
9
16
  allowSelectionDifference?: boolean;
17
+ sessionDir?: string;
10
18
  }): Promise<{
11
19
  head: undefined;
12
20
  snapshot: undefined;
@@ -23,6 +31,6 @@ export declare function readRemoteSnapshot(backend: SyncBackend, config: AnySync
23
31
  syncSessions: boolean | undefined;
24
32
  selection: import("../snapshot/snapshot-types.js").SnapshotSelection;
25
33
  files: import("../snapshot/snapshot-types.js").SnapshotFile[];
26
- };
34
+ } | undefined;
27
35
  selectionState: RemoteSelectionState;
28
36
  }>;
@@ -3,8 +3,9 @@ import { filterSnapshotForConfigPolicy } 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,58 @@ 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 function sameRemoteHead(backend, left, right) {
47
+ if (!left || !right)
48
+ return left === right;
49
+ return left.snapshotId === right.snapshotId && backend.sameRevision(left.revision, right.revision);
50
+ }
21
51
  export function requireCompatibleRemoteSelection(config, snapshot) {
52
+ const state = inspectRemoteSelection(config.include, snapshot, config.exclude, config);
53
+ if (state.kind === "different" && state.ignorePolicyComparison)
54
+ throw selectionMismatch(config, state);
22
55
  if (!sameLocalFields(config.localFields, snapshot.localFields))
23
56
  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);
25
- if (state.kind === "different") {
26
- throw remoteSelectionMismatch(config, state.include, syncConfigReviewFingerprint(config), state.exclude);
27
- }
57
+ if (state.kind === "different")
58
+ throw selectionMismatch(config, state);
59
+ }
60
+ export async function inspectHeadSelection(backend, config, head, signal) {
61
+ const remote = !head.selection && config.ignorePolicy
62
+ ? await readValidatedSnapshotForHead(backend, head, signal)
63
+ : { selection: head.selection, files: [] };
64
+ return inspectRemoteSelection(config.include, remote, config.exclude, config);
65
+ }
66
+ function selectionMismatch(config, state) {
67
+ return remoteSelectionMismatch(config, state.include, syncConfigReviewFingerprint(config), state.exclude, state);
28
68
  }
29
69
  export function formatRemoteSelectionStatus(state) {
30
70
  if (!state)
31
71
  return "remote included content: unavailable (remote is empty)";
72
+ if (state.ignorePolicyComparison)
73
+ return formatIgnorePolicyComparison(state.ignorePolicyComparison);
32
74
  if (state.kind === "same")
33
75
  return "remote included content: matches this setup";
34
76
  if (state.kind === "legacy") {
@@ -39,6 +81,9 @@ export function formatRemoteSelectionStatus(state) {
39
81
  `remote-only selection: ${safeList(state.remoteOnly)}`,
40
82
  `local-only selection: ${safeList(state.localOnly)}`,
41
83
  `remote excluded paths: ${safeList(state.exclude ?? [])}`,
84
+ ...(state.scope
85
+ ? [`remote scope: ${state.scope}`, `remote re-included paths: ${safeList(state.reinclude ?? [])}`]
86
+ : []),
42
87
  ].join("\n");
43
88
  }
44
89
  function safeList(values) {
@@ -48,15 +93,12 @@ export async function readRemoteSnapshot(backend, config, signal, options = {})
48
93
  const head = await backend.readHead(signal);
49
94
  if (!head)
50
95
  return { head: undefined, snapshot: undefined, selectionState: undefined };
51
- const snapshot = await readSnapshotForHead(backend, head, signal);
52
- const selectionState = inspectRemoteSelection(config.include, snapshot, config.exclude);
53
- if (!options.allowSelectionDifference && selectionState.kind === "different") {
54
- const configIdentity = syncConfigReviewFingerprint(config);
55
- throw remoteSelectionMismatch(config, selectionState.include, configIdentity, selectionState.exclude);
56
- }
57
- return {
58
- head,
59
- snapshot: filterSnapshotForConfigPolicy(snapshot, config),
60
- selectionState,
61
- };
96
+ const rawSnapshot = await readValidatedSnapshotForHead(backend, head, signal);
97
+ const selectionState = inspectRemoteSelection(config.include, rawSnapshot, config.exclude, config);
98
+ if (!options.allowSelectionDifference && selectionState.kind === "different")
99
+ throw selectionMismatch(config, selectionState);
100
+ const snapshot = selectionState.ignorePolicyComparison === "local-legacy-remote-ignore"
101
+ ? undefined
102
+ : filterSnapshotForConfigPolicy(rawSnapshot, config, { sessionDir: options.sessionDir });
103
+ return { head, snapshot, selectionState };
62
104
  }
@@ -1,12 +1,12 @@
1
1
  import { loadConfig } from "../settings/config.js";
2
- import { snapshotOptionsForContext } from "../snapshot/session-paths.js";
2
+ import { resolvedSnapshotOptionsForContext } from "../snapshot/session-paths.js";
3
3
  import { createSnapshot } from "../snapshot/snapshot.js";
4
4
  import { withLock } from "../state/lock.js";
5
5
  import { withStateDirectoryAccess } from "../state/state-directory.js";
6
6
  import { readStateForConfig } from "../state/sync-state-store.js";
7
7
  import { captureMutationOwner } from "./sync-local.js";
8
8
  import { syncSessionsSelected } from "./sync-policy.js";
9
- import { hasLocalChanges } from "./sync-state.js";
9
+ 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);
@@ -17,10 +17,11 @@ export async function pushSessionsOnShutdown(ctx, options, loaders = { operation
17
17
  await withStateDirectoryAccess(() => withLock("auto-session-push", async () => {
18
18
  const state = await readStateForConfig(config);
19
19
  validate();
20
- const local = await createSnapshot(config.snapshotIdentity, {
21
- ...snapshotOptionsForContext(ctx, config),
22
- signal: options.signal,
23
- });
20
+ if ((config.scope || state.scope) && (!state.lastAppliedSnapshot || syncPolicyChanged(state, config)))
21
+ return;
22
+ const snapshotOptions = await resolvedSnapshotOptionsForContext(ctx, config, options.signal);
23
+ validate();
24
+ const local = await createSnapshot(config.snapshotIdentity, snapshotOptions);
24
25
  validate();
25
26
  if (!hasLocalChanges(local, state, config))
26
27
  return;
@@ -17,6 +17,10 @@ export interface SyncDecision {
17
17
  currentInclude: readonly string[];
18
18
  previousExclude?: readonly string[];
19
19
  currentExclude?: readonly string[];
20
+ previousScope?: "agent-directory";
21
+ currentScope?: "agent-directory";
22
+ previousReinclude?: readonly string[];
23
+ currentReinclude?: readonly string[];
20
24
  review: string;
21
25
  directions: readonly SyncResolutionDirection[];
22
26
  directMessage: string;