@narumitw/pi-sync 0.63.0 → 0.64.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.
- package/CHANGELOG.md +24 -0
- package/README.md +28 -18
- package/dist/chunks/{chunk-HLCML3OW.ts → chunk-4VKWHVUO.ts} +4 -3
- package/dist/chunks/chunk-4VKWHVUO.ts.map +7 -0
- package/dist/chunks/{chunk-27F5W7DX.ts → chunk-DAZZ5BEJ.ts} +3 -1
- package/dist/chunks/chunk-DAZZ5BEJ.ts.map +7 -0
- package/dist/chunks/{chunk-V76KCWHO.ts → chunk-F3VODLVQ.ts} +3 -3
- package/dist/chunks/{chunk-VQ47JBLF.ts → chunk-FI2F5JBS.ts} +2 -2
- package/dist/chunks/{chunk-S6FUUWV5.ts → chunk-NDEZ52SS.ts} +13 -13
- package/dist/chunks/{chunk-S6FUUWV5.ts.map → chunk-NDEZ52SS.ts.map} +1 -1
- package/dist/chunks/{chunk-UGS6RYDZ.ts → chunk-RW44KNFD.ts} +304 -70
- package/dist/chunks/chunk-RW44KNFD.ts.map +7 -0
- package/dist/chunks/{chunk-EXDWEFIJ.ts → chunk-TJ7YNITN.ts} +5 -5
- package/dist/chunks/{chunk-HSCAFOT5.ts → chunk-TZMVSTAM.ts} +5 -5
- package/dist/chunks/{chunk-SXCH4Q5O.ts → chunk-VPSC7BXM.ts} +3 -3
- package/dist/chunks/chunk-YT6PDRMM.ts +282 -0
- package/dist/chunks/chunk-YT6PDRMM.ts.map +7 -0
- package/dist/chunks/{command-handler-VINMQ7ZM.ts → command-handler-N45GY7AV.ts} +39 -27
- package/dist/chunks/command-handler-N45GY7AV.ts.map +7 -0
- package/dist/chunks/{conflict-review-PCDFRIVB.ts → conflict-review-5E4M44BA.ts} +2 -2
- package/dist/chunks/{file-selection-KID23GAD.ts → file-selection-DDQN4LVD.ts} +9 -9
- package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts → manager-result-dispatcher-FKW55L7I.ts} +5 -5
- package/dist/chunks/{manager-ui-YHDECYKI.ts → manager-ui-EV23DPZQ.ts} +104 -77
- package/dist/chunks/manager-ui-EV23DPZQ.ts.map +7 -0
- package/dist/chunks/{merge-review-SGDLMVS4.ts → merge-review-6YSLSMGS.ts} +3 -2
- package/dist/chunks/ownership-recovery-UDDHSDSZ.ts +59 -0
- package/dist/chunks/ownership-recovery-UDDHSDSZ.ts.map +7 -0
- package/dist/chunks/{remote-selection-ui-GPITNEBF.ts → remote-selection-ui-N4NMWFT2.ts} +4 -4
- package/dist/chunks/{setup-switch-L54X5U5I.ts → setup-switch-HY7K3442.ts} +4 -4
- package/dist/chunks/{setup-wizard-YO4MCPUF.ts → setup-wizard-LEKDQ3HK.ts} +9 -9
- package/dist/chunks/{sync-inspection-H2WX5SUT.ts → sync-inspection-OS2LVOLV.ts} +5 -5
- package/dist/chunks/{sync-operations-2MZAYHL2.ts → sync-operations-D3MDJUQQ.ts} +2 -2
- package/dist/daemon/dist/cli.js +2 -0
- package/dist/daemon/dist/client-transport.js +66 -0
- package/dist/daemon/dist/client.js +116 -86
- package/dist/daemon/dist/consent.js +33 -11
- package/dist/daemon/dist/daemon-debug.js +33 -0
- package/dist/daemon/dist/daemon-recovery.js +75 -0
- package/dist/daemon/dist/engine/backends/git/git-backend.js +39 -12
- package/dist/daemon/dist/engine/backends/git/git-runner.js +6 -1
- package/dist/daemon/dist/engine/backends/git/git-storage.js +5 -9
- package/dist/daemon/dist/engine/backends/publication-encoding.js +19 -0
- package/dist/daemon/dist/engine/backends/s3/s3-backend.js +10 -12
- package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +15 -26
- package/dist/daemon/dist/engine/backends/webdav/webdav-client.js +10 -0
- package/dist/daemon/dist/engine/debug-log.js +134 -0
- package/dist/daemon/dist/engine/ignore/ignore-initialization.js +50 -14
- package/dist/daemon/dist/engine/ignore/ignore-settings.js +11 -14
- package/dist/daemon/dist/engine/ignore/ignore-source.js +1 -1
- package/dist/daemon/dist/engine/paths.js +7 -1
- package/dist/daemon/dist/engine/settings/config-file.js +62 -17
- package/dist/daemon/dist/engine/settings/config.js +49 -14
- package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +30 -8
- package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +3 -1
- package/dist/daemon/dist/engine/snapshot/snapshot-payload.js +32 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-transaction-images.js +34 -0
- package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +50 -7
- package/dist/daemon/dist/engine/snapshot/snapshot.js +64 -25
- package/dist/daemon/dist/engine/state/lock.js +157 -17
- package/dist/daemon/dist/engine/sync/continuous-sync.js +35 -11
- package/dist/daemon/dist/engine/sync/initialization.js +2 -2
- package/dist/daemon/dist/engine/sync/local-fields.js +42 -19
- package/dist/daemon/dist/engine/sync/merged-sync.js +13 -10
- package/dist/daemon/dist/engine/sync/remote-snapshot.js +18 -3
- package/dist/daemon/dist/engine/sync/session-push.js +13 -4
- package/dist/daemon/dist/engine/sync/startup-bootstrap.js +105 -0
- package/dist/daemon/dist/engine/sync/startup-recovery-evidence.js +37 -0
- package/dist/daemon/dist/engine/sync/startup-timings.js +80 -8
- package/dist/daemon/dist/engine/sync/sync-error-guidance.js +22 -4
- package/dist/daemon/dist/engine/sync/sync-inspection.js +4 -7
- package/dist/daemon/dist/engine/sync/sync-local.js +3 -1
- package/dist/daemon/dist/engine/sync/sync-mutations.js +13 -7
- package/dist/daemon/dist/engine/sync/sync-policy.js +9 -1
- package/dist/daemon/dist/engine/sync/sync-state.js +12 -4
- package/dist/daemon/dist/engine/ui/sync-format.js +23 -55
- package/dist/daemon/dist/engine/ui/transfer-review.js +3 -3
- package/dist/daemon/dist/engine-service.js +54 -10
- package/dist/daemon/dist/identity.js +36 -6
- package/dist/daemon/dist/index.js +2 -1
- package/dist/daemon/dist/monitor.js +20 -1
- package/dist/daemon/dist/paged-review.js +177 -0
- package/dist/daemon/dist/participant-ledger.js +149 -0
- package/dist/daemon/dist/protocol.js +4 -0
- package/dist/daemon/dist/server.js +268 -120
- package/dist/daemon/dist/service-host.js +29 -9
- package/dist/daemon/dist/state-wait-jobs.js +23 -0
- package/dist/daemon/dist/state-wait.js +34 -0
- package/dist/daemon/package.json +1 -1
- package/dist/index.ts +128 -48
- package/dist/index.ts.map +2 -2
- package/docs/continuous-sync-verification.md +2 -0
- package/docs/daemon-migration.md +30 -2
- package/docs/tui-contract.md +8 -2
- package/package.json +2 -2
- package/skills/configure-pi-sync/SKILL.md +119 -18
- package/skills/configure-pi-sync/references/configuration.md +88 -48
- package/src/commands/command-execution.ts +11 -3
- package/src/commands/command-handler.ts +10 -3
- package/src/commands/command.ts +3 -2
- package/src/daemon/client-debug.ts +45 -0
- package/src/daemon/ownership-recovery.ts +50 -0
- package/src/daemon/pi-client.ts +288 -63
- package/src/daemon/startup-bootstrap-client.ts +26 -0
- package/src/settings/config.ts +1 -0
- package/src/sync/automatic-sync.ts +61 -18
- package/src/sync/startup-check.ts +13 -5
- package/src/sync-extension.ts +46 -8
- package/src/ui/manager-state.ts +35 -24
- package/src/ui/manager-ui.ts +39 -18
- package/src/ui/merge-review.ts +75 -12
- package/src/ui/settings-ui.ts +2 -2
- package/src/ui/setup/webdav-ui.ts +1 -1
- package/src/ui/sync-confirmation.ts +81 -65
- package/src/ui/sync-setups-ui.ts +15 -12
- package/dist/chunks/chunk-27F5W7DX.ts.map +0 -7
- package/dist/chunks/chunk-GSQGBVKG.ts +0 -218
- package/dist/chunks/chunk-GSQGBVKG.ts.map +0 -7
- package/dist/chunks/chunk-HLCML3OW.ts.map +0 -7
- package/dist/chunks/chunk-UGS6RYDZ.ts.map +0 -7
- package/dist/chunks/command-handler-VINMQ7ZM.ts.map +0 -7
- package/dist/chunks/manager-ui-YHDECYKI.ts.map +0 -7
- /package/dist/chunks/{chunk-V76KCWHO.ts.map → chunk-F3VODLVQ.ts.map} +0 -0
- /package/dist/chunks/{chunk-VQ47JBLF.ts.map → chunk-FI2F5JBS.ts.map} +0 -0
- /package/dist/chunks/{chunk-EXDWEFIJ.ts.map → chunk-TJ7YNITN.ts.map} +0 -0
- /package/dist/chunks/{chunk-HSCAFOT5.ts.map → chunk-TZMVSTAM.ts.map} +0 -0
- /package/dist/chunks/{chunk-SXCH4Q5O.ts.map → chunk-VPSC7BXM.ts.map} +0 -0
- /package/dist/chunks/{conflict-review-PCDFRIVB.ts.map → conflict-review-5E4M44BA.ts.map} +0 -0
- /package/dist/chunks/{file-selection-KID23GAD.ts.map → file-selection-DDQN4LVD.ts.map} +0 -0
- /package/dist/chunks/{manager-result-dispatcher-GDB74IOP.ts.map → manager-result-dispatcher-FKW55L7I.ts.map} +0 -0
- /package/dist/chunks/{merge-review-SGDLMVS4.ts.map → merge-review-6YSLSMGS.ts.map} +0 -0
- /package/dist/chunks/{remote-selection-ui-GPITNEBF.ts.map → remote-selection-ui-N4NMWFT2.ts.map} +0 -0
- /package/dist/chunks/{setup-switch-L54X5U5I.ts.map → setup-switch-HY7K3442.ts.map} +0 -0
- /package/dist/chunks/{setup-wizard-YO4MCPUF.ts.map → setup-wizard-LEKDQ3HK.ts.map} +0 -0
- /package/dist/chunks/{sync-inspection-H2WX5SUT.ts.map → sync-inspection-OS2LVOLV.ts.map} +0 -0
- /package/dist/chunks/{sync-operations-2MZAYHL2.ts.map → sync-operations-D3MDJUQQ.ts.map} +0 -0
|
@@ -2,8 +2,11 @@ import { constants, lstatSync, realpathSync, unlinkSync } from "node:fs";
|
|
|
2
2
|
import fs from "node:fs/promises";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { DEFAULT_IGNORE_CREATION_RECORD, DEFAULT_IGNORE_FILENAME, DEFAULT_IGNORE_RULES, ignoreFileIdentity, readIgnoreSource, sameFile, sameIdentity, } from "./ignore-source.js";
|
|
5
|
-
const
|
|
6
|
-
const
|
|
5
|
+
const recordPrefix = "pi-sync-ignore-creation-v1\n";
|
|
6
|
+
const records = [
|
|
7
|
+
Buffer.from(`${recordPrefix}${DEFAULT_IGNORE_RULES}`),
|
|
8
|
+
Buffer.from(`${recordPrefix}/npm/\n/sessions/\n/auth.json\n/truth.json\n`),
|
|
9
|
+
];
|
|
7
10
|
const noFollow = (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
|
|
8
11
|
const openRead = constants.O_RDONLY | noFollow;
|
|
9
12
|
const openExisting = process.platform === "win32" ? constants.O_RDWR | noFollow : openRead;
|
|
@@ -28,10 +31,35 @@ export async function checkAutomaticIgnoreCreation(root, signal) {
|
|
|
28
31
|
signal.throwIfAborted();
|
|
29
32
|
}
|
|
30
33
|
}
|
|
34
|
+
function creationRecordToken(stat) {
|
|
35
|
+
return `${ignoreFileIdentity(stat)}:${stat.size}:${stat.ctimeNs}:${stat.mtimeNs}`;
|
|
36
|
+
}
|
|
37
|
+
export async function readPendingIgnoreCreation(root, signal) {
|
|
38
|
+
signal.throwIfAborted();
|
|
39
|
+
root = path.resolve(root);
|
|
40
|
+
const initialRoot = await fs.lstat(root, { bigint: true });
|
|
41
|
+
const checkRoot = () => {
|
|
42
|
+
signal.throwIfAborted();
|
|
43
|
+
assertRoot(root, initialRoot);
|
|
44
|
+
};
|
|
45
|
+
checkRoot();
|
|
46
|
+
const target = path.join(root, DEFAULT_IGNORE_CREATION_RECORD);
|
|
47
|
+
const prior = await fs.lstat(target, { bigint: true });
|
|
48
|
+
assertOwned(prior, DEFAULT_IGNORE_CREATION_RECORD, true);
|
|
49
|
+
const marker = await fs.open(target, openRead);
|
|
50
|
+
try {
|
|
51
|
+
const { stat, bytes } = await verifyCreationFile(marker, target, target, records, checkRoot, prior, false);
|
|
52
|
+
return { token: creationRecordToken(stat), text: bytes.toString("utf8", recordPrefix.length) };
|
|
53
|
+
}
|
|
54
|
+
finally {
|
|
55
|
+
await marker.close();
|
|
56
|
+
signal.throwIfAborted();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
31
59
|
export async function initializeDefaultIgnoreSource(root, signal) {
|
|
32
60
|
return (await prepareDefaultIgnoreSource(root, signal)).source;
|
|
33
61
|
}
|
|
34
|
-
export async function prepareDefaultIgnoreSource(root, signal) {
|
|
62
|
+
export async function prepareDefaultIgnoreSource(root, signal, reviewedCreation) {
|
|
35
63
|
signal?.throwIfAborted();
|
|
36
64
|
root = path.resolve(root);
|
|
37
65
|
try {
|
|
@@ -43,6 +71,10 @@ export async function prepareDefaultIgnoreSource(root, signal) {
|
|
|
43
71
|
};
|
|
44
72
|
checkRoot();
|
|
45
73
|
const priorRecord = statAt(path.join(root, DEFAULT_IGNORE_CREATION_RECORD));
|
|
74
|
+
if (reviewedCreation !== undefined &&
|
|
75
|
+
reviewedCreation !== (priorRecord ? creationRecordToken(priorRecord) : null)) {
|
|
76
|
+
changed(DEFAULT_IGNORE_CREATION_RECORD);
|
|
77
|
+
}
|
|
46
78
|
if (!priorRecord) {
|
|
47
79
|
const source = await readIgnoreSource(root, DEFAULT_IGNORE_FILENAME, signal);
|
|
48
80
|
checkRoot();
|
|
@@ -67,7 +99,8 @@ export async function prepareDefaultIgnoreSource(root, signal) {
|
|
|
67
99
|
throw error;
|
|
68
100
|
});
|
|
69
101
|
try {
|
|
70
|
-
const markerStat = await
|
|
102
|
+
const { stat: markerStat, bytes } = await verifyCreationFile(marker, markerPath, path.join(root, DEFAULT_IGNORE_CREATION_RECORD), records, priorRecord ? checkRoot : verifyRoot, priorRecord);
|
|
103
|
+
const starter = bytes.subarray(recordPrefix.length);
|
|
71
104
|
await flushDirectory();
|
|
72
105
|
checkRoot();
|
|
73
106
|
assertCurrent(markerPath, markerStat);
|
|
@@ -85,7 +118,7 @@ export async function prepareDefaultIgnoreSource(root, signal) {
|
|
|
85
118
|
});
|
|
86
119
|
try {
|
|
87
120
|
const checkTargetRoot = priorFile ? checkRoot : verifyRoot;
|
|
88
|
-
const fileStat = await
|
|
121
|
+
const { stat: fileStat } = await verifyCreationFile(file, target, path.join(root, DEFAULT_IGNORE_FILENAME), [starter], () => {
|
|
89
122
|
checkTargetRoot();
|
|
90
123
|
assertCurrent(markerPath, markerStat);
|
|
91
124
|
}, priorFile);
|
|
@@ -98,7 +131,7 @@ export async function prepareDefaultIgnoreSource(root, signal) {
|
|
|
98
131
|
checkRoot();
|
|
99
132
|
const source = await readIgnoreSource(root, DEFAULT_IGNORE_FILENAME, signal);
|
|
100
133
|
checkRoot();
|
|
101
|
-
if (source.identity !== ignoreFileIdentity(fileStat) || source.text !==
|
|
134
|
+
if (source.identity !== ignoreFileIdentity(fileStat) || source.text !== starter.toString("utf8")) {
|
|
102
135
|
changed(DEFAULT_IGNORE_FILENAME);
|
|
103
136
|
}
|
|
104
137
|
return { source, created: priorFile === undefined };
|
|
@@ -210,8 +243,9 @@ function assertOwned(stat, name, privateRecord) {
|
|
|
210
243
|
throw new Error(`unsafe "${name}"; preserve it for manual recovery`);
|
|
211
244
|
}
|
|
212
245
|
}
|
|
213
|
-
async function
|
|
246
|
+
async function verifyCreationFile(handle, target, canonical, expected, checkRoot, prior, persist = true) {
|
|
214
247
|
const name = path.basename(target);
|
|
248
|
+
const privateRecord = name === DEFAULT_IGNORE_CREATION_RECORD;
|
|
215
249
|
const opened = await handle.stat({ bigint: true });
|
|
216
250
|
assertOwned(opened, name, privateRecord);
|
|
217
251
|
if (prior && !sameFile(prior, opened))
|
|
@@ -221,15 +255,15 @@ async function flushAndVerify(handle, target, canonical, expected, checkRoot, pr
|
|
|
221
255
|
throw new Error(`use the exact on-disk filename "${name}"`);
|
|
222
256
|
checkRoot();
|
|
223
257
|
assertCurrent(target, opened);
|
|
224
|
-
if (!prior)
|
|
225
|
-
await handle.writeFile(expected);
|
|
258
|
+
if (!prior && persist)
|
|
259
|
+
await handle.writeFile(expected[0]);
|
|
226
260
|
const before = await handle.stat({ bigint: true });
|
|
227
261
|
assertOwned(before, name, privateRecord);
|
|
228
262
|
if (!(prior ? sameFile(opened, before) : sameIdentity(opened, before)))
|
|
229
263
|
changed(name);
|
|
230
264
|
checkRoot();
|
|
231
265
|
assertCurrent(target, before);
|
|
232
|
-
const observed = Buffer.alloc(expected.length + 1);
|
|
266
|
+
const observed = Buffer.alloc(Math.max(...expected.map((bytes) => bytes.length)) + 1);
|
|
233
267
|
let count = 0;
|
|
234
268
|
while (count < observed.length) {
|
|
235
269
|
checkRoot();
|
|
@@ -238,15 +272,17 @@ async function flushAndVerify(handle, target, canonical, expected, checkRoot, pr
|
|
|
238
272
|
break;
|
|
239
273
|
count += bytesRead;
|
|
240
274
|
}
|
|
241
|
-
|
|
275
|
+
const bytes = expected.find((candidate) => observed.subarray(0, count).equals(candidate));
|
|
276
|
+
if (!bytes) {
|
|
242
277
|
throw new Error(privateRecord
|
|
243
278
|
? `invalid creation record "${name}"; preserve it for manual recovery`
|
|
244
|
-
: `unfinished creation of "${name}"; move the incomplete file outside the Pi agent directory or restore the full starter rules, then retry confirmed setup or migration`);
|
|
279
|
+
: `unfinished creation of "${name}"; move the incomplete file outside the Pi agent directory or restore the full starter rules recorded in "${DEFAULT_IGNORE_CREATION_RECORD}", then retry confirmed setup or migration`);
|
|
245
280
|
}
|
|
246
|
-
|
|
281
|
+
if (persist)
|
|
282
|
+
await handle.sync();
|
|
247
283
|
if (!sameFile(before, await handle.stat({ bigint: true })))
|
|
248
284
|
changed(name);
|
|
249
285
|
checkRoot();
|
|
250
286
|
assertCurrent(target, before);
|
|
251
|
-
return before;
|
|
287
|
+
return { stat: before, bytes };
|
|
252
288
|
}
|
|
@@ -21,7 +21,7 @@ import { requireNoMergeJournal } from "../sync/merge-journal.js";
|
|
|
21
21
|
import { configuredSnapshotPathMatcher } from "../sync/sync-policy.js";
|
|
22
22
|
import { safeTerminalText, snapshotPathLabel } from "../ui/terminal-text.js";
|
|
23
23
|
import { compileEffectiveIgnorePolicy } from "./effective-ignore-policy.js";
|
|
24
|
-
import { AutomaticIgnoreCreationUnavailable, checkAutomaticIgnoreCreation, prepareDefaultIgnoreSource, } from "./ignore-initialization.js";
|
|
24
|
+
import { AutomaticIgnoreCreationUnavailable, checkAutomaticIgnoreCreation, prepareDefaultIgnoreSource, readPendingIgnoreCreation, } from "./ignore-initialization.js";
|
|
25
25
|
import { assertCurrentIgnoreMigrationOffer } from "./ignore-migration-prompt.js";
|
|
26
26
|
import { compileIgnoreRules, DEFAULT_IGNORE_CREATION_RECORD, DEFAULT_IGNORE_FILENAME, DEFAULT_IGNORE_RULES, IgnoreCreationPendingError, ignoreSourceDigest, readIgnoreSource, validateIgnoreFilename, } from "./ignore-source.js";
|
|
27
27
|
export function runIgnorePolicyChange(operation, payload, execution) {
|
|
@@ -93,18 +93,14 @@ async function readSetupSource(root, filename, signal) {
|
|
|
93
93
|
!(error instanceof Error) ||
|
|
94
94
|
!(error.cause instanceof IgnoreCreationPendingError))
|
|
95
95
|
throw error;
|
|
96
|
-
|
|
97
|
-
throw error;
|
|
98
|
-
const marker = await fs.lstat(path.join(root, DEFAULT_IGNORE_CREATION_RECORD), { bigint: true });
|
|
96
|
+
const { text, token } = await readPendingIgnoreCreation(root, signal);
|
|
99
97
|
signal.throwIfAborted();
|
|
100
|
-
if (!marker.isFile() || marker.nlink !== 1n)
|
|
101
|
-
throw error;
|
|
102
98
|
return {
|
|
103
99
|
filename,
|
|
104
100
|
present: false,
|
|
105
|
-
text
|
|
106
|
-
sourceDigest: ignoreSourceDigest(filename, false, Buffer.from(
|
|
107
|
-
pendingCreation:
|
|
101
|
+
text,
|
|
102
|
+
sourceDigest: ignoreSourceDigest(filename, false, Buffer.from(text)),
|
|
103
|
+
pendingCreation: token,
|
|
108
104
|
};
|
|
109
105
|
}
|
|
110
106
|
}
|
|
@@ -170,7 +166,7 @@ export async function prepareReviewedIgnoreSource(root, reviewed, execution) {
|
|
|
170
166
|
stale();
|
|
171
167
|
if (current.present)
|
|
172
168
|
return { source: current, created: false };
|
|
173
|
-
const prepared = await prepareDefaultIgnoreSource(root, execution.signal).catch((error) => {
|
|
169
|
+
const prepared = await prepareDefaultIgnoreSource(root, execution.signal, current.pendingCreation ?? null).catch((error) => {
|
|
174
170
|
execution.validate();
|
|
175
171
|
throw creationFailure(root, current, error);
|
|
176
172
|
});
|
|
@@ -342,11 +338,12 @@ export async function migrateIgnoreSetup(execution, setupName, offerToken) {
|
|
|
342
338
|
}));
|
|
343
339
|
}
|
|
344
340
|
function describeSource(source) {
|
|
345
|
-
if (source.
|
|
346
|
-
return "
|
|
347
|
-
|
|
348
|
-
? "
|
|
341
|
+
if (source.present)
|
|
342
|
+
return "Keep the existing rule file unchanged.";
|
|
343
|
+
const action = source.pendingCreation
|
|
344
|
+
? "Verify or complete the interrupted creation of the starter rules. Incomplete content will not be used."
|
|
349
345
|
: "Create the default rule file with the starter rules.";
|
|
346
|
+
return `${action}\n${source.text.trimEnd()}`;
|
|
350
347
|
}
|
|
351
348
|
function describeChanges(label, before, after) {
|
|
352
349
|
const oldPaths = new Set(before);
|
|
@@ -6,7 +6,7 @@ import ignore from "ignore";
|
|
|
6
6
|
import { isDeniedPath } from "../paths.js";
|
|
7
7
|
export const DEFAULT_IGNORE_FILENAME = ".syncignore";
|
|
8
8
|
export const DEFAULT_IGNORE_CREATION_RECORD = ".pi-sync.json.syncignore-creation";
|
|
9
|
-
export const DEFAULT_IGNORE_RULES = "/npm/\n/sessions/\n/
|
|
9
|
+
export const DEFAULT_IGNORE_RULES = "/auth.json\n/git/\n/npm/\n/sessions/\n/truth.json\n";
|
|
10
10
|
export const MAX_IGNORE_BYTES = 64 * 1024;
|
|
11
11
|
const MAX_MATCH_PATH_BYTES = 4_096;
|
|
12
12
|
const MATCH_CACHE_PATH_BUDGET = 2_048;
|
|
@@ -1,10 +1,16 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
|
+
export const DEBUG_LOG_FILENAME = "pi-sync.log";
|
|
3
|
+
export function isDebugLogPath(relativePath) {
|
|
4
|
+
const root = relativePath.split(/[/\\:]/u, 1)[0].toLowerCase();
|
|
5
|
+
return root.startsWith(DEBUG_LOG_FILENAME) && /^[ .]*$/u.test(root.slice(DEBUG_LOG_FILENAME.length));
|
|
6
|
+
}
|
|
2
7
|
export function isDeniedPath(relativePath) {
|
|
3
8
|
const normalized = toPosix(relativePath);
|
|
4
9
|
const lower = normalized.toLowerCase();
|
|
5
10
|
const segments = lower.split("/");
|
|
6
11
|
const base = path.posix.basename(lower);
|
|
7
|
-
return (
|
|
12
|
+
return (isDebugLogPath(normalized) ||
|
|
13
|
+
segments.includes("node_modules") ||
|
|
8
14
|
segments.includes(".git") ||
|
|
9
15
|
segments.includes(".pisync") ||
|
|
10
16
|
segments.includes("pi-sync") ||
|
|
@@ -24,6 +24,9 @@ const LOCKFILE_FS_ADAPTER = {
|
|
|
24
24
|
utimesSync,
|
|
25
25
|
};
|
|
26
26
|
let configUpdateQueue = Promise.resolve();
|
|
27
|
+
let pendingMutations = 0;
|
|
28
|
+
let mutationGeneration = 0;
|
|
29
|
+
let localReadLock;
|
|
27
30
|
let publishConfigFile = publishFileWithGuard;
|
|
28
31
|
let beforeConfigPublicationHook = async () => undefined;
|
|
29
32
|
let afterMissingConfigReadProbeHook = async () => undefined;
|
|
@@ -118,6 +121,31 @@ async function peekUnlocked(maxBytes, securePermissions = true) {
|
|
|
118
121
|
const filePath = (await pathExists(canonicalPath)) ? canonicalPath : legacyLocalConfigPath();
|
|
119
122
|
return readConfigDocumentIfExists(filePath, maxBytes, securePermissions);
|
|
120
123
|
}
|
|
124
|
+
export async function readLocalConfigForDiagnostics(root) {
|
|
125
|
+
if (pendingMutations)
|
|
126
|
+
return undefined;
|
|
127
|
+
const generation = mutationGeneration;
|
|
128
|
+
const canonical = path.join(root, CONFIG_FILE_NAME);
|
|
129
|
+
const legacy = path.join(root, LEGACY_CONFIG_FILE_NAME);
|
|
130
|
+
const filePath = (await pathExists(canonical)) ? canonical : legacy;
|
|
131
|
+
if (filePath === legacy)
|
|
132
|
+
await assertNoInterruptedConfigReplacement(canonical);
|
|
133
|
+
const document = await readConfigDocumentIfExists(filePath, MAX_SETTINGS_BYTES, false);
|
|
134
|
+
if (!document)
|
|
135
|
+
return undefined;
|
|
136
|
+
const locked = () => pendingMutations ||
|
|
137
|
+
mutationGeneration !== generation ||
|
|
138
|
+
(localReadLock !== canonical && lstatSync(configMutationLockPath(canonical), { throwIfNoEntry: false }));
|
|
139
|
+
return {
|
|
140
|
+
document,
|
|
141
|
+
stillCurrent() {
|
|
142
|
+
if (locked())
|
|
143
|
+
return false;
|
|
144
|
+
assertCurrentDocument(document, canonical, legacy);
|
|
145
|
+
return !locked();
|
|
146
|
+
},
|
|
147
|
+
};
|
|
148
|
+
}
|
|
121
149
|
async function readConfigDocumentIfExists(filePath, maxBytes, securePermissions = true) {
|
|
122
150
|
const snapshot = await readConfigSnapshotIfExists(filePath, maxBytes, securePermissions);
|
|
123
151
|
return snapshot ? { path: filePath, ...snapshot } : undefined;
|
|
@@ -136,7 +164,7 @@ export function withLockedLocalConfigDocument(run, signal, forWrite = false, { s
|
|
|
136
164
|
assertCurrentDocument(document);
|
|
137
165
|
});
|
|
138
166
|
});
|
|
139
|
-
});
|
|
167
|
+
}, forWrite);
|
|
140
168
|
}
|
|
141
169
|
export async function readMigratingLocalConfigDocument(validateForMigration) {
|
|
142
170
|
const authority = engineHost().config;
|
|
@@ -158,17 +186,24 @@ export async function readMigratingLocalConfigDocument(validateForMigration) {
|
|
|
158
186
|
}
|
|
159
187
|
async function withLocalConfigReadLockIfNeeded(read) {
|
|
160
188
|
if ((await pathExists(localConfigPath())) || (await pathExists(legacyLocalConfigPath()))) {
|
|
161
|
-
return withLocalConfigFileLock(read);
|
|
189
|
+
return withLocalConfigFileLock(read, true);
|
|
162
190
|
}
|
|
163
191
|
await afterMissingConfigReadProbeHook();
|
|
164
192
|
if (await pathExists(configMutationLockPath()))
|
|
165
|
-
return withLocalConfigFileLock(read);
|
|
193
|
+
return withLocalConfigFileLock(read, true);
|
|
166
194
|
await assertNoInterruptedConfigReplacement();
|
|
167
195
|
return read();
|
|
168
196
|
}
|
|
169
|
-
function
|
|
197
|
+
function beginConfigMutation() {
|
|
198
|
+
pendingMutations++;
|
|
199
|
+
mutationGeneration++;
|
|
200
|
+
return () => pendingMutations--;
|
|
201
|
+
}
|
|
202
|
+
function queueConfigOperation(run, mayMutate = false) {
|
|
170
203
|
// Mutation callbacks use the unlocked helpers below, never a queued public read.
|
|
171
|
-
const
|
|
204
|
+
const finished = mayMutate ? beginConfigMutation() : undefined;
|
|
205
|
+
const queued = configUpdateQueue.then(run);
|
|
206
|
+
const operation = finished ? queued.finally(finished) : queued;
|
|
172
207
|
configUpdateQueue = operation.then(() => undefined, () => undefined);
|
|
173
208
|
return operation;
|
|
174
209
|
}
|
|
@@ -218,7 +253,7 @@ export function updateLocalConfigDocument(defaultValue, update, validate, signal
|
|
|
218
253
|
await installPrivateConfigExclusively(localConfigPath(), serializedConfig(next), signal, review);
|
|
219
254
|
return next;
|
|
220
255
|
});
|
|
221
|
-
});
|
|
256
|
+
}, true);
|
|
222
257
|
}
|
|
223
258
|
export function createLocalConfigDocument(value, signal) {
|
|
224
259
|
const authority = engineHost().config;
|
|
@@ -239,13 +274,13 @@ export function createLocalConfigDocument(value, signal) {
|
|
|
239
274
|
throw error;
|
|
240
275
|
}
|
|
241
276
|
});
|
|
242
|
-
});
|
|
277
|
+
}, true);
|
|
243
278
|
}
|
|
244
279
|
export function replaceLocalConfigDocument(document, value) {
|
|
245
280
|
const authority = engineHost().config;
|
|
246
281
|
if (authority)
|
|
247
282
|
return authority.replace(document, value);
|
|
248
|
-
return queueConfigOperation(() => withLocalConfigFileLock(() => replaceLocalConfigDocumentUnlocked(document, value)));
|
|
283
|
+
return queueConfigOperation(() => withLocalConfigFileLock(() => replaceLocalConfigDocumentUnlocked(document, value)), true);
|
|
249
284
|
}
|
|
250
285
|
async function replaceLocalConfigDocumentUnlocked(document, value, signal, review) {
|
|
251
286
|
const nextBytes = serializedConfig(value);
|
|
@@ -353,6 +388,15 @@ async function prepareLocalConfigPath(validateForMigration) {
|
|
|
353
388
|
if (!legacy)
|
|
354
389
|
return canonicalPath;
|
|
355
390
|
validateForMigration(legacy.parsed);
|
|
391
|
+
const finished = beginConfigMutation();
|
|
392
|
+
try {
|
|
393
|
+
return await migrateLegacyConfig(canonicalPath, legacyPath, legacy);
|
|
394
|
+
}
|
|
395
|
+
finally {
|
|
396
|
+
finished();
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
async function migrateLegacyConfig(canonicalPath, legacyPath, legacy) {
|
|
356
400
|
let installedIdentity;
|
|
357
401
|
try {
|
|
358
402
|
installedIdentity = await installPrivateConfigExclusively(canonicalPath, legacy.bytes);
|
|
@@ -407,9 +451,7 @@ async function secureIgnoredLegacyIfPresent(filePath) {
|
|
|
407
451
|
await handle?.close().catch(() => undefined);
|
|
408
452
|
}
|
|
409
453
|
}
|
|
410
|
-
function assertCurrentDocument(document) {
|
|
411
|
-
const canonical = localConfigPath();
|
|
412
|
-
const legacy = legacyLocalConfigPath();
|
|
454
|
+
function assertCurrentDocument(document, canonical = localConfigPath(), legacy = legacyLocalConfigPath()) {
|
|
413
455
|
const filePath = lstatSync(canonical, { throwIfNoEntry: false }) ? canonical : legacy;
|
|
414
456
|
const before = lstatSync(filePath, { throwIfNoEntry: false });
|
|
415
457
|
if (!document) {
|
|
@@ -568,7 +610,7 @@ async function configSnapshotStillMatches(filePath, snapshot) {
|
|
|
568
610
|
return fileIdentityAndContentsMatch(filePath, snapshot.identity, snapshot.bytes);
|
|
569
611
|
}
|
|
570
612
|
export function quarantineAndRemoveConfigIfMatches(filePath, identity, expectedBytes) {
|
|
571
|
-
return queueConfigOperation(() => withLocalConfigFileLock(() => quarantineAndRemoveConfigIfMatchesUnlocked(filePath, identity, expectedBytes)));
|
|
613
|
+
return queueConfigOperation(() => withLocalConfigFileLock(() => quarantineAndRemoveConfigIfMatchesUnlocked(filePath, identity, expectedBytes)), true);
|
|
572
614
|
}
|
|
573
615
|
async function quarantineAndRemoveConfigIfMatchesUnlocked(filePath, identity, expectedBytes) {
|
|
574
616
|
const quarantinePath = path.join(path.dirname(filePath), `.${path.basename(filePath)}.${randomUUID()}.migration-retired`);
|
|
@@ -634,10 +676,10 @@ async function restoreQuarantinedConfig(filePath, quarantinePath) {
|
|
|
634
676
|
// Preserve the quarantine rather than risk deleting settings that changed concurrently.
|
|
635
677
|
}
|
|
636
678
|
}
|
|
637
|
-
function configMutationLockPath() {
|
|
638
|
-
return `${
|
|
679
|
+
function configMutationLockPath(configPath = localConfigPath()) {
|
|
680
|
+
return `${configPath}.mutation-lock`;
|
|
639
681
|
}
|
|
640
|
-
export async function withLocalConfigFileLock(run) {
|
|
682
|
+
export async function withLocalConfigFileLock(run, readOnly = false) {
|
|
641
683
|
const configPath = localConfigPath();
|
|
642
684
|
await fs.mkdir(path.dirname(configPath), { recursive: true });
|
|
643
685
|
let compromisedError;
|
|
@@ -652,6 +694,8 @@ export async function withLocalConfigFileLock(run) {
|
|
|
652
694
|
compromisedError = error;
|
|
653
695
|
},
|
|
654
696
|
});
|
|
697
|
+
if (readOnly)
|
|
698
|
+
localReadLock = configPath;
|
|
655
699
|
try {
|
|
656
700
|
await assertNoInterruptedConfigReplacement();
|
|
657
701
|
const result = await run();
|
|
@@ -660,6 +704,8 @@ export async function withLocalConfigFileLock(run) {
|
|
|
660
704
|
return result;
|
|
661
705
|
}
|
|
662
706
|
finally {
|
|
707
|
+
if (readOnly)
|
|
708
|
+
localReadLock = undefined;
|
|
663
709
|
await release();
|
|
664
710
|
}
|
|
665
711
|
}
|
|
@@ -701,8 +747,7 @@ async function renameFileWithoutReplacement(source, destination, signal) {
|
|
|
701
747
|
signal?.throwIfAborted();
|
|
702
748
|
await fs.rename(source, destination);
|
|
703
749
|
}
|
|
704
|
-
async function assertNoInterruptedConfigReplacement() {
|
|
705
|
-
const configPath = localConfigPath();
|
|
750
|
+
async function assertNoInterruptedConfigReplacement(configPath = localConfigPath()) {
|
|
706
751
|
if (await pathExists(configPath))
|
|
707
752
|
return;
|
|
708
753
|
let names;
|
|
@@ -33,7 +33,7 @@ async function operationalConfig(document, setupName, signal) {
|
|
|
33
33
|
return config;
|
|
34
34
|
if (engineHost().ignoreFileOperationsAvailable === false)
|
|
35
35
|
return requireLegacyOperationConfig(config);
|
|
36
|
-
return resolveOperationPolicy(config, setupName, signal, document);
|
|
36
|
+
return resolveOperationPolicy(config, setupName, signal, document && { kind: "checked", document });
|
|
37
37
|
}
|
|
38
38
|
export async function loadSettingsConfig(setupName) {
|
|
39
39
|
return configFromSettings(await readSettingsForCheck(), setupName);
|
|
@@ -56,10 +56,31 @@ export async function resolveIgnoreConfig(settings, setupName, signal) {
|
|
|
56
56
|
signal?.throwIfAborted();
|
|
57
57
|
return resolveOperationPolicy(configFromSettings(validateSettingsDocument(settings), setupName), setupName, signal);
|
|
58
58
|
}
|
|
59
|
+
export function createSettingsConfigView(document) {
|
|
60
|
+
const settings = validateSettingsDocument(document.parsed);
|
|
61
|
+
const ignoreNames = reservedIgnoreFilenames(settings);
|
|
62
|
+
const metadata = (setupName) => projectSettingsConfig(settings, setupName, () => ignoreNames);
|
|
63
|
+
let fingerprint;
|
|
64
|
+
return {
|
|
65
|
+
activeSetupName: settings.activeSyncSetup,
|
|
66
|
+
setupNames: Object.keys(settings.syncSetups),
|
|
67
|
+
metadata,
|
|
68
|
+
async observe(setupName, signal) {
|
|
69
|
+
signal?.throwIfAborted();
|
|
70
|
+
const config = metadata(setupName);
|
|
71
|
+
if (!config.reservedIgnoreNames)
|
|
72
|
+
return config;
|
|
73
|
+
if (engineHost().ignoreFileOperationsAvailable === false)
|
|
74
|
+
return requireLegacyOperationConfig(config);
|
|
75
|
+
fingerprint ??= settingsDocumentFingerprint(document);
|
|
76
|
+
return resolveOperationPolicy(config, setupName, signal, { kind: "view", fingerprint });
|
|
77
|
+
},
|
|
78
|
+
};
|
|
79
|
+
}
|
|
59
80
|
function settingsDocumentFingerprint(document) {
|
|
60
81
|
return documentFingerprint(document && { bytes: document.bytes.toString("base64"), identity: document.identity });
|
|
61
82
|
}
|
|
62
|
-
async function resolveOperationPolicy(config, setupName, signal,
|
|
83
|
+
async function resolveOperationPolicy(config, setupName, signal, settingsSource) {
|
|
63
84
|
if (!config.reservedIgnoreNames)
|
|
64
85
|
return config;
|
|
65
86
|
const root = getEngineRoot();
|
|
@@ -68,8 +89,9 @@ async function resolveOperationPolicy(config, setupName, signal, original) {
|
|
|
68
89
|
if (root !== getEngineRoot())
|
|
69
90
|
throw new Error("The Pi agent directory changed; reopen the review before continuing.");
|
|
70
91
|
};
|
|
71
|
-
const
|
|
72
|
-
const
|
|
92
|
+
const original = settingsSource?.kind === "checked" ? settingsSource.document : undefined;
|
|
93
|
+
const configDocumentFingerprint = settingsSource?.kind === "view" ? settingsSource.fingerprint : original && settingsDocumentFingerprint(original);
|
|
94
|
+
const settingsFingerprint = settingsSource?.kind === "view" ? undefined : syncCheckConfigFingerprint(config);
|
|
73
95
|
const validateSettings = (document) => {
|
|
74
96
|
validateRoot();
|
|
75
97
|
if ((original &&
|
|
@@ -81,16 +103,21 @@ async function resolveOperationPolicy(config, setupName, signal, original) {
|
|
|
81
103
|
};
|
|
82
104
|
const source = config.pathPolicy === "ignore-file" ? await readIgnoreSource(root, config.ignoreFile, signal) : undefined;
|
|
83
105
|
validateRoot();
|
|
84
|
-
if (
|
|
106
|
+
if (settingsSource && source && !source.present) {
|
|
85
107
|
throw new Error(`Ignore file is missing: ${safeTerminalText(path.join(root, source.filename))}. Create it and reopen Pi Sync; starter rules are only a preview.`);
|
|
86
108
|
}
|
|
87
109
|
if (original && source)
|
|
88
110
|
validateSettings(await readActiveLocalConfigDocumentForRepair());
|
|
89
|
-
|
|
111
|
+
const observed = {
|
|
90
112
|
...config,
|
|
91
113
|
...(configDocumentFingerprint ? { configDocumentFingerprint } : {}),
|
|
92
114
|
...(source ? { ignorePolicy: compileEffectiveIgnorePolicy(source, ignorePolicyInput(config)) } : {}),
|
|
93
115
|
...(source?.identity ? { ignoreSourceIdentity: source.identity } : {}),
|
|
116
|
+
};
|
|
117
|
+
if (settingsSource?.kind === "view")
|
|
118
|
+
return observed;
|
|
119
|
+
return {
|
|
120
|
+
...observed,
|
|
94
121
|
validateIgnorePolicy: async () => {
|
|
95
122
|
validateRoot();
|
|
96
123
|
await withLockedLocalConfigDocument(async (document, recheck) => {
|
|
@@ -121,7 +148,21 @@ function ignorePolicyInput(config) {
|
|
|
121
148
|
configuredFilenames: config.reservedIgnoreNames ?? [],
|
|
122
149
|
};
|
|
123
150
|
}
|
|
151
|
+
function reservedIgnoreFilenames(settings) {
|
|
152
|
+
const names = new Set();
|
|
153
|
+
for (const { sync } of Object.values(settings.syncSetups)) {
|
|
154
|
+
if (sync.pathPolicy === "ignore-file")
|
|
155
|
+
names.add(validateIgnoreFilename(sync.ignoreFile ?? DEFAULT_IGNORE_FILENAME).toLowerCase());
|
|
156
|
+
}
|
|
157
|
+
if (names.size === 0)
|
|
158
|
+
return undefined;
|
|
159
|
+
names.add(DEFAULT_IGNORE_FILENAME);
|
|
160
|
+
return [...names].sort();
|
|
161
|
+
}
|
|
124
162
|
export function configFromSettings(settings, setupName) {
|
|
163
|
+
return projectSettingsConfig(settings, setupName, () => reservedIgnoreFilenames(settings));
|
|
164
|
+
}
|
|
165
|
+
function projectSettingsConfig(settings, setupName, getReservedIgnoreNames) {
|
|
125
166
|
const selectedName = setupName ?? settings.activeSyncSetup;
|
|
126
167
|
if (!selectedName)
|
|
127
168
|
throw new Error("No sync setups are configured.");
|
|
@@ -134,17 +175,11 @@ export function configFromSettings(settings, setupName) {
|
|
|
134
175
|
if (!connection) {
|
|
135
176
|
throw new Error(`Invalid pi-sync settings: sync setup “${selectedName}” references missing storage connection “${connectionName}”.`);
|
|
136
177
|
}
|
|
137
|
-
const
|
|
138
|
-
for (const { sync } of Object.values(settings.syncSetups)) {
|
|
139
|
-
if (sync.pathPolicy === "ignore-file")
|
|
140
|
-
ignoreNames.add(validateIgnoreFilename(sync.ignoreFile ?? DEFAULT_IGNORE_FILENAME).toLowerCase());
|
|
141
|
-
}
|
|
142
|
-
if (ignoreNames.size > 0)
|
|
143
|
-
ignoreNames.add(DEFAULT_IGNORE_FILENAME);
|
|
178
|
+
const reservedIgnoreNames = getReservedIgnoreNames();
|
|
144
179
|
return {
|
|
145
180
|
...resolveSyncConfig(selectedName, setup, connectionName, connection, settings.onSwitch, settings.skipSecretScan ?? false, settings.showStatus ?? true),
|
|
146
181
|
debug: settings.debug ?? false,
|
|
147
|
-
...(
|
|
182
|
+
...(reservedIgnoreNames ? { reservedIgnoreNames } : {}),
|
|
148
183
|
};
|
|
149
184
|
}
|
|
150
185
|
/** A validated setup-facing projection used by manager and settings UI. */
|
|
@@ -4,7 +4,8 @@ import path from "node:path";
|
|
|
4
4
|
import { assertWithinRoot, isDeniedPath, isPathInside, parentPaths, safeJoin, toPosix } from "../paths.js";
|
|
5
5
|
import { syncDirectory } from "../state/json-file.js";
|
|
6
6
|
import { stateDir } from "../state/state-directory.js";
|
|
7
|
-
import {
|
|
7
|
+
import { collidingPaths } from "../sync/file-merge-planner.js";
|
|
8
|
+
import { assertSnapshotExcludesDebugLog, compileSyncPolicyExclude, requireLegacyTransferPolicy, sameSnapshotSelection, selectionForSnapshot, } from "../sync/sync-policy.js";
|
|
8
9
|
import { agentDir } from "./session-paths.js";
|
|
9
10
|
import { agentDirectoryConfiguredSessionDir, agentDirectoryInventory, createSnapshot, isSessionFilePath, isSessionPath, sessionStorageRoot, snapshotIncludesSessions, snapshotTarget, } from "./snapshot.js";
|
|
10
11
|
import { assertAgentDirectorySnapshotBound } from "./snapshot-bounds.js";
|
|
@@ -12,7 +13,7 @@ import { assertProjectedAgentDirectoryBudget } from "./snapshot-entry-projection
|
|
|
12
13
|
import { agentDirectoryPhysicalSessionPath, assertUnexcludedTargets } from "./snapshot-exclude-safety.js";
|
|
13
14
|
import { decodeBase64Strict } from "./snapshot-payload.js";
|
|
14
15
|
import { reviewedSnapshotPreimages } from "./snapshot-reviewed-preimages.js";
|
|
15
|
-
import { applySnapshotTransaction, recoverPendingSnapshotTransactions } from "./snapshot-transaction.js";
|
|
16
|
+
import { applySnapshotTransaction, recoverPendingSnapshotTransactions, } from "./snapshot-transaction.js";
|
|
16
17
|
import { ignorePolicyValidator } from "./snapshot-transaction-policy.js";
|
|
17
18
|
import { IGNORE_SNAPSHOT_VERSION, } from "./snapshot-types.js";
|
|
18
19
|
function sha256(value) {
|
|
@@ -22,6 +23,7 @@ function fileHashMap(snapshot) {
|
|
|
22
23
|
return Object.fromEntries(snapshot.files.map((file) => [file.path, file.sha256]));
|
|
23
24
|
}
|
|
24
25
|
function assertSnapshotApplyPolicy(snapshot, options) {
|
|
26
|
+
assertSnapshotExcludesDebugLog(snapshot);
|
|
25
27
|
if (snapshot.version !== IGNORE_SNAPSHOT_VERSION) {
|
|
26
28
|
requireLegacyTransferPolicy(snapshot);
|
|
27
29
|
if (options.ignorePolicy)
|
|
@@ -77,6 +79,16 @@ export async function applySnapshot(snapshot, protectedRelativePaths = new Set()
|
|
|
77
79
|
]);
|
|
78
80
|
}
|
|
79
81
|
const plan = await addTopLevelCaseVariantDeletes(root, protectSnapshotApplyPlan(root, preflightSnapshotApply(root, snapshot, current, options), protectedRelativePaths, sessionDir), snapshot, options);
|
|
82
|
+
const currentHashes = new Map(current.files.map(({ path, sha256 }) => [path, sha256]));
|
|
83
|
+
const dependencies = collidingPaths([...plan.deletes, ...plan.writes.map(({ target }) => target)].map(toPosix));
|
|
84
|
+
const unchangedHashes = new Map();
|
|
85
|
+
for (const file of snapshot.files) {
|
|
86
|
+
if (currentHashes.get(file.path) !== file.sha256)
|
|
87
|
+
continue;
|
|
88
|
+
const target = snapshotTarget(root, file.path, sessionDir);
|
|
89
|
+
if (!dependencies.has(toPosix(target)))
|
|
90
|
+
unchangedHashes.set(target, file.sha256);
|
|
91
|
+
}
|
|
80
92
|
if (inventory) {
|
|
81
93
|
assertProjectedAgentDirectoryBudget(inventory, {
|
|
82
94
|
deletes: plan.deletes,
|
|
@@ -85,8 +97,10 @@ export async function applySnapshot(snapshot, protectedRelativePaths = new Set()
|
|
|
85
97
|
{ target: stateDir(root) },
|
|
86
98
|
],
|
|
87
99
|
}, options);
|
|
88
|
-
await preflightSnapshotMutations(root, plan, sessionDir, options);
|
|
89
100
|
}
|
|
101
|
+
const skipped = inventory
|
|
102
|
+
? await preflightSnapshotMutations(root, plan, sessionDir, options, unchangedHashes)
|
|
103
|
+
: undefined;
|
|
90
104
|
if (options.reviewedLocal || inventory) {
|
|
91
105
|
const images = reviewedSnapshotPreimages(root, sessionDir, current.files, plan, inventory);
|
|
92
106
|
const reviewed = options.reviewedLocal;
|
|
@@ -102,9 +116,7 @@ export async function applySnapshot(snapshot, protectedRelativePaths = new Set()
|
|
|
102
116
|
transactionOptions.expectedPreimages.set(target, image);
|
|
103
117
|
}
|
|
104
118
|
}
|
|
105
|
-
|
|
106
|
-
await preflightSnapshotMutations(root, plan, sessionDir, options);
|
|
107
|
-
await applySnapshotTransaction(plan, transactionOptions);
|
|
119
|
+
await applySnapshotTransaction(plan, transactionOptions, skipped ?? (await preflightSnapshotMutations(root, plan, sessionDir, options, unchangedHashes)));
|
|
108
120
|
return appliedFileHashMap(snapshot, current, protectedRelativePaths);
|
|
109
121
|
}
|
|
110
122
|
function sameReviewedFiles(scanned, reviewed) {
|
|
@@ -242,7 +254,8 @@ function excludedApplyPath(root, options) {
|
|
|
242
254
|
return (relative) => excluded(relative) ||
|
|
243
255
|
(/^sessions(?:\/|$)/iu.test(relative) ? !isSessionFilePath(relative) : physicalSessionPath(relative));
|
|
244
256
|
}
|
|
245
|
-
export async function preflightSnapshotMutations(root, plan, sessionDir, options = {}) {
|
|
257
|
+
export async function preflightSnapshotMutations(root, plan, sessionDir, options = {}, unchangedHashes) {
|
|
258
|
+
const skipped = [];
|
|
246
259
|
assertMutationCurrent(options);
|
|
247
260
|
await assertUnexcludedTargets(root, [...plan.deletes, ...plan.writes.map((item) => item.target)], {
|
|
248
261
|
...options,
|
|
@@ -255,9 +268,17 @@ export async function preflightSnapshotMutations(root, plan, sessionDir, options
|
|
|
255
268
|
assertMutationCurrent(options);
|
|
256
269
|
}
|
|
257
270
|
for (const item of plan.writes) {
|
|
258
|
-
await prepareSnapshotWrite(rootForTarget(root, item.target, sessionDir), item.target, deletePaths, options);
|
|
271
|
+
const stat = await prepareSnapshotWrite(rootForTarget(root, item.target, sessionDir), item.target, deletePaths, options);
|
|
259
272
|
assertMutationCurrent(options);
|
|
273
|
+
const hash = unchangedHashes?.get(item.target);
|
|
274
|
+
if (hash !== undefined && stat?.isFile() && stat.nlink === 1) {
|
|
275
|
+
const canonical = await fs.realpath(item.target);
|
|
276
|
+
assertMutationCurrent(options);
|
|
277
|
+
if (canonical === item.target)
|
|
278
|
+
skipped.push({ ...item, preimage: `file:${hash}` });
|
|
279
|
+
}
|
|
260
280
|
}
|
|
281
|
+
return skipped;
|
|
261
282
|
}
|
|
262
283
|
function assertMutationCurrent(options) {
|
|
263
284
|
options.validateMutation?.();
|
|
@@ -296,6 +317,7 @@ async function prepareSnapshotWrite(root, target, deletePaths, options) {
|
|
|
296
317
|
if (stat?.isDirectory() && !deletePaths.has(target)) {
|
|
297
318
|
throw new Error(`Refusing to overwrite directory during snapshot apply: ${target}`);
|
|
298
319
|
}
|
|
320
|
+
return stat;
|
|
299
321
|
}
|
|
300
322
|
async function ensureSafeDirectory(root, directory, deletePaths, options) {
|
|
301
323
|
assertMutationCurrent(options);
|
|
@@ -4,7 +4,7 @@ import { pipeline } from "node:stream/promises";
|
|
|
4
4
|
import { promisify } from "node:util";
|
|
5
5
|
import { createGunzip, gzip } from "node:zlib";
|
|
6
6
|
import { throwIfAborted } from "../sync/signals.js";
|
|
7
|
-
import { snapshotSelectionInclude, validateSnapshotSelection } from "../sync/sync-policy.js";
|
|
7
|
+
import { assertSnapshotExcludesDebugLog, snapshotSelectionInclude, validateSnapshotSelection, } from "../sync/sync-policy.js";
|
|
8
8
|
import { IGNORE_SNAPSHOT_VERSION, isSupportedSnapshotVersion } from "./snapshot-types.js";
|
|
9
9
|
const VERSION = 1;
|
|
10
10
|
const MAX_DECOMPRESSED_SNAPSHOT_BYTES = 512 * 1024 * 1024;
|
|
@@ -12,6 +12,7 @@ const gzipAsync = promisify(gzip);
|
|
|
12
12
|
export async function encodeSnapshot(snapshot) {
|
|
13
13
|
if (!isSupportedSnapshotVersion(snapshot?.version))
|
|
14
14
|
throw new Error("Unsupported snapshot format.");
|
|
15
|
+
assertSnapshotExcludesDebugLog(snapshot);
|
|
15
16
|
if (snapshot.version !== IGNORE_SNAPSHOT_VERSION)
|
|
16
17
|
snapshotSelectionInclude(snapshot);
|
|
17
18
|
validateSnapshotSelection(snapshot);
|
|
@@ -46,6 +47,7 @@ export async function decodeSnapshot(buffer, options = {}) {
|
|
|
46
47
|
}
|
|
47
48
|
if (parsed.version === IGNORE_SNAPSHOT_VERSION && !isUtf8(payload))
|
|
48
49
|
throw new Error("Invalid snapshot UTF-8.");
|
|
50
|
+
assertSnapshotExcludesDebugLog(parsed);
|
|
49
51
|
validateSnapshotSelection(parsed);
|
|
50
52
|
if (parsed.version !== VERSION) {
|
|
51
53
|
const { normalizeLocalFields, validatePortableSnapshot } = await import("../sync/local-fields.js");
|