@narumitw/pi-sync 0.65.0 → 0.67.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 (84) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +13 -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-SQC2L2FJ.ts} +9 -7
  16. package/dist/chunks/{command-handler-YZ4DXQ7N.ts.map → command-handler-SQC2L2FJ.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-DWOMAJKE.ts} +170 -45
  21. package/dist/chunks/manager-ui-DWOMAJKE.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/ignore-edit.js +2 -2
  31. package/dist/daemon/dist/engine/ignore/ignore-settings.js +2 -1
  32. package/dist/daemon/dist/engine/ignore/snapshot-ignore-rules.js +39 -0
  33. package/dist/daemon/dist/engine/settings/config-file.js +3 -0
  34. package/dist/daemon/dist/engine/settings/config.js +5 -5
  35. package/dist/daemon/dist/engine/settings/settings-management.js +6 -1
  36. package/dist/daemon/dist/engine/settings/settings-validation.js +21 -2
  37. package/dist/daemon/dist/engine/snapshot/snapshot-apply.js +2 -2
  38. package/dist/daemon/dist/engine/snapshot/snapshot-codec.js +6 -6
  39. package/dist/daemon/dist/engine/snapshot/snapshot-types.js +5 -1
  40. package/dist/daemon/dist/engine/snapshot/snapshot.js +5 -2
  41. package/dist/daemon/dist/engine/sync/conflict-review.js +2 -0
  42. package/dist/daemon/dist/engine/sync/continuous-errors.js +6 -0
  43. package/dist/daemon/dist/engine/sync/continuous-sync.js +4 -2
  44. package/dist/daemon/dist/engine/sync/continuous-watch.js +3 -2
  45. package/dist/daemon/dist/engine/sync/directional-action.js +3 -8
  46. package/dist/daemon/dist/engine/sync/ignore-adoption-recovery.js +50 -0
  47. package/dist/daemon/dist/engine/sync/ignore-adoption.js +410 -0
  48. package/dist/daemon/dist/engine/sync/ignore-publication.js +23 -0
  49. package/dist/daemon/dist/engine/sync/initialization.js +12 -0
  50. package/dist/daemon/dist/engine/sync/local-fields.js +6 -3
  51. package/dist/daemon/dist/engine/sync/merge-apply.js +18 -1
  52. package/dist/daemon/dist/engine/sync/merge-journal.js +2 -2
  53. package/dist/daemon/dist/engine/sync/merged-sync.js +50 -7
  54. package/dist/daemon/dist/engine/sync/push-review.js +33 -0
  55. package/dist/daemon/dist/engine/sync/sync-local.js +2 -1
  56. package/dist/daemon/dist/engine/sync/sync-mutations.js +108 -55
  57. package/dist/daemon/dist/engine/sync/sync-policy.js +5 -5
  58. package/dist/daemon/dist/engine/sync/sync-queries.js +1 -1
  59. package/dist/daemon/dist/engine/sync/sync-rollback.js +25 -5
  60. package/dist/daemon/dist/engine/sync/transfer-freshness.js +3 -2
  61. package/dist/daemon/dist/engine/sync/transfer-size-limits.js +92 -0
  62. package/dist/daemon/dist/engine/ui/ignore-rule-preview.js +18 -0
  63. package/dist/daemon/dist/engine-service.js +1 -1
  64. package/dist/daemon/package.json +1 -1
  65. package/dist/index.ts +1 -1
  66. package/docs/daemon-migration.md +6 -0
  67. package/docs/tui-contract.md +6 -5
  68. package/package.json +2 -2
  69. package/skills/configure-pi-sync/SKILL.md +1 -1
  70. package/skills/configure-pi-sync/references/configuration.md +43 -14
  71. package/src/ui/ignore-file-ui.ts +13 -5
  72. package/src/ui/manager-state.ts +15 -8
  73. package/src/ui/manager-ui.ts +1 -1
  74. package/src/ui/remote-selection-ui.ts +43 -2
  75. package/src/ui/settings-ui.ts +156 -32
  76. package/dist/chunks/chunk-MANNB4WZ.ts.map +0 -7
  77. package/dist/chunks/chunk-OBVJTKVY.ts.map +0 -7
  78. package/dist/chunks/chunk-OWEOZZZE.ts.map +0 -7
  79. package/dist/chunks/manager-ui-RGA26Z6G.ts.map +0 -7
  80. /package/dist/chunks/{chunk-IOM6E5FW.ts.map → chunk-BESRBKVO.ts.map} +0 -0
  81. /package/dist/chunks/{chunk-TZMVSTAM.ts.map → chunk-BYVHABNR.ts.map} +0 -0
  82. /package/dist/chunks/{file-selection-DDQN4LVD.ts.map → file-selection-XWACUTAH.ts.map} +0 -0
  83. /package/dist/chunks/{manager-result-dispatcher-XB75YLEG.ts.map → ignore-file-ui-OHFISFVC.ts.map} +0 -0
  84. /package/dist/chunks/{remote-selection-ui-WVMET5RI.ts.map → manager-result-dispatcher-WXE2BAQO.ts.map} +0 -0
@@ -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
+ }
@@ -0,0 +1,410 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { lstatSync, renameSync, statSync } from "node:fs";
3
+ import fs from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { getEngineRoot, withEngineMutationQueue } from "../host.js";
6
+ import { completeAdoptionJournal, createAdoptionJournal, recordInstalledIdentity, verifyAdoptionBackup, } from "../ignore/adoption-journal.js";
7
+ import { DEFAULT_IGNORE_FILENAME, ignoreFileIdentity, ignorePolicyFingerprint, ignoreSourceDigest, readIgnoreSource, sameFile, } from "../ignore/ignore-source.js";
8
+ import { validateSnapshotIgnoreRules } from "../ignore/snapshot-ignore-rules.js";
9
+ import { loadConfigForCheck, syncConfigReviewFingerprint, syncSettingsConfigFingerprint } from "../settings/config.js";
10
+ import { readActiveLocalConfigDocumentForRepair, withLockedLocalConfigDocument } from "../settings/config-file.js";
11
+ import { validateSettingsDocument } from "../settings/settings-validation.js";
12
+ import { effectiveSessionRoot, requireStableMergeSessionRoot } from "../snapshot/session-paths.js";
13
+ import { createSnapshot, filterSnapshotForConfigPolicy, regenerateSnapshotIdentity } from "../snapshot/snapshot.js";
14
+ import { appliedFileHashMap, applySnapshot } from "../snapshot/snapshot-apply.js";
15
+ import { recoverPendingSnapshotTransactions } from "../snapshot/snapshot-transaction.js";
16
+ import { pendingTransactionEntries } from "../snapshot/snapshot-transaction-directory.js";
17
+ import { syncDirectory } from "../state/json-file.js";
18
+ import { readStateForConfig, syncStateFingerprint, writeStateForConfig } from "../state/sync-state-store.js";
19
+ import { formatRuleChanges } from "../ui/ignore-rule-preview.js";
20
+ import { formatPullSummary, formatTransferReview } from "../ui/sync-format.js";
21
+ import { snapshotPathLabel } from "../ui/terminal-text.js";
22
+ import { confirmTransferReview } from "../ui/transfer-review.js";
23
+ import { inspectCaseCleanup, revalidateCaseCleanup } from "./apply-review.js";
24
+ import { checkpointDirectionalAction, localRestoreGuidance, notifyDirectionalSuccess } from "./directional-action.js";
25
+ import { overlayLocalFields, portableSnapshot, sameLocalFields } from "./local-fields.js";
26
+ import { readMergeJournal } from "./merge-journal.js";
27
+ import { readSnapshotForHead, sameRemoteHead } from "./remote-snapshot.js";
28
+ import { backupDirectionalSnapshot, captureMutationOwner, maybeReload, protectedSessionPaths } from "./sync-local.js";
29
+ import { acceptedSelection, fileHashMap, rawSnapshotHashIdentity, sameHashes } from "./sync-state.js";
30
+ import { checkLiveProtection } from "./transfer-freshness.js";
31
+ import { requireTransferSize, selectedPullImage, transferSizeLimitsEnabled } from "./transfer-size-limits.js";
32
+ export function canReviewAdoption(ctx, options) {
33
+ return (ctx.hasUI &&
34
+ (ctx.mode === "tui" || ctx.mode === "rpc") &&
35
+ !options.auto &&
36
+ !options.background &&
37
+ !options.yes &&
38
+ !options.agentRetryRefusal);
39
+ }
40
+ export function adoptionSettingsFingerprint(config) {
41
+ return syncConfigReviewFingerprint({ ...config, ignorePolicy: undefined, ignoreSourceIdentity: undefined });
42
+ }
43
+ function scopeChangeReview(label, paths) {
44
+ if (!paths.length)
45
+ return { lines: [], content: "" };
46
+ return {
47
+ lines: [`${label}: ${paths.length} file(s). View details for paths.`],
48
+ content: paths.map((name) => `${label}: ${snapshotPathLabel(name)}`).join("\n"),
49
+ };
50
+ }
51
+ async function assertDedicatedSource(config, filename) {
52
+ const doc = await readActiveLocalConfigDocumentForRepair();
53
+ if (!doc)
54
+ throw new Error("Sync setup no longer exists; reopen Pull.");
55
+ const settings = validateSettingsDocument(doc.parsed);
56
+ if (Object.entries(settings.syncSetups).some(([name, setup]) => name !== config.setupName &&
57
+ setup.sync.pathPolicy === "ignore-file" &&
58
+ (setup.sync.ignoreFile ?? DEFAULT_IGNORE_FILENAME).toLowerCase() === filename.toLowerCase()))
59
+ throw new Error("The ignore file is shared by other setups. Select a dedicated rule file before Pull.");
60
+ return doc;
61
+ }
62
+ function assertNotLiveRuleTarget(ctx, target, identity) {
63
+ const live = [...(ctx.protectedSessionFiles ?? []), ctx.sessionManager.getSessionFile?.()];
64
+ for (const entry of live) {
65
+ if (!entry)
66
+ continue;
67
+ const stat = statSync(entry, { bigint: true, throwIfNoEntry: false });
68
+ if (path.resolve(entry) === target || (stat && ignoreFileIdentity(stat) === identity))
69
+ throw new Error("The rule file is a protected live session; Pull cannot replace it.");
70
+ }
71
+ }
72
+ export async function adoptRemoteRules(input) {
73
+ const { ctx, options, config, state, backend, head, remote, snapshotOptions, validateMutation } = input;
74
+ const signal = options.signal;
75
+ const validateCommittedOwner = captureMutationOwner(ctx);
76
+ if (!canReviewAdoption(ctx, options) || !config.ignorePolicy)
77
+ throw new Error("Rule adoption requires a reviewed foreground Pull.");
78
+ const remotePolicy = validateSnapshotIgnoreRules(remote);
79
+ if (!remotePolicy || !remote.ignoreRules) {
80
+ throw new Error(remote.ignoreRules === null
81
+ ? "Remote rules exclude their own file. Match the publisher's rules manually before Pull."
82
+ : "Remote snapshot does not contain rule text. Match the publisher's rules or publish a new snapshot first.");
83
+ }
84
+ const { text } = remote.ignoreRules;
85
+ const { filename, sessions, reservedNames } = config.ignorePolicy;
86
+ if (sessions !== remotePolicy.sessions)
87
+ throw new Error("Sessions opt-in differs. Review your local Sessions setting and reopen Pull.");
88
+ if (remotePolicy.matches(filename))
89
+ throw new Error("The remote rules exclude this setup's rule filename. Review a matching rule filename before Pull.");
90
+ if (!sameLocalFields(config.localFields, remote.localFields))
91
+ throw new Error("Machine-local field policy differs. Match that policy before adopting remote ignore rules.");
92
+ const root = getEngineRoot();
93
+ const target = path.join(root, filename);
94
+ const source = await readIgnoreSource(root, filename, signal);
95
+ if (!source.present ||
96
+ source.identity !== config.ignoreSourceIdentity ||
97
+ source.sourceDigest !== config.ignorePolicy.sourceDigest)
98
+ throw new Error("Local ignore source changed; reopen Pull.");
99
+ const doc = await assertDedicatedSource(config, filename);
100
+ validateMutation();
101
+ assertNotLiveRuleTarget(ctx, target, source.identity);
102
+ if (state.unresolved?.length || (await readMergeJournal(config)))
103
+ throw new Error("Resolve or recover pending merge work before adopting rules.");
104
+ const adoptedPolicy = {
105
+ ...remotePolicy,
106
+ filename,
107
+ reservedNames,
108
+ sourceDigest: ignoreSourceDigest(filename, true, Buffer.from(text)),
109
+ };
110
+ const setupFingerprint = adoptionSettingsFingerprint(config);
111
+ const settingsFreshness = syncSettingsConfigFingerprint(config);
112
+ const stateFingerprint = syncStateFingerprint(state);
113
+ const sessionDir = snapshotOptions.sessionDir;
114
+ const protectedPaths = protectedSessionPaths(ctx, sessionDir);
115
+ const remoteFilesIdentity = rawSnapshotHashIdentity(remote);
116
+ const resuming = input.journal !== undefined;
117
+ let current = input.journal;
118
+ if (current &&
119
+ (current.setupName !== config.setupName ||
120
+ current.setupFingerprint !== setupFingerprint ||
121
+ current.filename !== filename ||
122
+ current.afterRules !== text ||
123
+ current.remoteFilesIdentity !== remoteFilesIdentity ||
124
+ current.sessionDir !== sessionDir ||
125
+ !sameRemoteHead(backend, current.head, head) ||
126
+ (source.text === text
127
+ ? current.installedIdentity !== source.identity
128
+ : current.beforeRules !== source.text || current.sourceIdentity !== source.identity)))
129
+ throw new Error("Pending rule adoption no longer matches this setup, source, or remote. Preserve its journal.");
130
+ if (!current && (await pendingTransactionEntries()).length)
131
+ throw new Error("Recover the pending file transaction before adopting rules.");
132
+ const policyConfig = { ...config, ignorePolicy: adoptedPolicy };
133
+ const validateSource = async () => {
134
+ validateMutation();
135
+ const latest = await loadConfigForCheck(config.setupName, signal);
136
+ validateMutation();
137
+ if (getEngineRoot() !== root ||
138
+ latest.configDocumentFingerprint !== config.configDocumentFingerprint ||
139
+ syncSettingsConfigFingerprint(latest) !== settingsFreshness ||
140
+ latest.ignoreSourceIdentity !== source.identity ||
141
+ latest.ignorePolicy?.sourceDigest !== source.sourceDigest)
142
+ throw new Error("Local rules or settings changed during Pull; reopen the review.");
143
+ assertNotLiveRuleTarget(ctx, target, source.identity);
144
+ checkLiveProtection(ctx, sessionDir, protectedPaths);
145
+ };
146
+ const projected = {
147
+ ...snapshotOptions,
148
+ ignorePolicy: adoptedPolicy,
149
+ ignoreSourceIdentity: current?.sourceIdentity ?? source.identity,
150
+ validateMutation,
151
+ validateIgnorePolicy: validateSource,
152
+ };
153
+ const logical = portableSnapshot(filterSnapshotForConfigPolicy(remote, policyConfig, projected), config.localFields);
154
+ let before = await createSnapshot(config.snapshotIdentity, projected);
155
+ let physical = overlayLocalFields(logical, before, config.localFields);
156
+ const prior = current ? undefined : await createSnapshot(config.snapshotIdentity, snapshotOptions);
157
+ const beforePaths = new Set(before.files.map((file) => file.path));
158
+ const priorPaths = new Set(prior?.files.map((file) => file.path));
159
+ const left = prior?.files.filter((file) => !beforePaths.has(file.path)).map((file) => file.path) ?? [];
160
+ const incomingPaths = new Set(physical.files.map((file) => file.path));
161
+ const newlyRemoved = before.files
162
+ .filter((file) => !priorPaths.has(file.path) && !protectedPaths.has(file.path) && !incomingPaths.has(file.path))
163
+ .map((file) => file.path);
164
+ const caseCleanup = current ? [] : await inspectCaseCleanup(physical, projected);
165
+ requireStableMergeSessionRoot(before, physical, config.scope);
166
+ await validateSource();
167
+ const checkSize = () => {
168
+ if (transferSizeLimitsEnabled(config))
169
+ requireTransferSize(config, selectedPullImage(logical, before, protectedPaths, { filename, text }));
170
+ };
171
+ if (!resuming)
172
+ checkSize();
173
+ const approved = await confirmTransferReview(ctx, current ? "Resume reviewed ignore-rule Pull?" : "Overwrite local rules and pull?", formatTransferReview(`Local rule file: ${snapshotPathLabel(target)}. The remote will not change.`, `Sessions opt-in: ${sessions ? "on" : "off"} (unchanged).`, ...(current
174
+ ? ["Resume from the recorded snapshot, not the current remote head. Local evidence must still match."]
175
+ : []), formatPullSummary(policyConfig, backend.destination, before, physical, protectedPaths, caseCleanup.map((item) => item.path)), ...(left.length ? [scopeChangeReview("Now excluded; leave local", left)] : []), ...(!current && newlyRemoved.length ? [scopeChangeReview("Newly selected; remove locally", newlyRemoved)] : []), formatRuleChanges(current?.beforeRules ?? source.text, text)), signal, validateMutation);
176
+ if (!approved)
177
+ return "cancelled";
178
+ await checkpointDirectionalAction(options, {
179
+ direction: "pull",
180
+ config,
181
+ state,
182
+ local: before,
183
+ remote,
184
+ head,
185
+ sessionDir,
186
+ protectedPaths,
187
+ });
188
+ validateMutation();
189
+ const validateHead = async () => {
190
+ if (resuming)
191
+ return;
192
+ const latestHead = await backend.readHead(signal);
193
+ validateMutation();
194
+ if (!sameRemoteHead(backend, head, latestHead))
195
+ throw new Error("Remote changed during Pull; reopen the review.");
196
+ };
197
+ const validateContext = async () => {
198
+ await validateHead();
199
+ if ((await effectiveSessionRoot(ctx, config, signal)) !== sessionDir)
200
+ throw new Error("Session storage changed; reopen Pull.");
201
+ await validateSource();
202
+ };
203
+ const latest = await readSnapshotForHead(backend, head, signal, config);
204
+ if (latest.version !== remote.version ||
205
+ latest.ignoreRules?.text !== text ||
206
+ latest.ignoreRules.filename !== remote.ignoreRules.filename ||
207
+ !sameLocalFields(latest.localFields, remote.localFields) ||
208
+ rawSnapshotHashIdentity(latest) !== remoteFilesIdentity)
209
+ throw new Error("The reviewed remote snapshot changed; reopen Pull.");
210
+ if (current)
211
+ await verifyAdoptionBackup(current, signal);
212
+ await validateContext();
213
+ const refresh = async () => {
214
+ const next = await createSnapshot(config.snapshotIdentity, projected);
215
+ await validateSource();
216
+ return next;
217
+ };
218
+ let commitStarted = false;
219
+ const markCommit = () => {
220
+ if (!commitStarted)
221
+ options.onCommit?.();
222
+ commitStarted = true;
223
+ };
224
+ if (current && (await pendingTransactionEntries()).length) {
225
+ if (source.text === text || current.stateFingerprint !== stateFingerprint)
226
+ throw new Error("Pending local files and rule adoption cannot be reconciled; preserve both journals.");
227
+ markCommit();
228
+ await recoverPendingSnapshotTransactions({ ...projected, protectedTargets: liveSessionFiles(ctx) });
229
+ before = await refresh();
230
+ physical = overlayLocalFields(logical, before, config.localFields);
231
+ }
232
+ if (!current) {
233
+ await revalidateCaseCleanup(caseCleanup, physical, projected);
234
+ if (!sameHashes(fileHashMap(await refresh()), fileHashMap(before)))
235
+ throw new Error("Local files changed; reopen Pull.");
236
+ const backup = await backupDirectionalSnapshot(regenerateSnapshotIdentity(before), signal);
237
+ await validateContext();
238
+ if (syncStateFingerprint(await readStateForConfig(config)) !== stateFingerprint)
239
+ throw new Error("Baseline changed; reopen Pull.");
240
+ await backup.validate();
241
+ await validateSource();
242
+ current = {
243
+ version: 1,
244
+ setupName: config.setupName,
245
+ setupFingerprint,
246
+ stateFingerprint,
247
+ filename,
248
+ sourceIdentity: source.identity,
249
+ beforeRules: source.text,
250
+ afterRules: text,
251
+ beforeFiles: fileHashMap(before),
252
+ afterFiles: appliedFileHashMap(physical, before, protectedPaths),
253
+ head,
254
+ remoteFilesIdentity,
255
+ sessionDir,
256
+ backupId: path.basename(backup.backupPath, ".json.gz"),
257
+ backupDigest: backup.digest,
258
+ };
259
+ markCommit();
260
+ await createAdoptionJournal(current);
261
+ }
262
+ let journal = current;
263
+ const installedHashes = journal.afterFiles;
264
+ const stateFor = (acceptedConfig) => ({
265
+ version: 1,
266
+ profile: config.snapshotIdentity,
267
+ lastAppliedSnapshot: head.snapshotId,
268
+ lastRemoteRevision: head.revision,
269
+ lastFileHashes: config.localFields?.length
270
+ ? { ...installedHashes, "settings.json": fileHashMap(logical)["settings.json"] }
271
+ : installedHashes,
272
+ ...acceptedSelection(acceptedConfig),
273
+ ...(config.localFields !== undefined ? { localFields: config.localFields } : {}),
274
+ });
275
+ const hashes = fileHashMap(await refresh());
276
+ if (resuming && source.identity !== journal.installedIdentity)
277
+ checkSize();
278
+ if (source.text !== text && journal.stateFingerprint !== stateFingerprint)
279
+ throw new Error("Baseline changed after the reviewed Pull. Preserve its journal.");
280
+ if (!sameHashes(hashes, journal.afterFiles)) {
281
+ if (source.text === text ||
282
+ !sameHashes(hashes, journal.beforeFiles) ||
283
+ !sameHashes(appliedFileHashMap(physical, before, protectedPaths), journal.afterFiles))
284
+ throw new Error("Local files changed after the reviewed Pull. Preserve its journal.");
285
+ markCommit();
286
+ await applySnapshot(physical, protectedPaths, {
287
+ ...projected,
288
+ reviewedLocal: before,
289
+ validateApplyReview: async () => {
290
+ await validateContext();
291
+ if (syncStateFingerprint(await readStateForConfig(config)) !== journal.stateFingerprint)
292
+ throw new Error("Baseline changed at Pull's commit boundary.");
293
+ },
294
+ });
295
+ }
296
+ await validateContext();
297
+ if (!sameHashes(fileHashMap(await refresh()), journal.afterFiles))
298
+ throw new Error("Installed files changed before rule adoption completed; preserve the journal.");
299
+ markCommit();
300
+ if (source.text !== text) {
301
+ await withEngineMutationQueue(target, async () => {
302
+ await validateContext();
303
+ if (!sameHashes(fileHashMap(await refresh()), installedHashes))
304
+ throw new Error("Local files changed while reserving the rule file; preserve the journal.");
305
+ await withLockedLocalConfigDocument(async (latest, recheck) => {
306
+ if (!latest?.bytes.equals(doc.bytes) || JSON.stringify(latest.identity) !== JSON.stringify(doc.identity))
307
+ throw new Error("Sync settings changed; preserve the journal.");
308
+ await installRuleFile(ctx, root, target, source.identity, source.sourceDigest, filename, text, signal, async (identity) => {
309
+ journal = await recordInstalledIdentity(journal, identity);
310
+ await validateHead();
311
+ }, () => {
312
+ recheck();
313
+ validateMutation();
314
+ checkLiveProtection(ctx, sessionDir, protectedPaths);
315
+ });
316
+ }, signal, true);
317
+ });
318
+ }
319
+ else {
320
+ await syncDirectory(root);
321
+ validateCommittedOwner();
322
+ }
323
+ const installed = await loadConfigForCheck(config.setupName);
324
+ if (installed.configDocumentFingerprint !== config.configDocumentFingerprint ||
325
+ adoptionSettingsFingerprint(installed) !== setupFingerprint ||
326
+ installed.ignorePolicy?.fingerprint !== ignorePolicyFingerprint(text, sessions) ||
327
+ installed.ignorePolicy?.sourceDigest !== adoptedPolicy.sourceDigest ||
328
+ installed.ignoreSourceIdentity !== journal.installedIdentity)
329
+ throw new Error("Cannot verify the installed rule file. Preserve the adoption journal.");
330
+ const finalState = stateFor(installed);
331
+ const latestFingerprint = syncStateFingerprint(await readStateForConfig(installed));
332
+ const validateFinal = () => {
333
+ validateCommittedOwner();
334
+ checkLiveProtection(ctx, sessionDir, protectedPaths);
335
+ };
336
+ validateFinal();
337
+ const installedFiles = await createSnapshot(config.snapshotIdentity, {
338
+ ...projected,
339
+ ignorePolicy: installed.ignorePolicy,
340
+ ignoreSourceIdentity: installed.ignoreSourceIdentity,
341
+ validateMutation: validateFinal,
342
+ validateIgnorePolicy: installed.validateIgnorePolicy,
343
+ });
344
+ if (!sameHashes(fileHashMap(installedFiles), installedHashes))
345
+ throw new Error("Local files changed during adoption. Preserve the journal.");
346
+ await installed.validateIgnorePolicy?.();
347
+ validateFinal();
348
+ if (latestFingerprint === journal.stateFingerprint)
349
+ await writeStateForConfig(installed, finalState, logical, validateFinal);
350
+ else if (latestFingerprint !== syncStateFingerprint(finalState))
351
+ throw new Error("Baseline changed during installation; preserve the adoption journal.");
352
+ validateFinal();
353
+ const archive = await completeAdoptionJournal(journal);
354
+ validateFinal();
355
+ if (!signal?.aborted) {
356
+ notifyDirectionalSuccess(ctx, options, [
357
+ `Adopted remote rules and pulled snapshot ${snapshotPathLabel(head.snapshotId)}.`,
358
+ localRestoreGuidance(path.join(path.dirname(archive), `${journal.backupId}.json.gz`)),
359
+ `Previous rule text: ${snapshotPathLabel(archive)}.`,
360
+ ].join("\n"));
361
+ if (!options.directionalAction && options.reload)
362
+ await maybeReload(ctx, signal, validateFinal);
363
+ }
364
+ return "applied";
365
+ }
366
+ function liveSessionFiles(ctx) {
367
+ const current = ctx.sessionManager.getSessionFile?.();
368
+ return [...(ctx.protectedSessionFiles ?? []), ...(current ? [current] : [])];
369
+ }
370
+ async function installRuleFile(ctx, root, target, identity, digest, filename, text, signal, recordIdentity, validate) {
371
+ const before = lstatSync(target, { bigint: true });
372
+ const temporary = path.join(root, `.pi-sync.json.${randomUUID()}.ignore-adopt`);
373
+ const handle = await fs.open(temporary, "wx", 0o600);
374
+ let temporaryIdentity;
375
+ try {
376
+ let staged;
377
+ try {
378
+ temporaryIdentity = ignoreFileIdentity(await handle.stat({ bigint: true }));
379
+ await handle.writeFile(text, "utf8");
380
+ if (process.platform !== "win32")
381
+ await handle.chmod(Number(before.mode & 511n));
382
+ await handle.sync();
383
+ staged = await handle.stat({ bigint: true });
384
+ }
385
+ finally {
386
+ await handle.close();
387
+ }
388
+ await recordIdentity(ignoreFileIdentity(staged));
389
+ const current = await readIgnoreSource(root, filename, signal);
390
+ validate();
391
+ signal?.throwIfAborted();
392
+ const after = lstatSync(target, { bigint: true });
393
+ assertNotLiveRuleTarget(ctx, target, identity);
394
+ const stagedNow = lstatSync(temporary, { bigint: true });
395
+ if (!sameFile(staged, stagedNow) ||
396
+ stagedNow.nlink !== 1n ||
397
+ !sameFile(before, after) ||
398
+ !current.present ||
399
+ current.identity !== identity ||
400
+ current.sourceDigest !== digest)
401
+ throw new Error("Local rule file changed; preserve the adoption journal.");
402
+ renameSync(temporary, target);
403
+ await syncDirectory(root);
404
+ }
405
+ finally {
406
+ const remaining = lstatSync(temporary, { bigint: true, throwIfNoEntry: false });
407
+ if (remaining && ignoreFileIdentity(remaining) === temporaryIdentity)
408
+ await fs.rm(temporary, { force: true });
409
+ }
410
+ }
@@ -0,0 +1,23 @@
1
+ import { getEngineRoot } from "../host.js";
2
+ import { readIgnoreSource } from "../ignore/ignore-source.js";
3
+ import { selectSnapshotIgnoreRules } from "../ignore/snapshot-ignore-rules.js";
4
+ import { regenerateSnapshotIdentity } from "../snapshot/snapshot.js";
5
+ import { RULES_SNAPSHOT_VERSION } from "../snapshot/snapshot-types.js";
6
+ import { safeTerminalText } from "../ui/terminal-text.js";
7
+ export async function withPublishedIgnoreRules(snapshot, config, signal) {
8
+ const policy = config.ignorePolicy;
9
+ if (!policy)
10
+ return snapshot;
11
+ const source = await readIgnoreSource(getEngineRoot(), policy.filename, signal);
12
+ if (!source.present || source.identity !== config.ignoreSourceIdentity)
13
+ throw new Error("Ignore file was replaced before publication; reopen the review.");
14
+ const ignoreRules = selectSnapshotIgnoreRules(source, policy);
15
+ return regenerateSnapshotIdentity({ ...snapshot, version: RULES_SNAPSHOT_VERSION, ignoreRules });
16
+ }
17
+ export function ignorePublicationNotice(snapshot) {
18
+ if (snapshot.ignoreRules === null)
19
+ return "The active rule file excludes itself; this snapshot omits its text.";
20
+ if (!snapshot.ignoreRules)
21
+ return undefined;
22
+ return `This snapshot includes ${safeTerminalText(snapshot.ignoreRules.filename)}. Its rules and comments will be retained in remote history. Peers must support snapshot version ${RULES_SNAPSHOT_VERSION}.`;
23
+ }
@@ -1,3 +1,4 @@
1
+ import { hasPendingAdoption } from "../ignore/adoption-journal.js";
1
2
  import { loadConfig } from "../settings/config.js";
2
3
  import { isMissingConfigError } from "../settings/config-errors.js";
3
4
  import { consumeLocalConfigMigrationNotice } from "../settings/config-file.js";
@@ -23,6 +24,17 @@ export async function initializeSync(ctx, signal, publish, observe) {
23
24
  await timings.measure("transaction recovery", async () => {
24
25
  const pending = await pendingTransactionEntries();
25
26
  validate();
27
+ if (hasPendingAdoption()) {
28
+ if (pending.length) {
29
+ const { recoverAdoptionFilesOnStartup } = await import("./ignore-adoption-recovery.js");
30
+ validate();
31
+ await recoverAdoptionFilesOnStartup(ctx, signal, validate);
32
+ validate();
33
+ }
34
+ if (ctx.hasUI)
35
+ ctx.ui.notify("Ignore-rule adoption is pending. Resume from the originating setup with /sync pull.", "warning");
36
+ return;
37
+ }
26
38
  if (!pending.some((entry) => entry.isDirectory()))
27
39
  return;
28
40
  const { recoverSnapshotTransactionsOnStartup } = await import("../snapshot/snapshot-transaction.js");
@@ -1,8 +1,9 @@
1
1
  import { createHash } from "node:crypto";
2
+ import { validateSnapshotIgnoreRules } from "../ignore/snapshot-ignore-rules.js";
2
3
  import { regenerateSnapshotIdentity } from "../snapshot/snapshot.js";
3
4
  import { assertAgentDirectorySnapshotBound } from "../snapshot/snapshot-bounds.js";
4
5
  import { assertSnapshotFilePayload } from "../snapshot/snapshot-payload.js";
5
- import { IGNORE_SNAPSHOT_VERSION, isSupportedSnapshotVersion, } from "../snapshot/snapshot-types.js";
6
+ import { isIgnoreSnapshotVersion, isSupportedSnapshotVersion, } from "../snapshot/snapshot-types.js";
6
7
  import { jsonEqual, parseSettingsDocument, renderSettingsMembers, } from "./json-document.js";
7
8
  import { normalizeLocalFields } from "./local-field-policy.js";
8
9
  import { compileSyncPolicyExclude, configuredSnapshotPathMatcher, validateSnapshotSelection } from "./sync-policy.js";
@@ -55,6 +56,7 @@ function validateIgnoreSnapshotEnvelope(snapshot, selection) {
55
56
  "profile",
56
57
  "syncSessions",
57
58
  "selection",
59
+ "ignoreRules",
58
60
  "localFields",
59
61
  "files",
60
62
  ].includes(key)))
@@ -77,14 +79,15 @@ export function validatePortableSnapshot(snapshot) {
77
79
  validateSnapshotFieldPolicy(snapshot);
78
80
  validateSnapshotSelection(snapshot);
79
81
  const selection = snapshot.selection;
82
+ const policy = validateSnapshotIgnoreRules(snapshot);
80
83
  if (selection?.version === 4)
81
84
  validateIgnoreSnapshotEnvelope(snapshot, selection);
82
85
  if (selection?.scope) {
83
- const selected = configuredSnapshotPathMatcher(selection);
86
+ const selected = configuredSnapshotPathMatcher(policy ? { ...selection, ignorePolicy: policy } : selection);
84
87
  if (snapshot.files.some((file) => typeof file?.path !== "string" || !selected(file.path)))
85
88
  throw new Error("Portable snapshot retains excluded or unsafe agent-directory paths.");
86
89
  assertAgentDirectorySnapshotBound(snapshot.files);
87
- if (snapshot.version === IGNORE_SNAPSHOT_VERSION)
90
+ if (isIgnoreSnapshotVersion(snapshot.version))
88
91
  validateIgnoreSnapshotFiles(snapshot.files);
89
92
  }
90
93
  else {
@@ -4,7 +4,7 @@ import fs from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { withEngineMutationQueue as withFileMutationQueue } from "../host.js";
6
6
  import { agentDir } from "../snapshot/session-paths.js";
7
- import { agentDirectoryConfiguredSessionDir, agentDirectoryInventory, createSnapshot, snapshotTarget, } from "../snapshot/snapshot.js";
7
+ import { agentDirectoryConfiguredSessionDir, agentDirectoryInventory, createSnapshot, observeSnapshot, snapshotTarget, } from "../snapshot/snapshot.js";
8
8
  import { preflightSnapshotApply, preflightSnapshotMutations } from "../snapshot/snapshot-apply.js";
9
9
  import { assertAgentDirectorySnapshotBound, MAX_AGENT_DIRECTORY_BYTES } from "../snapshot/snapshot-bounds.js";
10
10
  import { assertProjectedAgentDirectoryBudget, recheckAgentDirectoryBudget, } from "../snapshot/snapshot-entry-projection.js";
@@ -16,6 +16,7 @@ import { recheckScopedImage, scopedTransactionImage } from "../snapshot/snapshot
16
16
  import { ignorePolicyValidator } from "../snapshot/snapshot-transaction-policy.js";
17
17
  import { syncDirectory } from "../state/json-file.js";
18
18
  import { syncMutationParents } from "../state/mutation-directory-sync.js";
19
+ import { ContinuousError } from "./continuous-errors.js";
19
20
  import { mergePathIdentity } from "./file-merge-planner.js";
20
21
  import { configuredSnapshotPathMatcher } from "./sync-policy.js";
21
22
  import { fileHashMap } from "./sync-state.js";
@@ -433,6 +434,18 @@ export async function applyMergedSnapshot(before, after, protectedPaths, options
433
434
  requireReviewedHash(relative, hash);
434
435
  return kind;
435
436
  };
437
+ let checkApplyImage = options.requireReviewedApplyImage;
438
+ const requireReviewedApplyImage = async () => {
439
+ const latest = fileHashMap(await observeSnapshot(options));
440
+ await validate();
441
+ options.validateMutation?.();
442
+ if ([...new Set([...Object.keys(latest), ...paths])].some((relative) => {
443
+ const hash = Object.hasOwn(latest, relative) ? latest[relative] : undefined;
444
+ return hash !== beforeHashes[relative] && hash !== afterHashes[relative];
445
+ }))
446
+ throw new ContinuousError("unsafe", "Cannot verify the size-limited local apply image: local files changed. Keep the merge journal and backup for review.");
447
+ checkApplyImage = false;
448
+ };
436
449
  if (options.scope === "agent-directory" && plan.deletes.length)
437
450
  await recheckAgentDirectoryBudget(root, plan, options);
438
451
  for (const target of plan.deletes) {
@@ -443,6 +456,8 @@ export async function applyMergedSnapshot(before, after, protectedPaths, options
443
456
  await validate();
444
457
  kind = stat.isDirectory() ? "directory" : "file";
445
458
  }
459
+ if (kind !== "missing" && checkApplyImage)
460
+ await requireReviewedApplyImage();
446
461
  if (kind === "directory")
447
462
  await fs.rmdir(target); // Only an empty, reviewed directory may be replaced.
448
463
  else if (kind === "file")
@@ -497,6 +512,8 @@ export async function applyMergedSnapshot(before, after, protectedPaths, options
497
512
  if (validateIgnore)
498
513
  await validateIgnore();
499
514
  await assertFilesystemTarget(root, relative, options, new Set());
515
+ if (checkApplyImage)
516
+ await requireReviewedApplyImage();
500
517
  await fs.mkdir(path.dirname(item.target), { recursive: true });
501
518
  const temporary = path.join(path.dirname(item.target), `.pi-sync.json.${randomUUID()}.apply`);
502
519
  let mode = 0o600;