@narumitw/pi-sync-daemon 0.6.1 → 0.7.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 (72) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/README.md +3 -1
  3. package/dist/consent.js +11 -1
  4. package/dist/engine/backends/git/git-storage.js +11 -6
  5. package/dist/engine/paths.js +1 -1
  6. package/dist/engine/settings/config-file.js +2 -0
  7. package/dist/engine/settings/config.d.ts +2 -4
  8. package/dist/engine/settings/config.js +22 -7
  9. package/dist/engine/settings/settings-management.d.ts +2 -2
  10. package/dist/engine/settings/settings-management.js +27 -33
  11. package/dist/engine/settings/settings-types.d.ts +18 -4
  12. package/dist/engine/settings/settings-validation.js +34 -24
  13. package/dist/engine/snapshot/session-paths.d.ts +5 -3
  14. package/dist/engine/snapshot/session-paths.js +55 -9
  15. package/dist/engine/snapshot/snapshot-apply.d.ts +6 -7
  16. package/dist/engine/snapshot/snapshot-apply.js +88 -21
  17. package/dist/engine/snapshot/snapshot-bounds.d.ts +4 -0
  18. package/dist/engine/snapshot/snapshot-bounds.js +20 -0
  19. package/dist/engine/snapshot/snapshot-codec.js +3 -4
  20. package/dist/engine/snapshot/snapshot-entry-projection.d.ts +10 -0
  21. package/dist/engine/snapshot/snapshot-entry-projection.js +78 -0
  22. package/dist/engine/snapshot/snapshot-exclude-safety.d.ts +7 -2
  23. package/dist/engine/snapshot/snapshot-exclude-safety.js +180 -22
  24. package/dist/engine/snapshot/snapshot-payload.d.ts +2 -0
  25. package/dist/engine/snapshot/snapshot-payload.js +10 -0
  26. package/dist/engine/snapshot/snapshot-reviewed-preimages.d.ts +2 -0
  27. package/dist/engine/snapshot/snapshot-reviewed-preimages.js +60 -0
  28. package/dist/engine/snapshot/snapshot-root-transition.d.ts +4 -0
  29. package/dist/engine/snapshot/snapshot-root-transition.js +16 -0
  30. package/dist/engine/snapshot/snapshot-transaction-images.d.ts +37 -0
  31. package/dist/engine/snapshot/snapshot-transaction-images.js +357 -0
  32. package/dist/engine/snapshot/snapshot-transaction-policy.d.ts +50 -0
  33. package/dist/engine/snapshot/snapshot-transaction-policy.js +172 -0
  34. package/dist/engine/snapshot/snapshot-transaction-stage.d.ts +32 -0
  35. package/dist/engine/snapshot/snapshot-transaction-stage.js +303 -0
  36. package/dist/engine/snapshot/snapshot-transaction.d.ts +2 -1
  37. package/dist/engine/snapshot/snapshot-transaction.js +379 -331
  38. package/dist/engine/snapshot/snapshot-types.d.ts +24 -1
  39. package/dist/engine/snapshot/snapshot.d.ts +19 -2
  40. package/dist/engine/snapshot/snapshot.js +283 -26
  41. package/dist/engine/state/merge-baseline-store.js +20 -9
  42. package/dist/engine/state/state-types.d.ts +2 -0
  43. package/dist/engine/sync/apply-review.d.ts +3 -3
  44. package/dist/engine/sync/apply-review.js +5 -4
  45. package/dist/engine/sync/continuous-sync.js +19 -9
  46. package/dist/engine/sync/continuous-watch.d.ts +4 -1
  47. package/dist/engine/sync/continuous-watch.js +86 -14
  48. package/dist/engine/sync/exclude-policy.d.ts +4 -0
  49. package/dist/engine/sync/exclude-policy.js +8 -1
  50. package/dist/engine/sync/initialization.js +9 -5
  51. package/dist/engine/sync/local-fields.js +27 -8
  52. package/dist/engine/sync/merge-apply.js +155 -40
  53. package/dist/engine/sync/merge-journal.js +13 -4
  54. package/dist/engine/sync/merged-sync.js +21 -18
  55. package/dist/engine/sync/partial-progress.js +5 -3
  56. package/dist/engine/sync/remote-snapshot.d.ts +1 -0
  57. package/dist/engine/sync/remote-snapshot.js +8 -5
  58. package/dist/engine/sync/session-push.js +7 -6
  59. package/dist/engine/sync/sync-decision.d.ts +4 -0
  60. package/dist/engine/sync/sync-decision.js +17 -2
  61. package/dist/engine/sync/sync-inspection.js +3 -3
  62. package/dist/engine/sync/sync-mutations.d.ts +8 -1
  63. package/dist/engine/sync/sync-mutations.js +153 -72
  64. package/dist/engine/sync/sync-policy.d.ts +20 -10
  65. package/dist/engine/sync/sync-policy.js +170 -16
  66. package/dist/engine/sync/sync-queries.js +41 -31
  67. package/dist/engine/sync/sync-state.d.ts +11 -0
  68. package/dist/engine/sync/sync-state.js +24 -5
  69. package/dist/engine/ui/sync-format.js +22 -7
  70. package/dist/resolver-host.js +1 -1
  71. package/docs/architecture.md +6 -0
  72. package/package.json +4 -4
@@ -0,0 +1,357 @@
1
+ import { createHash } from "node:crypto";
2
+ import nodeFs, { constants } from "node:fs";
3
+ import fs from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { syncDirectory } from "../state/json-file.js";
6
+ import { mergePathIdentity } from "../sync/file-merge-planner.js";
7
+ import { MAX_AGENT_DIRECTORY_ENTRIES, MAX_AGENT_DIRECTORY_FILES } from "../sync/sync-policy.js";
8
+ import { MAX_AGENT_DIRECTORY_BYTES } from "./snapshot-bounds.js";
9
+ import { fileImage } from "./snapshot-transaction-plan.js";
10
+ import { isScopedIdentity } from "./snapshot-transaction-policy.js";
11
+ export const MAX_TRANSACTION_JOURNAL_BYTES = 32 * 1024 * 1024;
12
+ const CHUNK_BYTES = 64 * 1024;
13
+ export async function scopedPathIdentity(target, guards) {
14
+ validate(guards);
15
+ const stat = await fs.lstat(target, { bigint: true });
16
+ validate(guards);
17
+ return scopedIdentity(stat);
18
+ }
19
+ export function scopedIdentity(stat) {
20
+ const identity = `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`;
21
+ if (!isScopedIdentity(identity))
22
+ changedImage();
23
+ return identity;
24
+ }
25
+ export function stableScopedIdentity(target, stat) {
26
+ const identity = scopedIdentity(stat);
27
+ if (stat.birthtimeNs > 0n) {
28
+ if (stat.birthtimeNs !== stat.ctimeNs)
29
+ return identity;
30
+ if (["darwin", "freebsd", "netbsd", "win32"].includes(process.platform))
31
+ return identity;
32
+ if (process.platform === "linux" || process.platform === "android") {
33
+ const current = nodeFs.lstatSync(target, { bigint: true });
34
+ if (!sameObservation(stat, current))
35
+ changedImage();
36
+ for (let ancestor = target; ancestor !== path.dirname(ancestor);) {
37
+ ancestor = path.dirname(ancestor);
38
+ const witness = nodeFs.lstatSync(ancestor, { bigint: true });
39
+ if (!witness.isDirectory() || witness.dev !== stat.dev)
40
+ break;
41
+ if (witness.birthtimeNs > 0n && witness.birthtimeNs !== witness.ctimeNs)
42
+ return identity;
43
+ }
44
+ }
45
+ }
46
+ throw new Error("Stable filesystem birth time is unavailable; preserve transaction evidence for reviewed recovery.");
47
+ }
48
+ function validate(guards) {
49
+ guards.signal?.throwIfAborted();
50
+ guards.validateMutation?.();
51
+ }
52
+ function changedImage() {
53
+ throw new Error("Transaction image changed or is unsafe; preserve evidence for review.");
54
+ }
55
+ function sameIdentity(a, b) {
56
+ return (a.dev === b.dev &&
57
+ a.ino === b.ino &&
58
+ a.mode === b.mode &&
59
+ (a.birthtimeNs <= 0n || a.birthtimeNs === a.ctimeNs || a.birthtimeNs === b.birthtimeNs));
60
+ }
61
+ function sameObservation(a, b) {
62
+ return (sameIdentity(a, b) &&
63
+ a.nlink === b.nlink &&
64
+ a.size === b.size &&
65
+ a.mtimeNs === b.mtimeNs &&
66
+ a.ctimeNs === b.ctimeNs &&
67
+ a.birthtimeNs === b.birthtimeNs);
68
+ }
69
+ async function lstat(target, guards) {
70
+ validate(guards);
71
+ let stat;
72
+ try {
73
+ stat = await fs.lstat(target, { bigint: true });
74
+ }
75
+ catch (error) {
76
+ validate(guards);
77
+ const code = error.code;
78
+ if (code === "ENOENT" || code === "ENOTDIR")
79
+ return undefined;
80
+ throw error;
81
+ }
82
+ validate(guards);
83
+ return stat;
84
+ }
85
+ async function recheck(target, original, guards, identityOnly = false) {
86
+ const current = await lstat(target, guards);
87
+ if (!current || !(identityOnly ? sameIdentity : sameObservation)(original, current))
88
+ changedImage();
89
+ }
90
+ async function readStableFile(target, original, guards, consume) {
91
+ validate(guards);
92
+ const handle = await fs.open(target, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0));
93
+ try {
94
+ const opened = await handle.stat({ bigint: true });
95
+ validate(guards);
96
+ if (!opened.isFile() || !sameObservation(original, opened))
97
+ changedImage();
98
+ await recheck(target, original, guards);
99
+ const size = Number(original.size);
100
+ const buffer = Buffer.alloc(Math.min(CHUNK_BYTES, size));
101
+ for (let offset = 0; offset < size;) {
102
+ validate(guards);
103
+ const { bytesRead } = await handle.read(buffer, 0, Math.min(buffer.length, size - offset), offset);
104
+ validate(guards);
105
+ if (bytesRead === 0)
106
+ changedImage();
107
+ await consume(buffer.subarray(0, bytesRead), offset);
108
+ offset += bytesRead;
109
+ }
110
+ if (!sameObservation(original, await handle.stat({ bigint: true })))
111
+ changedImage();
112
+ }
113
+ finally {
114
+ await handle.close();
115
+ }
116
+ await recheck(target, original, guards);
117
+ }
118
+ export async function readTransactionJournal(file, guards, maxBytes = MAX_TRANSACTION_JOURNAL_BYTES) {
119
+ const stat = await lstat(file, guards);
120
+ if (!stat)
121
+ return undefined;
122
+ if (!stat.isFile() || stat.nlink !== 1n || stat.size > maxBytes)
123
+ changedImage();
124
+ const content = Buffer.alloc(Number(stat.size));
125
+ await readStableFile(file, stat, guards, (chunk, offset) => {
126
+ chunk.copy(content, offset);
127
+ });
128
+ return content.toString("utf8");
129
+ }
130
+ export async function scopedTransactionImage(target, guards, copyTo, checkPath, beforeCopyFile) {
131
+ const stat = await lstat(target, guards);
132
+ if (!stat)
133
+ return { kind: "missing", value: "missing" };
134
+ let entries = 1;
135
+ let files = 0;
136
+ let bytes = 0;
137
+ async function visit(source, observed, destination) {
138
+ if (checkPath)
139
+ await checkPath(source);
140
+ validate(guards);
141
+ if (observed.isDirectory()) {
142
+ const names = [];
143
+ for await (const entry of await fs.opendir(source)) {
144
+ validate(guards);
145
+ if (++entries > MAX_AGENT_DIRECTORY_ENTRIES)
146
+ throw new Error("Transaction image exceeds the agent-directory entry bound.");
147
+ names.push(entry.name);
148
+ }
149
+ await recheck(source, observed, guards);
150
+ if (destination)
151
+ await fs.mkdir(destination, { mode: 0o700 });
152
+ const children = [];
153
+ for (const name of names.sort()) {
154
+ const child = path.join(source, name);
155
+ const stat = await lstat(child, guards);
156
+ if (!stat)
157
+ changedImage();
158
+ children.push([name, await visit(child, stat, destination && path.join(destination, name))]);
159
+ }
160
+ if (destination) {
161
+ validate(guards);
162
+ await fs.chmod(destination, Number(observed.mode & 511n));
163
+ validate(guards);
164
+ await fs.utimes(destination, observed.atime, observed.mtime);
165
+ validate(guards);
166
+ await syncDirectory(destination);
167
+ }
168
+ await recheck(source, observed, guards);
169
+ const rows = children.map(([name, child]) => [name, child.value]);
170
+ const value = `directory:${createHash("sha256").update(JSON.stringify(rows)).digest("hex")}`;
171
+ return { kind: "directory", value, stat: observed, children };
172
+ }
173
+ if (!observed.isFile() || observed.nlink !== 1n)
174
+ changedImage();
175
+ if (++files > MAX_AGENT_DIRECTORY_FILES)
176
+ throw new Error("Transaction image exceeds the agent-directory file bound.");
177
+ bytes += Number(observed.size);
178
+ if (bytes > MAX_AGENT_DIRECTORY_BYTES)
179
+ throw new Error("Transaction image exceeds the 64 MiB byte bound.");
180
+ const hash = createHash("sha256");
181
+ const copy = destination ? await fs.open(destination, "wx", 0o600) : undefined;
182
+ try {
183
+ if (copy)
184
+ await beforeCopyFile?.(copy);
185
+ await readStableFile(source, observed, guards, async (chunk) => {
186
+ hash.update(chunk);
187
+ if (copy)
188
+ await copy.writeFile(chunk);
189
+ });
190
+ if (copy) {
191
+ validate(guards);
192
+ await copy.chmod(Number(observed.mode & 511n));
193
+ validate(guards);
194
+ await copy.utimes(observed.atime, observed.mtime);
195
+ validate(guards);
196
+ await copy.sync();
197
+ }
198
+ }
199
+ finally {
200
+ await copy?.close();
201
+ }
202
+ validate(guards);
203
+ return { kind: "file", value: `file:${hash.digest("hex")}`, stat: observed };
204
+ }
205
+ return visit(target, stat, copyTo);
206
+ }
207
+ export function ownedScopedSubset(image, expected) {
208
+ if (image.kind !== expected.kind)
209
+ return false;
210
+ if (image.kind !== "directory" || expected.kind !== "directory")
211
+ return image.value === expected.value;
212
+ const children = new Map(expected.children);
213
+ return image.children.every(([name, child]) => {
214
+ const original = children.get(name);
215
+ return original !== undefined && ownedScopedSubset(child, original);
216
+ });
217
+ }
218
+ export async function matchesScopedFilePrefix(source, original, partial, guards) {
219
+ if (original.kind !== "file" || partial.kind !== "file" || partial.stat.size > original.stat.size)
220
+ return false;
221
+ const hash = createHash("sha256");
222
+ const size = Number(partial.stat.size);
223
+ await readStableFile(source, original.stat, guards, (chunk, offset) => {
224
+ if (offset < size)
225
+ hash.update(chunk.subarray(0, size - offset));
226
+ });
227
+ return partial.value === `file:${hash.digest("hex")}`;
228
+ }
229
+ export function scopedDescendant(image, relative) {
230
+ let node = image;
231
+ for (const name of relative ? relative.split(path.sep) : []) {
232
+ if (node?.kind !== "directory")
233
+ return;
234
+ const directory = node;
235
+ node = directory.children.find(([child]) => child === name)?.[1];
236
+ }
237
+ return node;
238
+ }
239
+ export async function removeScopedImage(target, image, guards) {
240
+ if (image.kind === "missing")
241
+ return;
242
+ async function remove(target, node) {
243
+ await recheck(target, node.stat, guards);
244
+ if (node.kind === "file") {
245
+ const observed = await scopedTransactionImage(target, guards);
246
+ if (observed.kind !== "file" || !sameObservation(node.stat, observed.stat) || observed.value !== node.value)
247
+ changedImage();
248
+ validate(guards);
249
+ await fs.unlink(target);
250
+ return;
251
+ }
252
+ for (const [name, child] of node.children)
253
+ await remove(path.join(target, name), child);
254
+ await recheck(target, node.stat, guards, true);
255
+ validate(guards);
256
+ await fs.rmdir(target);
257
+ }
258
+ await remove(target, image);
259
+ }
260
+ export async function legacyImage(target, durable = false) {
261
+ const stat = await lstat(target, {});
262
+ if (!stat)
263
+ return "missing";
264
+ if (stat.isSymbolicLink())
265
+ return `symlink:${await fs.readlink(target)}`;
266
+ if (stat.isFile()) {
267
+ const content = await fs.readFile(target);
268
+ if (durable) {
269
+ const handle = await fs.open(target, process.platform === "win32" ? "r+" : "r");
270
+ try {
271
+ await handle.sync();
272
+ }
273
+ finally {
274
+ await handle.close();
275
+ }
276
+ }
277
+ return fileImage(content);
278
+ }
279
+ if (!stat.isDirectory())
280
+ throw new Error("Unsupported transaction image.");
281
+ const entries = [];
282
+ for (const name of (await fs.readdir(target)).sort())
283
+ entries.push([name, await legacyImage(path.join(target, name), durable)]);
284
+ if (durable)
285
+ await syncDirectory(target);
286
+ return `directory:${createHash("sha256").update(JSON.stringify(entries)).digest("hex")}`;
287
+ }
288
+ function postTreePaths(files, key) {
289
+ const expected = new Map(files.map((file) => [key(file.relative), file.image]));
290
+ const prefixes = new Set();
291
+ for (const relative of expected.keys()) {
292
+ for (let parent = path.dirname(relative); parent !== "." && parent !== path.dirname(parent); parent = path.dirname(parent))
293
+ prefixes.add(parent);
294
+ }
295
+ return { expected, prefixes };
296
+ }
297
+ export function ownedScopedPostTree(image, files, requireComplete) {
298
+ if (image.kind !== "directory" || !files.length)
299
+ return false;
300
+ const { expected, prefixes } = postTreePaths(files, (relative) => relative);
301
+ if (expected.size !== files.length)
302
+ return false;
303
+ const seen = new Set();
304
+ let seenFiles = 0;
305
+ function visit(directory, parent) {
306
+ for (const [name, child] of directory.children) {
307
+ const relative = path.join(parent, name);
308
+ if (seen.has(relative))
309
+ return false;
310
+ seen.add(relative);
311
+ if (child.kind === "directory") {
312
+ if (!prefixes.has(relative) || !visit(child, relative))
313
+ return false;
314
+ }
315
+ else {
316
+ if (expected.get(relative) !== child.value)
317
+ return false;
318
+ seenFiles++;
319
+ }
320
+ }
321
+ return true;
322
+ }
323
+ return visit(image, "") && (!requireComplete || seenFiles === expected.size);
324
+ }
325
+ export async function ownedLegacyPostTree(target, files, requireComplete) {
326
+ if (!files.length)
327
+ return false;
328
+ const { expected, prefixes } = postTreePaths(files, mergePathIdentity);
329
+ const seen = new Set();
330
+ async function visit(directory) {
331
+ let stat;
332
+ try {
333
+ stat = await fs.lstat(directory);
334
+ }
335
+ catch {
336
+ return false;
337
+ }
338
+ if (!stat.isDirectory() || stat.isSymbolicLink())
339
+ return false;
340
+ for (const name of await fs.readdir(directory)) {
341
+ const child = path.join(directory, name);
342
+ const relative = mergePathIdentity(path.relative(target, child));
343
+ const stat = await fs.lstat(child);
344
+ if (stat.isDirectory() && !stat.isSymbolicLink()) {
345
+ if (!prefixes.has(relative) || !(await visit(child)))
346
+ return false;
347
+ }
348
+ else {
349
+ if (expected.get(relative) !== (await legacyImage(child)))
350
+ return false;
351
+ seen.add(relative);
352
+ }
353
+ }
354
+ return true;
355
+ }
356
+ return (await visit(target)) && (!requireComplete || [...expected.keys()].every((key) => seen.has(key)));
357
+ }
@@ -0,0 +1,50 @@
1
+ import { type SyncSelectionConfig } from "../sync/sync-policy.js";
2
+ import { type SessionRootTransition } from "./snapshot-root-transition.js";
3
+ import type { SnapshotSelection } from "./snapshot-types.js";
4
+ export declare const LEGACY_AGENT_DIRECTORY_JOURNAL_VERSION = 8;
5
+ export declare const FIXED_WORKSPACE_JOURNAL_VERSION = 9;
6
+ export declare const AGENT_DIRECTORY_JOURNAL_VERSION = 10;
7
+ export declare function isScopedJournal(journal: TransactionJournalPolicy): boolean;
8
+ export declare function isRecoveryStageId(value: unknown): value is string;
9
+ export declare function isScopedIdentity(value: unknown): value is string;
10
+ export interface TransactionJournalPolicy {
11
+ version: number;
12
+ exclude?: string[];
13
+ selection?: SnapshotSelection;
14
+ }
15
+ export declare function validateJournalPolicy(journal: TransactionJournalPolicy): void;
16
+ export declare function assertRecoveryPolicy(journal: TransactionJournalPolicy, options: SyncSelectionConfig): void;
17
+ export interface TransactionEntry {
18
+ target: string;
19
+ afterTarget?: string;
20
+ backupName: string;
21
+ kind: "missing" | "file" | "directory" | "symlink";
22
+ linkTarget?: string;
23
+ beforeImage?: string;
24
+ afterImage?: string;
25
+ postFiles?: {
26
+ relative: string;
27
+ image: string;
28
+ }[];
29
+ removalPending?: boolean;
30
+ replacementStarted?: boolean;
31
+ recoveryStaged?: boolean;
32
+ recoveryWorkspace?: string;
33
+ recoveryWorkspaceId?: string;
34
+ scopedRemoval?: {
35
+ image: "before" | "after";
36
+ identity: string;
37
+ };
38
+ vacantInstall?: string;
39
+ }
40
+ export interface TransactionJournal extends TransactionJournalPolicy {
41
+ completed?: boolean;
42
+ root: string;
43
+ sessionRoot?: string;
44
+ sessionRootTransition?: SessionRootTransition;
45
+ entries: TransactionEntry[];
46
+ }
47
+ export declare function validateJournal(directory: string, journal: TransactionJournal, sessionDir?: string): void;
48
+ export declare function transactionHasSessionTargets(journal: TransactionJournal): boolean;
49
+ export declare function isStrictlyInside(root: string, target: string): boolean;
50
+ export declare function assertAllowedTarget(root: string, sessionRoot: string | undefined, target: string): void;
@@ -0,0 +1,172 @@
1
+ import path from "node:path";
2
+ import { assertWithinRoot, isDeniedPath, isPathInside } from "../paths.js";
3
+ import { normalizeSyncExclude, sameSyncExclude } from "../sync/exclude-policy.js";
4
+ import { portableSnapshotSelection, syncDirectoryPolicyKey } from "../sync/sync-policy.js";
5
+ import { agentDir } from "./session-paths.js";
6
+ import { isCaseReplacement } from "./snapshot-case-replacement.js";
7
+ import { sessionStorageRoot } from "./snapshot-paths.js";
8
+ import { validateSessionRootTransition } from "./snapshot-root-transition.js";
9
+ export const LEGACY_AGENT_DIRECTORY_JOURNAL_VERSION = 8;
10
+ export const FIXED_WORKSPACE_JOURNAL_VERSION = 9;
11
+ export const AGENT_DIRECTORY_JOURNAL_VERSION = 10;
12
+ export function isScopedJournal(journal) {
13
+ return [
14
+ LEGACY_AGENT_DIRECTORY_JOURNAL_VERSION,
15
+ FIXED_WORKSPACE_JOURNAL_VERSION,
16
+ AGENT_DIRECTORY_JOURNAL_VERSION,
17
+ ].includes(journal.version);
18
+ }
19
+ export function isRecoveryStageId(value) {
20
+ return (typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/u.test(value));
21
+ }
22
+ export function isScopedIdentity(value) {
23
+ return typeof value === "string" && /^\d{1,20}:[1-9]\d{0,19}:\d{1,20}$/u.test(value);
24
+ }
25
+ export function validateJournalPolicy(journal) {
26
+ if (!journal || (![1, 2, 3, 4, 5, 6, 7].includes(journal.version) && !isScopedJournal(journal)))
27
+ throw new Error("Unsupported pi-sync transaction journal; preserve evidence for review.");
28
+ if (isScopedJournal(journal)) {
29
+ if (journal.exclude !== undefined || portableSnapshotSelection(journal.selection).version !== 3)
30
+ throw new Error("Invalid agent-directory transaction policy; preserve evidence.");
31
+ }
32
+ else if (journal.selection !== undefined) {
33
+ throw new Error("Unsupported pi-sync transaction journal policy; preserve evidence for review.");
34
+ }
35
+ if (journal.exclude !== undefined && !Array.isArray(journal.exclude))
36
+ throw new Error("Invalid transaction exclude policy; preserve evidence.");
37
+ normalizeSyncExclude(journal.exclude);
38
+ }
39
+ export function assertRecoveryPolicy(journal, options) {
40
+ const directoryKey = syncDirectoryPolicyKey(journal.selection ?? {});
41
+ const effectiveDirectoryKey = syncDirectoryPolicyKey(options);
42
+ if (directoryKey !== undefined
43
+ ? directoryKey === effectiveDirectoryKey
44
+ : effectiveDirectoryKey === undefined && sameSyncExclude(journal.exclude, options.exclude))
45
+ return;
46
+ throw new Error("Pending transaction has a different exclude policy or directory scope; preserve its backup for reviewed recovery.");
47
+ }
48
+ export function validateJournal(directory, journal, sessionDir) {
49
+ validateJournalPolicy(journal);
50
+ const wholeDirectory = isScopedJournal(journal);
51
+ if (!Array.isArray(journal.entries) || journal.entries.length > 16_384)
52
+ throw new Error("Unsupported pi-sync transaction journal; preserve evidence for review.");
53
+ if (journal.completed !== undefined &&
54
+ ((!wholeDirectory && ![6, 7].includes(journal.version)) || journal.completed !== true))
55
+ throw new Error("Invalid transaction completion evidence.");
56
+ const root = path.resolve(agentDir());
57
+ if (typeof journal.root !== "string" || path.resolve(journal.root) !== root)
58
+ throw new Error("Transaction root no longer matches the Pi agent directory.");
59
+ if (journal.sessionRootTransition !== undefined) {
60
+ if (journal.version !== 7 || typeof journal.sessionRoot !== "string")
61
+ throw new Error("Invalid session root-transition version.");
62
+ validateSessionRootTransition(journal.sessionRootTransition);
63
+ }
64
+ else if (journal.version === 7)
65
+ throw new Error("Missing session root-transition evidence.");
66
+ const trustedSessionRoot = sessionDir
67
+ ? path.resolve(sessionStorageRoot(root, sessionDir))
68
+ : path.join(root, "sessions");
69
+ if (wholeDirectory && journal.sessionRoot === undefined)
70
+ throw new Error("Missing agent-directory transaction session root evidence.");
71
+ if (journal.sessionRoot !== undefined &&
72
+ (typeof journal.sessionRoot !== "string" ||
73
+ !path.isAbsolute(journal.sessionRoot) ||
74
+ path.resolve(journal.sessionRoot) !== journal.sessionRoot ||
75
+ (!journal.completed &&
76
+ (wholeDirectory || transactionHasSessionTargets(journal)) &&
77
+ journal.sessionRoot !== trustedSessionRoot)))
78
+ throw new Error("Transaction session root is not owned by this context; preserve evidence for review.");
79
+ for (const entry of journal.entries) {
80
+ if (!entry ||
81
+ typeof entry.target !== "string" ||
82
+ !path.isAbsolute(entry.target) ||
83
+ path.resolve(entry.target) !== entry.target ||
84
+ typeof entry.backupName !== "string" ||
85
+ !/^\d+$/u.test(entry.backupName) ||
86
+ !["missing", "file", "directory", "symlink"].includes(entry.kind))
87
+ throw new Error("Invalid pi-sync transaction entry.");
88
+ assertWithinRoot(directory, path.join(directory, "before", entry.backupName));
89
+ assertAllowedTarget(root, journal.sessionRoot, entry.target);
90
+ if (entry.afterTarget !== undefined &&
91
+ ((!wholeDirectory && ![5, 6, 7].includes(journal.version)) ||
92
+ typeof entry.afterTarget !== "string" ||
93
+ !isCaseReplacement(root, entry.target, entry.afterTarget) ||
94
+ path.resolve(entry.afterTarget) !== entry.afterTarget ||
95
+ entry.kind !== "file"))
96
+ throw new Error("Invalid transaction case replacement evidence.");
97
+ if (entry.afterTarget)
98
+ assertAllowedTarget(root, journal.sessionRoot, entry.afterTarget);
99
+ if (journal.version >= 2 &&
100
+ ((entry.beforeImage === undefined ? !journal.completed : typeof entry.beforeImage !== "string") ||
101
+ (entry.afterImage === undefined ? !journal.completed : typeof entry.afterImage !== "string") ||
102
+ (entry.postFiles === undefined ? !journal.completed : !Array.isArray(entry.postFiles))))
103
+ throw new Error("Invalid transaction postimage evidence.");
104
+ if (entry.recoveryStaged !== undefined &&
105
+ (typeof entry.recoveryStaged !== "boolean" || journal.version >= FIXED_WORKSPACE_JOURNAL_VERSION))
106
+ throw new Error("Invalid recovery staging evidence.");
107
+ if (entry.removalPending !== undefined && (journal.version < 3 || typeof entry.removalPending !== "boolean"))
108
+ throw new Error("Invalid transaction removal evidence.");
109
+ if (entry.replacementStarted !== undefined &&
110
+ (journal.version < 4 || typeof entry.replacementStarted !== "boolean"))
111
+ throw new Error("Invalid transaction replacement evidence.");
112
+ if (entry.removalPending && entry.replacementStarted)
113
+ throw new Error("Conflicting transaction replacement evidence.");
114
+ if ((entry.recoveryWorkspace !== undefined &&
115
+ (journal.version < FIXED_WORKSPACE_JOURNAL_VERSION ||
116
+ !isScopedIdentity(entry.recoveryWorkspace) ||
117
+ entry.recoveryStaged ||
118
+ !["file", "directory"].includes(entry.kind))) ||
119
+ (entry.recoveryWorkspaceId !== undefined &&
120
+ (journal.version !== AGENT_DIRECTORY_JOURNAL_VERSION ||
121
+ !entry.recoveryWorkspace ||
122
+ !isRecoveryStageId(entry.recoveryWorkspaceId))) ||
123
+ (entry.scopedRemoval !== undefined &&
124
+ (journal.version < FIXED_WORKSPACE_JOURNAL_VERSION ||
125
+ !entry.removalPending ||
126
+ !["before", "after"].includes(entry.scopedRemoval?.image) ||
127
+ !isScopedIdentity(entry.scopedRemoval?.identity) ||
128
+ (entry.scopedRemoval.image === "before"
129
+ ? !["file", "directory"].includes(entry.kind)
130
+ : entry.afterImage === "missing" && !entry.postFiles?.length))) ||
131
+ (entry.vacantInstall !== undefined &&
132
+ (journal.version < FIXED_WORKSPACE_JOURNAL_VERSION ||
133
+ !entry.recoveryWorkspace ||
134
+ !isScopedIdentity(entry.vacantInstall) ||
135
+ entry.removalPending ||
136
+ entry.replacementStarted)))
137
+ throw new Error("Invalid scoped transaction progress evidence.");
138
+ for (const file of entry.postFiles ?? []) {
139
+ if (typeof file.relative !== "string" ||
140
+ typeof file.image !== "string" ||
141
+ !isStrictlyInside(entry.target, path.resolve(entry.target, file.relative)))
142
+ throw new Error("Invalid transaction subtree evidence.");
143
+ }
144
+ }
145
+ }
146
+ export function transactionHasSessionTargets(journal) {
147
+ const root = path.resolve(agentDir());
148
+ return (Array.isArray(journal.entries) &&
149
+ journal.entries.some((entry) => typeof entry?.target === "string" &&
150
+ (!isPathInside(root, entry.target) ||
151
+ isPathInside(path.join(root, "sessions"), entry.target) ||
152
+ (typeof journal.sessionRoot === "string" && isPathInside(journal.sessionRoot, entry.target)))));
153
+ }
154
+ export function isStrictlyInside(root, target) {
155
+ return path.relative(path.resolve(root), path.resolve(target)) !== "" && isPathInside(root, target);
156
+ }
157
+ export function assertAllowedTarget(root, sessionRoot, target) {
158
+ const resolved = path.resolve(target);
159
+ if (isStrictlyInside(root, resolved)) {
160
+ if (isDeniedPath(path.relative(root, resolved)))
161
+ throw new Error("Transaction targets denied private storage.");
162
+ assertWithinRoot(root, resolved);
163
+ return;
164
+ }
165
+ if (sessionRoot && isStrictlyInside(sessionRoot, resolved)) {
166
+ if (isDeniedPath(`sessions/${path.relative(sessionRoot, resolved)}`))
167
+ throw new Error("Transaction targets denied session storage.");
168
+ assertWithinRoot(sessionRoot, resolved);
169
+ return;
170
+ }
171
+ throw new Error("Transaction target is outside configured roots.");
172
+ }
@@ -0,0 +1,32 @@
1
+ import { type ScopedImage } from "./snapshot-transaction-images.js";
2
+ import { type TransactionEntry } from "./snapshot-transaction-policy.js";
3
+ interface Guards {
4
+ signal?: AbortSignal;
5
+ validateMutation?: () => void;
6
+ }
7
+ export declare function recoveryStagePath(directory: string, entry: TransactionEntry): string;
8
+ export declare function prepareLegacyRecoveryStage(directory: string, entry: TransactionEntry, options: Guards, persist: () => Promise<void>): Promise<string>;
9
+ export declare function assertNoUnclaimedLegacyStage(directory: string, entry: TransactionEntry, options: Guards): Promise<void>;
10
+ export declare function cleanScopedLegacyStage(directory: string, entry: TransactionEntry, options: Guards): Promise<void>;
11
+ export declare function inspectScopedRecoveryStage(directory: string, entry: TransactionEntry, options: Guards, requireStableWorkspace?: boolean): Promise<{
12
+ workspace: string;
13
+ backup: string;
14
+ source: ScopedImage;
15
+ payload: string;
16
+ image: ScopedImage;
17
+ scratch: string;
18
+ partial: {
19
+ kind: "file";
20
+ value: string;
21
+ stat: import("node:fs").BigIntStats;
22
+ } | {
23
+ kind: "missing";
24
+ value: "missing";
25
+ };
26
+ evidence: string;
27
+ container: string | undefined;
28
+ containerIdentity: string | undefined;
29
+ } | undefined>;
30
+ export declare function buildScopedRecoveryStage(directory: string, entry: TransactionEntry, options: Guards, persist: () => Promise<void>): Promise<void>;
31
+ export declare function cleanScopedWorkspace(directory: string, entry: TransactionEntry, options: Guards): Promise<void>;
32
+ export {};