@narumitw/pi-sync 0.64.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 (116) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +80 -11
  3. package/dist/chunks/{chunk-TJ7YNITN.ts → chunk-5YOLQKNZ.ts} +39 -3
  4. package/dist/chunks/chunk-5YOLQKNZ.ts.map +7 -0
  5. package/dist/chunks/{chunk-NDEZ52SS.ts → chunk-ASU3GZPW.ts} +11 -93
  6. package/dist/chunks/chunk-ASU3GZPW.ts.map +7 -0
  7. package/dist/chunks/{chunk-CKUGCBHP.ts → chunk-AYGMIMCV.ts} +2 -2
  8. package/dist/chunks/chunk-AYGMIMCV.ts.map +7 -0
  9. package/dist/chunks/{chunk-F3VODLVQ.ts → chunk-BESRBKVO.ts} +3 -3
  10. package/dist/chunks/{chunk-TZMVSTAM.ts → chunk-BYVHABNR.ts} +4 -4
  11. package/dist/chunks/chunk-ECYCNZOE.ts +12 -0
  12. package/dist/chunks/chunk-ECYCNZOE.ts.map +7 -0
  13. package/dist/chunks/{chunk-RW44KNFD.ts → chunk-JQ5BAWW2.ts} +182 -12
  14. package/dist/chunks/chunk-JQ5BAWW2.ts.map +7 -0
  15. package/dist/chunks/{chunk-MANNB4WZ.ts → chunk-KNEUL4XN.ts} +1 -7
  16. package/dist/chunks/chunk-KNEUL4XN.ts.map +7 -0
  17. package/dist/chunks/{chunk-VPSC7BXM.ts → chunk-SZJOUVCL.ts} +2 -2
  18. package/dist/chunks/{chunk-YT6PDRMM.ts → chunk-WJQ4TGN5.ts} +17 -17
  19. package/dist/chunks/chunk-WJQ4TGN5.ts.map +7 -0
  20. package/dist/chunks/{chunk-4VKWHVUO.ts → chunk-XUZV4OGI.ts} +3 -2
  21. package/dist/chunks/{chunk-4VKWHVUO.ts.map → chunk-XUZV4OGI.ts.map} +2 -2
  22. package/dist/chunks/chunk-Z5JMOXJM.ts +106 -0
  23. package/dist/chunks/chunk-Z5JMOXJM.ts.map +7 -0
  24. package/dist/chunks/{command-handler-N45GY7AV.ts → command-handler-44EFGPWH.ts} +54 -13
  25. package/dist/chunks/command-handler-44EFGPWH.ts.map +7 -0
  26. package/dist/chunks/{conflict-review-5E4M44BA.ts → conflict-review-J7L7S4AR.ts} +2 -2
  27. package/dist/chunks/{file-selection-DDQN4LVD.ts → file-selection-XWACUTAH.ts} +8 -8
  28. package/dist/chunks/ignore-file-ui-OHFISFVC.ts +21 -0
  29. package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts → manager-result-dispatcher-WXE2BAQO.ts} +4 -4
  30. package/dist/chunks/{manager-ui-EV23DPZQ.ts → manager-ui-CVZLMXJ5.ts} +90 -76
  31. package/dist/chunks/manager-ui-CVZLMXJ5.ts.map +7 -0
  32. package/dist/chunks/{merge-review-6YSLSMGS.ts → merge-review-AAC674C6.ts} +3 -3
  33. package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts → remote-selection-ui-E4XZCQ7A.ts} +3 -3
  34. package/dist/chunks/{setup-switch-HY7K3442.ts → setup-switch-644T6KHG.ts} +3 -3
  35. package/dist/chunks/setup-switch-644T6KHG.ts.map +7 -0
  36. package/dist/chunks/{setup-wizard-LEKDQ3HK.ts → setup-wizard-IEW56AZE.ts} +10 -8
  37. package/dist/chunks/{setup-wizard-LEKDQ3HK.ts.map → setup-wizard-IEW56AZE.ts.map} +1 -1
  38. package/dist/chunks/{sync-inspection-OS2LVOLV.ts → sync-inspection-NBBTSMKR.ts} +2 -2
  39. package/dist/chunks/{sync-operations-D3MDJUQQ.ts → sync-operations-AIEM2KL2.ts} +2 -2
  40. package/dist/daemon/dist/client.js +125 -287
  41. package/dist/daemon/dist/consent.js +14 -2
  42. package/dist/daemon/dist/daemon-recovery.js +85 -2
  43. package/dist/daemon/dist/daemon-startup.js +257 -0
  44. package/dist/daemon/dist/engine/backends/git/git-backend.js +15 -4
  45. package/dist/daemon/dist/engine/backends/git/git-storage.js +15 -3
  46. package/dist/daemon/dist/engine/backends/s3/s3-backend.js +20 -9
  47. package/dist/daemon/dist/engine/backends/sync-backend.js +16 -0
  48. package/dist/daemon/dist/engine/backends/webdav/webdav-backend.js +19 -6
  49. package/dist/daemon/dist/engine/ignore/adoption-journal.js +143 -0
  50. package/dist/daemon/dist/engine/ignore/snapshot-ignore-rules.js +39 -0
  51. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +2 -2
  52. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +6 -6
  53. package/dist/daemon/dist/engine/snapshot/snapshot-types.js +5 -1
  54. package/dist/daemon/dist/engine/snapshot/snapshot.js +5 -2
  55. package/dist/daemon/dist/engine/sync/conflict-review.js +2 -0
  56. package/dist/daemon/dist/engine/sync/continuous-watch.js +3 -2
  57. package/dist/daemon/dist/engine/sync/directional-action.js +119 -0
  58. package/dist/daemon/dist/engine/sync/ignore-adoption-recovery.js +50 -0
  59. package/dist/daemon/dist/engine/sync/ignore-adoption.js +401 -0
  60. package/dist/daemon/dist/engine/sync/ignore-publication.js +23 -0
  61. package/dist/daemon/dist/engine/sync/initialization.js +12 -0
  62. package/dist/daemon/dist/engine/sync/local-fields.js +6 -3
  63. package/dist/daemon/dist/engine/sync/merge-journal.js +2 -2
  64. package/dist/daemon/dist/engine/sync/merged-sync.js +14 -3
  65. package/dist/daemon/dist/engine/sync/remote-snapshot.js +3 -1
  66. package/dist/daemon/dist/engine/sync/sync-errors.js +20 -0
  67. package/dist/daemon/dist/engine/sync/sync-local.js +57 -3
  68. package/dist/daemon/dist/engine/sync/sync-mutations.js +375 -346
  69. package/dist/daemon/dist/engine/sync/sync-policy.js +5 -5
  70. package/dist/daemon/dist/engine/sync/sync-queries.js +3 -2
  71. package/dist/daemon/dist/engine/sync/sync-rollback.js +204 -0
  72. package/dist/daemon/dist/engine/sync/transfer-freshness.js +11 -5
  73. package/dist/daemon/dist/engine/ui/ignore-rule-preview.js +18 -0
  74. package/dist/daemon/dist/engine-service.js +69 -1
  75. package/dist/daemon/dist/foreground-queue-outcome.js +9 -0
  76. package/dist/daemon/dist/monitor.js +1 -0
  77. package/dist/daemon/dist/server.js +76 -11
  78. package/dist/daemon/dist/service-host.js +56 -8
  79. package/dist/daemon/package.json +1 -1
  80. package/dist/index.ts +6 -6
  81. package/docs/daemon-migration.md +3 -6
  82. package/docs/tui-contract.md +3 -3
  83. package/package.json +2 -2
  84. package/skills/configure-pi-sync/references/configuration.md +10 -8
  85. package/src/commands/command-execution.ts +56 -2
  86. package/src/commands/command-handler.ts +2 -0
  87. package/src/commands/command.ts +2 -1
  88. package/src/daemon/directional-recovery.ts +103 -0
  89. package/src/daemon/pi-client.ts +112 -9
  90. package/src/ui/cancellable-operation.ts +5 -2
  91. package/src/ui/ignore-file-ui.ts +13 -5
  92. package/src/ui/manager-state.ts +17 -10
  93. package/src/ui/manager-ui.ts +30 -25
  94. package/src/ui/merge-review.ts +8 -9
  95. package/src/ui/remote-selection-ui.ts +43 -2
  96. package/src/ui/settings-ui.ts +30 -30
  97. package/src/ui/sync-confirmation.ts +7 -7
  98. package/dist/chunks/chunk-CKUGCBHP.ts.map +0 -7
  99. package/dist/chunks/chunk-MANNB4WZ.ts.map +0 -7
  100. package/dist/chunks/chunk-NDEZ52SS.ts.map +0 -7
  101. package/dist/chunks/chunk-RW44KNFD.ts.map +0 -7
  102. package/dist/chunks/chunk-TJ7YNITN.ts.map +0 -7
  103. package/dist/chunks/chunk-YT6PDRMM.ts.map +0 -7
  104. package/dist/chunks/command-handler-N45GY7AV.ts.map +0 -7
  105. package/dist/chunks/manager-ui-EV23DPZQ.ts.map +0 -7
  106. /package/dist/chunks/{chunk-F3VODLVQ.ts.map → chunk-BESRBKVO.ts.map} +0 -0
  107. /package/dist/chunks/{chunk-TZMVSTAM.ts.map → chunk-BYVHABNR.ts.map} +0 -0
  108. /package/dist/chunks/{chunk-VPSC7BXM.ts.map → chunk-SZJOUVCL.ts.map} +0 -0
  109. /package/dist/chunks/{conflict-review-5E4M44BA.ts.map → conflict-review-J7L7S4AR.ts.map} +0 -0
  110. /package/dist/chunks/{file-selection-DDQN4LVD.ts.map → file-selection-XWACUTAH.ts.map} +0 -0
  111. /package/dist/chunks/{manager-result-dispatcher-FKW55L7I.ts.map → ignore-file-ui-OHFISFVC.ts.map} +0 -0
  112. /package/dist/chunks/{merge-review-6YSLSMGS.ts.map → manager-result-dispatcher-WXE2BAQO.ts.map} +0 -0
  113. /package/dist/chunks/{remote-selection-ui-N4NMWFT2.ts.map → merge-review-AAC674C6.ts.map} +0 -0
  114. /package/dist/chunks/{setup-switch-HY7K3442.ts.map → remote-selection-ui-E4XZCQ7A.ts.map} +0 -0
  115. /package/dist/chunks/{sync-inspection-OS2LVOLV.ts.map → sync-inspection-NBBTSMKR.ts.map} +0 -0
  116. /package/dist/chunks/{sync-operations-D3MDJUQQ.ts.map → sync-operations-AIEM2KL2.ts.map} +0 -0
@@ -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 &&
@@ -0,0 +1,119 @@
1
+ import { createHash } from "node:crypto";
2
+ import { loadConfigForCheck, syncCheckConfigFingerprint } from "../settings/config.js";
3
+ import { effectiveSessionRoot } from "../snapshot/session-paths.js";
4
+ import { agentDirectoryInventory, filterSnapshotForConfigPolicy, snapshotWithoutSessions, } from "../snapshot/snapshot.js";
5
+ import { syncStateFingerprint } from "../state/sync-state-store.js";
6
+ import { safeTerminalText } from "../ui/terminal-text.js";
7
+ import { inspectCaseCleanup } from "./apply-review.js";
8
+ import { requireCompatibleRemoteSelection } from "./remote-snapshot.js";
9
+ import { syncSelectionHasContent, syncSessionsSelected } from "./sync-policy.js";
10
+ import { fileHashMap, syncPolicyChanged } from "./sync-state.js";
11
+ import { checkLiveProtection } from "./transfer-freshness.js";
12
+ export function foregroundDirectionalAction(ctx, options) {
13
+ const action = options.directionalAction;
14
+ if (action &&
15
+ (options.auto ||
16
+ options.background ||
17
+ options.force ||
18
+ options.yes ||
19
+ options.reload ||
20
+ options.stale ||
21
+ options.args.length > 0 ||
22
+ options.agentRetryRefusal ||
23
+ !ctx.hasUI ||
24
+ (ctx.mode !== "tui" && ctx.mode !== "rpc")))
25
+ throw new Error("Single-action transfer requires a bound foreground Push or Pull.");
26
+ return action;
27
+ }
28
+ export async function validateDirectionalSettings(options, config, validateMutation) {
29
+ const current = await loadConfigForCheck(undefined, options.signal);
30
+ validateMutation();
31
+ options.directionalAction?.validate(current);
32
+ if (syncCheckConfigFingerprint(current) !== syncCheckConfigFingerprint(config))
33
+ throw new Error("Settings changed before the directional transfer could write.");
34
+ }
35
+ export async function checkpointDirectionalAction(options, evidence) {
36
+ const { direction, config, state, head, local, remote, sessionDir, protectedPaths } = evidence;
37
+ const hash = createHash("sha256")
38
+ .update(JSON.stringify([
39
+ direction,
40
+ syncCheckConfigFingerprint(config),
41
+ syncStateFingerprint(state),
42
+ head,
43
+ Object.entries(fileHashMap(local)).sort(),
44
+ [...(agentDirectoryInventory(local)?.entries ?? [])].filter(([, kind]) => kind === "directory").sort(),
45
+ remote && Object.entries(fileHashMap(remote)).sort(),
46
+ sessionDir,
47
+ [...protectedPaths].sort(),
48
+ ]))
49
+ .digest("hex");
50
+ await options.directionalAction?.checkpoint?.(hash);
51
+ }
52
+ export function requireDirectionalSelection(config, state, local, remote, sessionDir) {
53
+ if (!syncSelectionHasContent(config))
54
+ throw new Error("This setup has no managed content for the transfer.");
55
+ const current = config.ignorePolicy;
56
+ const remoteProjected = current && remote && filterSnapshotForConfigPolicy(remote, config, { sessionDir });
57
+ const managed = new Set([...local.files, ...(remoteProjected?.files ?? [])].map((file) => file.path));
58
+ const provesNarrowing = (priorPaths, priorSessions) => {
59
+ if (!current || (!priorSessions && current.sessions))
60
+ return false;
61
+ const prior = new Set(priorPaths);
62
+ return ([...managed].every((item) => prior.has(item)) &&
63
+ ((priorSessions && !current.sessions) ||
64
+ priorPaths.some((item) => !managed.has(item) && current.matches(item, false))));
65
+ };
66
+ if (remote)
67
+ requireCompatibleRemoteSelection(config, remote);
68
+ if (state.lastAppliedSnapshot &&
69
+ syncPolicyChanged(state, config) &&
70
+ !(state.scope === config.scope &&
71
+ state.ignorePolicyKey &&
72
+ provesNarrowing(Object.keys(state.lastFileHashes), state.include?.includes("sessions") === true)))
73
+ throw new Error("Managed content policy changed and this transfer cannot prove that it only narrows the accepted selection. Review the new policy before transferring.");
74
+ }
75
+ export function keepProtectedRemoteSessions(config, upload, remote, sessionDir, protectedPaths) {
76
+ if (!protectedPaths.size)
77
+ return upload;
78
+ const retained = (remote?.files ?? []).filter((file) => protectedPaths.has(file.path));
79
+ const selectedRemote = remote && filterSnapshotForConfigPolicy(remote, config, { sessionDir });
80
+ const uploaded = new Set(upload.files.map((file) => file.path));
81
+ const selected = new Set(selectedRemote?.files.map((file) => file.path));
82
+ if (retained.some((file) => !selected.has(file.path) && !uploaded.has(file.path)))
83
+ throw new Error("Push would remove a protected live session from remote storage.");
84
+ const files = [...upload.files.filter((file) => !protectedPaths.has(file.path)), ...retained];
85
+ return {
86
+ ...upload,
87
+ ...(upload.selection?.version === 4
88
+ ? { syncSessions: files.some((file) => file.path.startsWith("sessions/")) }
89
+ : {}),
90
+ files: files.sort((a, b) => a.path.localeCompare(b.path)),
91
+ };
92
+ }
93
+ export async function requireDirectionalPullBoundary(ctx, options, config, physical, snapshotOptions, protectedPaths, validateMutation) {
94
+ await validateDirectionalSettings(options, config, validateMutation);
95
+ if ((await effectiveSessionRoot(ctx, config, options.signal)) !== snapshotOptions.sessionDir)
96
+ throw new Error("Pi session storage changed before Pull could write.");
97
+ if ((await inspectCaseCleanup(physical, snapshotOptions)).length)
98
+ throw new Error("Pull would remove case-variant paths not represented in its local backup. Review a separate Pull instead.");
99
+ validateMutation();
100
+ checkLiveProtection(ctx, snapshotOptions.sessionDir, protectedPaths);
101
+ }
102
+ export function notifyDirectionalSuccess(ctx, options, message, warning = false) {
103
+ if (options.directionalAction?.notifySuccess)
104
+ options.directionalAction.notifySuccess(message);
105
+ else if (!options.silent)
106
+ ctx.ui.notify(message, warning ? "warning" : "info");
107
+ }
108
+ export function remoteRestoreGuidance(head, previous, config, sessionDir) {
109
+ const ref = head.snapshotRef === head.snapshotId ? "" : ` (reference ${safeTerminalText(head.snapshotRef)})`;
110
+ const version = `${safeTerminalText(head.snapshotId)}${ref}`;
111
+ const eligible = config.ignorePolicy || syncSessionsSelected(config) ? previous : snapshotWithoutSessions(previous);
112
+ const selected = filterSnapshotForConfigPolicy(eligible, config, { sessionDir });
113
+ return selected.files.length === previous.files.length
114
+ ? `Restore the previous remote version ${version} from /sync → History.`
115
+ : `History retains remote version ${version}. Rollback uses the current rules and does not restore excluded files. See “Recover excluded files from History” in the Pi Sync README.`;
116
+ }
117
+ export function localRestoreGuidance(backup) {
118
+ return `Local backup: ${safeTerminalText(backup)}. To restore locally, close Pi and follow the local backup restore steps in the Pi Sync README.`;
119
+ }
@@ -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
+ }