@narumitw/pi-sync-daemon 0.8.0 → 0.9.1

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 (61) hide show
  1. package/CHANGELOG.md +18 -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 +8 -1
  10. package/dist/engine/ignore/ignore-initialization.js +142 -40
  11. package/dist/engine/ignore/ignore-settings.d.ts +16 -1
  12. package/dist/engine/ignore/ignore-settings.js +94 -26
  13. package/dist/engine/ignore/ignore-source.d.ts +1 -1
  14. package/dist/engine/ignore/ignore-source.js +1 -1
  15. package/dist/engine/settings/config-file.js +1 -1
  16. package/dist/engine/settings/config.d.ts +3 -2
  17. package/dist/engine/settings/config.js +71 -28
  18. package/dist/engine/settings/settings-management.d.ts +3 -1
  19. package/dist/engine/settings/settings-management.js +8 -2
  20. package/dist/engine/settings/settings-types.d.ts +2 -0
  21. package/dist/engine/snapshot/session-paths.js +7 -2
  22. package/dist/engine/snapshot/snapshot-apply.d.ts +1 -1
  23. package/dist/engine/snapshot/snapshot-transaction-policy.d.ts +7 -2
  24. package/dist/engine/snapshot/snapshot-transaction-policy.js +37 -17
  25. package/dist/engine/snapshot/snapshot-transaction.js +55 -13
  26. package/dist/engine/snapshot/snapshot-types.d.ts +4 -0
  27. package/dist/engine/sync/agent-plan.js +1 -0
  28. package/dist/engine/sync/agent-sync.js +8 -1
  29. package/dist/engine/sync/continuous-sync.d.ts +3 -1
  30. package/dist/engine/sync/continuous-sync.js +32 -15
  31. package/dist/engine/sync/merge-acceptance.d.ts +8 -0
  32. package/dist/engine/sync/merge-acceptance.js +29 -0
  33. package/dist/engine/sync/merge-apply.js +7 -4
  34. package/dist/engine/sync/merge-journal.d.ts +6 -0
  35. package/dist/engine/sync/merge-journal.js +33 -14
  36. package/dist/engine/sync/merged-sync.js +31 -39
  37. package/dist/engine/sync/remote-snapshot.d.ts +2 -1
  38. package/dist/engine/sync/remote-snapshot.js +17 -2
  39. package/dist/engine/sync/session-push.js +20 -6
  40. package/dist/engine/sync/sync-error-guidance.js +16 -3
  41. package/dist/engine/sync/sync-mutations.js +75 -54
  42. package/dist/engine/sync/sync-policy.d.ts +5 -0
  43. package/dist/engine/sync/sync-policy.js +28 -3
  44. package/dist/engine/sync/sync-state.d.ts +2 -0
  45. package/dist/engine/sync/sync-state.js +3 -8
  46. package/dist/engine/sync/transfer-freshness.d.ts +31 -0
  47. package/dist/engine/sync/transfer-freshness.js +82 -0
  48. package/dist/engine/ui/sync-format.d.ts +16 -5
  49. package/dist/engine/ui/sync-format.js +23 -55
  50. package/dist/engine/ui/transfer-review.d.ts +2 -1
  51. package/dist/engine/ui/transfer-review.js +3 -3
  52. package/dist/engine-service.d.ts +1 -1
  53. package/dist/engine-service.js +124 -27
  54. package/dist/monitor.d.ts +4 -1
  55. package/dist/monitor.js +84 -32
  56. package/dist/server.d.ts +1 -0
  57. package/dist/server.js +46 -5
  58. package/dist/service-host.d.ts +1 -1
  59. package/dist/service-host.js +2 -1
  60. package/docs/architecture.md +14 -6
  61. package/package.json +1 -1
@@ -8,8 +8,10 @@ export interface ContinuousClock {
8
8
  random(): number;
9
9
  schedule(ms: number, run: () => void, kind?: "wait" | "authorization"): () => void;
10
10
  }
11
+ type ContinuousTransfer = <T>(run: (committed: () => void) => Promise<T>) => Promise<T>;
11
12
  /** Created on first enabled session. No module/factory-owned timers or watchers. */
12
13
  export declare function createContinuousSync(loaders: SyncLoaders, clock?: ContinuousClock, publish?: StartupTimingPublisher): {
13
- start(ctx: ExtensionContext, sessionSignal: AbortSignal, explicitRetry?: boolean | string, debug?: boolean): void;
14
+ start(ctx: ExtensionContext, sessionSignal: AbortSignal, explicitRetry?: boolean | string, debug?: boolean, transfer?: ContinuousTransfer): void;
14
15
  stop(owner?: ExtensionContext["sessionManager"]): Promise<void>;
15
16
  };
17
+ export {};
@@ -37,7 +37,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
37
37
  let task;
38
38
  return {
39
39
  // A setup name binds retry to the configuration loaded after asynchronous eligibility checks.
40
- start(ctx, sessionSignal, explicitRetry = false, debug = false) {
40
+ start(ctx, sessionSignal, explicitRetry = false, debug = false, transfer) {
41
41
  if ((!ctx.backgroundAuthorized?.() && (!ctx.hasUI || (ctx.mode !== "tui" && ctx.mode !== "rpc"))) ||
42
42
  sessionSignal.aborted ||
43
43
  task)
@@ -68,7 +68,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
68
68
  let explicit = explicitRetry;
69
69
  while (!signal.aborted) {
70
70
  try {
71
- await run(ctx, signal, explicit, startup);
71
+ await run(ctx, signal, explicit, startup, transfer);
72
72
  return;
73
73
  }
74
74
  catch {
@@ -112,12 +112,12 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
112
112
  await current.promise;
113
113
  },
114
114
  };
115
- async function run(ctx, signal, explicitRetry, startup) {
115
+ async function run(ctx, signal, explicitRetry, startup, transfer) {
116
116
  const validateOwner = captureMutationOwner(ctx, signal);
117
117
  try {
118
118
  while (!signal.aborted) {
119
119
  validateOwner();
120
- const config = await loadConfigForCheck();
120
+ const config = await loadConfigForCheck(undefined, signal);
121
121
  validateOwner();
122
122
  if (!continuousEnabled(config) || (ctx.backgroundAuthorized && !ctx.backgroundAuthorized(config)))
123
123
  return;
@@ -135,7 +135,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
135
135
  });
136
136
  if (lease) {
137
137
  const retry = typeof explicitRetry === "string" ? explicitRetry === config.setupName : explicitRetry;
138
- await monitor(ctx, config, binding, lease, signal, retry, startup);
138
+ await monitor(ctx, config, binding, lease, signal, retry, startup, transfer);
139
139
  explicitRetry = false;
140
140
  }
141
141
  else
@@ -158,7 +158,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
158
158
  });
159
159
  }
160
160
  validateOwner();
161
- const current = await loadConfigForCheck();
161
+ const current = await loadConfigForCheck(undefined, signal);
162
162
  if (!continuousEnabled(current) || (ctx.backgroundAuthorized && !ctx.backgroundAuthorized(current)))
163
163
  return;
164
164
  validateOwner();
@@ -178,7 +178,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
178
178
  }
179
179
  }
180
180
  }
181
- async function monitor(ctx, initial, binding, lease, parent, explicitRetry, startup) {
181
+ async function monitor(ctx, initial, binding, lease, parent, explicitRetry, startup, transfer) {
182
182
  const signal = AbortSignal.any([parent, lease.signal]);
183
183
  const validateOwner = captureMutationOwner(ctx, signal);
184
184
  let config = initial;
@@ -220,7 +220,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
220
220
  validate();
221
221
  while (!signal.aborted && ctx.isIdle()) {
222
222
  validate();
223
- const latest = await loadConfigForCheck();
223
+ const latest = await loadConfigForCheck(undefined, signal);
224
224
  validate();
225
225
  if (!continuousEnabled(latest) ||
226
226
  (ctx.backgroundAuthorized && !ctx.backgroundAuthorized(latest)) ||
@@ -228,6 +228,9 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
228
228
  return;
229
229
  validate();
230
230
  if (syncCheckConfigFingerprint(latest) !== syncCheckConfigFingerprint(config)) {
231
+ if (config.reservedIgnoreNames !== undefined || latest.reservedIgnoreNames !== undefined)
232
+ return;
233
+ explicitRetry = false;
231
234
  closeWatch();
232
235
  config = latest;
233
236
  closeWatch = await openWatch();
@@ -289,7 +292,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
289
292
  return;
290
293
  try {
291
294
  validate();
292
- const latest = await loadConfigForCheck();
295
+ const latest = await loadConfigForCheck(undefined, guardSignal);
293
296
  if (guardSignal.aborted)
294
297
  return;
295
298
  validateCycle(latest);
@@ -300,7 +303,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
300
303
  }
301
304
  })().catch(() => { });
302
305
  try {
303
- await performCycle(ctx, config, binding, lease, AbortSignal.any([signal, cycle.signal]), validateCycle, configuration, force, timings);
306
+ await performCycle(ctx, config, binding, lease, AbortSignal.any([signal, cycle.signal]), validateCycle, configuration, force, timings, transfer);
304
307
  outcome = "completed";
305
308
  }
306
309
  catch (error) {
@@ -370,11 +373,15 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
370
373
  cycle?.abort();
371
374
  }
372
375
  }
373
- async function performCycle(ctx, config, binding, lease, signal, validateOwner, configuration, force, timings) {
376
+ async function performCycle(ctx, config, binding, lease, signal, validateOwner, configuration, force, timings, transfer) {
374
377
  const validate = (latest) => {
375
378
  signal.throwIfAborted();
376
379
  validateOwner(latest);
377
380
  };
381
+ const refresh = async () => {
382
+ validate();
383
+ validate(await loadConfigForCheck(undefined, signal));
384
+ };
378
385
  validate();
379
386
  const current = await readContinuousRecord(binding);
380
387
  validate();
@@ -398,8 +405,9 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
398
405
  const validateIgnore = ignorePolicyValidator({ ...snapshotOptions, validateMutation: validate });
399
406
  if (validateIgnore)
400
407
  await validateIgnore();
408
+ await refresh();
401
409
  const inspection = await inspectionModule.inspectSync(config, snapshotOptions, signal, undefined, timings);
402
- validate();
410
+ await refresh();
403
411
  let localIdentity = inspection.localIdentity;
404
412
  if (!localIdentity) {
405
413
  const snapshotModule = await loaders.snapshot();
@@ -455,7 +463,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
455
463
  const operations = await timings.measure("operations import", () => loaders.operations());
456
464
  validate();
457
465
  setSyncStatus(ctx, "sync syncing", { activity: "working" });
458
- const result = await timings.measure("automatic transfer", () => withStateDirectoryAccess(() => withAgentSyncLock(ctx, {
466
+ const runTransfer = (onCommit) => withStateDirectoryAccess(() => withAgentSyncLock(ctx, {
459
467
  args: [],
460
468
  yes: true,
461
469
  force: false,
@@ -465,11 +473,20 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
465
473
  auto: true,
466
474
  signal,
467
475
  startupTimings: timings,
476
+ onCommit,
468
477
  background: {
469
478
  validate,
470
- reserve: (key, requestSignal) => reserveContinuousRequest(binding, lease, key, () => clock.now(), requestSignal),
479
+ reserve: async (key, requestSignal) => {
480
+ await refresh();
481
+ await reserveContinuousRequest(binding, lease, key, () => clock.now(), requestSignal);
482
+ await refresh();
483
+ },
471
484
  },
472
- }, (options) => operations.syncBoth(ctx, options))));
485
+ }, async (options) => {
486
+ await refresh();
487
+ return operations.syncBoth(ctx, options);
488
+ }));
489
+ const result = await timings.measure("automatic transfer", () => transfer ? transfer(runTransfer) : runTransfer());
473
490
  validate();
474
491
  transferred = result === "applied";
475
492
  }
@@ -0,0 +1,8 @@
1
+ import type { RemoteHead } from "../backends/sync-backend.js";
2
+ import type { AnySyncConfig } from "../settings/settings-types.js";
3
+ import type { Snapshot } from "../snapshot/snapshot-types.js";
4
+ import type { SyncState } from "../state/state-types.js";
5
+ import { type PartialProgress } from "./partial-progress.js";
6
+ export declare function matchesAcceptedState(state: SyncState, config: AnySyncConfig, head: RemoteHead, snapshot: Snapshot, progress?: PartialProgress): boolean;
7
+ export declare function acceptedState(config: AnySyncConfig, head: RemoteHead, snapshot: Snapshot, progress?: PartialProgress, canonical?: boolean): SyncState;
8
+ export declare function writeAcceptedState(config: AnySyncConfig, head: RemoteHead, snapshot: Snapshot, validate: () => Promise<void>, progress?: PartialProgress): Promise<void>;
@@ -0,0 +1,29 @@
1
+ import { stageMergeBaseline } from "../state/merge-baseline-store.js";
2
+ import { syncStateFingerprint, writeStateForConfig } from "../state/sync-state-store.js";
3
+ import { portableSnapshot } from "./local-fields.js";
4
+ import { progressState } from "./partial-progress.js";
5
+ import { acceptedSelection, fileHashMap } from "./sync-state.js";
6
+ export function matchesAcceptedState(state, config, head, snapshot, progress) {
7
+ return [true, false].some((canonical) => syncStateFingerprint(state) === syncStateFingerprint(acceptedState(config, head, snapshot, progress, canonical)));
8
+ }
9
+ export function acceptedState(config, head, snapshot, progress, canonical = true) {
10
+ if (progress)
11
+ return progressState(config, head, snapshot, progress);
12
+ return {
13
+ version: 1,
14
+ profile: config.snapshotIdentity,
15
+ lastAppliedSnapshot: head.snapshotId,
16
+ lastRemoteRevision: head.revision,
17
+ lastFileHashes: fileHashMap(canonical ? portableSnapshot(snapshot, config.localFields) : snapshot),
18
+ ...acceptedSelection(config),
19
+ ...(config.localFields !== undefined ? { localFields: config.localFields } : {}),
20
+ };
21
+ }
22
+ export async function writeAcceptedState(config, head, snapshot, validate, progress) {
23
+ const accepted = portableSnapshot(snapshot, config.localFields);
24
+ const state = acceptedState(config, head, accepted, progress);
25
+ await stageMergeBaseline(config, accepted, state, progress?.previous);
26
+ await validate();
27
+ await writeStateForConfig(config, state);
28
+ await validate();
29
+ }
@@ -258,7 +258,7 @@ export async function applyMergedSnapshot(before, after, protectedPaths, options
258
258
  if (options.scope === "agent-directory" && options.sessionDir === undefined) {
259
259
  options = {
260
260
  ...options,
261
- sessionDir: sessionStorageRoot(root, await agentDirectoryConfiguredSessionDir(options.signal, root)),
261
+ sessionDir: sessionStorageRoot(root, await agentDirectoryConfiguredSessionDir(options.signal, root, options)),
262
262
  };
263
263
  options.validateMutation?.();
264
264
  options.signal?.throwIfAborted();
@@ -282,8 +282,7 @@ export async function applyMergedSnapshot(before, after, protectedPaths, options
282
282
  const targetSet = new Set(targets);
283
283
  await assertDistinctMergedTargets(root, paths, new Set(changed), options, protectedTarget, new Set(Object.keys(afterHashes)));
284
284
  await assertCanonicalMutationTargets(targets, options);
285
- if (options.scope === "agent-directory")
286
- await assertUnexcludedTargets(root, targets, options);
285
+ await assertUnexcludedTargets(root, targets, options);
287
286
  // Existing case aliases share Pi's non-reentrant realpath queue. Reserve the
288
287
  // missing destination separately only after deleting its reviewed preimage.
289
288
  const targetsByQueue = new Map();
@@ -383,6 +382,8 @@ export async function applyMergedSnapshot(before, after, protectedPaths, options
383
382
  const removedTargets = new Set([...removed].map((item) => snapshotTarget(root, item, options.sessionDir)));
384
383
  await assertCanonicalMergedTargets(root, changed, options);
385
384
  await validate();
385
+ if (options.validateApplyReview)
386
+ await options.validateApplyReview();
386
387
  const requireReviewedHash = (relative, hash) => {
387
388
  if (hash !== beforeHashes[relative] && hash !== afterHashes[relative])
388
389
  throw new Error("Local content changed at the apply boundary; journal retained, newer bytes untouched.");
@@ -392,7 +393,7 @@ export async function applyMergedSnapshot(before, after, protectedPaths, options
392
393
  const relative = relativeByTarget.get(target);
393
394
  if (!relative)
394
395
  throw new Error("Unowned merge target.");
395
- if (options.scope === "agent-directory") {
396
+ if (validateIgnore || options.scope === "agent-directory") {
396
397
  await assertCanonicalMutationTargets([target], options);
397
398
  await assertUnexcludedTargets(root, [target], options);
398
399
  }
@@ -475,6 +476,8 @@ export async function applyMergedSnapshot(before, after, protectedPaths, options
475
476
  // Writers registered after deletion must finish first; never accept their
476
477
  // bytes as our own, even if they match a recognizable pre/postimage.
477
478
  await requireAbsentDestinations();
479
+ if (deferredTargets.length && options.validateApplyReview)
480
+ await options.validateApplyReview();
478
481
  if (validateIgnore)
479
482
  await validateIgnore();
480
483
  await writeTargets();
@@ -8,9 +8,15 @@ import type { PartialProgress } from "./partial-progress.js";
8
8
  type MergeJournalPolicy = {
9
9
  version: 1;
10
10
  ignoreSource?: never;
11
+ localPolicyKey?: never;
11
12
  } | {
12
13
  version: 2;
13
14
  ignoreSource: NonNullable<TransactionJournalPolicy["ignoreSource"]>;
15
+ localPolicyKey?: never;
16
+ } | {
17
+ version: 3;
18
+ ignoreSource?: TransactionJournalPolicy["ignoreSource"];
19
+ localPolicyKey: string;
14
20
  };
15
21
  export type MergeJournal = MergeJournalPolicy & {
16
22
  identity: string;
@@ -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);