@narumitw/pi-sync-daemon 0.8.0 → 0.9.1

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 (61) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/cli.js +1 -1
  3. package/dist/consent.d.ts +14 -2
  4. package/dist/consent.js +134 -16
  5. package/dist/engine/backends/git/git-backend.d.ts +1 -2
  6. package/dist/engine/backends/git/git-backend.js +61 -30
  7. package/dist/engine/commands/command-types.d.ts +2 -1
  8. package/dist/engine/host.d.ts +1 -0
  9. package/dist/engine/ignore/ignore-initialization.d.ts +8 -1
  10. package/dist/engine/ignore/ignore-initialization.js +142 -40
  11. package/dist/engine/ignore/ignore-settings.d.ts +16 -1
  12. package/dist/engine/ignore/ignore-settings.js +94 -26
  13. package/dist/engine/ignore/ignore-source.d.ts +1 -1
  14. package/dist/engine/ignore/ignore-source.js +1 -1
  15. package/dist/engine/settings/config-file.js +1 -1
  16. package/dist/engine/settings/config.d.ts +3 -2
  17. package/dist/engine/settings/config.js +71 -28
  18. package/dist/engine/settings/settings-management.d.ts +3 -1
  19. package/dist/engine/settings/settings-management.js +8 -2
  20. package/dist/engine/settings/settings-types.d.ts +2 -0
  21. package/dist/engine/snapshot/session-paths.js +7 -2
  22. package/dist/engine/snapshot/snapshot-apply.d.ts +1 -1
  23. package/dist/engine/snapshot/snapshot-transaction-policy.d.ts +7 -2
  24. package/dist/engine/snapshot/snapshot-transaction-policy.js +37 -17
  25. package/dist/engine/snapshot/snapshot-transaction.js +55 -13
  26. package/dist/engine/snapshot/snapshot-types.d.ts +4 -0
  27. package/dist/engine/sync/agent-plan.js +1 -0
  28. package/dist/engine/sync/agent-sync.js +8 -1
  29. package/dist/engine/sync/continuous-sync.d.ts +3 -1
  30. package/dist/engine/sync/continuous-sync.js +32 -15
  31. package/dist/engine/sync/merge-acceptance.d.ts +8 -0
  32. package/dist/engine/sync/merge-acceptance.js +29 -0
  33. package/dist/engine/sync/merge-apply.js +7 -4
  34. package/dist/engine/sync/merge-journal.d.ts +6 -0
  35. package/dist/engine/sync/merge-journal.js +33 -14
  36. package/dist/engine/sync/merged-sync.js +31 -39
  37. package/dist/engine/sync/remote-snapshot.d.ts +2 -1
  38. package/dist/engine/sync/remote-snapshot.js +17 -2
  39. package/dist/engine/sync/session-push.js +20 -6
  40. package/dist/engine/sync/sync-error-guidance.js +16 -3
  41. package/dist/engine/sync/sync-mutations.js +75 -54
  42. package/dist/engine/sync/sync-policy.d.ts +5 -0
  43. package/dist/engine/sync/sync-policy.js +28 -3
  44. package/dist/engine/sync/sync-state.d.ts +2 -0
  45. package/dist/engine/sync/sync-state.js +3 -8
  46. package/dist/engine/sync/transfer-freshness.d.ts +31 -0
  47. package/dist/engine/sync/transfer-freshness.js +82 -0
  48. package/dist/engine/ui/sync-format.d.ts +16 -5
  49. package/dist/engine/ui/sync-format.js +23 -55
  50. package/dist/engine/ui/transfer-review.d.ts +2 -1
  51. package/dist/engine/ui/transfer-review.js +3 -3
  52. package/dist/engine-service.d.ts +1 -1
  53. package/dist/engine-service.js +124 -27
  54. package/dist/monitor.d.ts +4 -1
  55. package/dist/monitor.js +84 -32
  56. package/dist/server.d.ts +1 -0
  57. package/dist/server.js +46 -5
  58. package/dist/service-host.d.ts +1 -1
  59. package/dist/service-host.js +2 -1
  60. package/docs/architecture.md +14 -6
  61. package/package.json +1 -1
@@ -1,4 +1,4 @@
1
- import { loadConfig } from "../settings/config.js";
1
+ import { loadConfigForCheck, syncCheckConfigFingerprint } from "../settings/config.js";
2
2
  import { resolvedSnapshotOptionsForContext } from "../snapshot/session-paths.js";
3
3
  import { createSnapshot } from "../snapshot/snapshot.js";
4
4
  import { withLock } from "../state/lock.js";
@@ -10,23 +10,37 @@ import { hasLocalChanges, syncPolicyChanged } from "./sync-state.js";
10
10
  /** Existing legacy policy; service ownership/consent is established by its caller. */
11
11
  export async function pushSessionsOnShutdown(ctx, options, loaders = { operations: () => import("./sync-operations.js") }) {
12
12
  const validate = captureMutationOwner(ctx, options.signal);
13
- const config = await loadConfig(options.setup);
13
+ const config = await loadConfigForCheck(undefined, options.signal);
14
14
  validate();
15
+ options.background?.validate(config);
16
+ if (options.setup !== undefined && options.setup !== config.setupName)
17
+ throw new Error("An automatic session push requires the current active sync setup.");
18
+ const fingerprint = syncCheckConfigFingerprint(config);
19
+ const refresh = async () => {
20
+ validate();
21
+ options.background?.validate();
22
+ const latest = await loadConfigForCheck(undefined, options.signal);
23
+ validate();
24
+ options.background?.validate(latest);
25
+ if (fingerprint !== syncCheckConfigFingerprint(latest))
26
+ throw new Error("Settings changed before automatic session push.");
27
+ };
15
28
  if (!config.automatic || !syncSessionsSelected(config))
16
29
  return;
17
30
  await withStateDirectoryAccess(() => withLock("auto-session-push", async () => {
31
+ await refresh();
18
32
  const state = await readStateForConfig(config);
19
- validate();
33
+ await refresh();
20
34
  if ((config.scope || state.scope) && (!state.lastAppliedSnapshot || syncPolicyChanged(state, config)))
21
35
  return;
22
36
  const snapshotOptions = await resolvedSnapshotOptionsForContext(ctx, config, options.signal);
23
- validate();
37
+ await refresh();
24
38
  const local = await createSnapshot(config.snapshotIdentity, snapshotOptions);
25
- validate();
39
+ await refresh();
26
40
  if (!hasLocalChanges(local, state, config))
27
41
  return;
28
42
  const operations = await loaders.operations();
29
- validate();
43
+ await refresh();
30
44
  await operations.push(ctx, { ...options, auto: true, yes: true, silent: true, reload: false }, { config, state, local });
31
45
  validate();
32
46
  }));
@@ -15,20 +15,33 @@ export function syncErrorGuidance(error) {
15
15
  else if (code && ["EBUSY", "EIO", "EMFILE", "ENFILE"].includes(code)) {
16
16
  next = "Check local disk availability and other processes using the private settings file, then retry.";
17
17
  }
18
+ else if (/\bagent directory exceeds the scan entry bound\b/iu.test(message)) {
19
+ next =
20
+ "Reduce the number of entries Pi Sync must scan before retrying. Exclude whole subdirectories to skip their contents. Use /sync config to review the active scope.";
21
+ }
22
+ else if (/\bprojected agent directory exceeds the (64 MiB scan byte|scan file) bound\b/iu.test(message)) {
23
+ next =
24
+ "The resulting files would exceed the sync limit. Review the current scope with /sync config and reduce the local or incoming sync content before retrying.";
25
+ }
26
+ else if (/\bagent directory exceeds the (64 MiB scan byte|scan file) bound\b/iu.test(message)) {
27
+ next =
28
+ "Reduce the files managed by this setup before retrying. Use /sync config to find the active ignore file, or edit Agent directory scope in /sync → Settings for legacy rules.";
29
+ }
18
30
  else if (/changed while|type changed|reopen/iu.test(message)) {
19
31
  next = "Reopen the item in /sync and review its current settings before saving again.";
20
32
  }
21
33
  else if (status === 401 ||
22
34
  status === 403 ||
23
35
  /Permission denied|Authentication failed|HTTP (401|403)|failed \((401|403)\)/iu.test(message)) {
24
- next = "Check the storage connection's credentials and remote permissions in /sync → More → Storage connections.";
36
+ next =
37
+ "Check the storage connection's credentials and remote permissions. In the TUI, open /sync → Settings → Manage storage connections.";
25
38
  }
26
39
  else if (status === 404 || /HTTP 404|failed \(404\)/iu.test(message)) {
27
40
  next =
28
41
  "Verify the connection address and setup's bucket, branch, or path with your provider; this response alone does not prove which resource is missing.";
29
42
  }
30
43
  else if (status !== undefined && status >= 500) {
31
- next = "Check your storage provider's service status, then retry Check setup before syncing.";
44
+ next = "Check your storage provider's service status, then run /sync doctor before syncing.";
32
45
  }
33
46
  else if (/timed out|timeout|request failed|resolve host|Could not resolve|ENOTFOUND|ECONNREFUSED/iu.test(message)) {
34
47
  next = "Check the server address and network connection, then run /sync doctor for the affected setup.";
@@ -49,7 +62,7 @@ export function syncErrorGuidance(error) {
49
62
  "Correct the named field or item in /sync. If the settings file is invalid, repair it before retrying; do not replace it with defaults.";
50
63
  }
51
64
  else {
52
- next = "Open /sync → More → Check setup and review the reported checks before retrying.";
65
+ next = "For setup and storage checks, run /sync doctor or choose Diagnostics in /sync.";
53
66
  }
54
67
  return `${message}\n${next}`;
55
68
  }
@@ -2,12 +2,12 @@ import { createSyncBackend } from "../backends/backend-factory.js";
2
2
  import { expectedRemoteHead, } from "../backends/sync-backend.js";
3
3
  import { loadConfig, syncCheckConfigFingerprint } from "../settings/config.js";
4
4
  import { effectiveSessionRoot, requireStableMergeSessionRoot, resolvedSnapshotOptionsForContext, sessionDirForApply, } from "../snapshot/session-paths.js";
5
- import { createSnapshot, filterSnapshotForConfigPolicy, mergeRemotePreservedFiles, regenerateSnapshotIdentity, scanSnapshot, snapshotIncludesSessions, snapshotWithoutSessions, } from "../snapshot/snapshot.js";
5
+ import { createSnapshot, filterSnapshotForConfigPolicy, regenerateSnapshotIdentity, scanSnapshot, snapshotIncludesSessions, snapshotWithoutSessions, } from "../snapshot/snapshot.js";
6
6
  import { applySnapshot } from "../snapshot/snapshot-apply.js";
7
7
  import { ignorePolicyValidator } from "../snapshot/snapshot-transaction-policy.js";
8
8
  import { pruneMergeBaselines } from "../state/merge-baseline-store.js";
9
9
  import { readStateForConfig, syncStateFingerprint, writeStateForConfig } from "../state/sync-state-store.js";
10
- import { countPreservedRemoteFiles, formatPublicationPreview, formatPullSummary, formatPushSummary, formatRollbackSummary, } from "../ui/sync-format.js";
10
+ import { countPreservedRemoteFiles, formatPublicationPreview, formatPullSummary, formatPushSummary, formatRollbackSummary, formatTransferReview, } from "../ui/sync-format.js";
11
11
  import { setSyncStatus } from "../ui/sync-status.js";
12
12
  import { confirmTransferReview } from "../ui/transfer-review.js";
13
13
  import { startupTransferEnabled } from "./agent-policy.js";
@@ -16,28 +16,16 @@ import { confirmFieldMigration } from "./field-migration.js";
16
16
  import { overlayLocalFields, portableSnapshot, sameLocalFields, validatePortableSnapshot } from "./local-fields.js";
17
17
  import { readMergeJournal, requireNoMergeJournal, retireMergeJournal } from "./merge-journal.js";
18
18
  import { mergeSync } from "./merged-sync.js";
19
- import { readRemoteSnapshot, readRemoteSnapshotForUpload, readSnapshotForHead, requireCompatibleRemoteSelection, sameRemoteHead, } from "./remote-snapshot.js";
19
+ import { readRemoteSnapshot, readRemoteSnapshotForUpload, readSnapshotForHead, requireCompatibleRemoteSelection, sameRemoteHead, snapshotForUpload, } from "./remote-snapshot.js";
20
20
  import { throwIfAborted } from "./signals.js";
21
21
  import { createSyncDecision } from "./sync-decision.js";
22
22
  import { errorMessage } from "./sync-errors.js";
23
23
  import { backupLocal, captureMutationOwner, protectedSessionPaths } from "./sync-local.js";
24
24
  import { formatIgnorePolicyComparison, inspectRemoteSelection, requireLegacyTransferPolicy, syncSelectionHasContent, syncSessionsSelected, } from "./sync-policy.js";
25
25
  import { acceptedSelection, canPullRemoteSessionsOnFirstSync, canPullRemoteSettingsOnFirstSync, fileHashMap, hasLocalChanges, hasRemoteChanges, remoteChangedSinceState, sameHashes, shouldRefreshSyncedState, snapshotHashesMatchState, snapshotsMatch, syncPolicyChanged, } from "./sync-state.js";
26
+ import { directionalApplyGuards, requireIgnoreBaselineReview, requireResolvedDirectionalProgress, validateDirectionalPublication, } from "./transfer-freshness.js";
26
27
  const VERSION = 1;
27
28
  const POST_LOCAL_COMMIT_TIMEOUT_MS = 30_000;
28
- /** Whole-direction acceptance must never forget withheld state without an explicit recovery choice. */
29
- function requireResolvedDirectionalProgress(state, options, allowForce = true) {
30
- if (state.unresolved?.length && (options.auto || !options.force || !allowForce))
31
- throw new Error("Unresolved partial conflicts remain. Review /sync conflicts or explicitly choose push --force or pull --force; automatic transfer and rollback cannot accept unresolved groups.");
32
- }
33
- function requireIgnoreBaselineReview(ctx, config, state, options) {
34
- if (config.ignorePolicy &&
35
- state.lastAppliedSnapshot &&
36
- syncPolicyChanged(state, config) &&
37
- (options.auto || options.yes || !ctx.hasUI)) {
38
- throw new Error("Local ignore-file policy or source changed since the last accepted baseline. Review a foreground directional transfer.");
39
- }
40
- }
41
29
  export class PublicationStatePersistenceError extends Error {
42
30
  head;
43
31
  backupPath;
@@ -59,16 +47,23 @@ export class RollbackPublicationError extends Error {
59
47
  }
60
48
  }
61
49
  export async function push(ctx, options, input, factory = createSyncBackend) {
62
- const validateMutation = captureMutationOwner(ctx, options.signal);
50
+ const validateOwner = captureMutationOwner(ctx, options.signal);
63
51
  const validateCommittedOwner = captureMutationOwner(ctx);
64
- const config = input?.config ?? (await loadConfig(options.setup));
65
- throwIfAborted(options.signal);
52
+ const config = input?.config ?? (await loadConfig(options.setup, options.signal));
53
+ const validateMutation = () => {
54
+ validateOwner();
55
+ options.background?.validate(config);
56
+ };
57
+ validateMutation();
66
58
  await requireNoMergeJournal(config, options);
67
59
  const state = input?.state ?? (await readStateForConfig(config));
68
60
  validateMutation();
69
61
  requireResolvedDirectionalProgress(state, options);
70
62
  if (options.auto &&
71
- (config.scope === "agent-directory" || state.scope !== undefined) &&
63
+ (config.scope === "agent-directory" ||
64
+ state.scope !== undefined ||
65
+ config.reservedIgnoreNames !== undefined ||
66
+ state.ignorePolicyKey !== undefined) &&
72
67
  (options.force || !state.lastAppliedSnapshot || syncPolicyChanged(state, config))) {
73
68
  throw new Error("Automatic push requires an accepted baseline with matching content policy.");
74
69
  }
@@ -80,6 +75,8 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
80
75
  const validateIgnorePolicy = ignorePolicyValidator({ ...snapshotOptions, validateMutation });
81
76
  const localRaw = input?.local ?? (await createSnapshot(config.snapshotIdentity, snapshotOptions));
82
77
  const local = portableSnapshot(localRaw, config.localFields);
78
+ if (validateIgnorePolicy)
79
+ await validateIgnorePolicy();
83
80
  throwIfAborted(options.signal);
84
81
  let head = await backend.readHead(options.signal);
85
82
  let remoteForUpload = await readRemoteSnapshotForUpload(backend, config, head, state, options);
@@ -154,6 +151,7 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
154
151
  throw new Error("Settings changed during push review.");
155
152
  validateMutation();
156
153
  if (config.scope === "agent-directory" ||
154
+ validateIgnorePolicy ||
157
155
  !options.yes ||
158
156
  config.localFields !== undefined ||
159
157
  (await readMergeJournal(config))) {
@@ -162,7 +160,7 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
162
160
  throw new Error("Local content changed during push review; retry from current bytes.");
163
161
  }
164
162
  const currentState = await readStateForConfig(config);
165
- if ((config.ignorePolicy || !options.yes) && syncStateFingerprint(currentState) !== syncStateFingerprint(state))
163
+ if ((validateIgnorePolicy || !options.yes) && syncStateFingerprint(currentState) !== syncStateFingerprint(state))
166
164
  throw new Error("Baseline changed during push review.");
167
165
  requireResolvedDirectionalProgress(currentState, options);
168
166
  if (config.scope === "agent-directory" &&
@@ -172,6 +170,14 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
172
170
  if (configIdentity !== syncCheckConfigFingerprint(await loadConfig(options.setup)))
173
171
  throw new Error("Settings changed during push review.");
174
172
  validateMutation();
173
+ const validatePublication = validateIgnorePolicy || options.background
174
+ ? () => validateDirectionalPublication(ctx, config, snapshotOptions, state, fileHashMap(localRaw), validateIgnorePolicy ??
175
+ (async () => {
176
+ if (configIdentity !== syncCheckConfigFingerprint(await loadConfig(options.setup, options.signal)))
177
+ throw new Error("Settings changed before push publication.");
178
+ validateMutation();
179
+ }), "push")
180
+ : undefined;
175
181
  if (validateIgnorePolicy) {
176
182
  validatePortableSnapshot(upload);
177
183
  await validateIgnorePolicy();
@@ -179,7 +185,7 @@ export async function push(ctx, options, input, factory = createSyncBackend) {
179
185
  const result = await backend.publishSnapshot(upload, expectedRemoteHead(head), {
180
186
  signal: options.signal,
181
187
  onCommit: options.onCommit,
182
- ...(validateIgnorePolicy ? { validateIgnorePolicy } : {}),
188
+ ...(validatePublication ? { validateIgnorePolicy: validatePublication } : {}),
183
189
  });
184
190
  try {
185
191
  await writeStateForConfig(config, {
@@ -316,7 +322,7 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
316
322
  await requireFreshRecovery();
317
323
  const currentState = await readStateForConfig(config);
318
324
  validateMutation();
319
- if ((config.ignorePolicy || initial || !options.yes) &&
325
+ if ((validateIgnorePolicy || initial || !options.yes) &&
320
326
  syncStateFingerprint(currentState) !== syncStateFingerprint(state))
321
327
  throw new Error("Baseline changed during pull review.");
322
328
  requireResolvedDirectionalProgress(currentState, options);
@@ -337,14 +343,27 @@ export async function pull(ctx, options, factory = createSyncBackend, initial) {
337
343
  await validateIgnorePolicy();
338
344
  }
339
345
  const protectedPaths = protectedSessionPaths(ctx, snapshotOptions.sessionDir);
340
- if (validateIgnorePolicy && !samePaths(protectedPaths, reviewedProtectedPaths))
341
- throw new Error("Live session protection changed during pull review; reopen the review.");
342
- options.onCommit?.();
346
+ const applyGuards = directionalApplyGuards({
347
+ ctx,
348
+ config,
349
+ backend,
350
+ state,
351
+ sessionDir: snapshotOptions.sessionDir,
352
+ head,
353
+ protectedPaths: reviewedProtectedPaths,
354
+ signal: options.signal,
355
+ onCommit: options.onCommit,
356
+ validateMutation,
357
+ validateIgnorePolicy,
358
+ });
359
+ applyGuards.validateMutation();
360
+ if (!validateIgnorePolicy)
361
+ options.onCommit?.();
343
362
  const lastFileHashes = await applySnapshot(physical, protectedPaths, {
344
363
  ...snapshotOptions,
345
364
  sessionDir: applySessionDir,
346
- validateMutation,
347
- ...(config.scope === "agent-directory" ? { reviewedLocal: local } : {}),
365
+ ...applyGuards,
366
+ ...(config.scope === "agent-directory" || validateIgnorePolicy ? { reviewedLocal: local } : {}),
348
367
  expectedFileHashes: config.localFields?.length
349
368
  ? { "settings.json": fileHashMap(local)["settings.json"] ?? null }
350
369
  : undefined,
@@ -544,6 +563,7 @@ export async function rollback(ctx, options, factory = createSyncBackend, expect
544
563
  await requireNoMergeJournal(config);
545
564
  const state = await readStateForConfig(config);
546
565
  validateMutation();
566
+ requireIgnoreBaselineReview(ctx, config, state, options);
547
567
  requireResolvedDirectionalProgress(state, options, false);
548
568
  const decoded = await backend.readSnapshot(target, options.signal);
549
569
  validateMutation();
@@ -585,8 +605,8 @@ export async function rollback(ctx, options, factory = createSyncBackend, expect
585
605
  const title = snapshotIncludesSessions(remote) ? "Rollback pi settings and sessions?" : "Rollback pi settings?";
586
606
  const summary = formatRollbackSummary(config, backend.destination, local, physical, target, reviewedProtectedPaths, caseCleanup.map((item) => item.path));
587
607
  const confirmed = config.ignorePolicy
588
- ? await confirmTransferReview(ctx, title, `Historical files are projected through this device's current ignore rules. Historical rules are not adopted. Retained history is not erased.\n\n${summary}\n\nRemote publication:\n${formatPublicationPreview(currentRemote, upload)}`, options.signal, validateMutation)
589
- : await ctx.ui.confirm(title, summary, { signal: options.signal });
608
+ ? await confirmTransferReview(ctx, title, formatTransferReview("Historical files are projected through this device's current ignore rules. Historical rules are not adopted. Retained history is not erased.", "", summary, "", "Remote publication:", formatPublicationPreview(currentRemote, upload)), options.signal, validateMutation)
609
+ : await ctx.ui.confirm(title, summary.content, { signal: options.signal });
590
610
  validateMutation();
591
611
  if (!confirmed) {
592
612
  ctx.ui.notify("Rollback cancelled.", "info");
@@ -606,7 +626,7 @@ export async function rollback(ctx, options, factory = createSyncBackend, expect
606
626
  const backup = await backupLocal(config.snapshotIdentity, snapshotOptions, options.signal);
607
627
  const applySessionDir = await sessionDirForApply(ctx, config.scope ? physical : remote, snapshotOptions);
608
628
  const currentState = await readStateForConfig(config);
609
- if (!options.yes && syncStateFingerprint(currentState) !== syncStateFingerprint(state))
629
+ if ((validateIgnorePolicy || !options.yes) && syncStateFingerprint(currentState) !== syncStateFingerprint(state))
610
630
  throw new Error("Baseline changed during rollback review.");
611
631
  requireResolvedDirectionalProgress(currentState, options, false);
612
632
  if (!options.yes)
@@ -623,14 +643,27 @@ export async function rollback(ctx, options, factory = createSyncBackend, expect
623
643
  await validateIgnorePolicy();
624
644
  }
625
645
  const protectedPaths = protectedSessionPaths(ctx, snapshotOptions.sessionDir);
626
- if (validateIgnorePolicy && !samePaths(protectedPaths, reviewedProtectedPaths))
627
- throw new Error("Live session protection changed during rollback review; reopen the review.");
628
- options.onCommit?.();
646
+ const applyGuards = directionalApplyGuards({
647
+ ctx,
648
+ config,
649
+ backend,
650
+ state,
651
+ sessionDir: snapshotOptions.sessionDir,
652
+ head: expectedHead,
653
+ protectedPaths: reviewedProtectedPaths,
654
+ signal: options.signal,
655
+ onCommit: options.onCommit,
656
+ validateMutation,
657
+ validateIgnorePolicy,
658
+ });
659
+ applyGuards.validateMutation();
660
+ if (!validateIgnorePolicy)
661
+ options.onCommit?.();
629
662
  const lastFileHashes = await applySnapshot(physical, protectedPaths, {
630
663
  ...snapshotOptions,
631
664
  sessionDir: applySessionDir,
632
- validateMutation,
633
- ...(config.scope === "agent-directory" ? { reviewedLocal: local } : {}),
665
+ ...applyGuards,
666
+ ...(config.scope === "agent-directory" || validateIgnorePolicy ? { reviewedLocal: local } : {}),
634
667
  expectedFileHashes: config.localFields?.length
635
668
  ? { "settings.json": fileHashMap(local)["settings.json"] ?? null }
636
669
  : undefined,
@@ -640,14 +673,17 @@ export async function rollback(ctx, options, factory = createSyncBackend, expect
640
673
  let result;
641
674
  try {
642
675
  const signal = AbortSignal.timeout(POST_LOCAL_COMMIT_TIMEOUT_MS);
643
- const validateIgnorePolicy = ignorePolicyValidator({
676
+ const validatePolicy = ignorePolicyValidator({
644
677
  ...snapshotOptions,
645
678
  signal,
646
679
  validateMutation: validateCommittedOwner,
647
680
  });
681
+ const validatePublication = validatePolicy
682
+ ? () => validateDirectionalPublication(ctx, config, { ...snapshotOptions, sessionDir: applySessionDir, signal }, state, lastFileHashes, validatePolicy, "rollback")
683
+ : undefined;
648
684
  result = await backend.publishSnapshot(upload, expectedRemoteHead(expectedHead), {
649
685
  signal,
650
- ...(validateIgnorePolicy ? { validateIgnorePolicy } : {}),
686
+ ...(validatePublication ? { validateIgnorePolicy: validatePublication } : {}),
651
687
  });
652
688
  }
653
689
  catch (error) {
@@ -694,18 +730,6 @@ async function maybeReload(ctx, signal, validateMutation = captureMutationOwner(
694
730
  await ctx.reload();
695
731
  }
696
732
  }
697
- async function snapshotForUpload(backend, config, local, head, remote, options) {
698
- if (config.ignorePolicy)
699
- return filterSnapshotForConfigPolicy(local, config, { ...options, regenerateId: true });
700
- if (!head)
701
- return local;
702
- const snapshot = remote ?? (await readSnapshotForHead(backend, head, options.signal, config));
703
- const remoteScoped = snapshot.selection?.version === 3;
704
- if (remoteScoped !== (config.scope === "agent-directory")) {
705
- throw new Error("Converting an existing remote between included paths and agent-directory scope is not supported. Use a separate storage location.");
706
- }
707
- return mergeRemotePreservedFiles(local, snapshot, config, options);
708
- }
709
733
  async function confirmPush(ctx, options, config, backend, local, upload, head, remote, validateMutation, title = snapshotIncludesSessions(upload) ? "Push pi settings and sessions?" : "Push pi settings?") {
710
734
  validateMutation();
711
735
  if (options.yes)
@@ -715,7 +739,7 @@ async function confirmPush(ctx, options, config, backend, local, upload, head, r
715
739
  ? inspectRemoteSelection(config.include, remote, config.exclude, config).ignorePolicyComparison
716
740
  : undefined;
717
741
  const confirmed = await confirmTransferReview(ctx, title, comparison && comparison !== "match"
718
- ? `${formatIgnorePolicyComparison(comparison)}\nOnly files selected by this device's rules are published. Remote rules are not adopted.\n\n${summary}`
742
+ ? formatTransferReview(formatIgnorePolicyComparison(comparison), "Only files selected by this device's rules are published. Remote rules are not adopted.", "", summary)
719
743
  : summary, options.signal, validateMutation);
720
744
  throwIfAborted(options.signal);
721
745
  if (confirmed)
@@ -727,7 +751,4 @@ async function confirmPush(ctx, options, config, backend, local, upload, head, r
727
751
  function matchesInitialHead(initial, backend, current) {
728
752
  return sameRemoteHead(backend, initial.head, current);
729
753
  }
730
- function samePaths(left, right) {
731
- return left.size === right.size && [...left].every((item) => right.has(item));
732
- }
733
754
  export { backupLocal } from "./sync-local.js";
@@ -41,6 +41,11 @@ export type RemoteSelectionState = {
41
41
  export declare function compareIgnorePolicy(local: DirectoryScope["ignorePolicy"], remote: SnapshotSelection | undefined): IgnorePolicyComparison | undefined;
42
42
  export declare function formatIgnorePolicyComparison(comparison: IgnorePolicyComparison): "Remote ignore-file policy differs. Edit local rules to match, or review publishing this device's policy." | "Remote ignore-file policy matches this device." | "Remote uses a legacy content policy. Review publishing this device's ignore-file policy." | "Remote uses an ignore-file policy. Configure matching local rules before transferring.";
43
43
  export declare function syncDirectoryPolicyKey(config: SyncSelectionConfig): string | undefined;
44
+ export declare function localIgnorePolicyKey(config: SyncSelectionConfig & {
45
+ setupName?: string;
46
+ ignoreSourceIdentity?: string;
47
+ recoverySetupKey?: string;
48
+ }): string | undefined;
44
49
  export declare function inspectRemoteSelection(localInclude: unknown, snapshot: Pick<Snapshot, "selection" | "files">, localExclude?: unknown, directory?: DirectoryScope): RemoteSelectionState;
45
50
  export interface RemoteSelectionDecision {
46
51
  setupName: string;
@@ -1,3 +1,4 @@
1
+ import { createHash } from "node:crypto";
1
2
  import path from "node:path";
2
3
  import { isDeniedPath, toPosix } from "../paths.js";
3
4
  import { IGNORE_SNAPSHOT_VERSION, } from "../snapshot/snapshot-types.js";
@@ -262,6 +263,23 @@ export function syncDirectoryPolicyKey(config) {
262
263
  normalizeDirectoryRules(config.reinclude).map((rule) => rule.toLowerCase()),
263
264
  ]);
264
265
  }
266
+ export function localIgnorePolicyKey(config) {
267
+ if (!config.ignorePolicy && config.reservedIgnoreNames === undefined)
268
+ return undefined;
269
+ const reserved = reservedIgnoreSnapshotNames(config);
270
+ return createHash("sha256")
271
+ .update(JSON.stringify([
272
+ config.setupName,
273
+ config.recoverySetupKey,
274
+ syncDirectoryPolicyKey(config) ?? [
275
+ includeFromSelectionConfig(config),
276
+ normalizeSyncExclude(config.exclude).map((rule) => rule.toLowerCase()),
277
+ ],
278
+ config.ignoreSourceIdentity,
279
+ [...(reserved ?? [])].sort(),
280
+ ]))
281
+ .digest("hex");
282
+ }
265
283
  export function inspectRemoteSelection(localInclude, snapshot, localExclude, directory) {
266
284
  const selection = snapshot.selection === undefined ? undefined : portableSnapshotSelection(snapshot.selection);
267
285
  const ignorePolicyComparison = compareIgnorePolicy(directory?.ignorePolicy, selection);
@@ -469,12 +487,19 @@ export function isIgnoreControlPath(relativePath, reservedNames) {
469
487
  function isIgnoreSnapshotSelection(config) {
470
488
  return config.version === 4 && config.fingerprint !== undefined;
471
489
  }
472
- function compileIgnoreControlPath(config) {
490
+ function reservedIgnoreSnapshotNames(config) {
473
491
  const local = config.ignorePolicy;
474
492
  if (!local && !config.reservedIgnoreNames && !isIgnoreSnapshotSelection(config))
475
493
  return undefined;
476
- const names = new Set([...(local ? [local.filename, ...local.reservedNames] : []), ...(config.reservedIgnoreNames ?? [])].map((name) => name.toLowerCase()));
477
- return (relativePath) => isIgnoreControlPath(relativePath, names);
494
+ return new Set([
495
+ ".syncignore",
496
+ ...(local ? [local.filename, ...local.reservedNames] : []),
497
+ ...(config.reservedIgnoreNames ?? []),
498
+ ].map((name) => name.toLowerCase()));
499
+ }
500
+ function compileIgnoreControlPath(config) {
501
+ const names = reservedIgnoreSnapshotNames(config);
502
+ return names ? (relativePath) => isIgnoreControlPath(relativePath, names) : undefined;
478
503
  }
479
504
  function compileDirectoryPolicy(config) {
480
505
  const localIgnore = config.ignorePolicy;
@@ -4,6 +4,8 @@ import type { SyncState } from "../state/state-types.js";
4
4
  import { type SyncSelectionConfig } from "./sync-policy.js";
5
5
  type SyncPolicyConfig = SyncSelectionConfig & {
6
6
  localFields?: string[];
7
+ setupName?: string;
8
+ ignoreSourceIdentity?: string;
7
9
  };
8
10
  export declare function hasLocalChanges(local: Snapshot, state: SyncState, config: SyncPolicyConfig): boolean;
9
11
  export declare function remoteChangedSinceState(head: RemoteHead | undefined, state: SyncState, config: SyncPolicyConfig, sameRevision: (left: string, right: string) => boolean): boolean;
@@ -1,13 +1,8 @@
1
- import { createHash } from "node:crypto";
2
1
  import { toPosix } from "../paths.js";
3
2
  import { canonicalSnapshotPathForConfig, filterSnapshotForConfigPolicy, isSessionPath } from "../snapshot/snapshot.js";
4
3
  import { sameSyncExclude } from "./exclude-policy.js";
5
4
  import { portableSnapshot, sameLocalFields } from "./local-fields.js";
6
- import { compareIgnorePolicy, configuredSnapshotPathMatcher, customIncludePathsByLower, includeFromSelectionConfig, normalizeSyncInclude, syncDirectoryPolicyKey, syncSessionsSelected, } from "./sync-policy.js";
7
- function ignorePolicyKey(config) {
8
- const key = config.ignorePolicy && syncDirectoryPolicyKey(config);
9
- return key === undefined ? undefined : createHash("sha256").update(key).digest("hex");
10
- }
5
+ import { compareIgnorePolicy, configuredSnapshotPathMatcher, customIncludePathsByLower, includeFromSelectionConfig, localIgnorePolicyKey, normalizeSyncInclude, syncDirectoryPolicyKey, syncSessionsSelected, } from "./sync-policy.js";
11
6
  export function hasLocalChanges(local, state, config) {
12
7
  return ((Boolean(state.lastAppliedSnapshot) &&
13
8
  (state.scope !== config.scope ||
@@ -84,7 +79,7 @@ export function shouldRefreshSyncedState(remote, head, state, config, sameRevisi
84
79
  syncPolicyChanged(state, config));
85
80
  }
86
81
  export function acceptedSelection(config) {
87
- const key = ignorePolicyKey(config);
82
+ const key = localIgnorePolicyKey(config);
88
83
  return {
89
84
  include: config.ignorePolicy ? includeFromSelectionConfig(config) : [...config.include],
90
85
  ...(key === undefined ? {} : { ignorePolicyKey: key }),
@@ -94,7 +89,7 @@ export function acceptedSelection(config) {
94
89
  };
95
90
  }
96
91
  function sameSelectionRules(state, config) {
97
- const key = ignorePolicyKey(config);
92
+ const key = localIgnorePolicyKey(config);
98
93
  if (key !== undefined || state.ignorePolicyKey !== undefined)
99
94
  return key === state.ignorePolicyKey;
100
95
  return config.scope === "agent-directory" && state.scope === config.scope
@@ -0,0 +1,31 @@
1
+ import type { RemoteHead, SyncBackend } from "../backends/sync-backend.js";
2
+ import type { CommandOptions } from "../commands/command-types.js";
3
+ import type { EngineContext } from "../host.js";
4
+ import type { AnySyncConfig } from "../settings/settings-types.js";
5
+ import type { Snapshot, SnapshotOptions } from "../snapshot/snapshot-types.js";
6
+ import type { SyncState } from "../state/state-types.js";
7
+ export declare function requireResolvedDirectionalProgress(state: SyncState, options: CommandOptions, allowForce?: boolean): void;
8
+ export declare function requireIgnoreBaselineReview(ctx: EngineContext, config: AnySyncConfig, state: SyncState, options: CommandOptions): void;
9
+ export declare function validateDirectionalPublication(ctx: EngineContext, config: AnySyncConfig, options: SnapshotOptions, state: SyncState, expectedHashes: Record<string, string>, validatePolicy: () => Promise<void>, direction: "push" | "rollback"): Promise<void>;
10
+ export declare function checkLiveProtection(ctx: EngineContext, sessionDir: string | undefined, reviewed: ReadonlySet<string>): void;
11
+ export declare function directionalApplyGuards({ ctx, config, backend, state, sessionDir, head, protectedPaths, signal, validateMutation, validateIgnorePolicy, onCommit, }: {
12
+ ctx: EngineContext;
13
+ config: AnySyncConfig;
14
+ backend: SyncBackend;
15
+ state: SyncState;
16
+ sessionDir?: string;
17
+ head?: RemoteHead;
18
+ protectedPaths: ReadonlySet<string>;
19
+ signal?: AbortSignal;
20
+ validateMutation: () => void;
21
+ validateIgnorePolicy?: () => Promise<void>;
22
+ onCommit?: () => void;
23
+ }): {
24
+ validateMutation: () => void;
25
+ validateApplyReview?: undefined;
26
+ } | {
27
+ validateMutation: () => void;
28
+ validateApplyReview: () => Promise<void>;
29
+ };
30
+ export declare function validateMergeApplyReview(backend: SyncBackend, config: AnySyncConfig, head: RemoteHead, stateIdentity: string, validateFresh: () => Promise<void>, signal?: AbortSignal): Promise<void>;
31
+ export declare function validateMergedPublication(ctx: EngineContext, config: AnySyncConfig, options: SnapshotOptions, before: Snapshot, after: Snapshot, stateIdentity: string, validateFresh: () => Promise<void>): Promise<void>;
@@ -0,0 +1,82 @@
1
+ import { resolvedSnapshotOptionsForContext } from "../snapshot/session-paths.js";
2
+ import { createSnapshot } from "../snapshot/snapshot.js";
3
+ import { StaleIgnorePolicyError } from "../snapshot/snapshot-transaction-policy.js";
4
+ import { readStateForConfig, syncStateFingerprint } from "../state/sync-state-store.js";
5
+ import { ContinuousError } from "./continuous-errors.js";
6
+ import { preflightMergedTargets } from "./merge-apply.js";
7
+ import { sameRemoteHead } from "./remote-snapshot.js";
8
+ import { protectedSessionPaths } from "./sync-local.js";
9
+ import { fileHashMap, sameHashes, syncPolicyChanged } from "./sync-state.js";
10
+ export function requireResolvedDirectionalProgress(state, options, allowForce = true) {
11
+ if (state.unresolved?.length && (options.auto || !options.force || !allowForce))
12
+ throw new Error("Unresolved partial conflicts remain. Review /sync conflicts or explicitly choose push --force or pull --force; automatic transfer and rollback cannot accept unresolved groups.");
13
+ }
14
+ export function requireIgnoreBaselineReview(ctx, config, state, options) {
15
+ if ((config.ignorePolicy || config.reservedIgnoreNames !== undefined || state.ignorePolicyKey !== undefined) &&
16
+ state.lastAppliedSnapshot &&
17
+ syncPolicyChanged(state, config) &&
18
+ (options.auto || options.yes || !ctx.hasUI)) {
19
+ throw new Error("Local ignore-file policy or source changed since the last accepted baseline. Review a foreground directional transfer.");
20
+ }
21
+ }
22
+ export async function validateDirectionalPublication(ctx, config, options, state, expectedHashes, validatePolicy, direction) {
23
+ const current = await createSnapshot(config.snapshotIdentity, options);
24
+ if (!sameHashes(fileHashMap(current), expectedHashes))
25
+ throw new Error(`Local bytes changed at the ${direction} publication boundary.`);
26
+ if (syncStateFingerprint(await readStateForConfig(config)) !== syncStateFingerprint(state))
27
+ throw new Error(`Baseline changed at the ${direction} publication boundary.`);
28
+ if ((config.scope === "agent-directory" || direction === "push") &&
29
+ options.sessionDir !== (await resolvedSnapshotOptionsForContext(ctx, config, options.signal)).sessionDir)
30
+ throw new Error(`Pi session storage changed at the ${direction} publication boundary.`);
31
+ await validatePolicy();
32
+ }
33
+ export function checkLiveProtection(ctx, sessionDir, reviewed) {
34
+ const current = protectedSessionPaths(ctx, sessionDir);
35
+ if (current.size !== reviewed.size || [...current].some((item) => !reviewed.has(item)))
36
+ throw new StaleIgnorePolicyError("Live session protection changed during review; reopen the review.");
37
+ }
38
+ export function directionalApplyGuards({ ctx, config, backend, state, sessionDir, head, protectedPaths, signal, validateMutation, validateIgnorePolicy, onCommit, }) {
39
+ if (!validateIgnorePolicy)
40
+ return { validateMutation };
41
+ const validateOwner = () => {
42
+ validateMutation();
43
+ checkLiveProtection(ctx, sessionDir, protectedPaths);
44
+ };
45
+ let committed = false;
46
+ return {
47
+ validateMutation: validateOwner,
48
+ validateApplyReview: async () => {
49
+ if (!sameRemoteHead(backend, head, await backend.readHead(signal)))
50
+ throw new StaleIgnorePolicyError("Remote changed before local apply; reopen the review.");
51
+ if (syncStateFingerprint(await readStateForConfig(config)) !== syncStateFingerprint(state))
52
+ throw new StaleIgnorePolicyError("Baseline changed before local apply; reopen the review.");
53
+ if (sessionDir !== (await resolvedSnapshotOptionsForContext(ctx, config, signal)).sessionDir)
54
+ throw new StaleIgnorePolicyError("Pi session storage changed before local apply; reopen the review.");
55
+ await validateIgnorePolicy();
56
+ validateOwner();
57
+ if (!committed) {
58
+ onCommit?.();
59
+ committed = true;
60
+ }
61
+ },
62
+ };
63
+ }
64
+ export async function validateMergeApplyReview(backend, config, head, stateIdentity, validateFresh, signal) {
65
+ if (!sameRemoteHead(backend, head, await backend.readHead(signal)))
66
+ throw new Error("Remote head changed before merged apply; journal and backup retained.");
67
+ if (syncStateFingerprint(await readStateForConfig(config)) !== stateIdentity)
68
+ throw new Error("Sync baseline changed before merged apply; journal and backup retained.");
69
+ await validateFresh();
70
+ }
71
+ export async function validateMergedPublication(ctx, config, options, before, after, stateIdentity, validateFresh) {
72
+ await validateFresh();
73
+ const current = await createSnapshot(config.snapshotIdentity, options);
74
+ const state = await readStateForConfig(config);
75
+ if (!sameHashes(fileHashMap(current), fileHashMap(before)) || syncStateFingerprint(state) !== stateIdentity)
76
+ throw new ContinuousError("stale", "Local content or baseline changed at publication; journal and backup retained.");
77
+ await preflightMergedTargets(current, after, options, [
78
+ ...(ctx.protectedSessionFiles ?? []),
79
+ ...[ctx.sessionManager.getSessionFile?.()].filter((file) => Boolean(file)),
80
+ ]);
81
+ await validateFresh();
82
+ }
@@ -3,11 +3,22 @@ import type { CommonSyncConfig } from "../settings/settings-types.js";
3
3
  import type { Snapshot } from "../snapshot/snapshot-types.js";
4
4
  export declare function formatDiff(local: Snapshot, remote: Snapshot): string;
5
5
  export declare function formatSnapshotOnlyDiff(title: string, snapshot: Snapshot): string;
6
- export declare function formatPushSummary(config: CommonSyncConfig, destination: string, upload: Snapshot, head: RemoteHead | undefined, preservedRemoteFileCount?: number, remote?: Snapshot): string;
7
- export declare function formatApplyPreview(local: Snapshot, remote: Snapshot, protectedPaths?: ReadonlySet<string>, additionalRemovals?: readonly string[]): string;
8
- export declare function formatPullSummary(config: CommonSyncConfig, destination: string, local: Snapshot, remote: Snapshot, protectedPaths: ReadonlySet<string>, additionalRemovals?: readonly string[]): string;
9
- export declare function formatRollbackSummary(config: CommonSyncConfig, destination: string, local: Snapshot, remote: Snapshot, requestedSnapshot: string, protectedPaths: ReadonlySet<string>, additionalRemovals?: readonly string[]): string;
10
- export declare function formatPublicationPreview(remote: Snapshot | undefined, upload: Snapshot): string;
6
+ export interface TransferReview {
7
+ lines: readonly string[];
8
+ content: string;
9
+ }
10
+ export declare function formatTransferReview(...sections: (string | TransferReview)[]): TransferReview;
11
+ export declare function formatPushSummary(config: CommonSyncConfig, destination: string, upload: Snapshot, head: RemoteHead | undefined, preservedRemoteFileCount?: number, remote?: Snapshot): TransferReview;
12
+ export declare function formatApplyPreview(local: Snapshot, remote: Snapshot, protectedPaths?: ReadonlySet<string>, additionalRemovals?: readonly string[]): {
13
+ lines: string[];
14
+ content: string;
15
+ };
16
+ export declare function formatPullSummary(config: CommonSyncConfig, destination: string, local: Snapshot, remote: Snapshot, protectedPaths: ReadonlySet<string>, additionalRemovals?: readonly string[]): TransferReview;
17
+ export declare function formatRollbackSummary(config: CommonSyncConfig, destination: string, local: Snapshot, remote: Snapshot, requestedSnapshot: string, protectedPaths: ReadonlySet<string>, additionalRemovals?: readonly string[]): TransferReview;
18
+ export declare function formatPublicationPreview(remote: Snapshot | undefined, upload: Snapshot): {
19
+ lines: string[];
20
+ content: string;
21
+ };
11
22
  export declare function countPreservedRemoteFiles(local: Snapshot, upload: Snapshot): number;
12
23
  export declare function publicationCapabilityDescription(capability: PublicationCapability): "atomic-conditional (verified atomic precondition)" | "conditional-required (read-only until atomic preconditions are verified)" | "lease-protected (exact expected-ref update)" | "read-check-write-verify (visible races rejected; simultaneous unseen races remain possible)";
13
24
  export declare function redact(value: string): string;