@narumitw/pi-sync 0.62.0 → 0.63.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 (110) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +29 -15
  3. package/dist/chunks/{chunk-MNYRU5U5.ts → chunk-27F5W7DX.ts} +3 -2
  4. package/dist/chunks/{chunk-MNYRU5U5.ts.map → chunk-27F5W7DX.ts.map} +2 -2
  5. package/dist/chunks/chunk-CKUGCBHP.ts +114 -0
  6. package/dist/chunks/chunk-CKUGCBHP.ts.map +7 -0
  7. package/dist/chunks/chunk-EJDDRS6O.ts +17 -0
  8. package/dist/chunks/chunk-EJDDRS6O.ts.map +7 -0
  9. package/dist/chunks/{chunk-6PFZUEUG.ts → chunk-EXDWEFIJ.ts} +52 -135
  10. package/dist/chunks/chunk-EXDWEFIJ.ts.map +7 -0
  11. package/dist/chunks/{chunk-NHFGAZEC.ts → chunk-HSCAFOT5.ts} +7 -7
  12. package/dist/chunks/chunk-HSCAFOT5.ts.map +7 -0
  13. package/dist/chunks/chunk-MANNB4WZ.ts +36 -0
  14. package/dist/chunks/chunk-MANNB4WZ.ts.map +7 -0
  15. package/dist/chunks/{chunk-ZB3GNX3P.ts → chunk-S6FUUWV5.ts} +139 -12
  16. package/dist/chunks/chunk-S6FUUWV5.ts.map +7 -0
  17. package/dist/chunks/{chunk-PWESMTH6.ts → chunk-SXCH4Q5O.ts} +38 -20
  18. package/dist/chunks/chunk-SXCH4Q5O.ts.map +7 -0
  19. package/dist/chunks/{chunk-INECVQNR.ts → chunk-UGS6RYDZ.ts} +5 -3
  20. package/dist/chunks/chunk-UGS6RYDZ.ts.map +7 -0
  21. package/dist/chunks/{chunk-3E3TR3JE.ts → chunk-V76KCWHO.ts} +6 -4
  22. package/dist/chunks/{chunk-3E3TR3JE.ts.map → chunk-V76KCWHO.ts.map} +1 -1
  23. package/dist/chunks/{chunk-GSCZ4VXV.ts → chunk-VQ47JBLF.ts} +2 -2
  24. package/dist/chunks/chunk-WFBHWYI6.ts +18 -0
  25. package/dist/chunks/chunk-WFBHWYI6.ts.map +7 -0
  26. package/dist/chunks/{command-handler-6ATREPG7.ts → command-handler-VINMQ7ZM.ts} +19 -36
  27. package/dist/chunks/command-handler-VINMQ7ZM.ts.map +7 -0
  28. package/dist/chunks/{conflict-review-MAOGTIAI.ts → conflict-review-PCDFRIVB.ts} +2 -2
  29. package/dist/chunks/{file-selection-QR2KZVGD.ts → file-selection-KID23GAD.ts} +15 -8
  30. package/dist/chunks/file-selection-KID23GAD.ts.map +7 -0
  31. package/dist/chunks/{manager-result-dispatcher-MC6EQOQY.ts → manager-result-dispatcher-GDB74IOP.ts} +6 -5
  32. package/dist/chunks/{manager-ui-AOFUNXAJ.ts → manager-ui-YHDECYKI.ts} +197 -322
  33. package/dist/chunks/manager-ui-YHDECYKI.ts.map +7 -0
  34. package/dist/chunks/{remote-selection-ui-4BTP2OJR.ts → remote-selection-ui-GPITNEBF.ts} +5 -4
  35. package/dist/chunks/{setup-switch-Y6AMFFNK.ts → setup-switch-L54X5U5I.ts} +4 -4
  36. package/dist/chunks/{setup-wizard-5G426MOZ.ts → setup-wizard-YO4MCPUF.ts} +7 -3
  37. package/dist/chunks/{setup-wizard-5G426MOZ.ts.map → setup-wizard-YO4MCPUF.ts.map} +1 -1
  38. package/dist/chunks/{sync-inspection-ITZ6Z4DE.ts → sync-inspection-H2WX5SUT.ts} +3 -3
  39. package/dist/chunks/{sync-operations-NMVKF7SE.ts → sync-operations-2MZAYHL2.ts} +2 -2
  40. package/dist/daemon/dist/cli.js +1 -1
  41. package/dist/daemon/dist/consent.js +134 -16
  42. package/dist/daemon/dist/engine/backends/git/git-backend.js +61 -30
  43. package/dist/daemon/dist/engine/ignore/ignore-initialization.js +93 -27
  44. package/dist/daemon/dist/engine/ignore/ignore-settings.js +85 -14
  45. package/dist/daemon/dist/engine/settings/config-file.js +1 -1
  46. package/dist/daemon/dist/engine/settings/config.js +71 -28
  47. package/dist/daemon/dist/engine/settings/settings-management.js +8 -2
  48. package/dist/daemon/dist/engine/snapshot/session-paths.js +7 -2
  49. package/dist/daemon/dist/engine/snapshot/snapshot-transaction-policy.js +37 -17
  50. package/dist/daemon/dist/engine/snapshot/snapshot-transaction.js +55 -13
  51. package/dist/daemon/dist/engine/sync/agent-plan.js +1 -0
  52. package/dist/daemon/dist/engine/sync/agent-sync.js +8 -1
  53. package/dist/daemon/dist/engine/sync/continuous-sync.js +32 -15
  54. package/dist/daemon/dist/engine/sync/merge-acceptance.js +29 -0
  55. package/dist/daemon/dist/engine/sync/merge-apply.js +7 -4
  56. package/dist/daemon/dist/engine/sync/merge-journal.js +33 -14
  57. package/dist/daemon/dist/engine/sync/merged-sync.js +31 -39
  58. package/dist/daemon/dist/engine/sync/remote-snapshot.js +17 -2
  59. package/dist/daemon/dist/engine/sync/session-push.js +20 -6
  60. package/dist/daemon/dist/engine/sync/sync-mutations.js +71 -50
  61. package/dist/daemon/dist/engine/sync/sync-policy.js +28 -3
  62. package/dist/daemon/dist/engine/sync/sync-state.js +3 -8
  63. package/dist/daemon/dist/engine/sync/transfer-freshness.js +82 -0
  64. package/dist/daemon/dist/engine-service.js +124 -27
  65. package/dist/daemon/dist/monitor.js +84 -32
  66. package/dist/daemon/dist/server.js +46 -5
  67. package/dist/daemon/dist/service-host.js +2 -1
  68. package/dist/daemon/package.json +1 -1
  69. package/dist/index.ts +28 -25
  70. package/dist/index.ts.map +4 -4
  71. package/package.json +3 -3
  72. package/skills/configure-pi-sync/SKILL.md +17 -64
  73. package/skills/configure-pi-sync/references/configuration.md +60 -20
  74. package/src/commands/command-execution.ts +12 -8
  75. package/src/commands/command-types.ts +1 -0
  76. package/src/daemon/pi-client.ts +4 -2
  77. package/src/settings/config.ts +1 -0
  78. package/src/sync/automatic-sync.ts +9 -2
  79. package/src/sync/setup-switch.ts +38 -15
  80. package/src/sync/startup-check.ts +7 -4
  81. package/src/ui/excluded-paths-ui.ts +2 -2
  82. package/src/ui/file-selection.ts +7 -2
  83. package/src/ui/ignore-file-guidance.ts +7 -0
  84. package/src/ui/ignore-file-ui.ts +28 -202
  85. package/src/ui/manager-state.ts +27 -15
  86. package/src/ui/manager-ui.ts +4 -1
  87. package/src/ui/remote-selection-ui.ts +51 -24
  88. package/src/ui/settings-ui.ts +132 -81
  89. package/src/ui/setup/setup-actions.ts +16 -4
  90. package/src/ui/setup/setup-prompts.ts +55 -9
  91. package/src/ui/setup/setup-switcher.ts +24 -11
  92. package/src/ui/storage-connections-ui.ts +33 -11
  93. package/src/ui/sync-setups-ui.ts +24 -7
  94. package/dist/chunks/chunk-6PFZUEUG.ts.map +0 -7
  95. package/dist/chunks/chunk-ECYCNZOE.ts +0 -12
  96. package/dist/chunks/chunk-ECYCNZOE.ts.map +0 -7
  97. package/dist/chunks/chunk-INECVQNR.ts.map +0 -7
  98. package/dist/chunks/chunk-NHFGAZEC.ts.map +0 -7
  99. package/dist/chunks/chunk-PWESMTH6.ts.map +0 -7
  100. package/dist/chunks/chunk-ZB3GNX3P.ts.map +0 -7
  101. package/dist/chunks/command-handler-6ATREPG7.ts.map +0 -7
  102. package/dist/chunks/file-selection-QR2KZVGD.ts.map +0 -7
  103. package/dist/chunks/manager-ui-AOFUNXAJ.ts.map +0 -7
  104. /package/dist/chunks/{chunk-GSCZ4VXV.ts.map → chunk-VQ47JBLF.ts.map} +0 -0
  105. /package/dist/chunks/{conflict-review-MAOGTIAI.ts.map → conflict-review-PCDFRIVB.ts.map} +0 -0
  106. /package/dist/chunks/{manager-result-dispatcher-MC6EQOQY.ts.map → manager-result-dispatcher-GDB74IOP.ts.map} +0 -0
  107. /package/dist/chunks/{remote-selection-ui-4BTP2OJR.ts.map → remote-selection-ui-GPITNEBF.ts.map} +0 -0
  108. /package/dist/chunks/{setup-switch-Y6AMFFNK.ts.map → setup-switch-L54X5U5I.ts.map} +0 -0
  109. /package/dist/chunks/{sync-inspection-ITZ6Z4DE.ts.map → sync-inspection-H2WX5SUT.ts.map} +0 -0
  110. /package/dist/chunks/{sync-operations-NMVKF7SE.ts.map → sync-operations-2MZAYHL2.ts.map} +0 -0
@@ -1,15 +1,16 @@
1
1
  import { createHash, randomUUID } from "node:crypto";
2
+ import { lstatSync } from "node:fs";
2
3
  import fs from "node:fs/promises";
3
4
  import path from "node:path";
4
5
  import { requireHandover } from "../../consent.js";
5
6
  import { documentFingerprint } from "../../document.js";
6
- import { MAX_REVIEW_BYTES } from "../../protocol.js";
7
+ import { MAX_REVIEW_BYTES, record } from "../../protocol.js";
7
8
  import { createServiceContext } from "../../service-host.js";
8
9
  import { createSyncBackend } from "../backends/backend-factory.js";
9
10
  import { engineHost } from "../host.js";
10
11
  import { configFromSettings } from "../settings/config.js";
11
12
  import { peekLocalConfigDocument, updateLocalConfigDocument, } from "../settings/config-file.js";
12
- import { validateSettingsDocument } from "../settings/settings-validation.js";
13
+ import { validateConfigName, validateSettingsDocument } from "../settings/settings-validation.js";
13
14
  import { resolvedSnapshotOptionsForContext } from "../snapshot/session-paths.js";
14
15
  import { createSnapshot } from "../snapshot/snapshot.js";
15
16
  import { pendingTransactionEntries } from "../snapshot/snapshot-transaction-directory.js";
@@ -18,11 +19,32 @@ import { withLock } from "../state/lock.js";
18
19
  import { stateDir, withStateDirectoryAccess } from "../state/state-directory.js";
19
20
  import { requireNoMergeJournal } from "../sync/merge-journal.js";
20
21
  import { configuredSnapshotPathMatcher } from "../sync/sync-policy.js";
21
- import { safeTerminalText } from "../ui/terminal-text.js";
22
+ import { safeTerminalText, snapshotPathLabel } from "../ui/terminal-text.js";
22
23
  import { compileEffectiveIgnorePolicy } from "./effective-ignore-policy.js";
23
- import { prepareDefaultIgnoreSource } from "./ignore-initialization.js";
24
+ import { AutomaticIgnoreCreationUnavailable, checkAutomaticIgnoreCreation, prepareDefaultIgnoreSource, } from "./ignore-initialization.js";
24
25
  import { assertCurrentIgnoreMigrationOffer } from "./ignore-migration-prompt.js";
25
26
  import { compileIgnoreRules, DEFAULT_IGNORE_CREATION_RECORD, DEFAULT_IGNORE_FILENAME, DEFAULT_IGNORE_RULES, IgnoreCreationPendingError, ignoreSourceDigest, readIgnoreSource, validateIgnoreFilename, } from "./ignore-source.js";
27
+ export function runIgnorePolicyChange(operation, payload, execution) {
28
+ if (!record(payload) || typeof payload.setup !== "string")
29
+ throw new Error("Invalid ignore-file policy request.");
30
+ const { setup } = payload;
31
+ validateConfigName(setup, "sync setup");
32
+ if (operation === "ignore.migrate") {
33
+ const { offerToken } = payload;
34
+ if (Object.keys(payload).some((key) => key !== "setup" && key !== "offerToken") ||
35
+ (offerToken !== undefined && (typeof offerToken !== "string" || !/^[a-f0-9]{64}$/u.test(offerToken))))
36
+ throw new Error("Invalid ignore-file migration request.");
37
+ if (offerToken !== undefined && execution.facts()?.mode !== "tui")
38
+ throw new Error("Ignore migration offers require an attached TUI client.");
39
+ return migrateIgnoreSetup(execution, setup, offerToken);
40
+ }
41
+ const { filename, expectedFilename } = payload;
42
+ if (typeof filename !== "string" ||
43
+ typeof expectedFilename !== "string" ||
44
+ Object.keys(payload).some((key) => key !== "setup" && key !== "filename" && key !== "expectedFilename"))
45
+ throw new Error("Invalid ignore-file switch request.");
46
+ return switchIgnoreFile(execution, setup, filename, expectedFilename);
47
+ }
26
48
  function sourceToken(document) {
27
49
  return documentFingerprint(document ? { bytes: document.bytes.toString("base64"), identity: document.identity } : undefined);
28
50
  }
@@ -86,10 +108,47 @@ async function readSetupSource(root, filename, signal) {
86
108
  };
87
109
  }
88
110
  }
111
+ async function readPolicyReviewSource(root, filename, execution, allowCreation) {
112
+ const { signal } = execution;
113
+ execution.validate();
114
+ signal.throwIfAborted();
115
+ filename = validateIgnoreFilename(filename);
116
+ if (filename !== DEFAULT_IGNORE_FILENAME &&
117
+ lstatSync(path.resolve(root), { throwIfNoEntry: false })?.isDirectory() &&
118
+ !lstatSync(path.resolve(root, filename), { throwIfNoEntry: false })) {
119
+ throw manualCreationRequired(root, filename);
120
+ }
121
+ const source = await (allowCreation
122
+ ? readSetupSource(root, filename, signal)
123
+ : readIgnoreSource(root, filename, signal));
124
+ execution.validate();
125
+ if (source.present)
126
+ return source;
127
+ if (!allowCreation)
128
+ throw manualCreationRequired(root, filename);
129
+ await checkAutomaticIgnoreCreation(root, signal).catch((error) => {
130
+ execution.validate();
131
+ throw creationFailure(root, source, error);
132
+ });
133
+ execution.validate();
134
+ return source;
135
+ }
136
+ function manualCreationRequired(root, filename, cause) {
137
+ return new Error(`Ignore file does not exist: ${snapshotPathLabel(path.resolve(root, filename))}\n` +
138
+ `${cause ? `${cause.message}. ` : ""}Create a regular UTF-8 text file there manually with these starter rules, then retry the Pi Sync policy change:\n${DEFAULT_IGNORE_RULES}`, { cause });
139
+ }
140
+ function creationFailure(root, source, error) {
141
+ if (!(error instanceof AutomaticIgnoreCreationUnavailable))
142
+ return error;
143
+ if (!source.pendingCreation)
144
+ return manualCreationRequired(root, source.filename, error);
145
+ return new Error(`Interrupted creation of ${snapshotPathLabel(path.resolve(root, source.filename))}. ${error.message}. ` +
146
+ `Preserve the rule file and creation record ${snapshotPathLabel(path.resolve(root, DEFAULT_IGNORE_CREATION_RECORD))}. ` +
147
+ "Retry the reviewed Pi Sync policy change where safe automatic recovery is available.", { cause: error });
148
+ }
89
149
  export async function reviewNewIgnoreSource(root, filename, execution) {
90
150
  const ctx = requireInteractive(execution);
91
- const source = await readSetupSource(root, filename, execution.signal);
92
- execution.validate();
151
+ const source = await readPolicyReviewSource(root, filename, execution, true);
93
152
  compileIgnoreRules(source.text);
94
153
  const description = describeSource(source);
95
154
  if (!(await confirm(ctx, execution, "Review ignore-file policy", [
@@ -111,7 +170,10 @@ export async function prepareReviewedIgnoreSource(root, reviewed, execution) {
111
170
  stale();
112
171
  if (current.present)
113
172
  return { source: current, created: false };
114
- const prepared = await prepareDefaultIgnoreSource(root, execution.signal);
173
+ const prepared = await prepareDefaultIgnoreSource(root, execution.signal).catch((error) => {
174
+ execution.validate();
175
+ throw creationFailure(root, current, error);
176
+ });
115
177
  execution.validate();
116
178
  if (!prepared.source.present ||
117
179
  prepared.source.text !== reviewed.text ||
@@ -123,6 +185,10 @@ export async function switchIgnoreFile(execution, setupName, filename, expectedF
123
185
  const ctx = requireInteractive(execution);
124
186
  filename = validateIgnoreFilename(filename);
125
187
  expectedFilename = validateIgnoreFilename(expectedFilename);
188
+ if (expectedFilename !== filename) {
189
+ await readPolicyReviewSource(execution.root, filename, execution, false);
190
+ execution.validate();
191
+ }
126
192
  await requireHandover(execution);
127
193
  execution.validate();
128
194
  return withStateDirectoryAccess(() => withLock("sync", async () => {
@@ -139,10 +205,8 @@ export async function switchIgnoreFile(execution, setupName, filename, expectedF
139
205
  if ((await pendingTransactionEntries()).some((entry) => entry.isDirectory()))
140
206
  throw new Error("Resolve pending local recovery before changing the content policy.");
141
207
  await requireNoMergeJournal(configFromSettings(settings, setupName));
142
- const source = await readIgnoreSource(execution.root, filename, execution.signal);
208
+ const source = await readPolicyReviewSource(execution.root, filename, execution, false);
143
209
  execution.validate();
144
- if (!source.present)
145
- throw new Error(`Ignore file does not exist: ${safeTerminalText(path.join(execution.root, filename))}`);
146
210
  compileIgnoreRules(source.text);
147
211
  if (!(await confirm(ctx, execution, "Review changing the ignore file", [
148
212
  `Setup: ${safeTerminalText(setupName)}`,
@@ -162,6 +226,8 @@ export async function switchIgnoreFile(execution, setupName, filename, expectedF
162
226
  }
163
227
  export async function migrateIgnoreSetup(execution, setupName, offerToken) {
164
228
  const ctx = requireInteractive(execution);
229
+ await readPolicyReviewSource(execution.root, DEFAULT_IGNORE_FILENAME, execution, true);
230
+ execution.validate();
165
231
  await requireHandover(execution);
166
232
  execution.validate();
167
233
  return withStateDirectoryAccess(() => withLock("sync", async () => {
@@ -169,8 +235,13 @@ export async function migrateIgnoreSetup(execution, setupName, offerToken) {
169
235
  execution.validate();
170
236
  if (!document)
171
237
  throw new Error("No Pi Sync settings to migrate.");
172
- if (offerToken !== undefined)
173
- assertCurrentIgnoreMigrationOffer(document, execution.root, setupName, offerToken);
238
+ const guardSettings = settingsReviewGuard(document, execution);
239
+ const validateReview = (candidate) => {
240
+ guardSettings(candidate);
241
+ if (offerToken !== undefined)
242
+ assertCurrentIgnoreMigrationOffer(candidate, execution.root, setupName, offerToken);
243
+ };
244
+ validateReview(document);
174
245
  const before = validateSettingsDocument(document.parsed);
175
246
  const setup = Object.hasOwn(before.syncSetups, setupName) ? before.syncSetups[setupName] : undefined;
176
247
  if (!setup || ignoreFilename(setup))
@@ -188,7 +259,7 @@ export async function migrateIgnoreSetup(execution, setupName, offerToken) {
188
259
  next.syncSetups[setupName].sync = { ...common, scope: "agent-directory", sessions, pathPolicy: "ignore-file" };
189
260
  next.version = 8;
190
261
  validateSettingsDocument(next);
191
- const source = await readSetupSource(execution.root, DEFAULT_IGNORE_FILENAME, execution.signal);
262
+ const source = await readPolicyReviewSource(execution.root, DEFAULT_IGNORE_FILENAME, execution, true);
192
263
  execution.validate();
193
264
  const current = {
194
265
  ...configFromSettings(next, setupName),
@@ -242,7 +313,7 @@ export async function migrateIgnoreSetup(execution, setupName, offerToken) {
242
313
  : fresh)
243
314
  stale();
244
315
  };
245
- await updateLocalConfigDocument(next, () => next, validateSettingsDocument, execution.signal, settingsReviewGuard(document, execution), async () => {
316
+ await updateLocalConfigDocument(next, () => next, validateSettingsDocument, execution.signal, validateReview, async () => {
246
317
  verifyHead(await backend.readHead(execution.signal));
247
318
  execution.validate();
248
319
  if (!source.present && (await collect()).fingerprint !== review.fingerprint)
@@ -197,7 +197,7 @@ export function updateLocalConfigDocument(defaultValue, update, validate, signal
197
197
  signal?.throwIfAborted();
198
198
  if (document && JSON.stringify(document.parsed) === JSON.stringify(next))
199
199
  return next;
200
- if (beforePublish && document?.path !== localConfigPath()) {
200
+ if (beforePublish && document && document.path !== localConfigPath()) {
201
201
  throw new Error("This reviewed settings change requires pi-sync.json. No settings were saved; use the canonical filename and reopen the review.");
202
202
  }
203
203
  const review = reviewed
@@ -1,22 +1,39 @@
1
1
  import { createHash } from "node:crypto";
2
+ import path from "node:path";
3
+ import { documentFingerprint } from "../../document.js";
2
4
  import { backendIdentityCoordinates } from "../backends/backend-identity.js";
3
5
  import { normalizeGitBranch, normalizeGitDirectory, normalizeGitRemote } from "../backends/git/git-config.js";
4
6
  import { normalizeWebDavPath, normalizeWebDavUrl } from "../backends/webdav/webdav-config.js";
5
- import { getEngineRoot } from "../host.js";
6
- import { loadEffectiveIgnorePolicy } from "../ignore/effective-ignore-policy.js";
7
+ import { engineHost, getEngineRoot } from "../host.js";
8
+ import { compileEffectiveIgnorePolicy } from "../ignore/effective-ignore-policy.js";
7
9
  import { DEFAULT_IGNORE_FILENAME, readIgnoreSource, validateIgnoreFilename } from "../ignore/ignore-source.js";
8
10
  import { normalizeSyncExclude } from "../sync/exclude-policy.js";
9
11
  import { normalizeLocalFields } from "../sync/local-field-policy.js";
10
- import { normalizeDirectoryRules, normalizeSyncInclude, syncDirectoryPolicyKey, syncSessionsSelected, } from "../sync/sync-policy.js";
12
+ import { localIgnorePolicyKey, normalizeDirectoryRules, normalizeSyncInclude, syncDirectoryPolicyKey, syncSessionsSelected, } from "../sync/sync-policy.js";
13
+ import { safeTerminalText } from "../ui/terminal-text.js";
11
14
  import { localConfigPath, readActiveLocalConfigDocumentForRepair, withLockedLocalConfigDocument, } from "./config-file.js";
12
- import { requireSettings } from "./settings-store.js";
15
+ import { readLocalConfigDocument, requireSettings } from "./settings-store.js";
13
16
  import { DEFAULT_ON_SWITCH, isCloudflareR2Endpoint, normalizeS3Bucket, normalizeS3Endpoint, normalizeStoragePath, optionalString, ownObject, requiredString, validateConfigName, validateSettingsDocument, } from "./settings-validation.js";
14
- export async function loadConfig(setupName) {
15
- return requireLegacyOperationConfig(configFromSettings(await requireSettings(), setupName));
17
+ export async function loadConfig(setupName, signal) {
18
+ signal?.throwIfAborted();
19
+ const document = await readLocalConfigDocument();
20
+ if (!document)
21
+ throw new Error(`Missing pi-sync settings. Open /sync and choose Set up sync, or create ${localConfigPath()}.`);
22
+ return operationalConfig(document, setupName, signal);
16
23
  }
17
24
  /** A background freshness read must never trigger legacy-file publication. */
18
- export async function loadConfigForCheck() {
19
- return requireLegacyOperationConfig(configFromSettings(await readSettingsForCheck()));
25
+ export async function loadConfigForCheck(setupName, signal) {
26
+ signal?.throwIfAborted();
27
+ return operationalConfig(await readActiveLocalConfigDocumentForRepair(), setupName, signal);
28
+ }
29
+ async function operationalConfig(document, setupName, signal) {
30
+ signal?.throwIfAborted();
31
+ const config = configFromSettings(settingsFromCheckDocument(document), setupName);
32
+ if (!config.reservedIgnoreNames)
33
+ return config;
34
+ if (engineHost().ignoreFileOperationsAvailable === false)
35
+ return requireLegacyOperationConfig(config);
36
+ return resolveOperationPolicy(config, setupName, signal, document);
20
37
  }
21
38
  export async function loadSettingsConfig(setupName) {
22
39
  return configFromSettings(await readSettingsForCheck(), setupName);
@@ -37,46 +54,62 @@ export function requireLegacyOperationConfig(config) {
37
54
  }
38
55
  export async function resolveIgnoreConfig(settings, setupName, signal) {
39
56
  signal?.throwIfAborted();
40
- const config = configFromSettings(validateSettingsDocument(settings), setupName);
41
- if (config.pathPolicy !== "ignore-file")
42
- return requireLegacyOperationConfig(config);
57
+ return resolveOperationPolicy(configFromSettings(validateSettingsDocument(settings), setupName), setupName, signal);
58
+ }
59
+ function settingsDocumentFingerprint(document) {
60
+ return documentFingerprint(document && { bytes: document.bytes.toString("base64"), identity: document.identity });
61
+ }
62
+ async function resolveOperationPolicy(config, setupName, signal, original) {
63
+ if (!config.reservedIgnoreNames)
64
+ return config;
43
65
  const root = getEngineRoot();
44
66
  const validateRoot = () => {
67
+ signal?.throwIfAborted();
45
68
  if (root !== getEngineRoot())
46
69
  throw new Error("The Pi agent directory changed; reopen the review before continuing.");
47
70
  };
71
+ const configDocumentFingerprint = original && settingsDocumentFingerprint(original);
48
72
  const settingsFingerprint = syncCheckConfigFingerprint(config);
49
73
  const validateSettings = (document) => {
50
- signal?.throwIfAborted();
51
74
  validateRoot();
52
- const current = configFromSettings(document, setupName);
53
- if (settingsFingerprint !== syncCheckConfigFingerprint(current)) {
75
+ if ((original &&
76
+ (document?.path !== original.path || settingsDocumentFingerprint(document) !== configDocumentFingerprint)) ||
77
+ settingsFingerprint !==
78
+ syncCheckConfigFingerprint(configFromSettings(settingsFromCheckDocument(document), setupName))) {
54
79
  throw new Error("Pi Sync settings changed; reopen the review before continuing.");
55
80
  }
56
- return current;
57
81
  };
58
- const ignorePolicy = await loadEffectiveIgnorePolicy(root, ignorePolicyInput(config), signal);
59
- signal?.throwIfAborted();
82
+ const source = config.pathPolicy === "ignore-file" ? await readIgnoreSource(root, config.ignoreFile, signal) : undefined;
60
83
  validateRoot();
84
+ if (original && source && !source.present) {
85
+ 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
+ }
87
+ if (original && source)
88
+ validateSettings(await readActiveLocalConfigDocumentForRepair());
61
89
  return {
62
90
  ...config,
63
- ignorePolicy,
91
+ ...(configDocumentFingerprint ? { configDocumentFingerprint } : {}),
92
+ ...(source ? { ignorePolicy: compileEffectiveIgnorePolicy(source, ignorePolicyInput(config)) } : {}),
93
+ ...(source?.identity ? { ignoreSourceIdentity: source.identity } : {}),
64
94
  validateIgnorePolicy: async () => {
65
- signal?.throwIfAborted();
66
95
  validateRoot();
67
96
  await withLockedLocalConfigDocument(async (document, recheck) => {
68
- const current = validateSettings(settingsFromCheckDocument(document));
69
- const source = await readIgnoreSource(root, current.ignoreFile, signal);
70
- validateRoot();
71
- recheck();
72
- if (source.sourceDigest !== ignorePolicy.sourceDigest) {
73
- throw new Error("Pi Sync ignore policy changed; reopen the review before continuing.");
97
+ validateSettings(document);
98
+ if (source) {
99
+ const current = await readIgnoreSource(root, source.filename, signal);
100
+ validateRoot();
101
+ recheck();
102
+ if (current.sourceDigest !== source.sourceDigest || current.identity !== source.identity) {
103
+ throw new Error("Pi Sync ignore policy changed; reopen the review before continuing.");
104
+ }
105
+ if (!current.present) {
106
+ throw new Error(`Ignore file "${source.filename}" is missing; starter rules can only be used for a preview.`);
107
+ }
74
108
  }
75
- if (!source.present) {
76
- throw new Error(`Ignore file "${source.filename}" is missing; starter rules can only be used for a preview.`);
109
+ else {
110
+ recheck();
77
111
  }
78
112
  }, signal, true);
79
- signal?.throwIfAborted();
80
113
  validateRoot();
81
114
  },
82
115
  };
@@ -140,6 +173,7 @@ export function syncSetupReviewIdentity(setupName, setup, connectionName, connec
140
173
  return syncConfigReviewIdentity(resolveSyncConfig(setupName, setup, connectionName, connection, DEFAULT_ON_SWITCH, false, true));
141
174
  }
142
175
  export function syncConfigReviewIdentity(config) {
176
+ const localPolicy = localIgnorePolicyKey(config);
143
177
  const directoryPolicy = config.pathPolicy === "ignore-file" && !config.ignorePolicy
144
178
  ? JSON.stringify([config.pathPolicy, config.ignoreFile])
145
179
  : syncDirectoryPolicyKey(config);
@@ -162,6 +196,7 @@ export function syncConfigReviewIdentity(config) {
162
196
  : config.exclude === undefined
163
197
  ? []
164
198
  : ["exclude", normalizeSyncExclude(config.exclude).map((rule) => rule.toLowerCase())]),
199
+ ...(localPolicy ? [localPolicy] : []),
165
200
  ]);
166
201
  }
167
202
  export function syncConfigReviewFingerprint(config) {
@@ -173,6 +208,14 @@ export function syncCheckConfigFingerprint(config) {
173
208
  .update(JSON.stringify({ ...config, showStatus: undefined, debug: undefined }))
174
209
  .digest("hex");
175
210
  }
211
+ export function syncSettingsConfigFingerprint(config) {
212
+ return syncCheckConfigFingerprint({
213
+ ...config,
214
+ configDocumentFingerprint: undefined,
215
+ ignoreSourceIdentity: undefined,
216
+ ignorePolicy: undefined,
217
+ });
218
+ }
176
219
  function storageReviewFromConfig(config) {
177
220
  return {
178
221
  connectionName: config.connectionName,
@@ -122,8 +122,10 @@ export async function updateSyncSetup(name, update, options = {}) {
122
122
  }
123
123
  export async function removeSyncSetup(name, signal) {
124
124
  validateConfigName(name, "sync setup");
125
- await updateLocalConfig((settings) => {
126
- if (!Object.hasOwn(settings.syncSetups, name))
125
+ let removedLastIgnoreSetup = false;
126
+ const saved = await updateLocalConfig((settings) => {
127
+ const setup = settings.syncSetups[name];
128
+ if (!Object.hasOwn(settings.syncSetups, name) || !setup)
127
129
  throw new Error(`Sync setup not found: ${name}`);
128
130
  const isCurrent = settings.activeSyncSetup === name;
129
131
  if (isCurrent && Object.keys(settings.syncSetups).length > 1) {
@@ -131,11 +133,15 @@ export async function removeSyncSetup(name, signal) {
131
133
  }
132
134
  const syncSetups = { ...settings.syncSetups };
133
135
  delete syncSetups[name];
136
+ removedLastIgnoreSetup =
137
+ setup.sync.pathPolicy === "ignore-file" &&
138
+ !Object.values(syncSetups).some((remaining) => remaining.sync.pathPolicy === "ignore-file");
134
139
  const next = { ...settings, syncSetups };
135
140
  if (isCurrent)
136
141
  delete next.activeSyncSetup;
137
142
  return next;
138
143
  }, signal);
144
+ return { revertedToLegacyOnly: removedLastIgnoreSetup && saved.activeSyncSetup !== undefined };
139
145
  }
140
146
  export async function removeStorageConnection(name, signal) {
141
147
  validateConfigName(name, "storage connection");
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs/promises";
2
2
  import os from "node:os";
3
3
  import path from "node:path";
4
+ import { backendIdentityCoordinates } from "../backends/backend-identity.js";
4
5
  import { getEngineRoot as getAgentDir, } from "../host.js";
5
6
  import { configuredSnapshotPathMatcher } from "../sync/sync-policy.js";
6
7
  import { agentDirectorySessionRoot, reservedIgnoreTargetGuard } from "./snapshot-exclude-safety.js";
@@ -142,9 +143,13 @@ export function snapshotOptionsForContext(ctx, config) {
142
143
  return {
143
144
  include: config.include,
144
145
  ...(config.scope === undefined ? {} : { scope: config.scope }),
145
- ...(config.ignorePolicy
146
- ? { ignorePolicy: config.ignorePolicy, validateIgnorePolicy: config.validateIgnorePolicy }
146
+ ...(config.setupName === undefined ? {} : { setupName: config.setupName }),
147
+ ...(config.backend && (config.ignorePolicy || config.reservedIgnoreNames !== undefined)
148
+ ? { recoverySetupKey: JSON.stringify([backendIdentityCoordinates(config), config.localFields]) }
147
149
  : {}),
150
+ ...(config.ignorePolicy ? { ignorePolicy: config.ignorePolicy } : {}),
151
+ ...(config.ignoreSourceIdentity === undefined ? {} : { ignoreSourceIdentity: config.ignoreSourceIdentity }),
152
+ ...(config.validateIgnorePolicy === undefined ? {} : { validateIgnorePolicy: config.validateIgnorePolicy }),
148
153
  ...(config.exclude === undefined ? {} : { exclude: config.exclude }),
149
154
  ...(config.reinclude === undefined ? {} : { reinclude: config.reinclude }),
150
155
  ...(config.reservedIgnoreNames === undefined ? {} : { reservedIgnoreNames: config.reservedIgnoreNames }),
@@ -4,7 +4,7 @@ import { DEFAULT_IGNORE_FILENAME, validateIgnoreFilename } from "../ignore/ignor
4
4
  import { assertWithinRoot, isDeniedPath, isPathInside } from "../paths.js";
5
5
  import { normalizeSyncExclude, sameSyncExclude } from "../sync/exclude-policy.js";
6
6
  import { mergePathIdentity } from "../sync/file-merge-planner.js";
7
- import { portableSnapshotSelection, sameSnapshotSelection, selectionForSnapshot, syncDirectoryPolicyKey, } from "../sync/sync-policy.js";
7
+ import { localIgnorePolicyKey, portableSnapshotSelection, sameSnapshotSelection, selectionForSnapshot, syncDirectoryPolicyKey, } from "../sync/sync-policy.js";
8
8
  import { agentDir } from "./session-paths.js";
9
9
  import { isCaseReplacement } from "./snapshot-case-replacement.js";
10
10
  import { sessionStorageRoot } from "./snapshot-paths.js";
@@ -13,16 +13,25 @@ export const LEGACY_AGENT_DIRECTORY_JOURNAL_VERSION = 8;
13
13
  export const FIXED_WORKSPACE_JOURNAL_VERSION = 9;
14
14
  export const AGENT_DIRECTORY_JOURNAL_VERSION = 10;
15
15
  export const IGNORE_POLICY_JOURNAL_VERSION = 11;
16
+ export const BOUND_DIRECTORY_JOURNAL_VERSION = 12;
17
+ export const BOUND_INCLUDED_PATHS_JOURNAL_VERSION = 13;
18
+ function isLocallyBoundJournal(journal) {
19
+ return (journal.version === BOUND_DIRECTORY_JOURNAL_VERSION || journal.version === BOUND_INCLUDED_PATHS_JOURNAL_VERSION);
20
+ }
21
+ export function recoveryPolicyKey(options) {
22
+ return options.setupName || options.reservedIgnoreNames !== undefined ? localIgnorePolicyKey(options) : undefined;
23
+ }
16
24
  export function isScopedJournal(journal) {
17
25
  return [
18
26
  LEGACY_AGENT_DIRECTORY_JOURNAL_VERSION,
19
27
  FIXED_WORKSPACE_JOURNAL_VERSION,
20
28
  AGENT_DIRECTORY_JOURNAL_VERSION,
21
29
  IGNORE_POLICY_JOURNAL_VERSION,
30
+ BOUND_DIRECTORY_JOURNAL_VERSION,
22
31
  ].includes(journal.version);
23
32
  }
24
33
  function usesSlottedWorkspace(journal) {
25
- return journal.version === AGENT_DIRECTORY_JOURNAL_VERSION || journal.version === IGNORE_POLICY_JOURNAL_VERSION;
34
+ return journal.version >= AGENT_DIRECTORY_JOURNAL_VERSION && isScopedJournal(journal);
26
35
  }
27
36
  export function isRecoveryStageId(value) {
28
37
  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));
@@ -55,10 +64,12 @@ function sameIgnoreSource(left, right) {
55
64
  export class StaleIgnorePolicyError extends Error {
56
65
  }
57
66
  export function ignorePolicyValidator(options) {
58
- if (!options.ignorePolicy && options.version !== 4)
67
+ const scopedIgnore = options.ignorePolicy !== undefined || options.version === 4;
68
+ if (!scopedIgnore && options.reservedIgnoreNames === undefined && !options.validateIgnorePolicy)
59
69
  return;
60
70
  const validateIgnorePolicy = options.validateIgnorePolicy;
61
- if (!options.ignorePolicy || options.scope !== "agent-directory" || typeof validateIgnorePolicy !== "function")
71
+ if ((scopedIgnore && (!options.ignorePolicy || options.scope !== "agent-directory")) ||
72
+ typeof validateIgnorePolicy !== "function")
62
73
  throw new Error("Ignore-file mutation requires an explicit local policy and a freshness check.");
63
74
  return async () => {
64
75
  options.validateMutation?.();
@@ -77,9 +88,15 @@ export function ignorePolicyValidator(options) {
77
88
  };
78
89
  }
79
90
  export function validateJournalPolicy(journal) {
80
- if (!journal || (![1, 2, 3, 4, 5, 6, 7].includes(journal.version) && !isScopedJournal(journal)))
91
+ if (!journal ||
92
+ (![1, 2, 3, 4, 5, 6, 7].includes(journal.version) && !isScopedJournal(journal) && !isLocallyBoundJournal(journal)))
81
93
  throw new Error("Unsupported pi-sync transaction journal; preserve evidence for review.");
82
- if (journal.version === IGNORE_POLICY_JOURNAL_VERSION) {
94
+ if (isLocallyBoundJournal(journal)
95
+ ? typeof journal.localPolicyKey !== "string" || !/^[0-9a-f]{64}$/u.test(journal.localPolicyKey)
96
+ : journal.localPolicyKey !== undefined)
97
+ throw new Error("Invalid transaction local policy binding; preserve evidence for review.");
98
+ if (journal.version === IGNORE_POLICY_JOURNAL_VERSION ||
99
+ (journal.version === BOUND_DIRECTORY_JOURNAL_VERSION && journal.selection?.version === 4)) {
83
100
  const binding = journal.ignoreSource;
84
101
  try {
85
102
  if (journal.exclude === undefined &&
@@ -109,9 +126,11 @@ export function validateJournalPolicy(journal) {
109
126
  normalizeSyncExclude(journal.exclude);
110
127
  }
111
128
  export function assertRecoveryPolicy(journal, options) {
112
- if (journal.version === IGNORE_POLICY_JOURNAL_VERSION || options.ignorePolicy || options.version === 4) {
113
- if (journal.version === IGNORE_POLICY_JOURNAL_VERSION &&
114
- journal.ignoreSource &&
129
+ const localKey = recoveryPolicyKey(options);
130
+ if (journal.localPolicyKey !== localKey)
131
+ throw new Error("Pending transaction has different setup or ignore policy evidence; preserve its backup for reviewed recovery.");
132
+ if (journal.ignoreSource || options.ignorePolicy || options.version === 4) {
133
+ if (journal.ignoreSource &&
115
134
  options.scope === "agent-directory" &&
116
135
  options.ignorePolicy &&
117
136
  sameIgnoreSource(journal.ignoreSource, ignoreSourceBinding(options.ignorePolicy)) &&
@@ -130,16 +149,18 @@ export function assertRecoveryPolicy(journal, options) {
130
149
  export function validateJournal(directory, journal, sessionDir) {
131
150
  validateJournalPolicy(journal);
132
151
  const wholeDirectory = isScopedJournal(journal);
152
+ const scopedWorkspace = wholeDirectory && journal.version >= FIXED_WORKSPACE_JOURNAL_VERSION;
133
153
  if (!Array.isArray(journal.entries) || journal.entries.length > 16_384)
134
154
  throw new Error("Unsupported pi-sync transaction journal; preserve evidence for review.");
135
155
  if (journal.completed !== undefined &&
136
- ((!wholeDirectory && ![6, 7].includes(journal.version)) || journal.completed !== true))
156
+ ((!wholeDirectory && ![6, 7, BOUND_INCLUDED_PATHS_JOURNAL_VERSION].includes(journal.version)) ||
157
+ journal.completed !== true))
137
158
  throw new Error("Invalid transaction completion evidence.");
138
159
  const root = path.resolve(agentDir());
139
160
  if (typeof journal.root !== "string" || path.resolve(journal.root) !== root)
140
161
  throw new Error("Transaction root no longer matches the Pi agent directory.");
141
162
  if (journal.sessionRootTransition !== undefined) {
142
- if (journal.version !== 7 || typeof journal.sessionRoot !== "string")
163
+ if (![7, BOUND_INCLUDED_PATHS_JOURNAL_VERSION].includes(journal.version) || typeof journal.sessionRoot !== "string")
143
164
  throw new Error("Invalid session root-transition version.");
144
165
  validateSessionRootTransition(journal.sessionRootTransition);
145
166
  }
@@ -170,7 +191,7 @@ export function validateJournal(directory, journal, sessionDir) {
170
191
  assertWithinRoot(directory, path.join(directory, "before", entry.backupName));
171
192
  assertAllowedTarget(root, journal.sessionRoot, entry.target);
172
193
  if (entry.afterTarget !== undefined &&
173
- ((!wholeDirectory && ![5, 6, 7].includes(journal.version)) ||
194
+ ((!wholeDirectory && ![5, 6, 7, BOUND_INCLUDED_PATHS_JOURNAL_VERSION].includes(journal.version)) ||
174
195
  typeof entry.afterTarget !== "string" ||
175
196
  !isCaseReplacement(root, entry.target, entry.afterTarget) ||
176
197
  path.resolve(entry.afterTarget) !== entry.afterTarget ||
@@ -183,8 +204,7 @@ export function validateJournal(directory, journal, sessionDir) {
183
204
  (entry.afterImage === undefined ? !journal.completed : typeof entry.afterImage !== "string") ||
184
205
  (entry.postFiles === undefined ? !journal.completed : !Array.isArray(entry.postFiles))))
185
206
  throw new Error("Invalid transaction postimage evidence.");
186
- if (entry.recoveryStaged !== undefined &&
187
- (typeof entry.recoveryStaged !== "boolean" || journal.version >= FIXED_WORKSPACE_JOURNAL_VERSION))
207
+ if (entry.recoveryStaged !== undefined && (typeof entry.recoveryStaged !== "boolean" || scopedWorkspace))
188
208
  throw new Error("Invalid recovery staging evidence.");
189
209
  if (entry.removalPending !== undefined && (journal.version < 3 || typeof entry.removalPending !== "boolean"))
190
210
  throw new Error("Invalid transaction removal evidence.");
@@ -194,7 +214,7 @@ export function validateJournal(directory, journal, sessionDir) {
194
214
  if (entry.removalPending && entry.replacementStarted)
195
215
  throw new Error("Conflicting transaction replacement evidence.");
196
216
  if ((entry.recoveryWorkspace !== undefined &&
197
- (journal.version < FIXED_WORKSPACE_JOURNAL_VERSION ||
217
+ (!scopedWorkspace ||
198
218
  !isScopedIdentity(entry.recoveryWorkspace) ||
199
219
  entry.recoveryStaged ||
200
220
  !["file", "directory"].includes(entry.kind))) ||
@@ -203,7 +223,7 @@ export function validateJournal(directory, journal, sessionDir) {
203
223
  !entry.recoveryWorkspace ||
204
224
  !isRecoveryStageId(entry.recoveryWorkspaceId))) ||
205
225
  (entry.scopedRemoval !== undefined &&
206
- (journal.version < FIXED_WORKSPACE_JOURNAL_VERSION ||
226
+ (!scopedWorkspace ||
207
227
  !entry.removalPending ||
208
228
  !["before", "after"].includes(entry.scopedRemoval?.image) ||
209
229
  !isScopedIdentity(entry.scopedRemoval?.identity) ||
@@ -211,7 +231,7 @@ export function validateJournal(directory, journal, sessionDir) {
211
231
  ? !["file", "directory"].includes(entry.kind)
212
232
  : entry.afterImage === "missing" && !entry.postFiles?.length))) ||
213
233
  (entry.vacantInstall !== undefined &&
214
- (journal.version < FIXED_WORKSPACE_JOURNAL_VERSION ||
234
+ (!scopedWorkspace ||
215
235
  !entry.recoveryWorkspace ||
216
236
  !isScopedIdentity(entry.vacantInstall) ||
217
237
  entry.removalPending ||