@narumitw/pi-sync-daemon 0.0.0-stage → 0.2.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 (265) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/LICENSE +21 -0
  3. package/README.md +89 -2
  4. package/dist/cli.d.ts +2 -0
  5. package/dist/cli.js +128 -0
  6. package/dist/client.d.ts +55 -0
  7. package/dist/client.js +484 -0
  8. package/dist/consent.d.ts +24 -0
  9. package/dist/consent.js +205 -0
  10. package/dist/document.d.ts +10 -0
  11. package/dist/document.js +6 -0
  12. package/dist/endpoint.d.ts +8 -0
  13. package/dist/endpoint.js +91 -0
  14. package/dist/engine/backends/backend-factory.d.ts +6 -0
  15. package/dist/engine/backends/backend-factory.js +16 -0
  16. package/dist/engine/backends/backend-identity.d.ts +3 -0
  17. package/dist/engine/backends/backend-identity.js +38 -0
  18. package/dist/engine/backends/backend-types.d.ts +70 -0
  19. package/dist/engine/backends/backend-types.js +1 -0
  20. package/dist/engine/backends/git/git-backend.d.ts +55 -0
  21. package/dist/engine/backends/git/git-backend.js +700 -0
  22. package/dist/engine/backends/git/git-config.d.ts +5 -0
  23. package/dist/engine/backends/git/git-config.js +118 -0
  24. package/dist/engine/backends/git/git-runner.d.ts +25 -0
  25. package/dist/engine/backends/git/git-runner.js +232 -0
  26. package/dist/engine/backends/git/git-storage.d.ts +39 -0
  27. package/dist/engine/backends/git/git-storage.js +226 -0
  28. package/dist/engine/backends/s3/s3-backend.d.ts +32 -0
  29. package/dist/engine/backends/s3/s3-backend.js +436 -0
  30. package/dist/engine/backends/s3/s3-client.d.ts +36 -0
  31. package/dist/engine/backends/s3/s3-client.js +352 -0
  32. package/dist/engine/backends/s3/s3-conditions.d.ts +4 -0
  33. package/dist/engine/backends/s3/s3-conditions.js +66 -0
  34. package/dist/engine/backends/snapshot-pointer.d.ts +6 -0
  35. package/dist/engine/backends/snapshot-pointer.js +22 -0
  36. package/dist/engine/backends/sync-backend.d.ts +71 -0
  37. package/dist/engine/backends/sync-backend.js +23 -0
  38. package/dist/engine/backends/webdav/webdav-backend.d.ts +34 -0
  39. package/dist/engine/backends/webdav/webdav-backend.js +534 -0
  40. package/dist/engine/backends/webdav/webdav-client.d.ts +36 -0
  41. package/dist/engine/backends/webdav/webdav-client.js +326 -0
  42. package/dist/engine/backends/webdav/webdav-config.d.ts +5 -0
  43. package/dist/engine/backends/webdav/webdav-config.js +73 -0
  44. package/dist/engine/commands/command-types.d.ts +31 -0
  45. package/dist/engine/commands/command-types.js +1 -0
  46. package/dist/engine/host.d.ts +70 -0
  47. package/dist/engine/host.js +16 -0
  48. package/dist/engine/paths.d.ts +9 -0
  49. package/dist/engine/paths.js +71 -0
  50. package/dist/engine/settings/config-errors.d.ts +1 -0
  51. package/dist/engine/settings/config-errors.js +4 -0
  52. package/dist/engine/settings/config-file.d.ts +33 -0
  53. package/dist/engine/settings/config-file.js +630 -0
  54. package/dist/engine/settings/config.d.ts +24 -0
  55. package/dist/engine/settings/config.js +200 -0
  56. package/dist/engine/settings/settings-management.d.ts +24 -0
  57. package/dist/engine/settings/settings-management.js +191 -0
  58. package/dist/engine/settings/settings-store.d.ts +8 -0
  59. package/dist/engine/settings/settings-store.js +41 -0
  60. package/dist/engine/settings/settings-types.d.ts +134 -0
  61. package/dist/engine/settings/settings-types.js +1 -0
  62. package/dist/engine/settings/settings-validation.d.ts +15 -0
  63. package/dist/engine/settings/settings-validation.js +356 -0
  64. package/dist/engine/snapshot/session-paths.d.ts +12 -0
  65. package/dist/engine/snapshot/session-paths.js +91 -0
  66. package/dist/engine/snapshot/snapshot-apply.d.ts +22 -0
  67. package/dist/engine/snapshot/snapshot-apply.js +262 -0
  68. package/dist/engine/snapshot/snapshot-case-replacement.d.ts +15 -0
  69. package/dist/engine/snapshot/snapshot-case-replacement.js +82 -0
  70. package/dist/engine/snapshot/snapshot-codec.d.ts +6 -0
  71. package/dist/engine/snapshot/snapshot-codec.js +53 -0
  72. package/dist/engine/snapshot/snapshot-exclude-safety.d.ts +7 -0
  73. package/dist/engine/snapshot/snapshot-exclude-safety.js +47 -0
  74. package/dist/engine/snapshot/snapshot-mutation-queues.d.ts +9 -0
  75. package/dist/engine/snapshot/snapshot-mutation-queues.js +133 -0
  76. package/dist/engine/snapshot/snapshot-paths.d.ts +1 -0
  77. package/dist/engine/snapshot/snapshot-paths.js +11 -0
  78. package/dist/engine/snapshot/snapshot-root-transition.d.ts +25 -0
  79. package/dist/engine/snapshot/snapshot-root-transition.js +122 -0
  80. package/dist/engine/snapshot/snapshot-transaction-directory.d.ts +2 -0
  81. package/dist/engine/snapshot/snapshot-transaction-directory.js +16 -0
  82. package/dist/engine/snapshot/snapshot-transaction-plan.d.ts +12 -0
  83. package/dist/engine/snapshot/snapshot-transaction-plan.js +68 -0
  84. package/dist/engine/snapshot/snapshot-transaction.d.ts +15 -0
  85. package/dist/engine/snapshot/snapshot-transaction.js +787 -0
  86. package/dist/engine/snapshot/snapshot-types.d.ts +48 -0
  87. package/dist/engine/snapshot/snapshot-types.js +1 -0
  88. package/dist/engine/snapshot/snapshot.d.ts +30 -0
  89. package/dist/engine/snapshot/snapshot.js +364 -0
  90. package/dist/engine/state/json-file.d.ts +6 -0
  91. package/dist/engine/state/json-file.js +49 -0
  92. package/dist/engine/state/lock-policy.d.ts +2 -0
  93. package/dist/engine/state/lock-policy.js +2 -0
  94. package/dist/engine/state/lock.d.ts +20 -0
  95. package/dist/engine/state/lock.js +259 -0
  96. package/dist/engine/state/lockfile-fs.d.ts +13 -0
  97. package/dist/engine/state/lockfile-fs.js +13 -0
  98. package/dist/engine/state/merge-baseline-store.d.ts +11 -0
  99. package/dist/engine/state/merge-baseline-store.js +187 -0
  100. package/dist/engine/state/mutation-directory-sync.d.ts +5 -0
  101. package/dist/engine/state/mutation-directory-sync.js +34 -0
  102. package/dist/engine/state/operation-availability.d.ts +49 -0
  103. package/dist/engine/state/operation-availability.js +40 -0
  104. package/dist/engine/state/state-directory.d.ts +14 -0
  105. package/dist/engine/state/state-directory.js +225 -0
  106. package/dist/engine/state/state-types.d.ts +27 -0
  107. package/dist/engine/state/state-types.js +1 -0
  108. package/dist/engine/state/sync-state-store.d.ts +11 -0
  109. package/dist/engine/state/sync-state-store.js +54 -0
  110. package/dist/engine/sync/agent-candidate.d.ts +44 -0
  111. package/dist/engine/sync/agent-candidate.js +207 -0
  112. package/dist/engine/sync/agent-plan.d.ts +8 -0
  113. package/dist/engine/sync/agent-plan.js +84 -0
  114. package/dist/engine/sync/agent-policy.d.ts +9 -0
  115. package/dist/engine/sync/agent-policy.js +10 -0
  116. package/dist/engine/sync/agent-refusal-retry.d.ts +4 -0
  117. package/dist/engine/sync/agent-refusal-retry.js +39 -0
  118. package/dist/engine/sync/agent-request.d.ts +14 -0
  119. package/dist/engine/sync/agent-request.js +13 -0
  120. package/dist/engine/sync/agent-runner.d.ts +6 -0
  121. package/dist/engine/sync/agent-runner.js +183 -0
  122. package/dist/engine/sync/agent-store.d.ts +7 -0
  123. package/dist/engine/sync/agent-store.js +177 -0
  124. package/dist/engine/sync/agent-sync.d.ts +4 -0
  125. package/dist/engine/sync/agent-sync.js +132 -0
  126. package/dist/engine/sync/apply-review.d.ts +8 -0
  127. package/dist/engine/sync/apply-review.js +51 -0
  128. package/dist/engine/sync/conflict-artifact-ownership.d.ts +4 -0
  129. package/dist/engine/sync/conflict-artifact-ownership.js +53 -0
  130. package/dist/engine/sync/conflict-artifacts.d.ts +32 -0
  131. package/dist/engine/sync/conflict-artifacts.js +158 -0
  132. package/dist/engine/sync/conflict-groups.d.ts +9 -0
  133. package/dist/engine/sync/conflict-groups.js +76 -0
  134. package/dist/engine/sync/conflict-preview.d.ts +4 -0
  135. package/dist/engine/sync/conflict-preview.js +53 -0
  136. package/dist/engine/sync/conflict-resolution.d.ts +13 -0
  137. package/dist/engine/sync/conflict-resolution.js +53 -0
  138. package/dist/engine/sync/conflict-retention.d.ts +5 -0
  139. package/dist/engine/sync/conflict-retention.js +61 -0
  140. package/dist/engine/sync/conflict-review.d.ts +4 -0
  141. package/dist/engine/sync/conflict-review.js +73 -0
  142. package/dist/engine/sync/content-conflicts.d.ts +10 -0
  143. package/dist/engine/sync/content-conflicts.js +70 -0
  144. package/dist/engine/sync/continuous-errors.d.ts +14 -0
  145. package/dist/engine/sync/continuous-errors.js +66 -0
  146. package/dist/engine/sync/continuous-lease.d.ts +9 -0
  147. package/dist/engine/sync/continuous-lease.js +206 -0
  148. package/dist/engine/sync/continuous-record.d.ts +31 -0
  149. package/dist/engine/sync/continuous-record.js +199 -0
  150. package/dist/engine/sync/continuous-storage.d.ts +14 -0
  151. package/dist/engine/sync/continuous-storage.js +59 -0
  152. package/dist/engine/sync/continuous-sync.d.ts +15 -0
  153. package/dist/engine/sync/continuous-sync.js +496 -0
  154. package/dist/engine/sync/continuous-watch.d.ts +3 -0
  155. package/dist/engine/sync/continuous-watch.js +65 -0
  156. package/dist/engine/sync/exclude-policy.d.ts +5 -0
  157. package/dist/engine/sync/exclude-policy.js +79 -0
  158. package/dist/engine/sync/field-migration.d.ts +5 -0
  159. package/dist/engine/sync/field-migration.js +20 -0
  160. package/dist/engine/sync/file-merge-planner.d.ts +36 -0
  161. package/dist/engine/sync/file-merge-planner.js +123 -0
  162. package/dist/engine/sync/initialization.d.ts +12 -0
  163. package/dist/engine/sync/initialization.js +75 -0
  164. package/dist/engine/sync/json-document.d.ts +29 -0
  165. package/dist/engine/sync/json-document.js +172 -0
  166. package/dist/engine/sync/local-field-policy.d.ts +2 -0
  167. package/dist/engine/sync/local-field-policy.js +26 -0
  168. package/dist/engine/sync/local-fields.d.ts +9 -0
  169. package/dist/engine/sync/local-fields.js +116 -0
  170. package/dist/engine/sync/merge-apply.d.ts +5 -0
  171. package/dist/engine/sync/merge-apply.js +386 -0
  172. package/dist/engine/sync/merge-journal.d.ts +31 -0
  173. package/dist/engine/sync/merge-journal.js +179 -0
  174. package/dist/engine/sync/merge-transfer-error.d.ts +3 -0
  175. package/dist/engine/sync/merge-transfer-error.js +64 -0
  176. package/dist/engine/sync/merged-sync.d.ts +6 -0
  177. package/dist/engine/sync/merged-sync.js +618 -0
  178. package/dist/engine/sync/mutation-owner.d.ts +2 -0
  179. package/dist/engine/sync/mutation-owner.js +18 -0
  180. package/dist/engine/sync/package-merge.d.ts +3 -0
  181. package/dist/engine/sync/package-merge.js +82 -0
  182. package/dist/engine/sync/partial-progress.d.ts +15 -0
  183. package/dist/engine/sync/partial-progress.js +39 -0
  184. package/dist/engine/sync/remote-snapshot.d.ts +28 -0
  185. package/dist/engine/sync/remote-snapshot.js +62 -0
  186. package/dist/engine/sync/resolver-stream.d.ts +4 -0
  187. package/dist/engine/sync/resolver-stream.js +34 -0
  188. package/dist/engine/sync/session-merge.d.ts +3 -0
  189. package/dist/engine/sync/session-merge.js +178 -0
  190. package/dist/engine/sync/session-push.d.ts +5 -0
  191. package/dist/engine/sync/session-push.js +32 -0
  192. package/dist/engine/sync/settings-conflicts.d.ts +8 -0
  193. package/dist/engine/sync/settings-conflicts.js +56 -0
  194. package/dist/engine/sync/settings-merge.d.ts +13 -0
  195. package/dist/engine/sync/settings-merge.js +93 -0
  196. package/dist/engine/sync/signals.d.ts +2 -0
  197. package/dist/engine/sync/signals.js +8 -0
  198. package/dist/engine/sync/startup-timings.d.ts +11 -0
  199. package/dist/engine/sync/startup-timings.js +44 -0
  200. package/dist/engine/sync/sync-decision.d.ts +35 -0
  201. package/dist/engine/sync/sync-decision.js +66 -0
  202. package/dist/engine/sync/sync-error-guidance.d.ts +2 -0
  203. package/dist/engine/sync/sync-error-guidance.js +55 -0
  204. package/dist/engine/sync/sync-errors.d.ts +9 -0
  205. package/dist/engine/sync/sync-errors.js +18 -0
  206. package/dist/engine/sync/sync-inspection.d.ts +26 -0
  207. package/dist/engine/sync/sync-inspection.js +40 -0
  208. package/dist/engine/sync/sync-loaders.d.ts +7 -0
  209. package/dist/engine/sync/sync-loaders.js +8 -0
  210. package/dist/engine/sync/sync-local.d.ts +5 -0
  211. package/dist/engine/sync/sync-local.js +40 -0
  212. package/dist/engine/sync/sync-mutations.d.ts +30 -0
  213. package/dist/engine/sync/sync-mutations.js +589 -0
  214. package/dist/engine/sync/sync-operations.d.ts +2 -0
  215. package/dist/engine/sync/sync-operations.js +3 -0
  216. package/dist/engine/sync/sync-policy.d.ts +85 -0
  217. package/dist/engine/sync/sync-policy.js +356 -0
  218. package/dist/engine/sync/sync-queries.d.ts +7 -0
  219. package/dist/engine/sync/sync-queries.js +195 -0
  220. package/dist/engine/sync/sync-state.d.ts +31 -0
  221. package/dist/engine/sync/sync-state.js +92 -0
  222. package/dist/engine/sync/text-merge.d.ts +19 -0
  223. package/dist/engine/sync/text-merge.js +124 -0
  224. package/dist/engine/types.d.ts +5 -0
  225. package/dist/engine/types.js +2 -0
  226. package/dist/engine/ui/merge-review.d.ts +2 -0
  227. package/dist/engine/ui/merge-review.js +7 -0
  228. package/dist/engine/ui/merged-sync-summary.d.ts +25 -0
  229. package/dist/engine/ui/merged-sync-summary.js +86 -0
  230. package/dist/engine/ui/sync-format.d.ts +13 -0
  231. package/dist/engine/ui/sync-format.js +150 -0
  232. package/dist/engine/ui/sync-status.d.ts +9 -0
  233. package/dist/engine/ui/sync-status.js +30 -0
  234. package/dist/engine/ui/terminal-text.d.ts +3 -0
  235. package/dist/engine/ui/terminal-text.js +9 -0
  236. package/dist/engine/ui/transfer-changes.d.ts +12 -0
  237. package/dist/engine/ui/transfer-changes.js +24 -0
  238. package/dist/engine/ui/transfer-review.d.ts +3 -0
  239. package/dist/engine/ui/transfer-review.js +19 -0
  240. package/dist/engine-service.d.ts +11 -0
  241. package/dist/engine-service.js +315 -0
  242. package/dist/identity.d.ts +20 -0
  243. package/dist/identity.js +133 -0
  244. package/dist/index.d.ts +8 -0
  245. package/dist/index.js +4 -0
  246. package/dist/lifecycle-log.d.ts +7 -0
  247. package/dist/lifecycle-log.js +53 -0
  248. package/dist/lifecycle.d.ts +2 -0
  249. package/dist/lifecycle.js +21 -0
  250. package/dist/model-signature.d.ts +2 -0
  251. package/dist/model-signature.js +7 -0
  252. package/dist/monitor.d.ts +11 -0
  253. package/dist/monitor.js +245 -0
  254. package/dist/participant-admission.d.ts +5 -0
  255. package/dist/participant-admission.js +30 -0
  256. package/dist/protocol.d.ts +97 -0
  257. package/dist/protocol.js +90 -0
  258. package/dist/resolver-host.d.ts +11 -0
  259. package/dist/resolver-host.js +78 -0
  260. package/dist/server.d.ts +18 -0
  261. package/dist/server.js +724 -0
  262. package/dist/service-host.d.ts +7 -0
  263. package/dist/service-host.js +174 -0
  264. package/docs/architecture.md +133 -0
  265. package/package.json +54 -4
@@ -0,0 +1,31 @@
1
+ import type { RemoteHead } from "../backends/sync-backend.js";
2
+ import type { Snapshot } from "../snapshot/snapshot-types.js";
3
+ import type { SyncState } from "../state/state-types.js";
4
+ import { type SyncSelectionConfig } from "./sync-policy.js";
5
+ type SyncPolicyConfig = SyncSelectionConfig & {
6
+ localFields?: string[];
7
+ };
8
+ export declare function hasLocalChanges(local: Snapshot, state: SyncState, config: SyncPolicyConfig): boolean;
9
+ export declare function remoteChangedSinceState(head: RemoteHead | undefined, state: SyncState, config: SyncPolicyConfig, sameRevision: (left: string, right: string) => boolean): boolean;
10
+ export declare function hasRemoteChanges(remote: Snapshot, state: SyncState, config: SyncPolicyConfig, ignoredPaths?: Set<string>): boolean;
11
+ export declare function sameHashes(left: Record<string, string>, right: Record<string, string>): boolean;
12
+ export declare function fileHashMap(snapshot: Snapshot): {
13
+ [k: string]: string;
14
+ };
15
+ export declare function snapshotHashesMatchState(snapshot: Snapshot, state: SyncState, config: SyncPolicyConfig, ignoredPaths?: Set<string>): boolean;
16
+ export declare function snapshotsMatch(left: Snapshot, right: Snapshot): boolean;
17
+ export declare function syncPolicyChanged(state: SyncState, config: SyncPolicyConfig): boolean;
18
+ export declare function shouldRefreshSyncedState(remote: Snapshot, head: RemoteHead | undefined, state: SyncState, config: SyncPolicyConfig, sameRevision: (left: string, right: string) => boolean): boolean;
19
+ export declare function settingsHashMap(snapshot: Snapshot): {
20
+ [k: string]: string;
21
+ };
22
+ export declare function sessionHashMap(snapshot: Snapshot): {
23
+ [k: string]: string;
24
+ };
25
+ export declare function settingsHashMapFromState(state: SyncState): {
26
+ [k: string]: string;
27
+ };
28
+ export declare function settingsHashesMatchState(remote: Snapshot, state: SyncState): boolean;
29
+ export declare function canPullRemoteSettingsOnFirstSync(local: Snapshot, remote: Snapshot): boolean;
30
+ export declare function canPullRemoteSessionsOnFirstSync(local: Snapshot, remote: Snapshot): boolean;
31
+ export {};
@@ -0,0 +1,92 @@
1
+ import { toPosix } from "../paths.js";
2
+ import { canonicalSnapshotPathForConfig, filterSnapshotForConfigPolicy, isSessionPath } from "../snapshot/snapshot.js";
3
+ import { sameSyncExclude } from "./exclude-policy.js";
4
+ import { portableSnapshot, sameLocalFields } from "./local-fields.js";
5
+ import { configuredSnapshotPathMatcher, customIncludePathsByLower, includeFromSelectionConfig, normalizeSyncInclude, syncSessionsSelected, } from "./sync-policy.js";
6
+ export function hasLocalChanges(local, state, config) {
7
+ return ((Boolean(state.lastAppliedSnapshot) &&
8
+ (!sameLocalFields(state.localFields, config.localFields) || !sameSyncExclude(state.exclude, config.exclude))) ||
9
+ !sameHashes(fileHashMap(portableSnapshot(local, config.localFields)), stateHashMapForConfig(state, config)));
10
+ }
11
+ export function remoteChangedSinceState(head, state, config, sameRevision) {
12
+ if (!head)
13
+ return Boolean(state.lastAppliedSnapshot);
14
+ if (head.snapshotId !== state.lastAppliedSnapshot)
15
+ return true;
16
+ if (state.lastRemoteRevision && !sameRevision(head.revision, state.lastRemoteRevision))
17
+ return true;
18
+ if (syncPolicyChanged(state, config))
19
+ return true;
20
+ return (syncSessionsSelected(config) &&
21
+ (!state.include?.includes("sessions") || !syncSessionsSelected(state)) &&
22
+ head.syncSessions);
23
+ }
24
+ export function hasRemoteChanges(remote, state, config, ignoredPaths = new Set()) {
25
+ if (remote.id === state.lastAppliedSnapshot && !syncPolicyChanged(state, config))
26
+ return false;
27
+ return !snapshotHashesMatchState(portableSnapshot(filterSnapshotForConfigPolicy(remote, config), remote.localFields), state, config, ignoredPaths);
28
+ }
29
+ export function sameHashes(left, right) {
30
+ const keys = new Set([...Object.keys(left), ...Object.keys(right)]);
31
+ for (const key of keys)
32
+ if (left[key] !== right[key])
33
+ return false;
34
+ return true;
35
+ }
36
+ export function fileHashMap(snapshot) {
37
+ return Object.fromEntries(snapshot.files.map((file) => [file.path, file.sha256]));
38
+ }
39
+ function stateHashMapForConfig(state, config) {
40
+ const includePaths = customIncludePathsByLower(includeFromSelectionConfig(config));
41
+ const configured = configuredSnapshotPathMatcher(config);
42
+ return Object.fromEntries(Object.entries(state.lastFileHashes)
43
+ .filter(([filePath]) => configured(filePath))
44
+ .map(([filePath, hash]) => [canonicalSnapshotPathForConfig(filePath, includePaths), hash]));
45
+ }
46
+ export function snapshotHashesMatchState(snapshot, state, config, ignoredPaths = new Set()) {
47
+ return sameHashes(withoutHashPaths(fileHashMap(snapshot), ignoredPaths), withoutHashPaths(stateHashMapForConfig(state, config), ignoredPaths));
48
+ }
49
+ export function snapshotsMatch(left, right) {
50
+ return left.syncSessions === right.syncSessions && sameHashes(fileHashMap(left), fileHashMap(right));
51
+ }
52
+ function withoutHashPaths(hashes, ignoredPaths) {
53
+ if (ignoredPaths.size === 0)
54
+ return hashes;
55
+ return Object.fromEntries(Object.entries(hashes).filter(([filePath]) => !ignoredPaths.has(toPosix(filePath))));
56
+ }
57
+ export function syncPolicyChanged(state, config) {
58
+ return (syncIncludeChanged(state, config) ||
59
+ !sameSyncExclude(state.exclude, config.exclude) ||
60
+ !sameLocalFields(state.localFields, config.localFields));
61
+ }
62
+ export function shouldRefreshSyncedState(remote, head, state, config, sameRevision) {
63
+ return (remote.id !== state.lastAppliedSnapshot ||
64
+ Boolean(head && (!state.lastRemoteRevision || !sameRevision(head.revision, state.lastRemoteRevision))) ||
65
+ syncPolicyChanged(state, config));
66
+ }
67
+ function syncIncludeChanged(state, config) {
68
+ const stored = state.include ? normalizeSyncInclude(state.include) : includeFromSelectionConfig(state);
69
+ const current = includeFromSelectionConfig(config);
70
+ return stored.length !== current.length || stored.some((item, index) => item !== current[index]);
71
+ }
72
+ export function settingsHashMap(snapshot) {
73
+ return Object.fromEntries(snapshot.files.filter((file) => !isSessionPath(file.path)).map((file) => [file.path, file.sha256]));
74
+ }
75
+ export function sessionHashMap(snapshot) {
76
+ return Object.fromEntries(snapshot.files.filter((file) => isSessionPath(file.path)).map((file) => [file.path, file.sha256]));
77
+ }
78
+ export function settingsHashMapFromState(state) {
79
+ return Object.fromEntries(Object.entries(state.lastFileHashes).filter(([filePath]) => !isSessionPath(filePath)));
80
+ }
81
+ export function settingsHashesMatchState(remote, state) {
82
+ return sameHashes(settingsHashMap(remote), settingsHashMapFromState(state));
83
+ }
84
+ export function canPullRemoteSettingsOnFirstSync(local, remote) {
85
+ const remoteSettings = settingsHashMap(remote);
86
+ return Object.entries(settingsHashMap(local)).every(([filePath, hash]) => remoteSettings[filePath] === hash);
87
+ }
88
+ export function canPullRemoteSessionsOnFirstSync(local, remote) {
89
+ const localSessions = sessionHashMap(local);
90
+ const remoteSessions = sessionHashMap(remote);
91
+ return Object.entries(localSessions).every(([filePath, hash]) => remoteSessions[filePath] === hash);
92
+ }
@@ -0,0 +1,19 @@
1
+ export declare const TEXT_LIMIT: number;
2
+ export declare const TEXT_MERGE_WORK_LIMIT = 8000000;
3
+ export interface TextMergeBudget {
4
+ remaining: number;
5
+ }
6
+ export interface TextMergeOptions {
7
+ budget?: TextMergeBudget;
8
+ signal?: AbortSignal;
9
+ }
10
+ export declare function isMergeTextPath(filePath: string): boolean;
11
+ export declare function text(bytes: Buffer): string;
12
+ export type Hunk = {
13
+ start: number;
14
+ end: number;
15
+ lines: string[];
16
+ };
17
+ export declare function lines(value: string): RegExpMatchArray | [];
18
+ export declare function edits(base: string[], next: string[], signal?: AbortSignal): Hunk[];
19
+ export declare function mergeText(baseBytes: Buffer, localBytes: Buffer, remoteBytes: Buffer, options?: TextMergeOptions): Buffer | undefined;
@@ -0,0 +1,124 @@
1
+ import path from "node:path";
2
+ export const TEXT_LIMIT = 1024 * 1024;
3
+ export const TEXT_MERGE_WORK_LIMIT = 8_000_000;
4
+ function charge(budget, work) {
5
+ if (work > budget.remaining)
6
+ throw new Error("Text merge operation complexity bound exceeded.");
7
+ budget.remaining -= work;
8
+ }
9
+ export function isMergeTextPath(filePath) {
10
+ return (filePath === "AGENTS.md" ||
11
+ (/\.(?:md|txt)$/u.test(filePath) &&
12
+ ["prompts", "skills"].includes(filePath.split("/")[0] ?? "") &&
13
+ path.posix.basename(filePath) !== "keybindings.json"));
14
+ }
15
+ export function text(bytes) {
16
+ if (bytes.length > TEXT_LIMIT)
17
+ throw new Error("Text merge bound exceeded.");
18
+ const decoded = bytes.toString("utf8");
19
+ if (!Buffer.from(decoded).equals(bytes) ||
20
+ bytes.some((byte) => (byte < 32 && byte !== 9 && byte !== 10 && byte !== 13) || byte === 127))
21
+ throw new Error("Unsupported text encoding.");
22
+ return decoded;
23
+ }
24
+ export function lines(value) {
25
+ return value.match(/[^\n]*\n|[^\n]+$/gu) ?? [];
26
+ }
27
+ export function edits(base, next, signal) {
28
+ const width = next.length + 1;
29
+ if ((base.length + 1) * width > 4_000_000)
30
+ throw new Error("Text merge complexity bound exceeded.");
31
+ // Intern once so each charged DP cell compares fixed-size IDs, not long line strings.
32
+ const ids = new Map();
33
+ const intern = (line) => {
34
+ let id = ids.get(line);
35
+ if (id === undefined) {
36
+ id = ids.size;
37
+ ids.set(line, id);
38
+ }
39
+ return id;
40
+ };
41
+ const baseIds = base.map(intern);
42
+ const nextIds = next.map(intern);
43
+ const grid = new Uint32Array((base.length + 1) * width);
44
+ for (let i = base.length - 1; i >= 0; i--) {
45
+ signal?.throwIfAborted();
46
+ for (let j = next.length - 1; j >= 0; j--)
47
+ grid[i * width + j] =
48
+ baseIds[i] === nextIds[j]
49
+ ? 1 + (grid[(i + 1) * width + j + 1] ?? 0)
50
+ : Math.max(grid[(i + 1) * width + j] ?? 0, grid[i * width + j + 1] ?? 0);
51
+ }
52
+ const result = [];
53
+ let i = 0;
54
+ let j = 0;
55
+ let active;
56
+ while (i < base.length || j < next.length) {
57
+ if (i < base.length && j < next.length && baseIds[i] === nextIds[j]) {
58
+ if (active) {
59
+ result.push(active);
60
+ active = undefined;
61
+ }
62
+ i++;
63
+ j++;
64
+ continue;
65
+ }
66
+ active ??= { start: i, end: i, lines: [] };
67
+ if (j < next.length && (i === base.length || (grid[i * width + j + 1] ?? 0) >= (grid[(i + 1) * width + j] ?? 0)))
68
+ active.lines.push(next[j++] ?? "");
69
+ else
70
+ active.end = ++i;
71
+ }
72
+ if (active)
73
+ result.push(active);
74
+ return result;
75
+ }
76
+ export function mergeText(baseBytes, localBytes, remoteBytes, options = {}) {
77
+ const budget = options.budget ?? { remaining: TEXT_MERGE_WORK_LIMIT };
78
+ try {
79
+ options.signal?.throwIfAborted();
80
+ const base = lines(text(baseBytes));
81
+ const ours = lines(text(localBytes));
82
+ const theirs = lines(text(remoteBytes));
83
+ const cells = [ours, theirs].map((next) => (base.length + 1) * (next.length + 1));
84
+ if (cells.some((count) => count > 4_000_000))
85
+ return;
86
+ charge(budget, (cells[0] ?? 0) + (cells[1] ?? 0));
87
+ const local = edits(base, ours, options.signal);
88
+ const remote = edits(base, theirs, options.signal);
89
+ const combined = [...local];
90
+ for (const right of remote) {
91
+ let same = false;
92
+ for (const left of local) {
93
+ options.signal?.throwIfAborted();
94
+ charge(budget, 1);
95
+ if (left.start === right.start && left.end === right.end && left.lines.join("") === right.lines.join("")) {
96
+ same = true;
97
+ continue;
98
+ }
99
+ const overlap = left.start === left.end || right.start === right.end
100
+ ? left.start <= right.end && right.start <= left.end
101
+ : left.start < right.end && right.start < left.end;
102
+ if (overlap)
103
+ return;
104
+ }
105
+ if (!same)
106
+ combined.push(right);
107
+ }
108
+ combined.sort((left, right) => left.start - right.start || left.end - right.end);
109
+ let cursor = 0;
110
+ const output = [];
111
+ for (const edit of combined) {
112
+ output.push(...base.slice(cursor, edit.start), ...edit.lines);
113
+ cursor = edit.end;
114
+ }
115
+ output.push(...base.slice(cursor));
116
+ const result = Buffer.from(output.join(""));
117
+ text(result);
118
+ return result;
119
+ }
120
+ catch {
121
+ options.signal?.throwIfAborted();
122
+ return;
123
+ }
124
+ }
@@ -0,0 +1,5 @@
1
+ export type { LatestPointer, RemoteObject, ResolvedGitBackend, ResolvedGitDestination, ResolvedGitStorageProfile, ResolvedS3Backend, ResolvedS3Destination, ResolvedS3StorageProfile, ResolvedSyncBackend, ResolvedWebDavBackend, ResolvedWebDavDestination, ResolvedWebDavStorageProfile, } from "./backends/backend-types.js";
2
+ export type { CommandArgumentCompletion, CommandOptions } from "./commands/command-types.js";
3
+ export type { AnySyncConfig, CommonSyncConfig, CommonSyncSetupStorageSettings, GitStorageConnectionSettings, GitSyncSetupStorageSettings, OnSwitchAction, PartialConfig, PiSyncSettingsV3, S3CredentialsSettings, S3StorageConnectionSettings, S3SyncSetupStorageSettings, StorageConnectionSettings, StorageConnectionType, SyncConfig, SyncPolicySettings, SyncSetupSettings, SyncSetupStorageSettings, WebDavCredentialsSettings, WebDavStorageConnectionSettings, WebDavSyncSetupStorageSettings, } from "./settings/settings-types.js";
4
+ export type { Snapshot, SnapshotApplyPlan, SnapshotFile, SnapshotOptions, SnapshotSelection, } from "./snapshot/snapshot-types.js";
5
+ export type { LockFile, SyncState } from "./state/state-types.js";
@@ -0,0 +1,2 @@
1
+ // Compatibility type surface; implementation modules import from the owning domain.
2
+ export {};
@@ -0,0 +1,2 @@
1
+ import { type EngineContext } from "../host.js";
2
+ export declare function confirmMergeReview(ctx: EngineContext, title: string, content: string, signal: AbortSignal | undefined, isCurrent: () => boolean, confirmationLabel?: string, summaryLines?: readonly string[]): Promise<boolean>;
@@ -0,0 +1,7 @@
1
+ import { engineHost } from "../host.js";
2
+ export async function confirmMergeReview(ctx, title, content, signal, isCurrent, confirmationLabel = "apply changes", summaryLines) {
3
+ if (signal?.aborted || !isCurrent())
4
+ return false;
5
+ const result = await engineHost().review(ctx, { title, content, confirmationLabel, summaryLines }, signal, isCurrent);
6
+ return !signal?.aborted && isCurrent() && result;
7
+ }
@@ -0,0 +1,25 @@
1
+ import type { PublicationCapability } from "../backends/sync-backend.js";
2
+ import type { Snapshot } from "../snapshot/snapshot-types.js";
3
+ import type { FileMergeDecision } from "../sync/file-merge-planner.js";
4
+ export interface MergedSyncSummaryInput {
5
+ setupName: string;
6
+ destination: string;
7
+ localBefore: Snapshot;
8
+ localAfter: Snapshot;
9
+ remoteBefore: Snapshot;
10
+ remoteAfter: Snapshot;
11
+ publish: boolean;
12
+ sessions: boolean;
13
+ groups: readonly {
14
+ paths: readonly string[];
15
+ }[];
16
+ decisions: readonly FileMergeDecision[];
17
+ capability: PublicationCapability;
18
+ }
19
+ /** Presentation only: counts describe snapshot differences, not planner decisions. */
20
+ export declare function mergedSyncSummary(input: MergedSyncSummaryInput): {
21
+ title: string;
22
+ confirmationLabel: string;
23
+ lines: string[];
24
+ content: string;
25
+ };
@@ -0,0 +1,86 @@
1
+ import { truncateToWidth } from "@earendil-works/pi-tui";
2
+ import { safeTerminalText, snapshotPathLabel } from "./terminal-text.js";
3
+ import { transferChanges as changes } from "./transfer-changes.js";
4
+ /** Presentation only: counts describe snapshot differences, not planner decisions. */
5
+ export function mergedSyncSummary(input) {
6
+ const local = changes(input.localBefore, input.localAfter);
7
+ const remote = changes(input.remoteBefore, input.remoteAfter);
8
+ const all = [...local, ...remote];
9
+ const updatesOnly = all.length > 0 && all.every((change) => change.action === "Update");
10
+ const verb = updatesOnly ? "Update" : "Apply changes to";
11
+ const title = local.length && remote.length
12
+ ? "Apply local and remote changes?"
13
+ : all.length
14
+ ? `${verb} ${all.length} ${local.length ? "local" : "remote"} ${all.length === 1 ? "file" : "files"}?`
15
+ : input.publish
16
+ ? "Publish a new remote snapshot?"
17
+ : "Pi Sync is already up to date.";
18
+ const confirmationLabel = local.length && remote.length
19
+ ? "apply local and remote changes"
20
+ : all.length
21
+ ? `${updatesOnly ? "update" : "apply changes to"} ${local.length ? "local" : "remote"} ${all.length === 1 ? "file" : "files"}`
22
+ : "publish remote snapshot";
23
+ const sources = new Map(input.decisions.filter((item) => item.kind === "accepted").map((item) => [item.path, item.source]));
24
+ const label = (change, side) => {
25
+ const source = sources.get(change.path);
26
+ const suffix = source === "merged"
27
+ ? " (merged content)"
28
+ : side === "local" && source === "remote"
29
+ ? change.action === "Delete"
30
+ ? " (deleted remotely)"
31
+ : " from remote"
32
+ : "";
33
+ return `${change.action} ${snapshotPathLabel(change.path)}${suffix}`;
34
+ };
35
+ const section = (items, side, compact) => {
36
+ const heading = side === "local" ? "Local changes" : "Remote file changes";
37
+ if (!items.length)
38
+ return [`${heading}: none`];
39
+ const counts = ["Add", "Update", "Delete"].flatMap((action) => {
40
+ const count = items.filter((item) => item.action === action).length;
41
+ return count ? [`${count} ${action.toLowerCase()}`] : [];
42
+ });
43
+ return [
44
+ `${heading}: ${counts.join(", ")}`,
45
+ ...(compact ? items.slice(0, 3) : items).map((item) => ` ${compact ? truncateToWidth(label(item, side), 80) : label(item, side)}`),
46
+ ...(compact && items.length > 3 ? [` ${items.length - 3} more files — View details`] : []),
47
+ ];
48
+ };
49
+ const context = [`Setup: ${safeTerminalText(input.setupName)}`, `Remote: ${safeTerminalText(input.destination)}`];
50
+ const safety = [
51
+ `Remote snapshot publication: ${input.publish ? "yes" : "no"}`,
52
+ "Remote removals affect the active snapshot; retained history is not erased.",
53
+ `Sessions: ${input.sessions ? "included — may contain private conversations" : "not included"}`,
54
+ input.groups.length
55
+ ? `Unresolved groups: ${input.groups.length} — these paths stay unchanged on each side`
56
+ : "Conflicts: none",
57
+ ...(input.publish && input.capability === "read-check-write-verify"
58
+ ? ["Warning: simultaneous remote writes can still race; visible changes are rejected."]
59
+ : []),
60
+ ...(input.publish && input.capability === "conditional-required"
61
+ ? ["Remote publication requires verified conditional writes; verification failure stops the transfer."]
62
+ : []),
63
+ "The current session is protected. A backup and recovery journal will be saved.",
64
+ "Resources will not reload automatically.",
65
+ ];
66
+ return {
67
+ title,
68
+ confirmationLabel,
69
+ lines: [
70
+ ...context.map((line) => truncateToWidth(line, 100)),
71
+ ...section(local, "local", true),
72
+ ...section(remote, "remote", true),
73
+ ...safety,
74
+ ],
75
+ content: [
76
+ ...context,
77
+ "",
78
+ ...section(local, "local", false),
79
+ "",
80
+ ...section(remote, "remote", false),
81
+ "",
82
+ ...safety,
83
+ ...input.groups.flatMap((group) => group.paths.map((filePath) => `Unchanged (unresolved): ${snapshotPathLabel(filePath)}`)),
84
+ ].join("\n"),
85
+ };
86
+ }
@@ -0,0 +1,13 @@
1
+ import type { PublicationCapability, RemoteHead } from "../backends/sync-backend.js";
2
+ import type { CommonSyncConfig } from "../settings/settings-types.js";
3
+ import type { Snapshot } from "../snapshot/snapshot-types.js";
4
+ export declare function formatDiff(local: Snapshot, remote: Snapshot): string;
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;
11
+ export declare function countPreservedRemoteFiles(local: Snapshot, upload: Snapshot): number;
12
+ 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
+ export declare function redact(value: string): string;
@@ -0,0 +1,150 @@
1
+ import { agentDir } from "../snapshot/session-paths.js";
2
+ import { inspectRemoteSelection } from "../sync/sync-policy.js";
3
+ import { fileHashMap } from "../sync/sync-state.js";
4
+ import { safeTerminalText, snapshotPathLabel } from "./terminal-text.js";
5
+ import { transferChanges, transferCounts } from "./transfer-changes.js";
6
+ export function formatDiff(local, remote) {
7
+ const localMap = fileHashMap(local);
8
+ const remoteMap = fileHashMap(remote);
9
+ const allPaths = [...new Set([...Object.keys(localMap), ...Object.keys(remoteMap)])].sort();
10
+ const lines = [
11
+ `local: ${local.files.length} files`,
12
+ `remote: ${safeTerminalText(remote.id)} (${remote.files.length} files)`,
13
+ "",
14
+ ];
15
+ let changed = 0;
16
+ for (const filePath of allPaths) {
17
+ if (!Object.hasOwn(localMap, filePath)) {
18
+ lines.push(`Remote only: ${snapshotPathLabel(filePath)}`);
19
+ changed += 1;
20
+ }
21
+ else if (!Object.hasOwn(remoteMap, filePath)) {
22
+ lines.push(`Local only: ${snapshotPathLabel(filePath)}`);
23
+ changed += 1;
24
+ }
25
+ else if (localMap[filePath] !== remoteMap[filePath]) {
26
+ lines.push(`Different: ${snapshotPathLabel(filePath)}`);
27
+ changed += 1;
28
+ }
29
+ }
30
+ if (changed === 0)
31
+ lines.push("No file differences.");
32
+ return lines.join("\n");
33
+ }
34
+ export function formatSnapshotOnlyDiff(title, snapshot) {
35
+ return [
36
+ `${safeTerminalText(title)}: ${safeTerminalText(snapshot.id)}`,
37
+ ...snapshot.files.map((file) => `Add: ${snapshotPathLabel(file.path)}`),
38
+ ].join("\n");
39
+ }
40
+ export function formatPushSummary(config, destination, upload, head, preservedRemoteFileCount = 0, remote) {
41
+ return [
42
+ `Sync setup: ${safeTerminalText(config.setupName)}`,
43
+ `Storage location: ${safeTerminalText(destination)}`,
44
+ `Direction: Local → Remote. Source: ${safeTerminalText(agentDir())}.`,
45
+ `Publish a snapshot containing ${upload.files.length} files; unchanged and preserved files are not counted as changes.`,
46
+ `Sessions: ${upload.syncSessions ? "included — may contain private conversations" : "not included"}`,
47
+ ...excludedPolicyLines(config),
48
+ head ? `Remote latest: ${safeTerminalText(head.snapshotId)}` : "Remote latest: empty",
49
+ "Publication effect: the backend's active head will reference the new immutable snapshot. Removed paths leave the active snapshot; retained history is not erased.",
50
+ ...(remote && inspectRemoteSelection(config.include, remote, config.exclude).kind === "different"
51
+ ? ["Included-content policy effect: replace the differing remote selection with this setup's local selection."]
52
+ : []),
53
+ formatPublicationPreview(remote, upload),
54
+ config.skipSecretScan
55
+ ? "Warning: possible-secret scanning is disabled for this push."
56
+ : preservedRemoteFileCount > 0
57
+ ? `Possible secrets in locally managed files were scanned before this prompt; ${preservedRemoteFileCount} preserved remote file(s) were not rescanned.`
58
+ : "Possible secrets were scanned before this prompt.",
59
+ ].join("\n");
60
+ }
61
+ function excludedPolicyLines(config) {
62
+ return config.exclude === undefined
63
+ ? []
64
+ : [
65
+ `Excluded paths: ${config.exclude.map(safeTerminalText).join(", ") || "none"}`,
66
+ "Excluded local files remain untouched; matching paths are omitted from new publications, not erased from history.",
67
+ ];
68
+ }
69
+ export function formatApplyPreview(local, remote, protectedPaths = new Set(), additionalRemovals = []) {
70
+ return formatDirectionalChanges(local, remote, {
71
+ add: "Add locally",
72
+ update: "Update locally",
73
+ remove: "Remove locally",
74
+ }, protectedPaths, additionalRemovals);
75
+ }
76
+ export function formatPullSummary(config, destination, local, remote, protectedPaths, additionalRemovals = []) {
77
+ return [
78
+ `Sync setup: ${safeTerminalText(config.setupName)}`,
79
+ `Storage location: ${safeTerminalText(destination)}`,
80
+ "Direction: Remote → Local.",
81
+ `Snapshot: ${safeTerminalText(remote.id)}`,
82
+ ...excludedPolicyLines(config),
83
+ `Sessions: ${remote.syncSessions ? "included — may contain private conversations" : "not included"}`,
84
+ `Protected live sessions: ${protectedPaths.size || "none"}`,
85
+ formatApplyPreview(local, remote, protectedPaths, additionalRemovals),
86
+ ...(additionalRemovals.length
87
+ ? ["Case-variant aliases listed above are removed before writing canonical paths."]
88
+ : []),
89
+ "A local backup is created before these writes/deletes. The remote active snapshot is unchanged.",
90
+ ].join("\n");
91
+ }
92
+ export function formatRollbackSummary(config, destination, local, remote, requestedSnapshot, protectedPaths, additionalRemovals = []) {
93
+ return [
94
+ `Sync setup: ${safeTerminalText(config.setupName)}`,
95
+ `Storage location: ${safeTerminalText(destination)}`,
96
+ "Direction: Historical snapshot → Local and remote active head.",
97
+ `Snapshot: ${safeTerminalText(requestedSnapshot)}`,
98
+ ...excludedPolicyLines(config),
99
+ `Sessions: ${remote.syncSessions ? "included — may contain private conversations" : "not included"}`,
100
+ `Protected live sessions: ${protectedPaths.size || "none"}`,
101
+ formatApplyPreview(local, remote, protectedPaths, additionalRemovals),
102
+ ...(additionalRemovals.length
103
+ ? ["Case-variant aliases listed above are removed before writing canonical paths."]
104
+ : []),
105
+ "A local backup is created before applying; the backend's active head will change.",
106
+ ].join("\n");
107
+ }
108
+ export function formatPublicationPreview(remote, upload) {
109
+ return formatDirectionalChanges(remote, upload, {
110
+ add: "Add remotely",
111
+ update: "Update remotely",
112
+ remove: "Remove remotely",
113
+ });
114
+ }
115
+ function formatDirectionalChanges(before, after, labels, protectedPaths = new Set(), additionalRemovals = []) {
116
+ const changes = transferChanges(before, after, protectedPaths);
117
+ const known = new Set(changes.map((change) => change.path));
118
+ for (const filePath of additionalRemovals) {
119
+ if (!known.has(filePath) && !protectedPaths.has(filePath)) {
120
+ changes.push({ path: filePath, action: "Delete" });
121
+ known.add(filePath);
122
+ }
123
+ }
124
+ const counts = transferCounts(changes);
125
+ const label = { Add: labels.add, Update: labels.update, Delete: labels.remove };
126
+ return [
127
+ `Changes: ${counts.add} add · ${counts.update} update · ${counts.remove} remove`,
128
+ ...changes.map((change) => `${label[change.action]}: ${snapshotPathLabel(change.path)}`),
129
+ ...(changes.length ? [] : ["No file changes."]),
130
+ ].join("\n");
131
+ }
132
+ export function countPreservedRemoteFiles(local, upload) {
133
+ const localPaths = new Set(local.files.map((file) => file.path));
134
+ return upload.files.filter((file) => !localPaths.has(file.path)).length;
135
+ }
136
+ export function publicationCapabilityDescription(capability) {
137
+ switch (capability) {
138
+ case "lease-protected":
139
+ return "lease-protected (exact expected-ref update)";
140
+ case "atomic-conditional":
141
+ return "atomic-conditional (verified atomic precondition)";
142
+ case "conditional-required":
143
+ return "conditional-required (read-only until atomic preconditions are verified)";
144
+ case "read-check-write-verify":
145
+ return "read-check-write-verify (visible races rejected; simultaneous unseen races remain possible)";
146
+ }
147
+ }
148
+ export function redact(value) {
149
+ return value.length <= 8 ? "configured" : `${value.slice(0, 4)}…${value.slice(-4)}`;
150
+ }
@@ -0,0 +1,9 @@
1
+ import { type EngineContext } from "../host.js";
2
+ import type { ContinuousErrorKind } from "../sync/continuous-errors.js";
3
+ export type SyncStatusPresentation = {
4
+ activity: string;
5
+ reason?: string;
6
+ };
7
+ export declare function syncStatusFailureReason(kind: ContinuousErrorKind | undefined): string;
8
+ export declare function configureSyncStatus(ctx: EngineContext, value: boolean): void;
9
+ export declare function setSyncStatus(ctx: EngineContext, value: string | undefined, presentation?: SyncStatusPresentation): void;
@@ -0,0 +1,30 @@
1
+ import { engineHost } from "../host.js";
2
+ const enabled = new WeakMap();
3
+ const reasons = {
4
+ transient: "temp",
5
+ contention: "busy",
6
+ stale: "stale",
7
+ authentication: "auth",
8
+ storage: "storage",
9
+ unsafe: "review",
10
+ model: "model",
11
+ budget: "limit",
12
+ unknown: "unknown",
13
+ };
14
+ export function syncStatusFailureReason(kind) {
15
+ return kind && Object.hasOwn(reasons, kind) ? reasons[kind] : "unknown";
16
+ }
17
+ export function configureSyncStatus(ctx, value) {
18
+ enabled.set(ctx.sessionManager, value);
19
+ if (!value)
20
+ setSyncStatus(ctx, undefined);
21
+ }
22
+ export function setSyncStatus(ctx, value, presentation) {
23
+ if (!ctx.hasUI || (value !== undefined && enabled.get(ctx.sessionManager) === false))
24
+ return;
25
+ const host = engineHost();
26
+ if (host.status)
27
+ host.status(ctx, value, presentation);
28
+ else
29
+ ctx.ui.setStatus("sync", value);
30
+ }
@@ -0,0 +1,3 @@
1
+ export declare function safeTerminalText(value: string): string;
2
+ /** Escape before joining a multiline review; raw filesystem paths remain unchanged. */
3
+ export declare function snapshotPathLabel(value: string): string;
@@ -0,0 +1,9 @@
1
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Terminal and display-direction controls.
2
+ const TERMINAL_CONTROLS = /[\u0000-\u001f\u007f-\u009f\u061c\u200b-\u200f\u202a-\u202e\u2060-\u2069\ufeff]/gu;
3
+ export function safeTerminalText(value) {
4
+ return value.replace(TERMINAL_CONTROLS, "?");
5
+ }
6
+ /** Escape before joining a multiline review; raw filesystem paths remain unchanged. */
7
+ export function snapshotPathLabel(value) {
8
+ return value.replace(TERMINAL_CONTROLS, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
9
+ }
@@ -0,0 +1,12 @@
1
+ import type { Snapshot } from "../snapshot/snapshot-types.js";
2
+ export interface TransferChange {
3
+ path: string;
4
+ action: "Add" | "Update" | "Delete";
5
+ }
6
+ /** Compare effective before/after snapshots, not raw planner decisions. */
7
+ export declare function transferChanges(before: Snapshot | undefined, after: Snapshot, protectedPaths?: ReadonlySet<string>): TransferChange[];
8
+ export declare function transferCounts(changes: readonly TransferChange[]): {
9
+ add: number;
10
+ update: number;
11
+ remove: number;
12
+ };