@narumitw/pi-sync-daemon 0.7.0 → 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 (74) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/README.md +16 -2
  3. package/dist/consent.js +21 -6
  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 +30 -9
  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/settings/config-file.d.ts +9 -2
  24. package/dist/engine/settings/config-file.js +124 -28
  25. package/dist/engine/settings/config.d.ts +3 -0
  26. package/dist/engine/settings/config.js +93 -7
  27. package/dist/engine/settings/settings-management.d.ts +2 -2
  28. package/dist/engine/settings/settings-management.js +16 -8
  29. package/dist/engine/settings/settings-types.d.ts +23 -2
  30. package/dist/engine/settings/settings-validation.js +23 -5
  31. package/dist/engine/snapshot/session-paths.d.ts +1 -1
  32. package/dist/engine/snapshot/session-paths.js +36 -13
  33. package/dist/engine/snapshot/snapshot-apply.d.ts +3 -3
  34. package/dist/engine/snapshot/snapshot-apply.js +23 -4
  35. package/dist/engine/snapshot/snapshot-codec.d.ts +1 -1
  36. package/dist/engine/snapshot/snapshot-codec.js +14 -5
  37. package/dist/engine/snapshot/snapshot-exclude-safety.d.ts +4 -2
  38. package/dist/engine/snapshot/snapshot-exclude-safety.js +76 -19
  39. package/dist/engine/snapshot/snapshot-transaction-images.d.ts +3 -1
  40. package/dist/engine/snapshot/snapshot-transaction-images.js +33 -3
  41. package/dist/engine/snapshot/snapshot-transaction-policy.d.ts +24 -1
  42. package/dist/engine/snapshot/snapshot-transaction-policy.js +106 -2
  43. package/dist/engine/snapshot/snapshot-transaction-verification.d.ts +7 -0
  44. package/dist/engine/snapshot/snapshot-transaction-verification.js +78 -0
  45. package/dist/engine/snapshot/snapshot-transaction.d.ts +1 -12
  46. package/dist/engine/snapshot/snapshot-transaction.js +86 -108
  47. package/dist/engine/snapshot/snapshot-types.d.ts +23 -1
  48. package/dist/engine/snapshot/snapshot-types.js +9 -1
  49. package/dist/engine/snapshot/snapshot.d.ts +6 -4
  50. package/dist/engine/snapshot/snapshot.js +91 -34
  51. package/dist/engine/state/state-types.d.ts +1 -0
  52. package/dist/engine/sync/continuous-sync.js +18 -3
  53. package/dist/engine/sync/continuous-watch.js +4 -1
  54. package/dist/engine/sync/initialization.js +3 -2
  55. package/dist/engine/sync/local-fields.d.ts +3 -1
  56. package/dist/engine/sync/local-fields.js +62 -1
  57. package/dist/engine/sync/merge-apply.js +35 -7
  58. package/dist/engine/sync/merge-journal.d.ts +18 -4
  59. package/dist/engine/sync/merge-journal.js +115 -8
  60. package/dist/engine/sync/merged-sync.d.ts +1 -1
  61. package/dist/engine/sync/merged-sync.js +103 -50
  62. package/dist/engine/sync/remote-snapshot.d.ts +9 -2
  63. package/dist/engine/sync/remote-snapshot.js +56 -17
  64. package/dist/engine/sync/sync-inspection.js +7 -5
  65. package/dist/engine/sync/sync-mutations.d.ts +2 -1
  66. package/dist/engine/sync/sync-mutations.js +110 -47
  67. package/dist/engine/sync/sync-policy.d.ts +24 -8
  68. package/dist/engine/sync/sync-policy.js +127 -16
  69. package/dist/engine/sync/sync-queries.js +8 -1
  70. package/dist/engine/sync/sync-state.d.ts +2 -2
  71. package/dist/engine/sync/sync-state.js +20 -2
  72. package/dist/engine-service.js +24 -2
  73. package/docs/architecture.md +22 -0
  74. package/package.json +2 -1
@@ -0,0 +1,186 @@
1
+ import { constants, lstatSync, realpathSync, unlinkSync } from "node:fs";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { DEFAULT_IGNORE_CREATION_RECORD, DEFAULT_IGNORE_FILENAME, DEFAULT_IGNORE_RULES, ignoreFileIdentity, readIgnoreSource, sameFile, sameIdentity, } from "./ignore-source.js";
5
+ const starter = Buffer.from(DEFAULT_IGNORE_RULES);
6
+ const record = Buffer.from(`pi-sync-ignore-creation-v1\n${DEFAULT_IGNORE_RULES}`);
7
+ const noFollow = (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0);
8
+ const openRead = constants.O_RDONLY | noFollow;
9
+ const openExclusive = constants.O_RDWR | constants.O_CREAT | constants.O_EXCL | noFollow;
10
+ export async function initializeDefaultIgnoreSource(root, signal) {
11
+ return (await prepareDefaultIgnoreSource(root, signal)).source;
12
+ }
13
+ export async function prepareDefaultIgnoreSource(root, signal) {
14
+ signal?.throwIfAborted();
15
+ root = path.resolve(root);
16
+ try {
17
+ const initialRoot = await fs.lstat(root, { bigint: true });
18
+ const assertRoot = () => {
19
+ const current = lstatSync(root, { bigint: true });
20
+ if (!current.isDirectory() || !sameIdentity(initialRoot, current) || realpathSync(root) !== root) {
21
+ throw new Error("the Pi agent directory is not canonical or changed during initialization");
22
+ }
23
+ };
24
+ const checkRoot = () => {
25
+ signal?.throwIfAborted();
26
+ assertRoot();
27
+ };
28
+ checkRoot();
29
+ const priorRecord = statAt(path.join(root, DEFAULT_IGNORE_CREATION_RECORD));
30
+ if (!priorRecord) {
31
+ const source = await readIgnoreSource(root, DEFAULT_IGNORE_FILENAME, signal);
32
+ checkRoot();
33
+ if (source.present)
34
+ return { source, created: false };
35
+ }
36
+ if (!constants.O_DIRECTORY || !constants.O_NOFOLLOW || !constants.O_NONBLOCK || process.platform === "win32") {
37
+ throw new Error("this platform does not support durable directory-relative creation; use an existing ignore file");
38
+ }
39
+ const directory = await fs.open(root, openRead | constants.O_DIRECTORY);
40
+ try {
41
+ if (!sameIdentity(initialRoot, await directory.stat({ bigint: true })))
42
+ changed("Pi agent directory");
43
+ const anchor = await directoryAnchor(directory, initialRoot);
44
+ checkRoot();
45
+ await directory.sync();
46
+ checkRoot();
47
+ const markerPath = path.join(anchor, DEFAULT_IGNORE_CREATION_RECORD);
48
+ const target = path.join(anchor, DEFAULT_IGNORE_FILENAME);
49
+ if (priorRecord)
50
+ assertOwned(priorRecord, DEFAULT_IGNORE_CREATION_RECORD, true);
51
+ else if (statAt(target))
52
+ changed(DEFAULT_IGNORE_FILENAME);
53
+ const marker = await fs.open(markerPath, priorRecord ? openRead : openExclusive, 0o600);
54
+ try {
55
+ const markerStat = await flushAndVerify(marker, markerPath, path.join(root, DEFAULT_IGNORE_CREATION_RECORD), record, priorRecord ? checkRoot : assertRoot, priorRecord, true);
56
+ await directory.sync();
57
+ checkRoot();
58
+ assertCurrent(markerPath, markerStat);
59
+ const priorFile = priorRecord ? statAt(target) : undefined;
60
+ if (priorFile)
61
+ assertOwned(priorFile, DEFAULT_IGNORE_FILENAME, false);
62
+ const file = await fs.open(target, priorFile ? openRead : openExclusive, 0o600).catch(async (cause) => {
63
+ if (!priorRecord && cause.code === "EEXIST") {
64
+ assertRoot();
65
+ assertCurrent(markerPath, markerStat);
66
+ unlinkSync(markerPath);
67
+ await directory.sync();
68
+ }
69
+ throw cause;
70
+ });
71
+ try {
72
+ const checkTargetRoot = priorFile ? checkRoot : assertRoot;
73
+ const fileStat = await flushAndVerify(file, target, path.join(root, DEFAULT_IGNORE_FILENAME), starter, () => {
74
+ checkTargetRoot();
75
+ assertCurrent(markerPath, markerStat);
76
+ }, priorFile);
77
+ await directory.sync();
78
+ checkTargetRoot();
79
+ assertCurrent(target, fileStat);
80
+ assertCurrent(markerPath, markerStat);
81
+ unlinkSync(markerPath);
82
+ await directory.sync();
83
+ checkRoot();
84
+ const source = await readIgnoreSource(root, DEFAULT_IGNORE_FILENAME, signal);
85
+ checkRoot();
86
+ if (source.identity !== ignoreFileIdentity(fileStat) || source.text !== DEFAULT_IGNORE_RULES) {
87
+ changed(DEFAULT_IGNORE_FILENAME);
88
+ }
89
+ return { source, created: priorFile === undefined };
90
+ }
91
+ finally {
92
+ await file.close();
93
+ }
94
+ }
95
+ finally {
96
+ await marker.close();
97
+ }
98
+ }
99
+ finally {
100
+ await directory.close();
101
+ signal?.throwIfAborted();
102
+ }
103
+ }
104
+ catch (cause) {
105
+ signal?.throwIfAborted();
106
+ const code = cause.code;
107
+ const detail = code === "EEXIST"
108
+ ? "a file or creation record appeared concurrently; review the current files and retry"
109
+ : code
110
+ ? "could not safely create or flush the file"
111
+ : cause.message;
112
+ throw new Error(`Ignore file "${DEFAULT_IGNORE_FILENAME}" initialization: ${detail}.`, { cause });
113
+ }
114
+ }
115
+ async function directoryAnchor(directory, expected) {
116
+ for (const base of ["/proc/self/fd", "/dev/fd"]) {
117
+ const candidate = `${base}/${directory.fd}`;
118
+ const observed = await fs.stat(`${candidate}/.`, { bigint: true }).catch((error) => {
119
+ if (["ENOENT", "ENOTDIR", "EACCES", "EPERM"].includes(error.code ?? ""))
120
+ return undefined;
121
+ throw error;
122
+ });
123
+ if (observed?.isDirectory() && sameIdentity(expected, observed))
124
+ return candidate;
125
+ }
126
+ throw new Error("directory-relative creation is unavailable; use an existing ignore file");
127
+ }
128
+ function statAt(target) {
129
+ return lstatSync(target, { bigint: true, throwIfNoEntry: false });
130
+ }
131
+ function changed(name) {
132
+ throw new Error(`"${name}" changed during initialization; review the current files and retry`);
133
+ }
134
+ function assertCurrent(target, expected) {
135
+ const current = statAt(target);
136
+ if (!current || !sameFile(expected, current))
137
+ changed(path.basename(target));
138
+ }
139
+ function assertOwned(stat, name, privateRecord) {
140
+ if (!stat.isFile() ||
141
+ stat.nlink !== 1n ||
142
+ (process.getuid && stat.uid !== BigInt(process.getuid())) ||
143
+ (privateRecord && (stat.mode & 63n) !== 0n)) {
144
+ throw new Error(`unsafe "${name}"; preserve it for manual recovery`);
145
+ }
146
+ }
147
+ async function flushAndVerify(handle, target, canonical, expected, checkRoot, prior, privateRecord = false) {
148
+ const name = path.basename(target);
149
+ const opened = await handle.stat({ bigint: true });
150
+ assertOwned(opened, name, privateRecord);
151
+ if (prior && !sameFile(prior, opened))
152
+ changed(name);
153
+ checkRoot();
154
+ if ((await fs.realpath(target)) !== canonical)
155
+ throw new Error(`use the exact on-disk filename "${name}"`);
156
+ checkRoot();
157
+ assertCurrent(target, opened);
158
+ if (!prior)
159
+ await handle.writeFile(expected);
160
+ const before = await handle.stat({ bigint: true });
161
+ assertOwned(before, name, privateRecord);
162
+ if (!(prior ? sameFile(opened, before) : sameIdentity(opened, before)))
163
+ changed(name);
164
+ checkRoot();
165
+ assertCurrent(target, before);
166
+ const observed = Buffer.alloc(expected.length + 1);
167
+ let count = 0;
168
+ while (count < observed.length) {
169
+ checkRoot();
170
+ const { bytesRead } = await handle.read(observed, count, observed.length - count, count);
171
+ if (bytesRead === 0)
172
+ break;
173
+ count += bytesRead;
174
+ }
175
+ if (count !== expected.length || !observed.subarray(0, count).equals(expected)) {
176
+ throw new Error(privateRecord
177
+ ? `invalid creation record "${name}"; preserve it for manual recovery`
178
+ : `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`);
179
+ }
180
+ await handle.sync();
181
+ if (!sameFile(before, await handle.stat({ bigint: true })))
182
+ changed(name);
183
+ checkRoot();
184
+ assertCurrent(target, before);
185
+ return before;
186
+ }
@@ -0,0 +1,7 @@
1
+ import { type Execution } from "../../protocol.js";
2
+ import { type LocalConfigDocument } from "../settings/config-file.js";
3
+ export declare function assertCurrentIgnoreMigrationOffer(document: LocalConfigDocument | undefined, root: string, setup: string, token: string): void;
4
+ export declare function readIgnoreMigrationOffer(payload: unknown, execution: Execution): Promise<{
5
+ token: string;
6
+ } | null>;
7
+ export declare function deferIgnoreMigrationOffer(payload: unknown, execution: Execution): Promise<true>;
@@ -0,0 +1,139 @@
1
+ import { createHash } from "node:crypto";
2
+ import { closeSync, constants, fstatSync, fsync, lstatSync, openSync, realpathSync } from "node:fs";
3
+ import path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import { documentFingerprint } from "../../document.js";
6
+ import { record } from "../../protocol.js";
7
+ import { getEngineRoot } from "../host.js";
8
+ import { withLockedLocalConfigDocument } from "../settings/config-file.js";
9
+ import { validateConfigName, validateSettingsDocument } from "../settings/settings-validation.js";
10
+ import { sameFile, sameIdentity } from "./ignore-source.js";
11
+ const MIGRATION_VERSION = 1;
12
+ const flush = promisify(fsync);
13
+ function markerPath(root, setup) {
14
+ const key = createHash("sha256")
15
+ .update(JSON.stringify([setup, MIGRATION_VERSION]))
16
+ .digest("hex");
17
+ return path.join(root, `.pi-sync.json.ignore-migration-${key}.deferred`);
18
+ }
19
+ function markerAt(target) {
20
+ const marker = lstatSync(target, { bigint: true, throwIfNoEntry: false });
21
+ if (marker &&
22
+ (!marker.isFile() ||
23
+ marker.nlink !== 1n ||
24
+ marker.size !== 0n ||
25
+ (process.getuid && marker.uid !== BigInt(process.getuid())) ||
26
+ (process.platform !== "win32" && (marker.mode & 63n) !== 0n) ||
27
+ realpathSync(target) !== target))
28
+ throw new Error(`Unsafe ignore migration deferral marker at "${target}"; preserve it for inspection.`);
29
+ return marker;
30
+ }
31
+ function eligibleToken(document, setup) {
32
+ if (!document)
33
+ return null;
34
+ const settings = validateSettingsDocument(document.parsed);
35
+ if (settings.activeSyncSetup !== setup ||
36
+ !Object.hasOwn(settings.syncSetups, setup) ||
37
+ settings.syncSetups[setup].sync.pathPolicy === "ignore-file")
38
+ return null;
39
+ const fingerprint = documentFingerprint({ bytes: document.bytes.toString("base64"), identity: document.identity });
40
+ return createHash("sha256")
41
+ .update(JSON.stringify([MIGRATION_VERSION, document.path, fingerprint]))
42
+ .digest("hex");
43
+ }
44
+ function stale() {
45
+ throw new Error("Ignore migration offer is stale; reopen Pi Sync.");
46
+ }
47
+ export function assertCurrentIgnoreMigrationOffer(document, root, setup, token) {
48
+ if (eligibleToken(document, setup) !== token || markerAt(markerPath(root, setup)))
49
+ stale();
50
+ }
51
+ function validateClient(execution) {
52
+ execution.validate();
53
+ const facts = execution.facts();
54
+ if (!execution.clientId || facts?.id !== execution.clientId || facts.mode !== "tui" || !facts.hasUI)
55
+ throw new Error("Ignore migration offers require an attached TUI client.");
56
+ }
57
+ function readRequest(payload, execution, fields) {
58
+ validateClient(execution);
59
+ if (!record(payload) ||
60
+ typeof payload.setup !== "string" ||
61
+ Object.keys(payload).some((key) => !fields.includes(key)))
62
+ throw new Error("Invalid ignore migration offer request.");
63
+ validateConfigName(payload.setup, "sync setup");
64
+ return payload.setup;
65
+ }
66
+ export async function readIgnoreMigrationOffer(payload, execution) {
67
+ const setup = readRequest(payload, execution, ["setup"]);
68
+ const result = await withLockedLocalConfigDocument(async (document, recheck) => {
69
+ validateClient(execution);
70
+ const token = eligibleToken(document, setup);
71
+ const deferred = token && markerAt(markerPath(getEngineRoot(), setup));
72
+ recheck();
73
+ return token && !deferred ? { token } : null;
74
+ }, execution.signal, false, { securePermissions: false });
75
+ validateClient(execution);
76
+ return result;
77
+ }
78
+ export function deferIgnoreMigrationOffer(payload, execution) {
79
+ const setup = readRequest(payload, execution, ["setup", "token"]);
80
+ if (!record(payload) || typeof payload.token !== "string" || !/^[a-f0-9]{64}$/u.test(payload.token))
81
+ throw new Error("Invalid ignore migration offer token.");
82
+ const { token } = payload;
83
+ return withLockedLocalConfigDocument(async (document, recheck) => {
84
+ validateClient(execution);
85
+ const root = getEngineRoot();
86
+ const target = markerPath(root, setup);
87
+ assertCurrentIgnoreMigrationOffer(document, root, setup, token);
88
+ await createMarker(root, target, () => {
89
+ if (execution.liveClients().some((peer) => peer.sessionFile && path.resolve(peer.sessionFile) === target))
90
+ throw new Error("Cannot defer ignore migration at a protected live session path.");
91
+ validateClient(execution);
92
+ recheck();
93
+ });
94
+ return true;
95
+ }, execution.signal, true, { securePermissions: false });
96
+ }
97
+ async function createMarker(root, target, beforeCreate) {
98
+ const noFollow = constants.O_NOFOLLOW ?? 0;
99
+ const directory = process.platform === "win32" ? undefined : openSync(root, constants.O_RDONLY | constants.O_DIRECTORY | noFollow);
100
+ try {
101
+ beforeCreate();
102
+ if (directory !== undefined &&
103
+ !sameIdentity(lstatSync(getEngineRoot(), { bigint: true }), fstatSync(directory, { bigint: true })))
104
+ throw new Error("The Pi agent directory changed before recording ignore migration deferral.");
105
+ const marker = openMarker(target, noFollow);
106
+ try {
107
+ const installed = fstatSync(marker, { bigint: true });
108
+ try {
109
+ await flush(marker);
110
+ if (directory !== undefined)
111
+ await flush(directory);
112
+ }
113
+ catch (cause) {
114
+ throw new Error("Ignore migration was deferred but marker durability could not be verified.", { cause });
115
+ }
116
+ getEngineRoot();
117
+ const current = markerAt(target);
118
+ if (!current || !sameFile(installed, current))
119
+ throw new Error("Ignore migration deferral marker changed during publication.");
120
+ }
121
+ finally {
122
+ closeSync(marker);
123
+ }
124
+ }
125
+ finally {
126
+ if (directory !== undefined)
127
+ closeSync(directory);
128
+ }
129
+ }
130
+ function openMarker(target, noFollow) {
131
+ try {
132
+ return openSync(target, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollow, 0o600);
133
+ }
134
+ catch (error) {
135
+ if (error.code === "EEXIST")
136
+ stale();
137
+ throw error;
138
+ }
139
+ }
@@ -0,0 +1,15 @@
1
+ import { type Execution } from "../../protocol.js";
2
+ import type { PiSyncSettingsV3 } from "../settings/settings-types.js";
3
+ import { type IgnoreSource } from "./ignore-source.js";
4
+ export declare function newIgnoreFilename(before: PiSyncSettingsV3 | undefined, next: PiSyncSettingsV3): string | undefined;
5
+ type ReviewedIgnoreSource = IgnoreSource & {
6
+ pendingCreation?: string;
7
+ };
8
+ export declare function reviewNewIgnoreSource(root: string, filename: string, execution: Execution): Promise<ReviewedIgnoreSource>;
9
+ export declare function prepareReviewedIgnoreSource(root: string, reviewed: ReviewedIgnoreSource, execution: Execution): Promise<{
10
+ source: IgnoreSource;
11
+ created: boolean;
12
+ }>;
13
+ export declare function switchIgnoreFile(execution: Execution, setupName: string, filename: string, expectedFilename: string): Promise<"cancelled" | "saved">;
14
+ export declare function migrateIgnoreSetup(execution: Execution, setupName: string, offerToken?: string): Promise<"cancelled" | "saved">;
15
+ export {};
@@ -0,0 +1,322 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { requireHandover } from "../../consent.js";
5
+ import { documentFingerprint } from "../../document.js";
6
+ import { MAX_REVIEW_BYTES } from "../../protocol.js";
7
+ import { createServiceContext } from "../../service-host.js";
8
+ import { createSyncBackend } from "../backends/backend-factory.js";
9
+ import { engineHost } from "../host.js";
10
+ import { configFromSettings } from "../settings/config.js";
11
+ import { peekLocalConfigDocument, updateLocalConfigDocument, } from "../settings/config-file.js";
12
+ import { validateSettingsDocument } from "../settings/settings-validation.js";
13
+ import { resolvedSnapshotOptionsForContext } from "../snapshot/session-paths.js";
14
+ import { createSnapshot } from "../snapshot/snapshot.js";
15
+ import { pendingTransactionEntries } from "../snapshot/snapshot-transaction-directory.js";
16
+ import { syncDirectory } from "../state/json-file.js";
17
+ import { withLock } from "../state/lock.js";
18
+ import { stateDir, withStateDirectoryAccess } from "../state/state-directory.js";
19
+ import { requireNoMergeJournal } from "../sync/merge-journal.js";
20
+ import { configuredSnapshotPathMatcher } from "../sync/sync-policy.js";
21
+ import { safeTerminalText } from "../ui/terminal-text.js";
22
+ import { compileEffectiveIgnorePolicy } from "./effective-ignore-policy.js";
23
+ import { prepareDefaultIgnoreSource } from "./ignore-initialization.js";
24
+ import { assertCurrentIgnoreMigrationOffer } from "./ignore-migration-prompt.js";
25
+ import { compileIgnoreRules, DEFAULT_IGNORE_CREATION_RECORD, DEFAULT_IGNORE_FILENAME, DEFAULT_IGNORE_RULES, IgnoreCreationPendingError, ignoreSourceDigest, readIgnoreSource, validateIgnoreFilename, } from "./ignore-source.js";
26
+ function sourceToken(document) {
27
+ return documentFingerprint(document ? { bytes: document.bytes.toString("base64"), identity: document.identity } : undefined);
28
+ }
29
+ function settingsReviewGuard(document, execution) {
30
+ const token = sourceToken(document);
31
+ return (candidate) => {
32
+ execution.validate();
33
+ if (document.path !== candidate?.path || token !== sourceToken(candidate))
34
+ stale();
35
+ };
36
+ }
37
+ function ignoreFilename(setup) {
38
+ return setup?.sync.pathPolicy === "ignore-file"
39
+ ? validateIgnoreFilename(setup.sync.ignoreFile ?? DEFAULT_IGNORE_FILENAME)
40
+ : undefined;
41
+ }
42
+ function configuredFilenames(settings) {
43
+ return Object.values(settings.syncSetups).flatMap((setup) => {
44
+ const filename = ignoreFilename(setup);
45
+ return filename ? [filename] : [];
46
+ });
47
+ }
48
+ export function newIgnoreFilename(before, next) {
49
+ let added;
50
+ for (const [name, setup] of Object.entries(next.syncSetups)) {
51
+ const previous = before && Object.hasOwn(before.syncSetups, name) ? before.syncSetups[name] : undefined;
52
+ const filename = ignoreFilename(setup);
53
+ if (previous && ignoreFilename(previous) !== filename) {
54
+ throw new Error("Use the reviewed Pi Sync ignore-file settings flow to change an existing setup policy.");
55
+ }
56
+ if (!previous && filename) {
57
+ if (added !== undefined)
58
+ throw new Error("Create one ignore-file setup at a time so its policy can be reviewed.");
59
+ added = filename;
60
+ }
61
+ }
62
+ return added;
63
+ }
64
+ async function readSetupSource(root, filename, signal) {
65
+ try {
66
+ return await readIgnoreSource(root, filename, signal);
67
+ }
68
+ catch (error) {
69
+ signal.throwIfAborted();
70
+ if (filename !== DEFAULT_IGNORE_FILENAME ||
71
+ !(error instanceof Error) ||
72
+ !(error.cause instanceof IgnoreCreationPendingError))
73
+ throw error;
74
+ if ((await fs.realpath(root)) !== root)
75
+ throw error;
76
+ const marker = await fs.lstat(path.join(root, DEFAULT_IGNORE_CREATION_RECORD), { bigint: true });
77
+ signal.throwIfAborted();
78
+ if (!marker.isFile() || marker.nlink !== 1n)
79
+ throw error;
80
+ return {
81
+ filename,
82
+ present: false,
83
+ text: DEFAULT_IGNORE_RULES,
84
+ sourceDigest: ignoreSourceDigest(filename, false, Buffer.from(DEFAULT_IGNORE_RULES)),
85
+ pendingCreation: `${marker.dev}:${marker.ino}:${marker.size}:${marker.ctimeNs}:${marker.mtimeNs}`,
86
+ };
87
+ }
88
+ }
89
+ export async function reviewNewIgnoreSource(root, filename, execution) {
90
+ const ctx = requireInteractive(execution);
91
+ const source = await readSetupSource(root, filename, execution.signal);
92
+ execution.validate();
93
+ compileIgnoreRules(source.text);
94
+ const description = describeSource(source);
95
+ if (!(await confirm(ctx, execution, "Review ignore-file policy", [
96
+ `Rules: ${safeTerminalText(path.join(root, filename))}`,
97
+ description,
98
+ "Every eligible path not excluded by the rules can be synced, including new files added later.",
99
+ "Saving this setup does not transfer files. Review the selected content before transferring.",
100
+ ].join("\n"))))
101
+ throw new Error("Setup cancelled; no settings or rule files were saved.");
102
+ return source;
103
+ }
104
+ export async function prepareReviewedIgnoreSource(root, reviewed, execution) {
105
+ execution.validate();
106
+ const current = await readSetupSource(root, reviewed.filename, execution.signal);
107
+ execution.validate();
108
+ if (current.sourceDigest !== reviewed.sourceDigest ||
109
+ current.identity !== reviewed.identity ||
110
+ current.pendingCreation !== reviewed.pendingCreation)
111
+ stale();
112
+ if (current.present)
113
+ return { source: current, created: false };
114
+ const prepared = await prepareDefaultIgnoreSource(root, execution.signal);
115
+ execution.validate();
116
+ if (!prepared.source.present ||
117
+ prepared.source.text !== reviewed.text ||
118
+ (!current.pendingCreation && !prepared.created))
119
+ stale();
120
+ return prepared;
121
+ }
122
+ export async function switchIgnoreFile(execution, setupName, filename, expectedFilename) {
123
+ const ctx = requireInteractive(execution);
124
+ filename = validateIgnoreFilename(filename);
125
+ expectedFilename = validateIgnoreFilename(expectedFilename);
126
+ await requireHandover(execution);
127
+ execution.validate();
128
+ return withStateDirectoryAccess(() => withLock("sync", async () => {
129
+ const document = await peekLocalConfigDocument();
130
+ execution.validate();
131
+ if (!document)
132
+ throw new Error("No Pi Sync settings are configured.");
133
+ const settings = validateSettingsDocument(document.parsed);
134
+ const setup = Object.hasOwn(settings.syncSetups, setupName) ? settings.syncSetups[setupName] : undefined;
135
+ if (ignoreFilename(setup) !== expectedFilename)
136
+ stale();
137
+ if (expectedFilename === filename)
138
+ return "saved";
139
+ if ((await pendingTransactionEntries()).some((entry) => entry.isDirectory()))
140
+ throw new Error("Resolve pending local recovery before changing the content policy.");
141
+ await requireNoMergeJournal(configFromSettings(settings, setupName));
142
+ const source = await readIgnoreSource(execution.root, filename, execution.signal);
143
+ execution.validate();
144
+ if (!source.present)
145
+ throw new Error(`Ignore file does not exist: ${safeTerminalText(path.join(execution.root, filename))}`);
146
+ compileIgnoreRules(source.text);
147
+ if (!(await confirm(ctx, execution, "Review changing the ignore file", [
148
+ `Setup: ${safeTerminalText(setupName)}`,
149
+ `Existing rule file to use: ${safeTerminalText(path.join(execution.root, filename))}`,
150
+ "Changing the file can add or remove paths from future transfers. No transfer starts when you save.",
151
+ ].join("\n"))))
152
+ return "cancelled";
153
+ await updateLocalConfigDocument(settings, (next) => {
154
+ next.syncSetups[setupName].sync.ignoreFile = filename;
155
+ return next;
156
+ }, validateSettingsDocument, execution.signal, settingsReviewGuard(document, execution), async () => {
157
+ await prepareReviewedIgnoreSource(execution.root, source, execution);
158
+ });
159
+ execution.committed();
160
+ return "saved";
161
+ }));
162
+ }
163
+ export async function migrateIgnoreSetup(execution, setupName, offerToken) {
164
+ const ctx = requireInteractive(execution);
165
+ await requireHandover(execution);
166
+ execution.validate();
167
+ return withStateDirectoryAccess(() => withLock("sync", async () => {
168
+ const document = await peekLocalConfigDocument();
169
+ execution.validate();
170
+ if (!document)
171
+ throw new Error("No Pi Sync settings to migrate.");
172
+ if (offerToken !== undefined)
173
+ assertCurrentIgnoreMigrationOffer(document, execution.root, setupName, offerToken);
174
+ const before = validateSettingsDocument(document.parsed);
175
+ const setup = Object.hasOwn(before.syncSetups, setupName) ? before.syncSetups[setupName] : undefined;
176
+ if (!setup || ignoreFilename(setup))
177
+ throw new Error("Choose a legacy Pi Sync setup to migrate.");
178
+ const previous = configFromSettings(before, setupName);
179
+ if ((await pendingTransactionEntries()).some((entry) => entry.isDirectory())) {
180
+ throw new Error("Resolve pending local recovery before changing the content policy.");
181
+ }
182
+ await requireNoMergeJournal(previous);
183
+ execution.validate();
184
+ const next = structuredClone(before);
185
+ const policy = next.syncSetups[setupName].sync;
186
+ const { include: _include, exclude: _exclude, reinclude: _reinclude, ...common } = policy;
187
+ const sessions = policy.scope === "agent-directory" ? policy.sessions === true : previous.include.includes("sessions");
188
+ next.syncSetups[setupName].sync = { ...common, scope: "agent-directory", sessions, pathPolicy: "ignore-file" };
189
+ next.version = 8;
190
+ validateSettingsDocument(next);
191
+ const source = await readSetupSource(execution.root, DEFAULT_IGNORE_FILENAME, execution.signal);
192
+ execution.validate();
193
+ const current = {
194
+ ...configFromSettings(next, setupName),
195
+ ignorePolicy: compileEffectiveIgnorePolicy(source, {
196
+ sessions,
197
+ configuredFilenames: configuredFilenames(next),
198
+ }),
199
+ };
200
+ const backend = await createSyncBackend(previous);
201
+ execution.validate();
202
+ const head = await backend.readHead(execution.signal);
203
+ execution.validate();
204
+ const remote = head ? await backend.readSnapshot(head.snapshotRef, execution.signal) : undefined;
205
+ execution.validate();
206
+ if (head && remote?.id !== head.snapshotId)
207
+ throw new Error("The remote snapshot changed during inspection.");
208
+ const collectPaths = async (config) => {
209
+ const options = await resolvedSnapshotOptionsForContext(ctx, config, execution.signal);
210
+ execution.validate();
211
+ const image = await createSnapshot(config.snapshotIdentity, options);
212
+ execution.validate();
213
+ return image.files.map(({ path }) => path).sort();
214
+ };
215
+ const collect = async (createdStarter) => {
216
+ const oldPaths = (await collectPaths(previous)).filter((name) => name !== createdStarter);
217
+ const newPaths = await collectPaths(current);
218
+ const fingerprint = createHash("sha256")
219
+ .update(JSON.stringify([oldPaths, newPaths]))
220
+ .digest("hex");
221
+ return { oldPaths, newPaths, fingerprint };
222
+ };
223
+ const review = await collect();
224
+ execution.validate();
225
+ const remotePaths = remote?.files.map(({ path }) => path) ?? [];
226
+ const content = [
227
+ `Destination: ${safeTerminalText(backend.destination)}`,
228
+ `Ignore file: ${safeTerminalText(path.join(execution.root, source.filename))}`,
229
+ describeSource(source),
230
+ "Directory-wide selection also applies to future files. Legacy rules are not translated automatically.",
231
+ "Migration changes this setup only. No transfer starts and retained history is not erased.",
232
+ ...describeChanges("Local", review.oldPaths, review.newPaths),
233
+ ...(remote
234
+ ? describeChanges("Remote", remotePaths.filter(configuredSnapshotPathMatcher(previous)), remotePaths.filter(configuredSnapshotPathMatcher(current)))
235
+ : ["Remote: no published snapshot."]),
236
+ ].join("\n");
237
+ if (!(await confirm(ctx, execution, "Review migration to ignore-file policy", content)))
238
+ return "cancelled";
239
+ const verifyHead = (fresh) => {
240
+ if (head
241
+ ? !fresh || head.snapshotId !== fresh.snapshotId || !backend.sameRevision(head.revision, fresh.revision)
242
+ : fresh)
243
+ stale();
244
+ };
245
+ await updateLocalConfigDocument(next, () => next, validateSettingsDocument, execution.signal, settingsReviewGuard(document, execution), async () => {
246
+ verifyHead(await backend.readHead(execution.signal));
247
+ execution.validate();
248
+ if (!source.present && (await collect()).fingerprint !== review.fingerprint)
249
+ stale();
250
+ execution.validate();
251
+ const { source: prepared, created } = await prepareReviewedIgnoreSource(execution.root, source, execution);
252
+ execution.validate();
253
+ await preserveLegacySettings(document);
254
+ execution.validate();
255
+ verifyHead(await backend.readHead(execution.signal));
256
+ execution.validate();
257
+ if ((await collect(created ? prepared.filename : undefined)).fingerprint !== review.fingerprint)
258
+ stale();
259
+ execution.validate();
260
+ verifyHead(await backend.readHead(execution.signal));
261
+ execution.validate();
262
+ const finalSource = await readIgnoreSource(execution.root, source.filename, execution.signal);
263
+ execution.validate();
264
+ if (!finalSource.present ||
265
+ finalSource.sourceDigest !== prepared.sourceDigest ||
266
+ finalSource.identity !== prepared.identity)
267
+ stale();
268
+ });
269
+ execution.committed();
270
+ return "saved";
271
+ }));
272
+ }
273
+ function describeSource(source) {
274
+ if (source.pendingCreation)
275
+ return "Verify or complete the interrupted creation of the starter rules. Incomplete content will not be used.";
276
+ return source.present
277
+ ? "Keep the existing rule file unchanged."
278
+ : "Create the default rule file with the starter rules.";
279
+ }
280
+ function describeChanges(label, before, after) {
281
+ const oldPaths = new Set(before);
282
+ const newPaths = new Set(after);
283
+ return [
284
+ `${label} — enters scope:`,
285
+ ...difference(newPaths, oldPaths),
286
+ `${label} — leaves scope:`,
287
+ ...difference(oldPaths, newPaths),
288
+ ];
289
+ }
290
+ function difference(left, right) {
291
+ const paths = [...left].filter((item) => !right.has(item)).sort();
292
+ return paths.length ? paths.map((item) => ` ${safeTerminalText(item)}`) : [" none"];
293
+ }
294
+ async function preserveLegacySettings(document) {
295
+ const directory = stateDir();
296
+ const target = path.join(directory, `settings-before-ignore-${randomUUID()}.json`);
297
+ const file = await fs.open(target, "wx", 0o600);
298
+ try {
299
+ await file.writeFile(document.bytes);
300
+ await file.sync();
301
+ }
302
+ finally {
303
+ await file.close();
304
+ }
305
+ await syncDirectory(directory);
306
+ }
307
+ function requireInteractive(execution) {
308
+ const ctx = createServiceContext(execution);
309
+ if (!ctx.hasUI || !["tui", "rpc"].includes(ctx.mode))
310
+ throw new Error("This policy change requires an interactive review.");
311
+ return ctx;
312
+ }
313
+ async function confirm(ctx, execution, title, content) {
314
+ if (Buffer.byteLength(content) > MAX_REVIEW_BYTES)
315
+ throw new Error("The policy review exceeds its supported size; no changes were saved.");
316
+ const result = await engineHost().review(ctx, { title, content, confirmationLabel: "Save local policy" }, execution.signal, () => !execution.signal.aborted);
317
+ execution.validate();
318
+ return result;
319
+ }
320
+ function stale() {
321
+ throw new Error("Settings, rule source, or visible content changed. Reopen the Pi Sync policy review.");
322
+ }