@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,47 +1,262 @@
1
+ import { lstatSync } from "node:fs";
1
2
  import fs from "node:fs/promises";
2
3
  import path from "node:path";
3
4
  import { isPathInside, toPosix } from "../paths.js";
4
- import { compileSyncExclude } from "../sync/exclude-policy.js";
5
+ import { mergePathIdentity } from "../sync/file-merge-planner.js";
6
+ import { compileSyncPolicyExclude, compileSyncPolicyTraversal, configuredSnapshotPathMatcher, isIgnoreControlPath, } from "../sync/sync-policy.js";
5
7
  import { sessionStorageRoot } from "./snapshot-paths.js";
8
+ function directoryStat(absolute) {
9
+ try {
10
+ return lstatSync(absolute, { throwIfNoEntry: false });
11
+ }
12
+ catch (error) {
13
+ if (error.code !== "ENOTDIR")
14
+ throw error;
15
+ return undefined;
16
+ }
17
+ }
18
+ function physicalRelative(root, target) {
19
+ root = path.resolve(root);
20
+ target = path.resolve(target);
21
+ if (target === root)
22
+ return "";
23
+ const prefix = root.endsWith(path.sep) ? root : `${root}${path.sep}`;
24
+ if (target.startsWith(prefix))
25
+ return target.slice(prefix.length);
26
+ const rootDepth = root.slice(path.parse(root).root.length).split(path.sep).filter(Boolean).length;
27
+ const targetVolume = path.parse(target).root;
28
+ const parts = target.slice(targetVolume.length).split(path.sep).filter(Boolean);
29
+ if (parts.length < rootDepth)
30
+ return undefined;
31
+ const ancestor = path.join(targetVolume, ...parts.slice(0, rootDepth));
32
+ return sameDirectoryPrefix(root, ancestor) ? parts.slice(rootDepth).join(path.sep) : undefined;
33
+ }
34
+ function sameDirectoryPrefix(left, right) {
35
+ if (left === right)
36
+ return true;
37
+ const samePortableName = mergePathIdentity(left) === mergePathIdentity(right);
38
+ if (!samePortableName && process.platform !== "win32")
39
+ return false;
40
+ const boundary = directoryStat(left);
41
+ const candidate = directoryStat(right);
42
+ if (boundary || candidate)
43
+ return Boolean(boundary?.isDirectory() &&
44
+ candidate?.isDirectory() &&
45
+ boundary.dev === candidate.dev &&
46
+ boundary.ino === candidate.ino);
47
+ return (samePortableName && path.dirname(left) !== left && sameDirectoryPrefix(path.dirname(left), path.dirname(right)));
48
+ }
49
+ export function agentDirectoryAnchor(root, boundary) {
50
+ let anchor = path.dirname(path.resolve(root));
51
+ while (!isPathInside(anchor, boundary)) {
52
+ const parent = path.dirname(anchor);
53
+ if (parent === anchor)
54
+ return path.parse(boundary).root;
55
+ anchor = parent;
56
+ }
57
+ return anchor;
58
+ }
59
+ export function agentDirectorySessionRoot(root, sessionDir, ignorePolicy, reservedIgnoreNames) {
60
+ const sessionRoot = sessionStorageRoot(root, sessionDir);
61
+ if (physicalRelative(sessionRoot, root) !== undefined)
62
+ throw new Error("Pi session storage overlaps the agent directory root.");
63
+ const relative = physicalRelative(root, sessionRoot);
64
+ if (relative !== undefined) {
65
+ const logical = toPosix(relative);
66
+ const canTraverse = compileSyncPolicyTraversal({ scope: "agent-directory", include: ["sessions"] });
67
+ const reserved = ignorePolicy || reservedIgnoreNames
68
+ ? new Set([
69
+ ...(ignorePolicy ? [ignorePolicy.filename, ...ignorePolicy.reservedNames] : []),
70
+ ...(reservedIgnoreNames ?? []),
71
+ ].map((name) => name.toLowerCase()))
72
+ : undefined;
73
+ if (!canTraverse(logical) || (reserved && isIgnoreControlPath(logical, reserved)))
74
+ throw new Error("Pi session storage overlaps protected agent files.");
75
+ }
76
+ return sessionRoot;
77
+ }
78
+ export function agentDirectoryPhysicalSessionPath(root, sessionDir, ignorePolicy, reservedIgnoreNames) {
79
+ const sessionRoot = agentDirectorySessionRoot(root, sessionDir, ignorePolicy, reservedIgnoreNames);
80
+ const nested = physicalRelative(root, sessionRoot) !== undefined;
81
+ return (relativePath) => nested && physicalRelative(sessionRoot, path.resolve(root, relativePath)) !== undefined;
82
+ }
83
+ async function realpathWithMissingTail(target) {
84
+ let ancestor = path.resolve(target);
85
+ for (;;) {
86
+ try {
87
+ const resolved = await fs.realpath(ancestor);
88
+ return path.resolve(resolved, path.relative(ancestor, target));
89
+ }
90
+ catch (error) {
91
+ const code = error.code;
92
+ const parent = path.dirname(ancestor);
93
+ if (parent === ancestor || (code !== "ENOENT" && code !== "ENOTDIR"))
94
+ throw error;
95
+ ancestor = parent;
96
+ }
97
+ }
98
+ }
99
+ export function reservedIgnoreTargetGuard(root, options) {
100
+ if (options.reservedIgnoreNames === undefined)
101
+ return undefined;
102
+ const reserved = new Set(options.reservedIgnoreNames);
103
+ function check(agentRoot, target) {
104
+ const relative = physicalRelative(agentRoot, target);
105
+ if (physicalRelative(target, agentRoot) !== undefined ||
106
+ (relative !== undefined && isIgnoreControlPath(toPosix(relative), reserved)))
107
+ throw new Error("Transfer would access a protected ignore rule path or its ancestor.");
108
+ }
109
+ return async (target) => {
110
+ check(root, target);
111
+ const canonicalRoot = await realpathWithMissingTail(root);
112
+ const canonicalTarget = await realpathWithMissingTail(target);
113
+ check(canonicalRoot, canonicalTarget);
114
+ return canonicalTarget;
115
+ };
116
+ }
6
117
  /** Metadata-only preflight: an ancestor replacement must not capture/remove excluded descendants. */
7
- export async function assertUnexcludedTargets(root, targets, options) {
8
- if (!options.exclude?.length)
118
+ export async function assertUnexcludedTargets(root, targets, options, { recursive = true } = {}) {
119
+ const wholeDirectory = options.scope === "agent-directory";
120
+ const guardReserved = reservedIgnoreTargetGuard(root, options);
121
+ if (!wholeDirectory &&
122
+ !guardReserved &&
123
+ (options.exclude === undefined || (Array.isArray(options.exclude) && !options.exclude.length)))
9
124
  return;
10
- const excluded = compileSyncExclude(options.exclude);
11
- const sessionRoot = sessionStorageRoot(root, options.sessionDir);
125
+ const excluded = compileSyncPolicyExclude(options);
126
+ const sessionRoot = wholeDirectory
127
+ ? agentDirectorySessionRoot(root, options.sessionDir, options.ignorePolicy, options.reservedIgnoreNames)
128
+ : sessionStorageRoot(root, options.sessionDir);
129
+ const configured = configuredSnapshotPathMatcher(options);
12
130
  let visited = 0;
13
131
  const validate = () => {
14
132
  options.signal?.throwIfAborted();
15
133
  options.validateMutation?.();
16
134
  };
17
- async function visit(target) {
135
+ const reserveVisit = () => {
18
136
  validate();
19
137
  if (++visited > 16_384)
20
138
  throw new Error("Exclude safety preflight exceeds its path bound; review a smaller transfer.");
21
- const candidates = [];
22
- if (isPathInside(root, target))
23
- candidates.push(toPosix(path.relative(root, target)));
24
- if (isPathInside(sessionRoot, target))
25
- candidates.push(`sessions/${toPosix(path.relative(sessionRoot, target))}`);
26
- if (candidates.some(excluded))
27
- throw new Error("Transfer would replace an excluded path or directory descendant; no replacement is authorized.");
28
- try {
29
- const stat = await fs.lstat(target);
30
- validate();
31
- if (!stat.isDirectory() || stat.isSymbolicLink())
32
- return;
33
- const names = await fs.readdir(target);
139
+ };
140
+ function refuse() {
141
+ throw new Error("Transfer would replace an excluded path or directory descendant; no replacement is authorized.");
142
+ }
143
+ async function visit(target) {
144
+ validate();
145
+ if (guardReserved) {
146
+ await guardReserved(target);
34
147
  validate();
35
- for (const name of names)
36
- await visit(path.join(target, name));
148
+ }
149
+ let logicalPath;
150
+ let sessionPath;
151
+ if (wholeDirectory) {
152
+ if (physicalRelative(target, sessionRoot) !== undefined)
153
+ refuse();
154
+ const sessionRelative = physicalRelative(sessionRoot, target);
155
+ if (sessionRelative !== undefined) {
156
+ sessionPath = `sessions/${toPosix(sessionRelative)}`;
157
+ logicalPath = sessionPath;
158
+ }
159
+ else {
160
+ const relative = physicalRelative(root, target);
161
+ if (!relative || /^sessions(?:\/|$)/iu.test(toPosix(relative)))
162
+ refuse();
163
+ logicalPath = toPosix(relative);
164
+ }
165
+ if (!options.ignorePolicy && excluded(logicalPath))
166
+ refuse();
167
+ }
168
+ else {
169
+ const candidates = [];
170
+ if (isPathInside(root, target))
171
+ candidates.push(toPosix(path.relative(root, target)));
172
+ if (isPathInside(sessionRoot, target))
173
+ candidates.push(`sessions/${toPosix(path.relative(sessionRoot, target))}`);
174
+ if (candidates.some((candidate) => excluded(candidate)))
175
+ refuse();
176
+ }
177
+ let observed;
178
+ try {
179
+ observed = await fs.lstat(target);
37
180
  }
38
181
  catch (error) {
39
- validate();
40
182
  const code = error.code;
41
- if (code !== "ENOENT" && code !== "ENOTDIR")
183
+ if (code !== "ENOENT" && code !== "ENOTDIR") {
184
+ validate();
42
185
  throw error;
186
+ }
43
187
  }
188
+ validate();
189
+ if (options.ignorePolicy && logicalPath !== undefined && excluded(logicalPath, observed?.isDirectory()))
190
+ refuse();
191
+ if (!observed)
192
+ return;
193
+ const stat = observed;
194
+ if ((wholeDirectory && !stat.isDirectory() && (!stat.isFile() || stat.nlink !== 1)) ||
195
+ (guardReserved && stat.isFile() && stat.nlink !== 1)) {
196
+ throw new Error("Refusing an unsafe symlink, hard link, or special file during snapshot mutation.");
197
+ }
198
+ if (sessionPath && stat.isFile() && !configured(sessionPath))
199
+ refuse();
200
+ if (!recursive || !stat.isDirectory())
201
+ return;
202
+ const children = [];
203
+ for await (const entry of await fs.opendir(target)) {
204
+ reserveVisit();
205
+ children.push(entry.name);
206
+ }
207
+ async function recheckDirectory() {
208
+ if (!wholeDirectory)
209
+ return;
210
+ const current = await fs.lstat(target);
211
+ validate();
212
+ if (!current.isDirectory() ||
213
+ current.dev !== stat.dev ||
214
+ current.ino !== stat.ino ||
215
+ current.ctimeMs !== stat.ctimeMs)
216
+ refuse();
217
+ }
218
+ await recheckDirectory();
219
+ for (const child of children)
220
+ await visit(path.join(target, child));
221
+ await recheckDirectory();
44
222
  }
45
- for (const target of new Set(targets))
223
+ async function assertParents(target, includeTarget = false) {
224
+ let parent = agentDirectoryAnchor(root, target);
225
+ const parts = path.relative(parent, target).split(path.sep);
226
+ if (!includeTarget)
227
+ parts.pop();
228
+ for (const part of parts) {
229
+ parent = path.join(parent, part);
230
+ validate();
231
+ try {
232
+ const stat = await fs.lstat(parent);
233
+ validate();
234
+ if (stat.isSymbolicLink())
235
+ throw new Error("Refusing to follow symlink during snapshot mutation.");
236
+ if (!stat.isDirectory()) {
237
+ if (includeTarget)
238
+ throw new Error("Pi session storage is not a directory.");
239
+ break;
240
+ }
241
+ }
242
+ catch (error) {
243
+ validate();
244
+ const code = error.code;
245
+ if (code !== "ENOENT" && code !== "ENOTDIR")
246
+ throw error;
247
+ break;
248
+ }
249
+ }
250
+ }
251
+ validate();
252
+ if (wholeDirectory && options.sessionDir)
253
+ await assertParents(sessionRoot, true);
254
+ for (const target of new Set(targets)) {
255
+ reserveVisit();
256
+ if (wholeDirectory &&
257
+ (physicalRelative(root, target) !== undefined || physicalRelative(sessionRoot, target) !== undefined)) {
258
+ await assertParents(target);
259
+ }
46
260
  await visit(target);
261
+ }
47
262
  }
@@ -0,0 +1,2 @@
1
+ export declare function snapshotBase64Size(value: string, filePath: string): number;
2
+ export declare function decodeBase64Strict(value: string, filePath: string): Buffer<ArrayBuffer>;
@@ -0,0 +1,10 @@
1
+ export function snapshotBase64Size(value, filePath) {
2
+ if (typeof value !== "string" || value.length % 4 !== 0 || !/^[A-Za-z0-9+/]*={0,2}(?![\s\S])/u.test(value))
3
+ throw new Error(`Invalid base64 content in snapshot file: ${filePath}`);
4
+ const padding = value.endsWith("==") ? 2 : value.endsWith("=") ? 1 : 0;
5
+ return (value.length / 4) * 3 - padding;
6
+ }
7
+ export function decodeBase64Strict(value, filePath) {
8
+ snapshotBase64Size(value, filePath);
9
+ return Buffer.from(value, "base64");
10
+ }
@@ -0,0 +1,2 @@
1
+ import type { AgentDirectoryInventory, SnapshotApplyPlan, SnapshotFile } from "./snapshot-types.js";
2
+ export declare function reviewedSnapshotPreimages(root: string, sessionDir: string | undefined, reviewed: readonly SnapshotFile[], plan: SnapshotApplyPlan, inventory?: AgentDirectoryInventory): Map<string, string>;
@@ -0,0 +1,60 @@
1
+ import { createHash } from "node:crypto";
2
+ import path from "node:path";
3
+ import { snapshotTarget } from "./snapshot.js";
4
+ function image(entry) {
5
+ if (entry === "unreviewed" || (typeof entry !== "string" && entry.unreviewed))
6
+ throw new Error("Reviewed directory contains an unreviewed entry; no replacement is authorized.");
7
+ if (typeof entry === "string")
8
+ return entry;
9
+ const rows = [...entry.entries.keys()]
10
+ .sort()
11
+ .map((name) => [name, image(entry.entries.get(name))]);
12
+ return `directory:${createHash("sha256").update(JSON.stringify(rows)).digest("hex")}`;
13
+ }
14
+ export function reviewedSnapshotPreimages(root, sessionDir, reviewed, plan, inventory) {
15
+ const images = new Map();
16
+ function insert(target, entry) {
17
+ const existing = images.get(target);
18
+ if (existing) {
19
+ if (typeof entry === "string" || typeof existing === "string")
20
+ throw new Error("Reviewed paths conflict before apply.");
21
+ return;
22
+ }
23
+ images.set(target, entry);
24
+ for (let parent = path.dirname(target); parent !== target; parent = path.dirname(target)) {
25
+ const existing = images.get(parent);
26
+ if (typeof existing === "string")
27
+ throw new Error("Reviewed paths conflict before apply.");
28
+ const directory = existing ?? { entries: new Map() };
29
+ directory.entries.set(path.basename(target), entry);
30
+ if (existing)
31
+ break;
32
+ images.set(parent, directory);
33
+ target = parent;
34
+ entry = directory;
35
+ }
36
+ }
37
+ for (const file of reviewed)
38
+ insert(snapshotTarget(root, file.path, sessionDir), `file:${file.sha256}`);
39
+ if (inventory) {
40
+ for (const [target, kind] of inventory.entries) {
41
+ if (kind === "directory")
42
+ insert(target, { entries: new Map() });
43
+ }
44
+ for (const [target, kind] of inventory.entries) {
45
+ if (kind !== "unreviewed")
46
+ continue;
47
+ const entry = images.get(target);
48
+ if (entry && typeof entry !== "string")
49
+ entry.unreviewed = true;
50
+ const parent = images.get(path.dirname(target));
51
+ if (parent && typeof parent !== "string")
52
+ parent.entries.set(path.basename(target), "unreviewed");
53
+ }
54
+ }
55
+ const targets = new Set([...plan.deletes, ...plan.writes.map(({ target }) => target)]);
56
+ return new Map([...targets].map((target) => {
57
+ const entry = inventory?.entries.get(target) === "unreviewed" ? "unreviewed" : images.get(target);
58
+ return [target, entry === undefined ? "missing" : image(entry)];
59
+ }));
60
+ }
@@ -18,6 +18,10 @@ interface SettingsEntry {
18
18
  beforeImage?: string;
19
19
  afterImage?: string;
20
20
  }
21
+ export declare function stableAgentDirectorySettingsImage(root: string, plan: SnapshotApplyPlan, guards: TransitionGuards): Promise<{
22
+ target: string;
23
+ image: string;
24
+ } | undefined>;
21
25
  export declare function prepareSessionRootTransition(directory: string, root: string, sessionRoot: string, entries: SettingsEntry[], plan: SnapshotApplyPlan, guards?: TransitionGuards): Promise<SessionRootTransition | undefined>;
22
26
  export declare function validateSessionRootTransition(value: SessionRootTransition): void;
23
27
  /** Authorization is bound to both settings images, never just an arbitrary pinned root. */
@@ -2,7 +2,9 @@ import fs from "node:fs/promises";
2
2
  import path from "node:path";
3
3
  import { isPathInside } from "../paths.js";
4
4
  import { syncDirectory } from "../state/json-file.js";
5
+ import { mergePathIdentity } from "../sync/file-merge-planner.js";
5
6
  import { expandSessionDir } from "./session-paths.js";
7
+ import { agentDirectorySessionDirFromSettings, readAgentDirectorySettings } from "./snapshot.js";
6
8
  import { sessionStorageRoot } from "./snapshot-paths.js";
7
9
  import { fileImage } from "./snapshot-transaction-plan.js";
8
10
  function validateOwner(guards) {
@@ -41,6 +43,20 @@ async function beforeRoot(directory, root, entry, guards) {
41
43
  throw new Error("Changed settings root-transition backup.");
42
44
  return rootFromSettings(root, bytes);
43
45
  }
46
+ export async function stableAgentDirectorySettingsImage(root, plan, guards) {
47
+ const settingsTarget = mergePathIdentity(path.join(root, "settings.json"));
48
+ const write = plan.writes.find(({ target }) => mergePathIdentity(target) === settingsTarget);
49
+ const target = write?.target ?? plan.deletes.find((target) => mergePathIdentity(target) === settingsTarget);
50
+ if (!target)
51
+ return;
52
+ const beforeBytes = await readAgentDirectorySettings(guards.signal, root);
53
+ validateOwner(guards);
54
+ const before = beforeBytes === undefined ? undefined : agentDirectorySessionDirFromSettings(beforeBytes);
55
+ const after = write ? agentDirectorySessionDirFromSettings(write.content) : undefined;
56
+ if (sessionStorageRoot(root, before) !== sessionStorageRoot(root, after))
57
+ throw new Error("Agent-directory transfers cannot change Pi session storage; keep the local sessionDir setting.");
58
+ return { target, image: beforeBytes === undefined ? "missing" : fileImage(beforeBytes) };
59
+ }
44
60
  export async function prepareSessionRootTransition(directory, root, sessionRoot, entries, plan, guards = {}) {
45
61
  const settingsTarget = path.join(root, "settings.json");
46
62
  const entry = entries.find((item) => item.target === settingsTarget || item.afterTarget === settingsTarget);
@@ -0,0 +1,39 @@
1
+ import { type BigIntStats } from "node:fs";
2
+ import { type FileHandle } from "node:fs/promises";
3
+ import { type TransactionEntry } from "./snapshot-transaction-policy.js";
4
+ export declare const MAX_TRANSACTION_JOURNAL_BYTES: number;
5
+ interface Guards {
6
+ signal?: AbortSignal;
7
+ validateMutation?: () => void;
8
+ }
9
+ interface ScopedDirectoryImage {
10
+ kind: "directory";
11
+ value: string;
12
+ stat: BigIntStats;
13
+ children: [string, ScopedNode][];
14
+ }
15
+ type ScopedNode = {
16
+ kind: "file";
17
+ value: string;
18
+ stat: BigIntStats;
19
+ } | ScopedDirectoryImage;
20
+ export type ScopedImage = {
21
+ kind: "missing";
22
+ value: "missing";
23
+ } | ScopedNode;
24
+ export declare function scopedPathIdentity(target: string, guards: Guards): Promise<string>;
25
+ export declare function scopedIdentity(stat: BigIntStats): string;
26
+ export declare function installedVacancyIdentityMatches(image: ScopedImage, expected: string): boolean;
27
+ export declare function stableScopedIdentity(target: string, stat: BigIntStats): string;
28
+ export declare function readTransactionJournal(file: string, guards: Guards, maxBytes?: number): Promise<string | undefined>;
29
+ export declare function scopedTransactionImage(target: string, guards: Guards, copyTo?: string, checkPath?: (source: string) => Promise<void>, beforeCopyFile?: (handle: FileHandle) => Promise<void>): Promise<ScopedImage>;
30
+ export declare function ownedScopedSubset(image: ScopedImage, expected: ScopedImage): boolean;
31
+ export declare function matchesScopedFilePrefix(source: string, original: ScopedImage, partial: ScopedImage, guards: Guards): Promise<boolean>;
32
+ export declare function scopedDescendant(image: ScopedImage, relative: string): ScopedImage | undefined;
33
+ export declare function recheckScopedImage(target: string, image: ScopedImage, guards: Guards): Promise<void>;
34
+ export declare function removeScopedImage(target: string, image: ScopedImage, guards: Guards, validateIgnorePolicy?: () => Promise<void>): Promise<void>;
35
+ export declare function legacyImage(target: string, durable?: boolean): Promise<string>;
36
+ type PostFiles = NonNullable<TransactionEntry["postFiles"]>;
37
+ export declare function ownedScopedPostTree(image: ScopedImage, files: PostFiles, requireComplete: boolean): boolean;
38
+ export declare function ownedLegacyPostTree(target: string, files: PostFiles, requireComplete: boolean): Promise<boolean>;
39
+ export {};