@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
@@ -6,12 +6,13 @@ import path from "node:path";
6
6
  import { isDeniedPath, posixJoin, safeJoin, toPosix } from "../paths.js";
7
7
  import { agentDir, configuredSessionDir, expandSessionDir } from "./session-paths.js";
8
8
  import { assertAgentDirectorySettingsSize, MAX_AGENT_DIRECTORY_BYTES } from "./snapshot-bounds.js";
9
- import { agentDirectoryAnchor, agentDirectoryPhysicalSessionPath, agentDirectorySessionRoot, } from "./snapshot-exclude-safety.js";
9
+ import { agentDirectoryAnchor, agentDirectoryPhysicalSessionPath, agentDirectorySessionRoot, reservedIgnoreTargetGuard, } from "./snapshot-exclude-safety.js";
10
10
  import { sessionStorageRoot } from "./snapshot-paths.js";
11
11
  export { isDeniedPath } from "../paths.js";
12
12
  export { sessionStorageRoot } from "./snapshot-paths.js";
13
13
  import { compileSyncExclude } from "../sync/exclude-policy.js";
14
- import { assertAgentDirectoryPathLayout, canonicalSnapshotPathForConfig, compileSyncPolicyExclude, compileSyncPolicyTraversal, configuredSnapshotPathMatcher, customIncludePathsByLower, DEFAULT_SYNC_INCLUDE, includeFromSelectionConfig, isPreservableUnmanagedSnapshotPath, MAX_AGENT_DIRECTORY_ENTRIES, MAX_AGENT_DIRECTORY_FILES, normalizeExtraFiles, normalizeSyncFiles, sameSnapshotSelection, selectionForSnapshot, snapshotSelectionExclude, snapshotSelectionInclude, syncIncludeSelection, syncSessionsSelected, } from "../sync/sync-policy.js";
14
+ import { assertAgentDirectoryPathLayout, canonicalSnapshotPathForConfig, compileSyncPolicyExclude, compileSyncPolicyTraversal, configuredSnapshotPathMatcher, customIncludePathsByLower, DEFAULT_SYNC_INCLUDE, includeFromSelectionConfig, isIgnoreControlPath, isPreservableUnmanagedSnapshotPath, MAX_AGENT_DIRECTORY_ENTRIES, MAX_AGENT_DIRECTORY_FILES, normalizeExtraFiles, normalizeSyncFiles, requireLegacyTransferPolicy, sameSnapshotSelection, selectionForSnapshot, snapshotSelectionExclude, snapshotSelectionInclude, syncIncludeSelection, syncSessionsSelected, } from "../sync/sync-policy.js";
15
+ import { IGNORE_SNAPSHOT_VERSION, } from "./snapshot-types.js";
15
16
  export { canonicalSnapshotPathForConfig, isConfiguredSnapshotPath } from "../sync/sync-policy.js";
16
17
  const VERSION = 1;
17
18
  const scanInventories = new WeakMap();
@@ -79,20 +80,27 @@ export async function createSnapshot(profile, options = {}) {
79
80
  const needsSessionConfig = syncSessions || !excluded("settings.json");
80
81
  const sessionDir = options.scope === "agent-directory"
81
82
  ? options.sessionDir
82
- : (options.sessionDir ?? (needsSessionConfig ? await configuredSessionDir() : undefined));
83
+ : (options.sessionDir ?? (needsSessionConfig ? await configuredSessionDir(options) : undefined));
83
84
  options.signal?.throwIfAborted();
84
85
  const collectionOptions = { ...policy, sessionDir };
85
86
  const collected = options.scope === "agent-directory" ? await collectAgentDirectory(agentDir(), collectionOptions) : undefined;
86
87
  const files = collected?.files ?? (await collectFiles(agentDir(), collectionOptions, excluded));
87
88
  options.signal?.throwIfAborted();
89
+ const selection = selectionForSnapshot(include, options.exclude, options);
88
90
  const snapshot = {
89
- version: options.scope === "agent-directory" ? 5 : options.exclude === undefined ? VERSION : 4,
91
+ version: selection.version === 4
92
+ ? IGNORE_SNAPSHOT_VERSION
93
+ : options.scope === "agent-directory"
94
+ ? 5
95
+ : options.exclude === undefined
96
+ ? VERSION
97
+ : 4,
90
98
  id: snapshotId(),
91
99
  createdAt: new Date().toISOString(),
92
100
  machine: os.hostname(),
93
101
  profile,
94
- syncSessions,
95
- selection: selectionForSnapshot(include, options.exclude, options),
102
+ syncSessions: selection.version === 4 ? files.some((file) => isSessionPath(file.path)) : syncSessions,
103
+ selection,
96
104
  files,
97
105
  };
98
106
  if (collected)
@@ -110,10 +118,12 @@ function effectiveInclude(options) {
110
118
  ...(options.syncSessions ? ["sessions"] : []),
111
119
  ];
112
120
  }
113
- export async function collectFiles(root, options = {}, excluded = compileSyncExclude(options.exclude)) {
121
+ export async function collectFiles(root, options = {}, excluded = compileSyncPolicyExclude(options)) {
114
122
  if (options.scope === "agent-directory")
115
123
  return (await collectAgentDirectory(root, options)).files;
116
124
  const signal = options.signal;
125
+ const guardReserved = reservedIgnoreTargetGuard(root, options);
126
+ const collection = { signal, excluded, guardReserved };
117
127
  signal?.throwIfAborted();
118
128
  const results = [];
119
129
  const entries = await fs.readdir(root, { withFileTypes: true });
@@ -125,7 +135,7 @@ export async function collectFiles(root, options = {}, excluded = compileSyncExc
125
135
  TOP_LEVEL_DIRS.has(entry.name) &&
126
136
  selectedFiles.has(entry.name) &&
127
137
  !excluded(entry.name)) {
128
- await collectDirectory(results, root, entry.name, { signal, excluded });
138
+ await collectDirectory(results, root, entry.name, collection);
129
139
  }
130
140
  }
131
141
  for (const fileName of TOP_LEVEL_FILES) {
@@ -133,19 +143,18 @@ export async function collectFiles(root, options = {}, excluded = compileSyncExc
133
143
  continue;
134
144
  const entry = selectTopLevelFileEntry(entries, fileName);
135
145
  if (entry)
136
- await addFile(results, root, entry.name, fileName, signal);
146
+ await addFile(results, root, entry.name, fileName, collection);
137
147
  }
138
148
  for (const relativePath of selection.custom) {
139
149
  if (!excluded(relativePath))
140
- await collectIncludedPath(results, root, relativePath, signal, excluded);
150
+ await collectIncludedPath(results, root, relativePath, collection);
141
151
  }
142
152
  if (selection.sessions && !excluded("sessions")) {
143
153
  try {
144
154
  await collectDirectory(results, sessionStorageRoot(root, options.sessionDir), "", {
155
+ ...collection,
145
156
  sessionsOnly: true,
146
- excluded,
147
157
  virtualPrefix: "sessions",
148
- signal,
149
158
  });
150
159
  }
151
160
  catch (error) {
@@ -203,11 +212,14 @@ async function readScannedFile(candidate, signal) {
203
212
  await handle.close();
204
213
  }
205
214
  }
206
- export async function agentDirectoryConfiguredSessionDir(signal, root = agentDir()) {
207
- const content = await readAgentDirectorySettings(signal, root);
215
+ export async function agentDirectoryConfiguredSessionDir(signal, root = agentDir(), options = {}) {
216
+ const content = await readAgentDirectorySettings(signal, root, options);
208
217
  return content === undefined ? undefined : agentDirectorySessionDirFromSettings(content);
209
218
  }
210
- export async function readAgentDirectorySettings(signal, root = agentDir()) {
219
+ export async function readAgentDirectorySettings(signal, root = agentDir(), options = {}) {
220
+ const guardReserved = reservedIgnoreTargetGuard(root, options);
221
+ if (guardReserved)
222
+ await guardReserved(path.join(root, "settings.json"));
211
223
  const absolute = path.resolve(root);
212
224
  const canonical = path.join(await fs.realpath(path.dirname(absolute)), path.basename(absolute));
213
225
  await identify(absolute, canonical, signal);
@@ -248,9 +260,9 @@ async function collectAgentDirectory(root, options, readContents = true, pending
248
260
  const signal = options.signal;
249
261
  const excluded = compileSyncPolicyExclude(options);
250
262
  const canTraverse = compileSyncPolicyTraversal(options);
251
- const sessionDir = options.sessionDir ?? (await agentDirectoryConfiguredSessionDir(signal, root));
252
- const isPhysicalSessionPath = agentDirectoryPhysicalSessionPath(root, sessionDir);
253
- const sessionRoot = agentDirectorySessionRoot(root, sessionDir);
263
+ const sessionDir = options.sessionDir ?? (await agentDirectoryConfiguredSessionDir(signal, root, options));
264
+ const isPhysicalSessionPath = agentDirectoryPhysicalSessionPath(root, sessionDir, options.ignorePolicy, options.reservedIgnoreNames);
265
+ const sessionRoot = agentDirectorySessionRoot(root, sessionDir, options.ignorePolicy, options.reservedIgnoreNames);
254
266
  const directories = [];
255
267
  const candidates = [];
256
268
  const entries = new Map();
@@ -282,7 +294,7 @@ async function collectAgentDirectory(root, options, readContents = true, pending
282
294
  continue;
283
295
  const candidate = await identify(path.join(directory.absolute, entry.name), path.join(directory.canonical, entry.name), signal);
284
296
  if (entry.isDirectory()) {
285
- if (!excluded(snapshotPath))
297
+ if (!excluded(snapshotPath, true))
286
298
  entries.set(candidate.absolute, "directory");
287
299
  await walk(candidate, snapshotPath, sessions);
288
300
  }
@@ -347,7 +359,8 @@ async function collectAgentDirectory(root, options, readContents = true, pending
347
359
  }
348
360
  for (const directory of directories)
349
361
  await recheck(directory, signal);
350
- if (options.sessionDir === undefined && (await agentDirectoryConfiguredSessionDir(signal, root)) !== sessionDir)
362
+ if (options.sessionDir === undefined &&
363
+ (await agentDirectoryConfiguredSessionDir(signal, root, options)) !== sessionDir)
351
364
  changedScan();
352
365
  const currentSessionDirectory = await identifySessionRoot();
353
366
  if (Boolean(sessionDirectory) !== Boolean(currentSessionDirectory) ||
@@ -372,16 +385,17 @@ async function collectAgentDirectory(root, options, readContents = true, pending
372
385
  },
373
386
  };
374
387
  }
375
- async function collectIncludedPath(results, root, relativePath, signal, excluded) {
388
+ async function collectIncludedPath(results, root, relativePath, options) {
389
+ const { signal } = options;
376
390
  signal?.throwIfAborted();
377
391
  const absolutePath = safeJoin(root, relativePath);
378
392
  try {
379
393
  const stat = await fs.lstat(absolutePath);
380
394
  signal?.throwIfAborted();
381
395
  if (stat.isFile())
382
- await addFile(results, root, relativePath, relativePath, signal);
396
+ await addFile(results, root, relativePath, relativePath, options);
383
397
  else if (stat.isDirectory())
384
- await collectDirectory(results, root, relativePath, { signal, excluded });
398
+ await collectDirectory(results, root, relativePath, options);
385
399
  }
386
400
  catch (error) {
387
401
  if (error.code !== "ENOENT")
@@ -391,33 +405,46 @@ async function collectIncludedPath(results, root, relativePath, signal, excluded
391
405
  signal?.throwIfAborted();
392
406
  const entry = selectTopLevelFileEntry(entries, relativePath);
393
407
  if (entry)
394
- await addFile(results, root, entry.name, relativePath, signal);
408
+ await addFile(results, root, entry.name, relativePath, options);
395
409
  }
396
410
  }
397
411
  }
398
- async function collectDirectory(results, root, relativeDirectory, options = {}) {
412
+ async function collectDirectory(results, root, relativeDirectory, options) {
399
413
  options.signal?.throwIfAborted();
400
414
  const absoluteDirectory = path.join(root, relativeDirectory);
415
+ if (options.guardReserved)
416
+ await options.guardReserved(absoluteDirectory);
417
+ options.signal?.throwIfAborted();
401
418
  for (const entry of await fs.readdir(absoluteDirectory, { withFileTypes: true })) {
402
419
  options.signal?.throwIfAborted();
403
420
  const relativePath = relativeDirectory ? posixJoin(relativeDirectory, entry.name) : entry.name;
404
421
  const snapshotPath = options.virtualPrefix ? posixJoin(options.virtualPrefix, relativePath) : relativePath;
405
- if (isDeniedPath(snapshotPath) || options.excluded?.(snapshotPath))
422
+ if (isDeniedPath(snapshotPath) || options.excluded(snapshotPath))
406
423
  continue;
407
424
  if (entry.isDirectory()) {
408
425
  await collectDirectory(results, root, relativePath, options);
409
426
  }
410
427
  else if (entry.isFile() && (!options.sessionsOnly || isSessionFilePath(snapshotPath))) {
411
- await addFile(results, root, relativePath, snapshotPath, options.signal);
428
+ await addFile(results, root, relativePath, snapshotPath, options);
412
429
  }
413
430
  }
414
431
  }
415
- async function addFile(results, root, relativePath, snapshotPath = relativePath, signal) {
432
+ export async function readLegacySnapshotSource(absolutePath, guardReserved, signal) {
433
+ if (!guardReserved)
434
+ return fs.readFile(absolutePath, { signal });
435
+ signal?.throwIfAborted();
436
+ const canonical = await guardReserved(absolutePath);
437
+ const candidate = await identify(absolutePath, canonical, signal);
438
+ if (!candidate.stat.isFile() || candidate.stat.nlink !== 1)
439
+ changedScan();
440
+ return readScannedFile(candidate, signal);
441
+ }
442
+ async function addFile(results, root, relativePath, snapshotPath, { signal, guardReserved }) {
416
443
  signal?.throwIfAborted();
417
444
  if (!isSafeSnapshotPath(snapshotPath))
418
445
  return;
419
446
  const absolutePath = safeJoin(root, relativePath);
420
- const content = await fs.readFile(absolutePath, { signal });
447
+ const content = await readLegacySnapshotSource(absolutePath, guardReserved, signal);
421
448
  signal?.throwIfAborted();
422
449
  results.push({
423
450
  path: snapshotPath,
@@ -449,6 +476,8 @@ export function snapshotTarget(root, relativePath, configuredSessionDir) {
449
476
  export function snapshotIncludesSessions(snapshot) {
450
477
  if (snapshot.selection?.version === 3)
451
478
  return syncSessionsSelected(snapshot.selection);
479
+ if (snapshot.selection?.version === 4)
480
+ return snapshot.files.some((file) => isSessionPath(file.path));
452
481
  return (snapshot.syncSessions === true ||
453
482
  (snapshotSelectionInclude(snapshot)?.includes("sessions") === true &&
454
483
  !compileSyncExclude(snapshotSelectionExclude(snapshot))("sessions")) ||
@@ -457,15 +486,28 @@ export function snapshotIncludesSessions(snapshot) {
457
486
  export function filterSnapshotForConfigPolicy(snapshot, config, options = {}) {
458
487
  const include = includeFromSelectionConfig(config);
459
488
  const wholeDirectory = config.scope === "agent-directory";
489
+ if (!wholeDirectory || !config.ignorePolicy)
490
+ requireLegacyTransferPolicy(snapshot);
460
491
  const exclude = config.exclude ?? (snapshot.version >= 4 ? [] : undefined);
492
+ const selection = selectionForSnapshot(include, exclude, config);
461
493
  const files = wholeDirectory
462
494
  ? filterAgentDirectoryFiles(snapshot.files, config, options.sessionDir)
463
495
  : canonicalizeSnapshotFilesForConfig(snapshot.files, config, customIncludePathsByLower(include));
464
496
  const filtered = {
465
497
  ...snapshot,
466
- version: wholeDirectory ? 5 : exclude === undefined ? snapshot.version : 4,
467
- syncSessions: syncSessionsSelected(config) ? snapshot.syncSessions : false,
468
- selection: selectionForSnapshot(include, exclude, config),
498
+ version: selection.version === 4
499
+ ? IGNORE_SNAPSHOT_VERSION
500
+ : wholeDirectory
501
+ ? 5
502
+ : exclude === undefined
503
+ ? snapshot.version
504
+ : 4,
505
+ syncSessions: selection.version === 4
506
+ ? files.some((file) => isSessionPath(file.path))
507
+ : syncSessionsSelected(config)
508
+ ? snapshot.syncSessions
509
+ : false,
510
+ selection,
469
511
  files,
470
512
  };
471
513
  if (!options.regenerateId || snapshotsMatch(snapshot, filtered))
@@ -479,7 +521,9 @@ export function filterSnapshotForConfigPolicy(snapshot, config, options = {}) {
479
521
  }
480
522
  function filterAgentDirectoryFiles(files, config, sessionDir) {
481
523
  const configured = configuredSnapshotPathMatcher(config);
482
- const isPhysicalSessionPath = sessionDir ? agentDirectoryPhysicalSessionPath(agentDir(), sessionDir) : undefined;
524
+ const isPhysicalSessionPath = sessionDir
525
+ ? agentDirectoryPhysicalSessionPath(agentDir(), sessionDir, config.ignorePolicy, config.reservedIgnoreNames)
526
+ : undefined;
483
527
  const projected = files.filter((file) => {
484
528
  if (!isSafeSnapshotPath(file.path) || !configured(file.path))
485
529
  return false;
@@ -522,11 +566,12 @@ function isPreferredExtraCandidate(left, right) {
522
566
  return left.originalPath.localeCompare(right.originalPath) < 0;
523
567
  }
524
568
  export function snapshotWithoutSessions(snapshot) {
569
+ requireLegacyTransferPolicy(snapshot);
525
570
  const files = snapshot.files.filter((file) => !isSessionPath(file.path));
526
571
  const include = snapshotSelectionInclude(snapshot)?.filter((item) => item !== "sessions");
527
572
  if (files.length === snapshot.files.length &&
528
573
  snapshot.syncSessions !== true &&
529
- include?.length === snapshot.selection?.include.length) {
574
+ include?.length === snapshot.selection?.include?.length) {
530
575
  return snapshot;
531
576
  }
532
577
  return {
@@ -560,8 +605,18 @@ export function scanSnapshot(snapshot) {
560
605
  return findings;
561
606
  }
562
607
  export function mergeRemotePreservedFiles(local, remote, config, options = {}) {
608
+ if (config.scope !== "agent-directory" || !config.ignorePolicy) {
609
+ requireLegacyTransferPolicy(local);
610
+ requireLegacyTransferPolicy(remote);
611
+ }
563
612
  if (config.scope === "agent-directory")
564
613
  return filterSnapshotForConfigPolicy(local, config, { ...options, regenerateId: true });
614
+ if (config.reservedIgnoreNames !== undefined) {
615
+ const names = new Set(config.reservedIgnoreNames);
616
+ const files = local.files.filter((file) => !isIgnoreControlPath(toPosix(file.path), names));
617
+ if (files.length !== local.files.length)
618
+ local = regenerateSnapshotIdentity({ ...local, files });
619
+ }
565
620
  const localPathNames = new Set(local.files.map((file) => file.path.toLowerCase()));
566
621
  const preservedPathNames = new Set();
567
622
  const configured = configuredSnapshotPathMatcher(config);
@@ -592,6 +647,8 @@ export function mergeRemotePreservedFiles(local, remote, config, options = {}) {
592
647
  };
593
648
  }
594
649
  export function mergeRemoteSessionFiles(local, remote) {
650
+ requireLegacyTransferPolicy(local);
651
+ requireLegacyTransferPolicy(remote);
595
652
  const directory = local.selection?.version === 3 ? local.selection : undefined;
596
653
  const excluded = directory
597
654
  ? compileSyncPolicyExclude(directory)
@@ -9,6 +9,7 @@ export interface SyncState {
9
9
  exclude?: string[];
10
10
  scope?: "agent-directory";
11
11
  reinclude?: string[];
12
+ ignorePolicyKey?: string;
12
13
  localFields?: string[];
13
14
  lastObservedSnapshot?: string;
14
15
  lastObservedRevision?: string;
@@ -45,6 +45,7 @@ export async function resolveAgentPlan(ctx, options, config, backend, state, loc
45
45
  1,
46
46
  backend.identity,
47
47
  syncConfigReviewIdentity(config),
48
+ ...(config.configDocumentFingerprint ? [config.configDocumentFingerprint] : []),
48
49
  syncStateFingerprint(state),
49
50
  head.revision,
50
51
  fileHashMap(localRaw),
@@ -66,8 +66,9 @@ export async function withAgentSyncLock(ctx, options, run) {
66
66
  if (!(await confirmAgentRefusalRetry(ctx, options.setup, request.evidence, validate, options.signal)))
67
67
  return "cancelled";
68
68
  }
69
+ const reserve = background?.reserve;
69
70
  const raw = cached === undefined || retry
70
- ? await runAgentResolver(ctx, request.evidence, validate, options.signal, background ? (signal) => background.reserve(request.key, signal) : undefined)
71
+ ? await runAgentResolver(ctx, request.evidence, validate, options.signal, reserve ? (signal) => reserve(request.key, signal) : undefined)
71
72
  : JSON.stringify(cached);
72
73
  let candidate;
73
74
  try {
@@ -84,6 +85,12 @@ export async function withAgentSyncLock(ctx, options, run) {
84
85
  await withLock("agent-cache-save", async () => {
85
86
  await assertOwner();
86
87
  options.signal?.throwIfAborted();
88
+ if (background) {
89
+ background.validate();
90
+ await request.validate(options.signal);
91
+ options.signal?.throwIfAborted();
92
+ background.validate();
93
+ }
87
94
  await saveAgentCandidate(request.key, candidate);
88
95
  });
89
96
  let retryCacheCommitted = false;
@@ -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 {};
@@ -1,5 +1,6 @@
1
1
  import { loadConfigForCheck, syncCheckConfigFingerprint } from "../settings/config.js";
2
2
  import { resolvedSnapshotOptionsForContext } from "../snapshot/session-paths.js";
3
+ import { ignorePolicyValidator } from "../snapshot/snapshot-transaction-policy.js";
3
4
  import { withLock } from "../state/lock.js";
4
5
  import { withStateDirectoryAccess } from "../state/state-directory.js";
5
6
  import { readStateForConfig } from "../state/sync-state-store.js";
@@ -10,7 +11,7 @@ import { acquireContinuousLease } from "./continuous-lease.js";
10
11
  import { normalizeContinuousClock, readContinuousRecord, reserveContinuousRequest, updateContinuousRecord, } from "./continuous-record.js";
11
12
  import { continuousBinding, hashContinuous } from "./continuous-storage.js";
12
13
  import { watchContinuous } from "./continuous-watch.js";
13
- import { readMergeJournal } from "./merge-journal.js";
14
+ import { assertMergeJournalPolicy, readMergeJournal } from "./merge-journal.js";
14
15
  import { createStartupTimings } from "./startup-timings.js";
15
16
  import { captureMutationOwner } from "./sync-local.js";
16
17
  import { fileHashMap } from "./sync-state.js";
@@ -36,7 +37,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
36
37
  let task;
37
38
  return {
38
39
  // A setup name binds retry to the configuration loaded after asynchronous eligibility checks.
39
- start(ctx, sessionSignal, explicitRetry = false, debug = false) {
40
+ start(ctx, sessionSignal, explicitRetry = false, debug = false, transfer) {
40
41
  if ((!ctx.backgroundAuthorized?.() && (!ctx.hasUI || (ctx.mode !== "tui" && ctx.mode !== "rpc"))) ||
41
42
  sessionSignal.aborted ||
42
43
  task)
@@ -67,7 +68,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
67
68
  let explicit = explicitRetry;
68
69
  while (!signal.aborted) {
69
70
  try {
70
- await run(ctx, signal, explicit, startup);
71
+ await run(ctx, signal, explicit, startup, transfer);
71
72
  return;
72
73
  }
73
74
  catch {
@@ -111,12 +112,12 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
111
112
  await current.promise;
112
113
  },
113
114
  };
114
- async function run(ctx, signal, explicitRetry, startup) {
115
+ async function run(ctx, signal, explicitRetry, startup, transfer) {
115
116
  const validateOwner = captureMutationOwner(ctx, signal);
116
117
  try {
117
118
  while (!signal.aborted) {
118
119
  validateOwner();
119
- const config = await loadConfigForCheck();
120
+ const config = await loadConfigForCheck(undefined, signal);
120
121
  validateOwner();
121
122
  if (!continuousEnabled(config) || (ctx.backgroundAuthorized && !ctx.backgroundAuthorized(config)))
122
123
  return;
@@ -134,7 +135,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
134
135
  });
135
136
  if (lease) {
136
137
  const retry = typeof explicitRetry === "string" ? explicitRetry === config.setupName : explicitRetry;
137
- await monitor(ctx, config, binding, lease, signal, retry, startup);
138
+ await monitor(ctx, config, binding, lease, signal, retry, startup, transfer);
138
139
  explicitRetry = false;
139
140
  }
140
141
  else
@@ -157,7 +158,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
157
158
  });
158
159
  }
159
160
  validateOwner();
160
- const current = await loadConfigForCheck();
161
+ const current = await loadConfigForCheck(undefined, signal);
161
162
  if (!continuousEnabled(current) || (ctx.backgroundAuthorized && !ctx.backgroundAuthorized(current)))
162
163
  return;
163
164
  validateOwner();
@@ -177,7 +178,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
177
178
  }
178
179
  }
179
180
  }
180
- async function monitor(ctx, initial, binding, lease, parent, explicitRetry, startup) {
181
+ async function monitor(ctx, initial, binding, lease, parent, explicitRetry, startup, transfer) {
181
182
  const signal = AbortSignal.any([parent, lease.signal]);
182
183
  const validateOwner = captureMutationOwner(ctx, signal);
183
184
  let config = initial;
@@ -219,7 +220,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
219
220
  validate();
220
221
  while (!signal.aborted && ctx.isIdle()) {
221
222
  validate();
222
- const latest = await loadConfigForCheck();
223
+ const latest = await loadConfigForCheck(undefined, signal);
223
224
  validate();
224
225
  if (!continuousEnabled(latest) ||
225
226
  (ctx.backgroundAuthorized && !ctx.backgroundAuthorized(latest)) ||
@@ -227,6 +228,9 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
227
228
  return;
228
229
  validate();
229
230
  if (syncCheckConfigFingerprint(latest) !== syncCheckConfigFingerprint(config)) {
231
+ if (config.reservedIgnoreNames !== undefined || latest.reservedIgnoreNames !== undefined)
232
+ return;
233
+ explicitRetry = false;
230
234
  closeWatch();
231
235
  config = latest;
232
236
  closeWatch = await openWatch();
@@ -242,7 +246,12 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
242
246
  await updateContinuousRecord(binding, lease, (current) => normalizeContinuousClock(current, now));
243
247
  validate();
244
248
  }
245
- const configuration = hashContinuous([{ ...config, showStatus: undefined, debug: undefined }, ctx.model]);
249
+ const configuration = hashContinuous([
250
+ config.ignorePolicy
251
+ ? syncCheckConfigFingerprint(config)
252
+ : { ...config, showStatus: undefined, debug: undefined },
253
+ ctx.model,
254
+ ]);
246
255
  const controlChanged = record.configuration !== configuration;
247
256
  if (controlChanged || explicitRetry) {
248
257
  record.next = 0;
@@ -269,7 +278,9 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
269
278
  // transfer adopt authorization that changed after this cycle's inspection.
270
279
  const validateCycle = (latest) => {
271
280
  validate();
272
- if ((latest && syncCheckConfigFingerprint(latest) !== expectedConfig) ||
281
+ if ((latest &&
282
+ (syncCheckConfigFingerprint(latest) !== expectedConfig ||
283
+ (ctx.backgroundAuthorized && !ctx.backgroundAuthorized(latest)))) ||
273
284
  hashContinuous(ctx.model) !== expectedModel)
274
285
  activeCycle.abort(new DOMException("Continuous authorization changed", "AbortError"));
275
286
  activeCycle.signal.throwIfAborted();
@@ -281,7 +292,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
281
292
  return;
282
293
  try {
283
294
  validate();
284
- const latest = await loadConfigForCheck();
295
+ const latest = await loadConfigForCheck(undefined, guardSignal);
285
296
  if (guardSignal.aborted)
286
297
  return;
287
298
  validateCycle(latest);
@@ -292,7 +303,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
292
303
  }
293
304
  })().catch(() => { });
294
305
  try {
295
- 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);
296
307
  outcome = "completed";
297
308
  }
298
309
  catch (error) {
@@ -362,17 +373,23 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
362
373
  cycle?.abort();
363
374
  }
364
375
  }
365
- 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) {
366
377
  const validate = (latest) => {
367
378
  signal.throwIfAborted();
368
379
  validateOwner(latest);
369
380
  };
381
+ const refresh = async () => {
382
+ validate();
383
+ validate(await loadConfigForCheck(undefined, signal));
384
+ };
370
385
  validate();
371
386
  const current = await readContinuousRecord(binding);
372
387
  validate();
373
388
  // A newly pending journal may prove an uncertain commit. It is never authority to republish.
374
389
  const pending = await guardedLock("continuous-journal", () => readMergeJournal(config));
375
390
  validate();
391
+ if (pending)
392
+ assertMergeJournalPolicy(pending, config);
376
393
  if (!force &&
377
394
  !pending &&
378
395
  current.phase === "blocked" &&
@@ -385,8 +402,12 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
385
402
  validate();
386
403
  const snapshotOptions = await resolvedSnapshotOptionsForContext(ctx, config, signal);
387
404
  validate();
405
+ const validateIgnore = ignorePolicyValidator({ ...snapshotOptions, validateMutation: validate });
406
+ if (validateIgnore)
407
+ await validateIgnore();
408
+ await refresh();
388
409
  const inspection = await inspectionModule.inspectSync(config, snapshotOptions, signal, undefined, timings);
389
- validate();
410
+ await refresh();
390
411
  let localIdentity = inspection.localIdentity;
391
412
  if (!localIdentity) {
392
413
  const snapshotModule = await loaders.snapshot();
@@ -397,6 +418,8 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
397
418
  }
398
419
  const journal = await readMergeJournal(config);
399
420
  validate();
421
+ if (journal)
422
+ assertMergeJournalPolicy(journal, config);
400
423
  return { inspection, journal, localIdentity };
401
424
  }));
402
425
  validate();
@@ -440,7 +463,7 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
440
463
  const operations = await timings.measure("operations import", () => loaders.operations());
441
464
  validate();
442
465
  setSyncStatus(ctx, "sync syncing", { activity: "working" });
443
- const result = await timings.measure("automatic transfer", () => withStateDirectoryAccess(() => withAgentSyncLock(ctx, {
466
+ const runTransfer = (onCommit) => withStateDirectoryAccess(() => withAgentSyncLock(ctx, {
444
467
  args: [],
445
468
  yes: true,
446
469
  force: false,
@@ -450,11 +473,20 @@ export function createContinuousSync(loaders, clock = systemClock, publish) {
450
473
  auto: true,
451
474
  signal,
452
475
  startupTimings: timings,
476
+ onCommit,
453
477
  background: {
454
478
  validate,
455
- 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
+ },
456
484
  },
457
- }, (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());
458
490
  validate();
459
491
  transferred = result === "applied";
460
492
  }
@@ -40,7 +40,10 @@ export async function watchContinuous(config, changed, options = {}) {
40
40
  const target = path.resolve(directory, String(file));
41
41
  if (!relativeWithin(directory, target))
42
42
  return;
43
- if (target === path.join(root, "pi-sync.json"))
43
+ if (target === path.join(root, "pi-sync.json") ||
44
+ (config.ignorePolicy &&
45
+ path.dirname(target) === root &&
46
+ path.basename(target).toLowerCase() === config.ignorePolicy.filename.toLowerCase()))
44
47
  changed(true);
45
48
  else if (scoped) {
46
49
  const relative = scopedPath(target);
@@ -1,4 +1,4 @@
1
- import { configFromSettings, loadConfig } from "../settings/config.js";
1
+ import { loadConfig } from "../settings/config.js";
2
2
  import { isMissingConfigError } from "../settings/config-errors.js";
3
3
  import { consumeLocalConfigMigrationNotice } from "../settings/config-file.js";
4
4
  import { readLocalConfigObject } from "../settings/settings-store.js";
@@ -29,7 +29,8 @@ export async function initializeSync(ctx, signal, publish) {
29
29
  validate();
30
30
  const settings = await readLocalConfigObject();
31
31
  validate();
32
- const config = settings?.activeSyncSetup ? configFromSettings(settings) : undefined;
32
+ const config = settings?.activeSyncSetup ? await loadConfig() : undefined;
33
+ validate();
33
34
  const sessionDir = config?.scope === "agent-directory"
34
35
  ? await effectiveSessionRoot(ctx, config, signal)
35
36
  : sessionDirFromContext(ctx);
@@ -1,7 +1,9 @@
1
- import type { Snapshot } from "../snapshot/snapshot-types.js";
1
+ import { type IgnoreSnapshotSelection, type Snapshot } from "../snapshot/snapshot-types.js";
2
2
  export { normalizeLocalFields } from "./local-field-policy.js";
3
3
  /** Shared transport contract: older snapshots cannot carry portable policy metadata. */
4
4
  export declare function validateSnapshotFieldPolicy(snapshot: Pick<Snapshot, "version" | "localFields">): void;
5
+ export declare function validateIgnoreSnapshotSessionFlag(selection: IgnoreSnapshotSelection, syncSessions: unknown): void;
6
+ export declare function validateIgnoreSnapshotIdentity({ id, createdAt, machine, profile, }: Pick<Snapshot, "id" | "createdAt" | "machine" | "profile">): void;
5
7
  /** Portable transport images must not carry values declared machine-local. Physical journal images are different. */
6
8
  export declare function validatePortableSnapshot(snapshot: Snapshot): void;
7
9
  export declare function sameLocalFields(left: unknown, right: unknown): boolean;