@narumitw/pi-sync-daemon 0.8.0 → 0.9.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 (54) hide show
  1. package/CHANGELOG.md +10 -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 +3 -0
  10. package/dist/engine/ignore/ignore-initialization.js +93 -27
  11. package/dist/engine/ignore/ignore-settings.d.ts +16 -1
  12. package/dist/engine/ignore/ignore-settings.js +85 -14
  13. package/dist/engine/settings/config-file.js +1 -1
  14. package/dist/engine/settings/config.d.ts +3 -2
  15. package/dist/engine/settings/config.js +71 -28
  16. package/dist/engine/settings/settings-management.d.ts +3 -1
  17. package/dist/engine/settings/settings-management.js +8 -2
  18. package/dist/engine/settings/settings-types.d.ts +2 -0
  19. package/dist/engine/snapshot/session-paths.js +7 -2
  20. package/dist/engine/snapshot/snapshot-apply.d.ts +1 -1
  21. package/dist/engine/snapshot/snapshot-transaction-policy.d.ts +7 -2
  22. package/dist/engine/snapshot/snapshot-transaction-policy.js +37 -17
  23. package/dist/engine/snapshot/snapshot-transaction.js +55 -13
  24. package/dist/engine/snapshot/snapshot-types.d.ts +4 -0
  25. package/dist/engine/sync/agent-plan.js +1 -0
  26. package/dist/engine/sync/agent-sync.js +8 -1
  27. package/dist/engine/sync/continuous-sync.d.ts +3 -1
  28. package/dist/engine/sync/continuous-sync.js +32 -15
  29. package/dist/engine/sync/merge-acceptance.d.ts +8 -0
  30. package/dist/engine/sync/merge-acceptance.js +29 -0
  31. package/dist/engine/sync/merge-apply.js +7 -4
  32. package/dist/engine/sync/merge-journal.d.ts +6 -0
  33. package/dist/engine/sync/merge-journal.js +33 -14
  34. package/dist/engine/sync/merged-sync.js +31 -39
  35. package/dist/engine/sync/remote-snapshot.d.ts +2 -1
  36. package/dist/engine/sync/remote-snapshot.js +17 -2
  37. package/dist/engine/sync/session-push.js +20 -6
  38. package/dist/engine/sync/sync-mutations.js +71 -50
  39. package/dist/engine/sync/sync-policy.d.ts +5 -0
  40. package/dist/engine/sync/sync-policy.js +28 -3
  41. package/dist/engine/sync/sync-state.d.ts +2 -0
  42. package/dist/engine/sync/sync-state.js +3 -8
  43. package/dist/engine/sync/transfer-freshness.d.ts +31 -0
  44. package/dist/engine/sync/transfer-freshness.js +82 -0
  45. package/dist/engine-service.d.ts +1 -1
  46. package/dist/engine-service.js +124 -27
  47. package/dist/monitor.d.ts +4 -1
  48. package/dist/monitor.js +84 -32
  49. package/dist/server.d.ts +1 -0
  50. package/dist/server.js +46 -5
  51. package/dist/service-host.d.ts +1 -1
  52. package/dist/service-host.js +2 -1
  53. package/docs/architecture.md +13 -5
  54. package/package.json +1 -1
@@ -2,7 +2,7 @@ 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";
@@ -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();
@@ -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)
@@ -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
+ }
@@ -1,6 +1,6 @@
1
1
  import { type Execute } from "./protocol.js";
2
2
  /** Engine dispatch is loaded only by the service, never by the public IPC client. */
3
- export declare function createEngineService(root: string): {
3
+ export declare function createEngineService(root: string, ignoreFileSettingsAvailable?: boolean): {
4
4
  execute: Execute;
5
5
  bind: (value: Awaited<ReturnType<typeof import("./server.js").startServer>>) => void;
6
6
  hooks: {