@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
@@ -1,37 +1,47 @@
1
- import type { Snapshot, SnapshotSelection } from "../snapshot/snapshot-types.js";
1
+ import { type DirectoryScope, type Snapshot, type SnapshotSelection } from "../snapshot/snapshot-types.js";
2
2
  export declare const BUILT_IN_SYNC_ROOTS: readonly ["settings.json", "keybindings.json", "models.json", "AGENTS.md", "APPEND_SYSTEM.md", "skills", "prompts", "themes", "extensions"];
3
3
  export declare const DEFAULT_SYNC_INCLUDE: readonly ["settings.json", "keybindings.json", "models.json", "AGENTS.md", "APPEND_SYSTEM.md", "skills", "prompts", "themes", "extensions"];
4
4
  export type BuiltInSyncFile = (typeof BUILT_IN_SYNC_ROOTS)[number];
5
5
  export declare function normalizeSyncInclude(value: unknown): string[];
6
+ export declare function normalizeDirectoryRules(value: unknown): string[];
6
7
  export declare function portableSnapshotSelection(value: unknown): SnapshotSelection;
7
8
  export declare function snapshotSelectionInclude(snapshot: Pick<Snapshot, "selection">): string[] | undefined;
8
9
  export declare function snapshotSelectionExclude(snapshot: Pick<Snapshot, "selection">): string[] | undefined;
9
- export declare function selectionForSnapshot(include: unknown, exclude?: unknown): SnapshotSelection;
10
+ export declare function selectionForSnapshot(include: unknown, exclude?: unknown, directory?: DirectoryScope): SnapshotSelection;
10
11
  /** Metadata equality, not policy compatibility: bind the whole projection to its immutable image. */
11
12
  export declare function sameSnapshotSelection(left: SnapshotSelection | undefined, right: SnapshotSelection | undefined): boolean;
12
13
  export declare function validateSnapshotSelection(snapshot: Pick<Snapshot, "version" | "selection">): void;
14
+ export declare function requireLegacyTransferPolicy(snapshot: Partial<Pick<Snapshot, "version" | "selection">>): void;
13
15
  export declare function sameSyncInclude(left: unknown, right: unknown): boolean;
14
16
  export declare function compareSyncInclude(local: unknown, remote: unknown): {
15
17
  same: boolean;
16
18
  remoteOnly: string[];
17
19
  localOnly: string[];
18
20
  };
21
+ export type IgnorePolicyComparison = "match" | "mismatch" | "local-ignore-remote-legacy" | "local-legacy-remote-ignore";
22
+ type PortableDirectoryScope = Pick<DirectoryScope, "scope" | "reinclude">;
19
23
  export type RemoteSelectionState = {
20
24
  kind: "legacy";
21
25
  discovered: string[];
22
- } | {
26
+ ignorePolicyComparison?: never;
27
+ } | ({
23
28
  kind: "same";
24
29
  include: string[];
25
30
  exclude?: string[];
26
- } | {
31
+ ignorePolicyComparison?: "match";
32
+ } & PortableDirectoryScope) | ({
27
33
  kind: "different";
28
34
  include: string[];
29
35
  exclude?: string[];
30
36
  remoteOnly: string[];
31
37
  localOnly: string[];
32
38
  excludeChanged?: boolean;
33
- };
34
- export declare function inspectRemoteSelection(localInclude: unknown, snapshot: Pick<Snapshot, "selection" | "files">, localExclude?: unknown): RemoteSelectionState;
39
+ ignorePolicyComparison?: Exclude<IgnorePolicyComparison, "match">;
40
+ } & PortableDirectoryScope);
41
+ export declare function compareIgnorePolicy(local: DirectoryScope["ignorePolicy"], remote: SnapshotSelection | undefined): IgnorePolicyComparison | undefined;
42
+ export declare function formatIgnorePolicyComparison(comparison: IgnorePolicyComparison): "Remote ignore-file policy differs. Edit local rules to match, or review publishing this device's policy." | "Remote ignore-file policy matches this device." | "Remote uses a legacy content policy. Review publishing this device's ignore-file policy." | "Remote uses an ignore-file policy. Configure matching local rules before transferring.";
43
+ export declare function syncDirectoryPolicyKey(config: SyncSelectionConfig): string | undefined;
44
+ export declare function inspectRemoteSelection(localInclude: unknown, snapshot: Pick<Snapshot, "selection" | "files">, localExclude?: unknown, directory?: DirectoryScope): RemoteSelectionState;
35
45
  export interface RemoteSelectionDecision {
36
46
  setupName: string;
37
47
  configIdentity: string;
@@ -39,20 +49,25 @@ export interface RemoteSelectionDecision {
39
49
  remoteInclude: readonly string[];
40
50
  localExclude?: readonly string[];
41
51
  remoteExclude?: readonly string[];
52
+ localDirectory?: PortableDirectoryScope;
53
+ remoteDirectory?: PortableDirectoryScope;
54
+ ignorePolicyComparison?: IgnorePolicyComparison;
42
55
  }
43
56
  export declare class RemoteSelectionMismatchError extends Error {
44
57
  readonly decision: RemoteSelectionDecision;
45
58
  readonly setupName: string;
46
59
  readonly localInclude: string[];
47
60
  readonly remoteInclude: string[];
48
- constructor(setupName: string, localInclude: unknown, remoteInclude: unknown, configIdentity?: string, localExclude?: string[], remoteExclude?: string[]);
61
+ constructor(setupName: string, localInclude: unknown, remoteInclude: unknown, configIdentity?: string, localExclude?: string[], remoteExclude?: string[], localDirectory?: DirectoryScope, remoteDirectory?: PortableDirectoryScope, ignorePolicyComparison?: IgnorePolicyComparison);
49
62
  }
50
63
  export declare function remoteSelectionMismatch(config: {
51
64
  setupName: string;
52
65
  include: unknown;
53
66
  exclude?: string[];
54
- }, remoteInclude: unknown, configIdentity?: string, remoteExclude?: string[]): RemoteSelectionMismatchError;
55
- export declare function formatRemoteSelectionMismatch(setupName: string, localInclude: readonly string[], remoteInclude: readonly string[], localExclude?: readonly string[], remoteExclude?: readonly string[]): string;
67
+ } & DirectoryScope, remoteInclude: unknown, configIdentity?: string, remoteExclude?: string[], remoteDirectory?: PortableDirectoryScope & {
68
+ ignorePolicyComparison?: IgnorePolicyComparison;
69
+ }): RemoteSelectionMismatchError;
70
+ export declare function formatRemoteSelectionMismatch(setupName: string, localInclude: readonly string[], remoteInclude: readonly string[], localExclude?: readonly string[], remoteExclude?: readonly string[], localDirectory?: DirectoryScope, remoteDirectory?: DirectoryScope): string;
56
71
  export declare function discoverLegacySnapshotInclude(snapshot: Pick<Snapshot, "files">): string[];
57
72
  export declare function syncIncludeSelection(value: unknown): {
58
73
  include: string[];
@@ -61,7 +76,10 @@ export declare function syncIncludeSelection(value: unknown): {
61
76
  sessions: boolean;
62
77
  };
63
78
  export declare function customIncludePathsByLower(value: unknown): Map<string, string>;
64
- export interface SyncSelectionConfig {
79
+ export interface SyncSelectionConfig extends DirectoryScope {
80
+ version?: number;
81
+ fingerprint?: string;
82
+ sessions?: boolean;
65
83
  include?: unknown;
66
84
  exclude?: unknown;
67
85
  syncFiles?: unknown;
@@ -69,6 +87,13 @@ export interface SyncSelectionConfig {
69
87
  extraFiles?: unknown;
70
88
  }
71
89
  export declare function includeFromSelectionConfig(config: SyncSelectionConfig): string[];
90
+ export declare function syncSelectionHasContent(config: SyncSelectionConfig): boolean;
91
+ export declare function isIgnoreControlPath(relativePath: string, reservedNames?: ReadonlySet<string>): boolean;
92
+ export declare const MAX_AGENT_DIRECTORY_ENTRIES = 65536;
93
+ export declare const MAX_AGENT_DIRECTORY_FILES = 16384;
94
+ export declare function assertAgentDirectoryPathLayout(files: Iterable<string>): void;
95
+ export declare function compileSyncPolicyExclude(config: SyncSelectionConfig): (relativePath: string, directory?: boolean) => boolean;
96
+ export declare function compileSyncPolicyTraversal(config: SyncSelectionConfig): (relativePath: string) => boolean;
72
97
  export declare function syncSessionsSelected(config: SyncSelectionConfig): boolean;
73
98
  export declare function isConfiguredSnapshotPath(relativePath: string, config: SyncSelectionConfig, _legacyExtraFiles?: Set<string>): boolean;
74
99
  export declare function configuredSnapshotPathMatcher(config: SyncSelectionConfig): (relativePath: string) => boolean;
@@ -83,3 +108,4 @@ export declare function normalizeExtraFiles(value: unknown): string[];
83
108
  export declare const extraFilePathsByLower: typeof customIncludePathsByLower;
84
109
  export declare const isSafeExtraFileName: typeof isSafeCustomIncludePath;
85
110
  export declare const selectedSyncFileSet: (value: unknown) => Set<"AGENTS.md" | "APPEND_SYSTEM.md" | "extensions" | "keybindings.json" | "models.json" | "prompts" | "settings.json" | "skills" | "themes">;
111
+ export {};
@@ -1,6 +1,7 @@
1
1
  import path from "node:path";
2
2
  import { isDeniedPath, toPosix } from "../paths.js";
3
- import { compileSyncExclude, normalizeSyncExclude, sameSyncExclude } from "./exclude-policy.js";
3
+ import { IGNORE_SNAPSHOT_VERSION, } from "../snapshot/snapshot-types.js";
4
+ import { compilePathRules, compileSyncExclude, normalizeSyncExclude, sameSyncExclude } from "./exclude-policy.js";
4
5
  export const BUILT_IN_SYNC_ROOTS = [
5
6
  "settings.json",
6
7
  "keybindings.json",
@@ -101,8 +102,37 @@ function validateAgentRelativeInclude(value) {
101
102
  throw new Error(`Invalid pi-sync settings: use the canonical ${topLevel} root instead of a nested sync.include path.`);
102
103
  }
103
104
  }
105
+ export function normalizeDirectoryRules(value) {
106
+ return normalizeSyncExclude(Array.isArray(value)
107
+ ? value.map((rule) => (typeof rule === "string" ? rule.replace(/(?<!\/)\/(?= *$)/u, "") : rule))
108
+ : value);
109
+ }
104
110
  export function portableSnapshotSelection(value) {
105
111
  const selection = value;
112
+ if (selection && typeof selection === "object" && !Array.isArray(selection) && selection.version === 4) {
113
+ if (selection.scope !== "agent-directory" ||
114
+ typeof selection.sessions !== "boolean" ||
115
+ typeof selection.fingerprint !== "string" ||
116
+ selection.fingerprint.length !== 64 ||
117
+ !/^[0-9a-f]{64}$/u.test(selection.fingerprint) ||
118
+ Object.keys(selection).length !== 4 ||
119
+ !["version", "scope", "sessions", "fingerprint"].every((key) => Object.hasOwn(selection, key)))
120
+ throw new Error("Invalid ignore-file snapshot policy.");
121
+ return {
122
+ version: 4,
123
+ scope: "agent-directory",
124
+ fingerprint: selection.fingerprint,
125
+ sessions: selection.sessions,
126
+ };
127
+ }
128
+ if (selection && typeof selection === "object" && !Array.isArray(selection) && selection.version === 3) {
129
+ if (selection.scope !== "agent-directory" ||
130
+ !Array.isArray(selection.exclude) ||
131
+ !Array.isArray(selection.reinclude) ||
132
+ Object.keys(selection).some((key) => !["version", "scope", "include", "exclude", "reinclude"].includes(key)))
133
+ throw new Error("Invalid agent-directory snapshot policy.");
134
+ return directorySelection(selection.include, selection.exclude, selection.reinclude);
135
+ }
106
136
  if (!selection ||
107
137
  typeof selection !== "object" ||
108
138
  Array.isArray(selection) ||
@@ -119,12 +149,39 @@ export function portableSnapshotSelection(value) {
119
149
  return { version: 2, include, exclude: normalizeSyncExclude(selection.exclude) };
120
150
  }
121
151
  export function snapshotSelectionInclude(snapshot) {
122
- return snapshot.selection === undefined ? undefined : portableSnapshotSelection(snapshot.selection).include;
152
+ if (snapshot.selection === undefined)
153
+ return undefined;
154
+ const selection = portableSnapshotSelection(snapshot.selection);
155
+ return selection.version === 4 ? (selection.sessions ? ["sessions"] : []) : selection.include;
123
156
  }
124
157
  export function snapshotSelectionExclude(snapshot) {
125
158
  return snapshot.selection === undefined ? undefined : portableSnapshotSelection(snapshot.selection).exclude;
126
159
  }
127
- export function selectionForSnapshot(include, exclude) {
160
+ function directorySelection(include, exclude, reinclude) {
161
+ const normalized = normalizeSyncInclude(include);
162
+ if (normalized.some((root) => root !== "sessions"))
163
+ throw new Error("Agent-directory snapshots only use include metadata for explicit session selection.");
164
+ return {
165
+ version: 3,
166
+ scope: "agent-directory",
167
+ include: normalized,
168
+ exclude: normalizeDirectoryRules(exclude),
169
+ reinclude: normalizeDirectoryRules(reinclude),
170
+ };
171
+ }
172
+ export function selectionForSnapshot(include, exclude, directory) {
173
+ if (directory?.ignorePolicy) {
174
+ if (directory.scope !== "agent-directory")
175
+ throw new Error("Ignore rules require agent-directory scope.");
176
+ return portableSnapshotSelection({
177
+ version: 4,
178
+ scope: directory.scope,
179
+ fingerprint: directory.ignorePolicy.fingerprint,
180
+ sessions: directory.ignorePolicy.sessions,
181
+ });
182
+ }
183
+ if (directory?.scope === "agent-directory")
184
+ return directorySelection(include, exclude, directory.reinclude);
128
185
  const normalized = normalizeSyncInclude(include);
129
186
  return exclude === undefined
130
187
  ? { version: 1, include: normalized }
@@ -139,6 +196,14 @@ export function validateSnapshotSelection(snapshot) {
139
196
  const selection = snapshot.selection === undefined ? undefined : portableSnapshotSelection(snapshot.selection);
140
197
  if ((snapshot.version === 4) !== (selection?.version === 2))
141
198
  throw new Error("Exclude policy requires snapshot version 4 and selection version 2.");
199
+ if ((snapshot.version === 5) !== (selection?.version === 3))
200
+ throw new Error("Agent-directory policy requires snapshot version 5 and selection version 3.");
201
+ if ((snapshot.version === IGNORE_SNAPSHOT_VERSION) !== (selection?.version === 4))
202
+ throw new Error("Ignore-file policy requires snapshot version 6 and selection version 4.");
203
+ }
204
+ export function requireLegacyTransferPolicy(snapshot) {
205
+ if (snapshot.version === IGNORE_SNAPSHOT_VERSION || snapshot.selection?.version === 4)
206
+ throw new Error("This setup cannot transfer an ignore-file snapshot without a reviewed local ignore policy.");
142
207
  }
143
208
  export function sameSyncInclude(left, right) {
144
209
  const normalizedLeft = normalizeSyncInclude(left);
@@ -157,21 +222,79 @@ export function compareSyncInclude(local, remote) {
157
222
  localOnly: localInclude.filter((item) => !remoteSet.has(item)),
158
223
  };
159
224
  }
160
- export function inspectRemoteSelection(localInclude, snapshot, localExclude) {
161
- const remoteInclude = snapshotSelectionInclude(snapshot);
162
- if (!remoteInclude)
225
+ export function compareIgnorePolicy(local, remote) {
226
+ if (remote?.version !== 4)
227
+ return local ? "local-ignore-remote-legacy" : undefined;
228
+ if (!local)
229
+ return "local-legacy-remote-ignore";
230
+ return local.fingerprint === remote.fingerprint && local.sessions === remote.sessions ? "match" : "mismatch";
231
+ }
232
+ export function formatIgnorePolicyComparison(comparison) {
233
+ switch (comparison) {
234
+ case "match":
235
+ return "Remote ignore-file policy matches this device.";
236
+ case "mismatch":
237
+ return "Remote ignore-file policy differs. Edit local rules to match, or review publishing this device's policy.";
238
+ case "local-ignore-remote-legacy":
239
+ return "Remote uses a legacy content policy. Review publishing this device's ignore-file policy.";
240
+ case "local-legacy-remote-ignore":
241
+ return "Remote uses an ignore-file policy. Configure matching local rules before transferring.";
242
+ }
243
+ }
244
+ export function syncDirectoryPolicyKey(config) {
245
+ if (config.scope !== "agent-directory")
246
+ return undefined;
247
+ const policy = config.ignorePolicy;
248
+ if (policy) {
249
+ return JSON.stringify([
250
+ "ignore-file",
251
+ policy.fingerprint,
252
+ policy.sessions,
253
+ policy.filename,
254
+ policy.sourceDigest,
255
+ policy.reservedNames,
256
+ ]);
257
+ }
258
+ return JSON.stringify([
259
+ config.scope,
260
+ includeFromSelectionConfig(config).includes("sessions"),
261
+ normalizeDirectoryRules(config.exclude).map((rule) => rule.toLowerCase()),
262
+ normalizeDirectoryRules(config.reinclude).map((rule) => rule.toLowerCase()),
263
+ ]);
264
+ }
265
+ export function inspectRemoteSelection(localInclude, snapshot, localExclude, directory) {
266
+ const selection = snapshot.selection === undefined ? undefined : portableSnapshotSelection(snapshot.selection);
267
+ const ignorePolicyComparison = compareIgnorePolicy(directory?.ignorePolicy, selection);
268
+ if (ignorePolicyComparison !== undefined) {
269
+ const include = snapshotSelectionInclude(snapshot) ?? discoverLegacySnapshotInclude(snapshot);
270
+ const scope = selection?.scope;
271
+ if (ignorePolicyComparison === "match")
272
+ return { kind: "same", include, scope, ignorePolicyComparison };
273
+ const comparison = compareSyncInclude(directory?.ignorePolicy ? (directory.ignorePolicy.sessions ? ["sessions"] : []) : localInclude, include);
274
+ return { kind: "different", include, scope, ...comparison, ignorePolicyComparison };
275
+ }
276
+ if (!selection && !directory?.scope)
163
277
  return { kind: "legacy", discovered: discoverLegacySnapshotInclude(snapshot) };
164
- const exclude = snapshotSelectionExclude(snapshot);
278
+ const remoteInclude = selection?.include ?? discoverLegacySnapshotInclude(snapshot);
279
+ const exclude = selection?.exclude;
165
280
  const comparison = compareSyncInclude(localInclude, remoteInclude);
166
- const rules = exclude === undefined ? {} : { exclude };
167
- return comparison.same && sameSyncExclude(localExclude, exclude)
281
+ const rules = {
282
+ ...(exclude === undefined ? {} : { exclude }),
283
+ ...(selection?.scope ? { scope: selection.scope, reinclude: selection.reinclude } : {}),
284
+ };
285
+ const directoryKey = syncDirectoryPolicyKey({ include: localInclude, exclude: localExclude, ...directory });
286
+ const sameDirectoryPolicy = directoryKey === syncDirectoryPolicyKey({ include: remoteInclude, ...rules });
287
+ const sameExclusions = directoryKey !== undefined
288
+ ? sameSyncExclude(normalizeDirectoryRules(localExclude), exclude)
289
+ : sameSyncExclude(localExclude, exclude);
290
+ return comparison.same && sameExclusions && sameDirectoryPolicy
168
291
  ? { kind: "same", include: remoteInclude, ...rules }
169
292
  : {
170
293
  kind: "different",
171
294
  include: remoteInclude,
172
295
  ...comparison,
173
296
  ...rules,
174
- ...(!sameSyncExclude(localExclude, exclude) ? { excludeChanged: true } : {}),
297
+ ...(!sameExclusions ? { excludeChanged: true } : {}),
175
298
  };
176
299
  }
177
300
  export class RemoteSelectionMismatchError extends Error {
@@ -179,10 +302,12 @@ export class RemoteSelectionMismatchError extends Error {
179
302
  setupName;
180
303
  localInclude;
181
304
  remoteInclude;
182
- constructor(setupName, localInclude, remoteInclude, configIdentity = JSON.stringify([setupName, normalizeSyncInclude(localInclude)]), localExclude, remoteExclude) {
305
+ constructor(setupName, localInclude, remoteInclude, configIdentity = JSON.stringify([setupName, normalizeSyncInclude(localInclude)]), localExclude, remoteExclude, localDirectory, remoteDirectory, ignorePolicyComparison) {
183
306
  const local = normalizeSyncInclude(localInclude);
184
307
  const remote = normalizeSyncInclude(remoteInclude);
185
- super(formatRemoteSelectionMismatch(setupName, local, remote, localExclude, remoteExclude));
308
+ super(ignorePolicyComparison
309
+ ? formatIgnorePolicyComparison(ignorePolicyComparison)
310
+ : formatRemoteSelectionMismatch(setupName, local, remote, localExclude, remoteExclude, localDirectory, remoteDirectory));
186
311
  this.name = "RemoteSelectionMismatchError";
187
312
  this.setupName = setupName;
188
313
  this.localInclude = local;
@@ -192,22 +317,34 @@ export class RemoteSelectionMismatchError extends Error {
192
317
  configIdentity,
193
318
  localInclude: [...local],
194
319
  remoteInclude: [...remote],
195
- ...(localExclude === undefined ? {} : { localExclude: normalizeSyncExclude(localExclude) }),
196
- ...(remoteExclude === undefined ? {} : { remoteExclude: normalizeSyncExclude(remoteExclude) }),
320
+ ...(ignorePolicyComparison
321
+ ? { ignorePolicyComparison }
322
+ : {
323
+ ...(localExclude === undefined ? {} : { localExclude: normalizeSyncExclude(localExclude) }),
324
+ ...(remoteExclude === undefined ? {} : { remoteExclude: normalizeSyncExclude(remoteExclude) }),
325
+ ...(localDirectory?.scope ? { localDirectory: directoryRules(localDirectory) } : {}),
326
+ ...(remoteDirectory?.scope ? { remoteDirectory: directoryRules(remoteDirectory) } : {}),
327
+ }),
197
328
  };
198
329
  }
199
330
  }
200
- export function remoteSelectionMismatch(config, remoteInclude, configIdentity, remoteExclude) {
201
- return new RemoteSelectionMismatchError(config.setupName, config.include, remoteInclude, configIdentity, config.exclude, remoteExclude);
331
+ function directoryRules(directory) {
332
+ return { scope: directory.scope, reinclude: normalizeDirectoryRules(directory.reinclude) };
333
+ }
334
+ export function remoteSelectionMismatch(config, remoteInclude, configIdentity, remoteExclude, remoteDirectory) {
335
+ return new RemoteSelectionMismatchError(config.setupName, config.include, remoteInclude, configIdentity, config.exclude, remoteExclude, config, remoteDirectory, remoteDirectory?.ignorePolicyComparison);
202
336
  }
203
- export function formatRemoteSelectionMismatch(setupName, localInclude, remoteInclude, localExclude, remoteExclude) {
337
+ export function formatRemoteSelectionMismatch(setupName, localInclude, remoteInclude, localExclude, remoteExclude, localDirectory, remoteDirectory) {
204
338
  const comparison = compareSyncInclude(localInclude, remoteInclude);
205
339
  const lines = [
206
340
  `Synced content differs for sync setup “${stripTerminalControls(setupName)}”.`,
207
341
  `Remote-only: ${comparison.remoteOnly.join(", ") || "none"}`,
208
342
  `This-device-only: ${comparison.localOnly.join(", ") || "none"}`,
209
343
  ];
210
- if (!sameSyncExclude(localExclude, remoteExclude)) {
344
+ if (localDirectory?.scope || remoteDirectory?.scope) {
345
+ lines.push(`Remote scope: ${remoteDirectory?.scope ?? "selected paths or legacy"}`, `This device scope: ${localDirectory?.scope ?? "selected paths"}`, `Remote excluded paths: ${normalizeSyncExclude(remoteExclude).join(", ") || "none"}`, `This device excluded paths: ${normalizeSyncExclude(localExclude).join(", ") || "none"}`, `Remote re-included paths: ${normalizeDirectoryRules(remoteDirectory?.reinclude).join(", ") || "none"}`, `This device re-included paths: ${normalizeDirectoryRules(localDirectory?.reinclude).join(", ") || "none"}`);
346
+ }
347
+ else if (!sameSyncExclude(localExclude, remoteExclude)) {
211
348
  lines.push(`Remote excluded paths: ${normalizeSyncExclude(remoteExclude).join(", ") || "none"}`, `This device excluded paths: ${normalizeSyncExclude(localExclude).join(", ") || "none"}`);
212
349
  }
213
350
  else if (comparison.remoteOnly.length === 0 && comparison.localOnly.length === 0) {
@@ -269,23 +406,151 @@ export function customIncludePathsByLower(value) {
269
406
  return new Map(syncIncludeSelection(value).custom.map((relativePath) => [relativePath.toLowerCase(), relativePath]));
270
407
  }
271
408
  export function includeFromSelectionConfig(config) {
409
+ if (config.ignorePolicy)
410
+ return config.ignorePolicy.sessions ? ["sessions"] : [];
272
411
  if (config.include !== undefined)
273
412
  return normalizeSyncInclude(config.include);
413
+ if (config.scope === "agent-directory")
414
+ return isIgnoreSnapshotSelection(config) && config.sessions ? ["sessions"] : [];
274
415
  return [
275
416
  ...normalizeSyncFiles(config.syncFiles),
276
417
  ...normalizeExtraFiles(config.extraFiles),
277
418
  ...(config.syncSessions ? ["sessions"] : []),
278
419
  ];
279
420
  }
421
+ export function syncSelectionHasContent(config) {
422
+ return config.scope === "agent-directory" || includeFromSelectionConfig(config).length > 0;
423
+ }
424
+ const DIRECTORY_SCOPE_LOCAL_ROOTS = new Set([
425
+ "auth.json",
426
+ "auth.json.lock",
427
+ "trust.json",
428
+ "trust.json.lock",
429
+ "settings.json.lock",
430
+ "models-store.json",
431
+ "models-store.json.lock",
432
+ "crashes.json",
433
+ "pi-debug.log",
434
+ ]);
435
+ function hasControlCharacter(value) {
436
+ for (let index = 0; index < value.length; index++) {
437
+ const code = value.charCodeAt(index);
438
+ if (code < 32 || (code >= 127 && code <= 159))
439
+ return true;
440
+ }
441
+ return false;
442
+ }
443
+ function isProtectedDirectoryPath(relativePath) {
444
+ if (Buffer.byteLength(relativePath, "utf8") > 4_096)
445
+ return true;
446
+ const segments = relativePath.split("/");
447
+ const root = segments[0]?.toLowerCase();
448
+ if (segments.some((segment) => !segment || /[. ]$/u.test(segment) || /^(?:con|prn|aux|nul|com[1-9¹²³]|lpt[1-9¹²³])(?:\.|$)/iu.test(segment)) ||
449
+ /[\\<>:"|?*]/u.test(relativePath) ||
450
+ hasControlCharacter(relativePath) ||
451
+ (root === "sessions" && segments[0] !== "sessions") ||
452
+ (root === "settings.json" && relativePath !== "settings.json") ||
453
+ (root !== undefined && DIRECTORY_SCOPE_LOCAL_ROOTS.has(root)))
454
+ return true;
455
+ for (let ancestor = relativePath; ancestor;) {
456
+ if (isDeniedPath(ancestor))
457
+ return true;
458
+ const slash = ancestor.lastIndexOf("/");
459
+ if (slash < 0)
460
+ break;
461
+ ancestor = ancestor.slice(0, slash);
462
+ }
463
+ return false;
464
+ }
465
+ export function isIgnoreControlPath(relativePath, reservedNames) {
466
+ const first = (relativePath.split("/", 1)[0] ?? "").toLowerCase();
467
+ return first === ".syncignore" || reservedNames?.has(first) === true;
468
+ }
469
+ function isIgnoreSnapshotSelection(config) {
470
+ return config.version === 4 && config.fingerprint !== undefined;
471
+ }
472
+ function compileIgnoreControlPath(config) {
473
+ const local = config.ignorePolicy;
474
+ if (!local && !config.reservedIgnoreNames && !isIgnoreSnapshotSelection(config))
475
+ return undefined;
476
+ const names = new Set([...(local ? [local.filename, ...local.reservedNames] : []), ...(config.reservedIgnoreNames ?? [])].map((name) => name.toLowerCase()));
477
+ return (relativePath) => isIgnoreControlPath(relativePath, names);
478
+ }
479
+ function compileDirectoryPolicy(config) {
480
+ const localIgnore = config.ignorePolicy;
481
+ const ignoreSelection = localIgnore !== undefined || isIgnoreSnapshotSelection(config);
482
+ const controlPath = compileIgnoreControlPath(config);
483
+ const sessions = includeFromSelectionConfig(config).includes("sessions");
484
+ const blocked = (relativePath) => isProtectedDirectoryPath(relativePath) ||
485
+ (ignoreSelection && !relativePath.isWellFormed()) ||
486
+ controlPath?.(relativePath) === true ||
487
+ (!sessions && /^sessions(?:\/|$)/iu.test(relativePath));
488
+ if (localIgnore) {
489
+ return {
490
+ excludes: (relativePath, directory = false) => blocked(relativePath) || localIgnore.matches(relativePath, directory),
491
+ descends: (relativePath) => !blocked(relativePath) && !localIgnore.matches(relativePath, true),
492
+ };
493
+ }
494
+ const excluded = compilePathRules(normalizeDirectoryRules(config.exclude));
495
+ const restored = compilePathRules(normalizeDirectoryRules(config.reinclude));
496
+ return {
497
+ excludes: (relativePath) => blocked(relativePath) || (excluded.matches(relativePath) && !restored.matches(relativePath)),
498
+ descends: (relativePath) => !blocked(relativePath) &&
499
+ (!excluded.matches(relativePath) || restored.matches(relativePath) || restored.mayMatchBelow(relativePath)),
500
+ };
501
+ }
502
+ export const MAX_AGENT_DIRECTORY_ENTRIES = 65_536;
503
+ export const MAX_AGENT_DIRECTORY_FILES = 16_384;
504
+ export function assertAgentDirectoryPathLayout(files) {
505
+ const prefixes = new Map();
506
+ let count = 0;
507
+ for (const file of files) {
508
+ if (++count > MAX_AGENT_DIRECTORY_FILES)
509
+ throw new Error("Agent-directory snapshot exceeds the file bound.");
510
+ for (let end = file.indexOf("/");; end = file.indexOf("/", end + 1)) {
511
+ const spelling = end === -1 ? file : file.slice(0, end);
512
+ const portable = spelling.normalize("NFC").toLowerCase();
513
+ const known = prefixes.get(portable);
514
+ if (known && (known.spelling !== spelling || known.file || end === -1))
515
+ throw new Error("Agent-directory snapshot has conflicting portable paths.");
516
+ if (!known) {
517
+ if (prefixes.size >= MAX_AGENT_DIRECTORY_ENTRIES)
518
+ throw new Error("Agent-directory snapshot exceeds the path bound.");
519
+ prefixes.set(portable, { spelling, file: end === -1 });
520
+ }
521
+ if (end === -1)
522
+ break;
523
+ }
524
+ }
525
+ }
526
+ export function compileSyncPolicyExclude(config) {
527
+ if (config.scope === "agent-directory")
528
+ return compileDirectoryPolicy(config).excludes;
529
+ const excludes = compileSyncExclude(config.exclude);
530
+ const controlPath = compileIgnoreControlPath(config);
531
+ return controlPath ? (relativePath) => controlPath(toPosix(relativePath)) || excludes(relativePath) : excludes;
532
+ }
533
+ export function compileSyncPolicyTraversal(config) {
534
+ if (config.scope === "agent-directory")
535
+ return compileDirectoryPolicy(config).descends;
536
+ const excludes = compileSyncPolicyExclude(config);
537
+ return (relativePath) => !excludes(relativePath);
538
+ }
280
539
  export function syncSessionsSelected(config) {
281
- return includeFromSelectionConfig(config).includes("sessions") && !compileSyncExclude(config.exclude)("sessions");
540
+ return includeFromSelectionConfig(config).includes("sessions") && compileSyncPolicyTraversal(config)("sessions");
282
541
  }
283
542
  export function isConfiguredSnapshotPath(relativePath, config, _legacyExtraFiles) {
284
543
  return configuredSnapshotPathMatcher(config)(relativePath);
285
544
  }
286
545
  export function configuredSnapshotPathMatcher(config) {
546
+ if (config.scope === "agent-directory") {
547
+ const excluded = compileSyncPolicyExclude(config);
548
+ return (relativePath) => !excluded(relativePath) &&
549
+ relativePath !== "sessions" &&
550
+ (!relativePath.startsWith("sessions/") || relativePath.endsWith(".jsonl"));
551
+ }
287
552
  const selection = syncIncludeSelection(includeFromSelectionConfig(config));
288
- const excluded = compileSyncExclude(config.exclude);
553
+ const excluded = compileSyncPolicyExclude(config);
289
554
  return (relativePath) => {
290
555
  const normalized = toPosix(relativePath);
291
556
  if (excluded(normalized))