@narumitw/pi-sync 0.65.0 → 0.66.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 (70) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/README.md +4 -4
  3. package/dist/chunks/{chunk-OWEOZZZE.ts → chunk-5YOLQKNZ.ts} +38 -2
  4. package/dist/chunks/chunk-5YOLQKNZ.ts.map +7 -0
  5. package/dist/chunks/{chunk-OBVJTKVY.ts → chunk-ASU3GZPW.ts} +10 -92
  6. package/dist/chunks/chunk-ASU3GZPW.ts.map +7 -0
  7. package/dist/chunks/{chunk-IOM6E5FW.ts → chunk-BESRBKVO.ts} +2 -2
  8. package/dist/chunks/{chunk-TZMVSTAM.ts → chunk-BYVHABNR.ts} +4 -4
  9. package/dist/chunks/chunk-ECYCNZOE.ts +12 -0
  10. package/dist/chunks/chunk-ECYCNZOE.ts.map +7 -0
  11. package/dist/chunks/{chunk-MANNB4WZ.ts → chunk-KNEUL4XN.ts} +1 -7
  12. package/dist/chunks/chunk-KNEUL4XN.ts.map +7 -0
  13. package/dist/chunks/chunk-Z5JMOXJM.ts +106 -0
  14. package/dist/chunks/chunk-Z5JMOXJM.ts.map +7 -0
  15. package/dist/chunks/{command-handler-YZ4DXQ7N.ts → command-handler-44EFGPWH.ts} +9 -7
  16. package/dist/chunks/{command-handler-YZ4DXQ7N.ts.map → command-handler-44EFGPWH.ts.map} +1 -1
  17. package/dist/chunks/{file-selection-DDQN4LVD.ts → file-selection-XWACUTAH.ts} +8 -8
  18. package/dist/chunks/ignore-file-ui-OHFISFVC.ts +21 -0
  19. package/dist/chunks/{manager-result-dispatcher-XB75YLEG.ts → manager-result-dispatcher-WXE2BAQO.ts} +3 -3
  20. package/dist/chunks/{manager-ui-RGA26Z6G.ts → manager-ui-CVZLMXJ5.ts} +57 -45
  21. package/dist/chunks/manager-ui-CVZLMXJ5.ts.map +7 -0
  22. package/dist/chunks/{remote-selection-ui-WVMET5RI.ts → remote-selection-ui-E4XZCQ7A.ts} +2 -2
  23. package/dist/chunks/remote-selection-ui-E4XZCQ7A.ts.map +7 -0
  24. package/dist/chunks/{setup-wizard-YP2KF2WQ.ts → setup-wizard-IEW56AZE.ts} +7 -5
  25. package/dist/chunks/{setup-wizard-YP2KF2WQ.ts.map → setup-wizard-IEW56AZE.ts.map} +1 -1
  26. package/dist/daemon/dist/consent.js +14 -2
  27. package/dist/daemon/dist/engine/backends/git/git-backend.js +5 -3
  28. package/dist/daemon/dist/engine/backends/git/git-storage.js +15 -3
  29. package/dist/daemon/dist/engine/ignore/adoption-journal.js +143 -0
  30. package/dist/daemon/dist/engine/ignore/snapshot-ignore-rules.js +39 -0
  31. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +2 -2
  32. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +6 -6
  33. package/dist/daemon/dist/engine/snapshot/snapshot-types.js +5 -1
  34. package/dist/daemon/dist/engine/snapshot/snapshot.js +5 -2
  35. package/dist/daemon/dist/engine/sync/conflict-review.js +2 -0
  36. package/dist/daemon/dist/engine/sync/continuous-watch.js +3 -2
  37. package/dist/daemon/dist/engine/sync/directional-action.js +3 -8
  38. package/dist/daemon/dist/engine/sync/ignore-adoption-recovery.js +50 -0
  39. package/dist/daemon/dist/engine/sync/ignore-adoption.js +401 -0
  40. package/dist/daemon/dist/engine/sync/ignore-publication.js +23 -0
  41. package/dist/daemon/dist/engine/sync/initialization.js +12 -0
  42. package/dist/daemon/dist/engine/sync/local-fields.js +6 -3
  43. package/dist/daemon/dist/engine/sync/merge-journal.js +2 -2
  44. package/dist/daemon/dist/engine/sync/merged-sync.js +14 -3
  45. package/dist/daemon/dist/engine/sync/sync-local.js +2 -1
  46. package/dist/daemon/dist/engine/sync/sync-mutations.js +82 -19
  47. package/dist/daemon/dist/engine/sync/sync-policy.js +5 -5
  48. package/dist/daemon/dist/engine/sync/sync-queries.js +1 -1
  49. package/dist/daemon/dist/engine/sync/sync-rollback.js +9 -3
  50. package/dist/daemon/dist/engine/ui/ignore-rule-preview.js +18 -0
  51. package/dist/daemon/dist/engine-service.js +1 -1
  52. package/dist/daemon/package.json +1 -1
  53. package/dist/index.ts +1 -1
  54. package/docs/tui-contract.md +3 -3
  55. package/package.json +2 -2
  56. package/skills/configure-pi-sync/references/configuration.md +10 -8
  57. package/src/ui/ignore-file-ui.ts +13 -5
  58. package/src/ui/manager-state.ts +15 -8
  59. package/src/ui/manager-ui.ts +1 -1
  60. package/src/ui/remote-selection-ui.ts +43 -2
  61. package/src/ui/settings-ui.ts +30 -30
  62. package/dist/chunks/chunk-MANNB4WZ.ts.map +0 -7
  63. package/dist/chunks/chunk-OBVJTKVY.ts.map +0 -7
  64. package/dist/chunks/chunk-OWEOZZZE.ts.map +0 -7
  65. package/dist/chunks/manager-ui-RGA26Z6G.ts.map +0 -7
  66. /package/dist/chunks/{chunk-IOM6E5FW.ts.map → chunk-BESRBKVO.ts.map} +0 -0
  67. /package/dist/chunks/{chunk-TZMVSTAM.ts.map → chunk-BYVHABNR.ts.map} +0 -0
  68. /package/dist/chunks/{file-selection-DDQN4LVD.ts.map → file-selection-XWACUTAH.ts.map} +0 -0
  69. /package/dist/chunks/{manager-result-dispatcher-XB75YLEG.ts.map → ignore-file-ui-OHFISFVC.ts.map} +0 -0
  70. /package/dist/chunks/{remote-selection-ui-WVMET5RI.ts.map → manager-result-dispatcher-WXE2BAQO.ts.map} +0 -0
@@ -169,7 +169,7 @@ export function consentFingerprint(root, config) {
169
169
  throw new Error("Review daemon handover first.");
170
170
  // Keep the original digest domain across package renames; never persist the internal freshness token.
171
171
  return createHmac("sha256", consent.nonce)
172
- .update("sync-daemon-consent/v1")
172
+ .update(config.ignorePolicy ? "sync-daemon-consent/portable-ignore/v1" : "sync-daemon-consent/v1")
173
173
  .update(syncCheckConfigFingerprint(config))
174
174
  .digest("hex");
175
175
  }
@@ -179,6 +179,17 @@ export function automaticPolicyAuthorized(root, config) {
179
179
  const saved = readConsent(root)?.setups[config.setupName];
180
180
  return saved?.automaticFingerprint !== undefined && saved.automaticFingerprint === consentFingerprint(root, config);
181
181
  }
182
+ function ignorePublicationConsentLines(config) {
183
+ const policy = config.ignorePolicy;
184
+ if (!policy)
185
+ return [];
186
+ return [
187
+ "Review this file before you approve its scope. Peers must be able to read snapshot version 7.",
188
+ policy.matches(policy.filename)
189
+ ? "The rule file excludes itself; new snapshots omit its text."
190
+ : "New snapshots include the rule file, including any rule comments and private path names.",
191
+ ];
192
+ }
182
193
  export async function reviewAutomaticPolicy(execution, config, expectedFingerprint) {
183
194
  if (consentFingerprint(execution.root, config) !== expectedFingerprint)
184
195
  throw new Error("Setup changed; reopen the automatic transfer review.");
@@ -227,7 +238,7 @@ export async function reviewAutomaticPolicy(execution, config, expectedFingerpri
227
238
  ...(config.ignorePolicy
228
239
  ? [
229
240
  `Local ignore file: ${safeTerminalText(config.ignorePolicy.filename)}`,
230
- "Review this file before you approve its scope.",
241
+ ...ignorePublicationConsentLines(config),
231
242
  ]
232
243
  : []),
233
244
  `Enabled modes: ${modes.join("; ")}`,
@@ -352,6 +363,7 @@ export async function authorizeAfterExit(execution, payload) {
352
363
  ? [
353
364
  "Selected content: eligible files in the Pi agent directory",
354
365
  `Local ignore file: ${safeTerminalText(config.ignorePolicy.filename)}`,
366
+ ...ignorePublicationConsentLines(config),
355
367
  `Session opt-in: ${config.ignorePolicy.sessions ? "On — ignore rules still apply" : "Off"}`,
356
368
  ].join("\n")
357
369
  : config.scope === "agent-directory"
@@ -4,7 +4,7 @@ import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { posixJoin } from "../../paths.js";
6
6
  import { snapshotFileFromBlob } from "../../snapshot/snapshot-payload.js";
7
- import { IGNORE_SNAPSHOT_VERSION } from "../../snapshot/snapshot-types.js";
7
+ import { isIgnoreSnapshotVersion } from "../../snapshot/snapshot-types.js";
8
8
  import { stateDir } from "../../state/state-directory.js";
9
9
  import { throwIfAborted } from "../../sync/signals.js";
10
10
  import { syncErrorGuidance } from "../../sync/sync-error-guidance.js";
@@ -119,6 +119,7 @@ export class GitSyncBackend {
119
119
  profile: manifest.profile,
120
120
  ...(manifest.snapshotSyncSessions === undefined ? {} : { syncSessions: manifest.snapshotSyncSessions }),
121
121
  ...(manifest.selection === undefined ? {} : { selection: structuredClone(manifest.selection) }),
122
+ ...(manifest.ignoreRules === undefined ? {} : { ignoreRules: structuredClone(manifest.ignoreRules) }),
122
123
  ...(manifest.localFields === undefined ? {} : { localFields: [...manifest.localFields] }),
123
124
  files,
124
125
  };
@@ -143,6 +144,7 @@ export class GitSyncBackend {
143
144
  syncSessions: snapshot.syncSessions === true || snapshot.files.some((file) => file.path.startsWith("sessions/")),
144
145
  ...(snapshot.syncSessions === undefined ? {} : { snapshotSyncSessions: snapshot.syncSessions }),
145
146
  ...(snapshot.selection === undefined ? {} : { selection: snapshot.selection }),
147
+ ...(snapshot.ignoreRules === undefined ? {} : { ignoreRules: snapshot.ignoreRules }),
146
148
  ...(snapshot.localFields === undefined ? {} : { localFields: snapshot.localFields }),
147
149
  files: files.map(({ path: filePath, sha256: fileSha, size }) => ({
148
150
  path: filePath,
@@ -566,7 +568,7 @@ export class GitSyncBackend {
566
568
  (await this.git(["show", `${commit}:${this.manifestPath()}`], { signal, maxOutputBytes: MAX_GIT_MANIFEST_BYTES }))
567
569
  .stdout;
568
570
  const manifest = parseGitManifest(bytes);
569
- const entries = await this.readPublicationTree(commit, signal, manifest.snapshotVersion === IGNORE_SNAPSHOT_VERSION);
571
+ const entries = await this.readPublicationTree(commit, signal, isIgnoreSnapshotVersion(manifest.snapshotVersion));
570
572
  const payloadEntries = validateGitPublicationTree(entries, manifest, this.manifestPath(), (filePath) => this.filePath(filePath));
571
573
  return { manifest, payloadEntries };
572
574
  }
@@ -633,7 +635,7 @@ function parseGitManifest(bytes) {
633
635
  if (parsed &&
634
636
  typeof parsed === "object" &&
635
637
  "snapshotVersion" in parsed &&
636
- parsed.snapshotVersion === IGNORE_SNAPSHOT_VERSION &&
638
+ isIgnoreSnapshotVersion(parsed.snapshotVersion) &&
637
639
  !isUtf8(bytes)) {
638
640
  throw new Error("Git publication manifest is not valid UTF-8.");
639
641
  }
@@ -1,6 +1,7 @@
1
+ import { validateSnapshotIgnoreRules } from "../../ignore/snapshot-ignore-rules.js";
1
2
  import { assertAgentDirectorySettingsSize, MAX_AGENT_DIRECTORY_BYTES } from "../../snapshot/snapshot-bounds.js";
2
3
  import { materializeSnapshotFilePayload } from "../../snapshot/snapshot-payload.js";
3
- import { IGNORE_SNAPSHOT_VERSION, isSupportedSnapshotVersion, } from "../../snapshot/snapshot-types.js";
4
+ import { isIgnoreSnapshotVersion, isSupportedSnapshotVersion, } from "../../snapshot/snapshot-types.js";
4
5
  import { sameLocalFields, validateIgnoreSnapshotIdentity, validateIgnoreSnapshotSessionFlag, validatePortableSnapshot, validateSnapshotFieldPolicy, } from "../../sync/local-fields.js";
5
6
  import { assertAgentDirectoryPathLayout, assertSnapshotExcludesDebugLog, assertSnapshotPathExcludesDebugLog, configuredSnapshotPathMatcher, portableSnapshotSelection, sameSnapshotSelection, snapshotSelectionInclude, validateSnapshotSelection, } from "../../sync/sync-policy.js";
6
7
  export const GIT_MANIFEST_VERSION = 2;
@@ -48,6 +49,7 @@ export function requireGitManifest(value) {
48
49
  "syncSessions",
49
50
  ...(manifest.snapshotSyncSessions === undefined ? [] : ["snapshotSyncSessions"]),
50
51
  ...(manifest.selection === undefined ? [] : ["selection"]),
52
+ ...(Object.hasOwn(manifest, "ignoreRules") ? ["ignoreRules"] : []),
51
53
  ...(manifest.localFields === undefined ? [] : ["localFields"]),
52
54
  "files",
53
55
  ])) {
@@ -56,6 +58,11 @@ export function requireGitManifest(value) {
56
58
  validateSnapshotFieldPolicy({ version: manifest.snapshotVersion, localFields: manifest.localFields });
57
59
  const selection = manifest.selection === undefined ? undefined : portableSnapshotSelection(manifest.selection);
58
60
  validateSnapshotSelection({ version: manifest.snapshotVersion, selection });
61
+ const policy = validateSnapshotIgnoreRules({
62
+ version: manifest.snapshotVersion,
63
+ selection,
64
+ ...(Object.hasOwn(manifest, "ignoreRules") ? { ignoreRules: manifest.ignoreRules } : {}),
65
+ });
59
66
  const ignoreSnapshot = selection?.version === 4;
60
67
  if (ignoreSnapshot) {
61
68
  validateIgnoreSnapshotIdentity({
@@ -66,7 +73,9 @@ export function requireGitManifest(value) {
66
73
  });
67
74
  validateIgnoreSnapshotSessionFlag(selection, manifest.snapshotSyncSessions);
68
75
  }
69
- const selected = selection?.scope ? configuredSnapshotPathMatcher(selection) : undefined;
76
+ const selected = selection?.scope
77
+ ? configuredSnapshotPathMatcher(policy ? { ...selection, ignorePolicy: policy } : selection)
78
+ : undefined;
70
79
  const byteLimit = ignoreSnapshot ? MAX_AGENT_DIRECTORY_BYTES : MAX_GIT_SNAPSHOT_BYTES;
71
80
  let total = 0;
72
81
  let hasSessionFiles = false;
@@ -121,6 +130,9 @@ export function validateGitSnapshot(snapshot, manifest, namespace) {
121
130
  snapshot.syncSessions !== manifest.snapshotSyncSessions ||
122
131
  syncSessions !== manifest.syncSessions ||
123
132
  !sameSnapshotSelection(snapshot.selection, manifest.selection) ||
133
+ (snapshot.ignoreRules === null) !== (manifest.ignoreRules === null) ||
134
+ snapshot.ignoreRules?.filename !== manifest.ignoreRules?.filename ||
135
+ snapshot.ignoreRules?.text !== manifest.ignoreRules?.text ||
124
136
  prepared.length !== manifest.files.length ||
125
137
  prepared.some((file, index) => {
126
138
  const expected = manifest.files[index];
@@ -131,7 +143,7 @@ export function validateGitSnapshot(snapshot, manifest, namespace) {
131
143
  }
132
144
  export function prepareGitSnapshot(snapshot, namespace) {
133
145
  assertSnapshotExcludesDebugLog(snapshot);
134
- if (snapshot.version !== IGNORE_SNAPSHOT_VERSION)
146
+ if (!isIgnoreSnapshotVersion(snapshot.version))
135
147
  snapshotSelectionInclude(snapshot);
136
148
  validatePortableSnapshot(snapshot);
137
149
  if (typeof snapshot.id !== "string" ||
@@ -0,0 +1,143 @@
1
+ import { createHash } from "node:crypto";
2
+ import { constants, lstatSync } from "node:fs";
3
+ import fs from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { validateConfigName } from "../settings/settings-validation.js";
6
+ import { syncDirectory, writeJson } from "../state/json-file.js";
7
+ import { stateDir } from "../state/state-directory.js";
8
+ import { compileIgnoreRules, sameFile, validateIgnoreFilename } from "./ignore-source.js";
9
+ const MAX_BYTES = 32 * 1024 * 1024;
10
+ const recoveryMessage = "Pending ignore-rule adoption. Run a reviewed Pull from the originating setup, or preserve its recovery evidence.";
11
+ function journalPath() {
12
+ return path.join(stateDir(), "ignore-adoption.json");
13
+ }
14
+ export function hasPendingAdoption() {
15
+ return lstatSync(journalPath(), { throwIfNoEntry: false }) !== undefined;
16
+ }
17
+ export function requireNoPendingAdoption() {
18
+ if (hasPendingAdoption())
19
+ throw new Error(recoveryMessage);
20
+ }
21
+ function hex(value) {
22
+ return typeof value === "string" && /^[a-f0-9]{64}$/u.test(value);
23
+ }
24
+ function fileIdentity(value) {
25
+ return typeof value === "string" && /^\d+:\d+:-?\d+$/u.test(value);
26
+ }
27
+ function hashMap(value) {
28
+ return Boolean(value &&
29
+ typeof value === "object" &&
30
+ !Array.isArray(value) &&
31
+ Object.keys(value).length <= 16_384 &&
32
+ Object.values(value).every(hex));
33
+ }
34
+ async function readAdoptionJournal() {
35
+ const target = journalPath();
36
+ const before = await fs.lstat(target);
37
+ if (!before.isFile() ||
38
+ before.nlink !== 1 ||
39
+ before.size > MAX_BYTES ||
40
+ (process.getuid && before.uid !== process.getuid()) ||
41
+ (process.platform !== "win32" && before.mode & 0o077))
42
+ throw new Error(recoveryMessage);
43
+ const handle = await fs.open(target, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
44
+ try {
45
+ const stat = await handle.stat();
46
+ if (stat.dev !== before.dev ||
47
+ stat.ino !== before.ino ||
48
+ stat.size !== before.size ||
49
+ stat.mtimeMs !== before.mtimeMs)
50
+ throw new Error(recoveryMessage);
51
+ const bytes = Buffer.alloc(stat.size);
52
+ const { bytesRead } = await handle.read(bytes);
53
+ if (bytesRead !== bytes.length || (await handle.stat()).mtimeMs !== stat.mtimeMs)
54
+ throw new Error(recoveryMessage);
55
+ return JSON.parse(bytes.toString("utf8"));
56
+ }
57
+ finally {
58
+ await handle.close();
59
+ }
60
+ }
61
+ export async function loadAdoptionJournal() {
62
+ if (!hasPendingAdoption())
63
+ return;
64
+ try {
65
+ const journal = await readAdoptionJournal();
66
+ if (journal?.version !== 1 ||
67
+ !hex(journal.setupFingerprint) ||
68
+ !hex(journal.stateFingerprint) ||
69
+ !fileIdentity(journal.sourceIdentity) ||
70
+ (journal.installedIdentity !== undefined && !fileIdentity(journal.installedIdentity)) ||
71
+ typeof journal.beforeRules !== "string" ||
72
+ typeof journal.afterRules !== "string" ||
73
+ !hashMap(journal.beforeFiles) ||
74
+ !hashMap(journal.afterFiles) ||
75
+ !hex(journal.remoteFilesIdentity) ||
76
+ !hex(journal.backupDigest) ||
77
+ typeof journal.head?.snapshotId !== "string" ||
78
+ typeof journal.head?.snapshotRef !== "string" ||
79
+ typeof journal.head?.revision !== "string" ||
80
+ (journal.sessionDir !== undefined && !path.isAbsolute(journal.sessionDir)) ||
81
+ typeof journal.backupId !== "string" ||
82
+ !/^[\w-]{1,128}$/u.test(journal.backupId))
83
+ throw new Error(recoveryMessage);
84
+ validateConfigName(journal.setupName, "sync setup");
85
+ validateIgnoreFilename(journal.filename);
86
+ compileIgnoreRules(journal.beforeRules);
87
+ compileIgnoreRules(journal.afterRules);
88
+ return journal;
89
+ }
90
+ catch (cause) {
91
+ throw new Error(recoveryMessage, { cause });
92
+ }
93
+ }
94
+ export async function verifyAdoptionBackup(journal, signal) {
95
+ const backups = path.join(stateDir(), "backups");
96
+ if (!(await fs.lstat(backups)).isDirectory())
97
+ throw new Error(recoveryMessage);
98
+ const backup = path.join(backups, `${journal.backupId}.json.gz`);
99
+ const handle = await fs.open(backup, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
100
+ try {
101
+ const stat = await handle.stat({ bigint: true });
102
+ if (!stat.isFile() || stat.nlink !== 1n || stat.size < 1n || stat.size > 128n * 1024n * 1024n)
103
+ throw new Error(recoveryMessage);
104
+ const hash = createHash("sha256");
105
+ const stream = handle.createReadStream({ start: 0, end: Number(stat.size) - 1, autoClose: false, signal });
106
+ for await (const chunk of stream)
107
+ hash.update(chunk);
108
+ if (hash.digest("hex") !== journal.backupDigest || !sameFile(stat, await fs.lstat(backup, { bigint: true })))
109
+ throw new Error("The original Pull backup changed; preserve the adoption journal.");
110
+ signal?.throwIfAborted();
111
+ }
112
+ finally {
113
+ await handle.close();
114
+ }
115
+ }
116
+ export async function createAdoptionJournal(journal) {
117
+ requireNoPendingAdoption();
118
+ const target = journalPath();
119
+ await writeJson(target, journal, { maxBytes: MAX_BYTES });
120
+ await syncDirectory(path.dirname(path.dirname(target)));
121
+ }
122
+ async function assertCurrentJournal(journal) {
123
+ if (JSON.stringify(await loadAdoptionJournal()) !== JSON.stringify(journal))
124
+ throw new Error(recoveryMessage);
125
+ }
126
+ export async function recordInstalledIdentity(journal, identity) {
127
+ await assertCurrentJournal(journal);
128
+ const next = { ...journal, installedIdentity: identity };
129
+ await writeJson(journalPath(), next, { maxBytes: MAX_BYTES });
130
+ return next;
131
+ }
132
+ export async function completeAdoptionJournal(journal) {
133
+ await assertCurrentJournal(journal);
134
+ const target = journalPath();
135
+ const backups = path.join(path.dirname(target), "backups");
136
+ if (!(await fs.lstat(backups)).isDirectory())
137
+ throw new Error(recoveryMessage);
138
+ const archived = path.join(backups, `${journal.backupId}.ignore-adoption.json`);
139
+ await fs.rename(target, archived);
140
+ await syncDirectory(backups);
141
+ await syncDirectory(path.dirname(target));
142
+ return archived;
143
+ }
@@ -0,0 +1,39 @@
1
+ import { RULES_SNAPSHOT_VERSION } from "../snapshot/snapshot-types.js";
2
+ import { compileIgnoreRules, DEFAULT_IGNORE_FILENAME, ignorePolicyFingerprint, ignoreSourceDigest, validateIgnoreFilename, } from "./ignore-source.js";
3
+ export function validateSnapshotIgnoreRules(snapshot) {
4
+ if (snapshot.version !== RULES_SNAPSHOT_VERSION) {
5
+ if (Object.hasOwn(snapshot, "ignoreRules"))
6
+ throw new Error("Unexpected snapshot ignore rules.");
7
+ return;
8
+ }
9
+ const selection = snapshot.selection;
10
+ if (selection?.version !== 4 || !Object.hasOwn(snapshot, "ignoreRules"))
11
+ throw new Error("Missing snapshot ignore policy.");
12
+ const rules = snapshot.ignoreRules;
13
+ if (rules === null)
14
+ return;
15
+ if (!rules ||
16
+ typeof rules !== "object" ||
17
+ !Object.hasOwn(rules, "text") ||
18
+ !Object.hasOwn(rules, "filename") ||
19
+ Object.keys(rules).length !== 2 ||
20
+ typeof rules.text !== "string")
21
+ throw new Error("Invalid snapshot ignore rules.");
22
+ const filename = validateIgnoreFilename(rules.filename);
23
+ const matches = compileIgnoreRules(rules.text);
24
+ if (matches(filename) || ignorePolicyFingerprint(rules.text, selection.sessions) !== selection.fingerprint)
25
+ throw new Error("Snapshot ignore rules do not match the published policy.");
26
+ return {
27
+ filename,
28
+ fingerprint: selection.fingerprint,
29
+ sessions: selection.sessions,
30
+ sourceDigest: ignoreSourceDigest(filename, true, Buffer.from(rules.text)),
31
+ reservedNames: [...new Set([DEFAULT_IGNORE_FILENAME, filename.toLowerCase()])].sort(),
32
+ matches,
33
+ };
34
+ }
35
+ export function selectSnapshotIgnoreRules(source, policy) {
36
+ if (!source.present || source.filename !== policy.filename || source.sourceDigest !== policy.sourceDigest)
37
+ throw new Error("Ignore file changed before publication; reopen the review.");
38
+ return policy.matches(source.filename) ? null : { filename: source.filename, text: source.text };
39
+ }
@@ -15,7 +15,7 @@ import { decodeBase64Strict } from "./snapshot-payload.js";
15
15
  import { reviewedSnapshotPreimages } from "./snapshot-reviewed-preimages.js";
16
16
  import { applySnapshotTransaction, recoverPendingSnapshotTransactions, } from "./snapshot-transaction.js";
17
17
  import { ignorePolicyValidator } from "./snapshot-transaction-policy.js";
18
- import { IGNORE_SNAPSHOT_VERSION, } from "./snapshot-types.js";
18
+ import { isIgnoreSnapshotVersion, } from "./snapshot-types.js";
19
19
  function sha256(value) {
20
20
  return createHash("sha256").update(value).digest("hex");
21
21
  }
@@ -24,7 +24,7 @@ function fileHashMap(snapshot) {
24
24
  }
25
25
  function assertSnapshotApplyPolicy(snapshot, options) {
26
26
  assertSnapshotExcludesDebugLog(snapshot);
27
- if (snapshot.version !== IGNORE_SNAPSHOT_VERSION) {
27
+ if (!isIgnoreSnapshotVersion(snapshot.version)) {
28
28
  requireLegacyTransferPolicy(snapshot);
29
29
  if (options.ignorePolicy)
30
30
  throw new Error("Project the snapshot into the reviewed local ignore-file policy before applying it.");
@@ -5,7 +5,7 @@ import { promisify } from "node:util";
5
5
  import { createGunzip, gzip } from "node:zlib";
6
6
  import { throwIfAborted } from "../sync/signals.js";
7
7
  import { assertSnapshotExcludesDebugLog, snapshotSelectionInclude, validateSnapshotSelection, } from "../sync/sync-policy.js";
8
- import { IGNORE_SNAPSHOT_VERSION, isSupportedSnapshotVersion } from "./snapshot-types.js";
8
+ import { isIgnoreSnapshotVersion, isSupportedSnapshotVersion } from "./snapshot-types.js";
9
9
  const VERSION = 1;
10
10
  const MAX_DECOMPRESSED_SNAPSHOT_BYTES = 512 * 1024 * 1024;
11
11
  const gzipAsync = promisify(gzip);
@@ -13,10 +13,10 @@ export async function encodeSnapshot(snapshot) {
13
13
  if (!isSupportedSnapshotVersion(snapshot?.version))
14
14
  throw new Error("Unsupported snapshot format.");
15
15
  assertSnapshotExcludesDebugLog(snapshot);
16
- if (snapshot.version !== IGNORE_SNAPSHOT_VERSION)
16
+ if (!isIgnoreSnapshotVersion(snapshot.version))
17
17
  snapshotSelectionInclude(snapshot);
18
18
  validateSnapshotSelection(snapshot);
19
- if (snapshot.version === 4 || snapshot.version === 5 || snapshot.version === IGNORE_SNAPSHOT_VERSION) {
19
+ if (snapshot.version >= 4 || Object.hasOwn(snapshot, "ignoreRules")) {
20
20
  const { validatePortableSnapshot } = await import("../sync/local-fields.js");
21
21
  validatePortableSnapshot(snapshot);
22
22
  }
@@ -45,11 +45,11 @@ export async function decodeSnapshot(buffer, options = {}) {
45
45
  if (!isSupportedSnapshotVersion(parsed?.version) || !Array.isArray(parsed.files)) {
46
46
  throw new Error("Unsupported snapshot format.");
47
47
  }
48
- if (parsed.version === IGNORE_SNAPSHOT_VERSION && !isUtf8(payload))
48
+ if (isIgnoreSnapshotVersion(parsed.version) && !isUtf8(payload))
49
49
  throw new Error("Invalid snapshot UTF-8.");
50
50
  assertSnapshotExcludesDebugLog(parsed);
51
51
  validateSnapshotSelection(parsed);
52
- if (parsed.version !== VERSION) {
52
+ if (parsed.version !== VERSION || Object.hasOwn(parsed, "ignoreRules")) {
53
53
  const { normalizeLocalFields, validatePortableSnapshot } = await import("../sync/local-fields.js");
54
54
  validatePortableSnapshot(parsed);
55
55
  if (parsed.localFields !== undefined)
@@ -57,7 +57,7 @@ export async function decodeSnapshot(buffer, options = {}) {
57
57
  }
58
58
  else if (parsed.localFields !== undefined)
59
59
  throw new Error("Portable field policy requires snapshot version 2.");
60
- if (parsed.version !== IGNORE_SNAPSHOT_VERSION)
60
+ if (!isIgnoreSnapshotVersion(parsed.version))
61
61
  snapshotSelectionInclude(parsed);
62
62
  return parsed;
63
63
  }
@@ -1,9 +1,13 @@
1
1
  export const IGNORE_SNAPSHOT_VERSION = 6;
2
+ export const RULES_SNAPSHOT_VERSION = 7;
3
+ export function isIgnoreSnapshotVersion(version) {
4
+ return version === IGNORE_SNAPSHOT_VERSION || version === RULES_SNAPSHOT_VERSION;
5
+ }
2
6
  export function isSupportedSnapshotVersion(version) {
3
7
  return (version === 1 ||
4
8
  version === 2 ||
5
9
  version === 3 ||
6
10
  version === 4 ||
7
11
  version === 5 ||
8
- version === IGNORE_SNAPSHOT_VERSION);
12
+ isIgnoreSnapshotVersion(version));
9
13
  }
@@ -532,8 +532,9 @@ export function filterSnapshotForConfigPolicy(snapshot, config, options = {}) {
532
532
  const files = wholeDirectory
533
533
  ? filterAgentDirectoryFiles(snapshot.files, config, options.sessionDir)
534
534
  : canonicalizeSnapshotFilesForConfig(snapshot.files, config, customIncludePathsByLower(include));
535
+ const { ignoreRules: _ignoreRules, ...image } = snapshot;
535
536
  const filtered = {
536
- ...snapshot,
537
+ ...image,
537
538
  version: selection.version === 4
538
539
  ? IGNORE_SNAPSHOT_VERSION
539
540
  : wholeDirectory
@@ -549,7 +550,7 @@ export function filterSnapshotForConfigPolicy(snapshot, config, options = {}) {
549
550
  selection,
550
551
  files,
551
552
  };
552
- if (!options.regenerateId || snapshotsMatch(snapshot, filtered))
553
+ if (!options.regenerateId || (snapshot.version === filtered.version && snapshotsMatch(snapshot, filtered)))
553
554
  return filtered;
554
555
  return {
555
556
  ...filtered,
@@ -641,6 +642,8 @@ export function scanSnapshot(snapshot) {
641
642
  }
642
643
  }
643
644
  }
645
+ if (snapshot.ignoreRules && SECRET_PATTERNS.some((pattern) => pattern.test(snapshot.ignoreRules?.text ?? "")))
646
+ findings.push(snapshot.ignoreRules.filename);
644
647
  return findings;
645
648
  }
646
649
  export function mergeRemotePreservedFiles(local, remote, config, options = {}) {
@@ -1,5 +1,6 @@
1
1
  import { truncateToWidth } from "@earendil-works/pi-tui";
2
2
  import { createSyncBackend } from "../backends/backend-factory.js";
3
+ import { requireNoPendingAdoption } from "../ignore/adoption-journal.js";
3
4
  import { loadConfig, syncCheckConfigFingerprint } from "../settings/config.js";
4
5
  import { readStateForConfig, syncStateFingerprint } from "../state/sync-state-store.js";
5
6
  import { confirmMergeReview } from "../ui/merge-review.js";
@@ -9,6 +10,7 @@ import { conflictPreview } from "./conflict-preview.js";
9
10
  import { mergeSync } from "./merged-sync.js";
10
11
  import { captureMutationOwner } from "./sync-local.js";
11
12
  export async function showConflicts(ctx, options, factory = createSyncBackend) {
13
+ requireNoPendingAdoption();
12
14
  const validate = captureMutationOwner(ctx, options.signal);
13
15
  const config = await loadConfig(options.setup);
14
16
  validate();
@@ -1,4 +1,4 @@
1
- import { watch } from "node:fs";
1
+ import { existsSync, watch } from "node:fs";
2
2
  import fs from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import { getEngineRoot as getAgentDir } from "../host.js";
@@ -38,7 +38,8 @@ export async function watchContinuous(config, changed, options = {}) {
38
38
  if (!file || closed || options.signal?.aborted)
39
39
  return;
40
40
  const target = path.resolve(directory, String(file));
41
- if (!relativeWithin(directory, target))
41
+ const directoryOnlyHint = event === "change" && file === path.basename(directory) && !existsSync(target);
42
+ if (!relativeWithin(directory, target) || directoryOnlyHint)
42
43
  return;
43
44
  if (target === path.join(root, "pi-sync.json") ||
44
45
  (config.ignorePolicy &&
@@ -6,7 +6,7 @@ import { syncStateFingerprint } from "../state/sync-state-store.js";
6
6
  import { safeTerminalText } from "../ui/terminal-text.js";
7
7
  import { inspectCaseCleanup } from "./apply-review.js";
8
8
  import { requireCompatibleRemoteSelection } from "./remote-snapshot.js";
9
- import { inspectRemoteSelection, syncSelectionHasContent, syncSessionsSelected } from "./sync-policy.js";
9
+ import { syncSelectionHasContent, syncSessionsSelected } from "./sync-policy.js";
10
10
  import { fileHashMap, syncPolicyChanged } from "./sync-state.js";
11
11
  import { checkLiveProtection } from "./transfer-freshness.js";
12
12
  export function foregroundDirectionalAction(ctx, options) {
@@ -63,13 +63,8 @@ export function requireDirectionalSelection(config, state, local, remote, sessio
63
63
  ((priorSessions && !current.sessions) ||
64
64
  priorPaths.some((item) => !managed.has(item) && current.matches(item, false))));
65
65
  };
66
- if (remote) {
67
- const selection = inspectRemoteSelection(config.include, remote, config.exclude, config);
68
- if (!(selection.ignorePolicyComparison === "mismatch" &&
69
- remote.selection?.version === 4 &&
70
- provesNarrowing(remote.files.map((file) => file.path), remote.selection.sessions)))
71
- requireCompatibleRemoteSelection(config, remote);
72
- }
66
+ if (remote)
67
+ requireCompatibleRemoteSelection(config, remote);
73
68
  if (state.lastAppliedSnapshot &&
74
69
  syncPolicyChanged(state, config) &&
75
70
  !(state.scope === config.scope &&
@@ -0,0 +1,50 @@
1
+ import { loadAdoptionJournal, verifyAdoptionBackup } from "../ignore/adoption-journal.js";
2
+ import { compileIgnoreRules, ignorePolicyFingerprint, ignoreSourceDigest } from "../ignore/ignore-source.js";
3
+ import { loadConfigForCheck } from "../settings/config.js";
4
+ import { resolvedSnapshotOptionsForContext } from "../snapshot/session-paths.js";
5
+ import { recoverPendingSnapshotTransactions } from "../snapshot/snapshot-transaction.js";
6
+ import { pendingTransactionEntries } from "../snapshot/snapshot-transaction-directory.js";
7
+ import { withLock } from "../state/lock.js";
8
+ import { readStateForConfig, syncStateFingerprint } from "../state/sync-state-store.js";
9
+ import { adoptionSettingsFingerprint } from "./ignore-adoption.js";
10
+ export async function recoverAdoptionFilesOnStartup(ctx, signal, validate) {
11
+ await withLock("recovery", async () => {
12
+ validate();
13
+ if (!(await pendingTransactionEntries()).length)
14
+ return;
15
+ const journal = await loadAdoptionJournal();
16
+ if (!journal)
17
+ throw new Error("Adoption recovery evidence changed; restart Pi Sync before editing files.");
18
+ const config = await loadConfigForCheck(journal.setupName, signal);
19
+ const policy = config.ignorePolicy;
20
+ const stale = () => new Error("Pending adoption and file transaction no longer match. Preserve both journals.");
21
+ if (!policy ||
22
+ adoptionSettingsFingerprint(config) !== journal.setupFingerprint ||
23
+ policy.filename !== journal.filename ||
24
+ config.ignoreSourceIdentity !== journal.sourceIdentity ||
25
+ policy.fingerprint !== ignorePolicyFingerprint(journal.beforeRules, policy.sessions) ||
26
+ syncStateFingerprint(await readStateForConfig(config)) !== journal.stateFingerprint)
27
+ throw stale();
28
+ const options = await resolvedSnapshotOptionsForContext(ctx, config, signal);
29
+ if (options.sessionDir !== journal.sessionDir)
30
+ throw stale();
31
+ await verifyAdoptionBackup(journal, signal);
32
+ validate();
33
+ const current = ctx.sessionManager.getSessionFile?.();
34
+ await recoverPendingSnapshotTransactions({
35
+ ...options,
36
+ ignorePolicy: {
37
+ ...policy,
38
+ fingerprint: ignorePolicyFingerprint(journal.afterRules, policy.sessions),
39
+ sourceDigest: ignoreSourceDigest(journal.filename, true, Buffer.from(journal.afterRules)),
40
+ matches: compileIgnoreRules(journal.afterRules),
41
+ },
42
+ validateMutation: validate,
43
+ protectedTargets: [...(ctx.protectedSessionFiles ?? []), ...(current ? [current] : [])],
44
+ });
45
+ validate();
46
+ if ((await pendingTransactionEntries()).length)
47
+ throw stale();
48
+ validate();
49
+ }, { reclaimStale: true });
50
+ }