@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,85 @@
1
+ import type { Snapshot, SnapshotSelection } from "../snapshot/snapshot-types.js";
2
+ export declare const BUILT_IN_SYNC_ROOTS: readonly ["settings.json", "keybindings.json", "models.json", "AGENTS.md", "APPEND_SYSTEM.md", "skills", "prompts", "themes", "extensions"];
3
+ export declare const DEFAULT_SYNC_INCLUDE: readonly ["settings.json", "keybindings.json", "models.json", "AGENTS.md", "APPEND_SYSTEM.md", "skills", "prompts", "themes", "extensions"];
4
+ export type BuiltInSyncFile = (typeof BUILT_IN_SYNC_ROOTS)[number];
5
+ export declare function normalizeSyncInclude(value: unknown): string[];
6
+ export declare function portableSnapshotSelection(value: unknown): SnapshotSelection;
7
+ export declare function snapshotSelectionInclude(snapshot: Pick<Snapshot, "selection">): string[] | undefined;
8
+ export declare function snapshotSelectionExclude(snapshot: Pick<Snapshot, "selection">): string[] | undefined;
9
+ export declare function selectionForSnapshot(include: unknown, exclude?: unknown): SnapshotSelection;
10
+ /** Metadata equality, not policy compatibility: bind the whole projection to its immutable image. */
11
+ export declare function sameSnapshotSelection(left: SnapshotSelection | undefined, right: SnapshotSelection | undefined): boolean;
12
+ export declare function validateSnapshotSelection(snapshot: Pick<Snapshot, "version" | "selection">): void;
13
+ export declare function sameSyncInclude(left: unknown, right: unknown): boolean;
14
+ export declare function compareSyncInclude(local: unknown, remote: unknown): {
15
+ same: boolean;
16
+ remoteOnly: string[];
17
+ localOnly: string[];
18
+ };
19
+ export type RemoteSelectionState = {
20
+ kind: "legacy";
21
+ discovered: string[];
22
+ } | {
23
+ kind: "same";
24
+ include: string[];
25
+ exclude?: string[];
26
+ } | {
27
+ kind: "different";
28
+ include: string[];
29
+ exclude?: string[];
30
+ remoteOnly: string[];
31
+ localOnly: string[];
32
+ excludeChanged?: boolean;
33
+ };
34
+ export declare function inspectRemoteSelection(localInclude: unknown, snapshot: Pick<Snapshot, "selection" | "files">, localExclude?: unknown): RemoteSelectionState;
35
+ export interface RemoteSelectionDecision {
36
+ setupName: string;
37
+ configIdentity: string;
38
+ localInclude: readonly string[];
39
+ remoteInclude: readonly string[];
40
+ localExclude?: readonly string[];
41
+ remoteExclude?: readonly string[];
42
+ }
43
+ export declare class RemoteSelectionMismatchError extends Error {
44
+ readonly decision: RemoteSelectionDecision;
45
+ readonly setupName: string;
46
+ readonly localInclude: string[];
47
+ readonly remoteInclude: string[];
48
+ constructor(setupName: string, localInclude: unknown, remoteInclude: unknown, configIdentity?: string, localExclude?: string[], remoteExclude?: string[]);
49
+ }
50
+ export declare function remoteSelectionMismatch(config: {
51
+ setupName: string;
52
+ include: unknown;
53
+ exclude?: string[];
54
+ }, remoteInclude: unknown, configIdentity?: string, remoteExclude?: string[]): RemoteSelectionMismatchError;
55
+ export declare function formatRemoteSelectionMismatch(setupName: string, localInclude: readonly string[], remoteInclude: readonly string[], localExclude?: readonly string[], remoteExclude?: readonly string[]): string;
56
+ export declare function discoverLegacySnapshotInclude(snapshot: Pick<Snapshot, "files">): string[];
57
+ export declare function syncIncludeSelection(value: unknown): {
58
+ include: string[];
59
+ builtIns: ("AGENTS.md" | "APPEND_SYSTEM.md" | "extensions" | "keybindings.json" | "models.json" | "prompts" | "settings.json" | "skills" | "themes")[];
60
+ custom: string[];
61
+ sessions: boolean;
62
+ };
63
+ export declare function customIncludePathsByLower(value: unknown): Map<string, string>;
64
+ export interface SyncSelectionConfig {
65
+ include?: unknown;
66
+ exclude?: unknown;
67
+ syncFiles?: unknown;
68
+ syncSessions?: boolean;
69
+ extraFiles?: unknown;
70
+ }
71
+ export declare function includeFromSelectionConfig(config: SyncSelectionConfig): string[];
72
+ export declare function syncSessionsSelected(config: SyncSelectionConfig): boolean;
73
+ export declare function isConfiguredSnapshotPath(relativePath: string, config: SyncSelectionConfig, _legacyExtraFiles?: Set<string>): boolean;
74
+ export declare function configuredSnapshotPathMatcher(config: SyncSelectionConfig): (relativePath: string) => boolean;
75
+ export declare function canonicalSnapshotPathForConfig(relativePath: string, includePaths: Map<string, string>): string;
76
+ export declare function isPreservableUnmanagedSnapshotPath(relativePath: string): boolean;
77
+ export declare function isSafeCustomIncludePath(relativePath: string): boolean;
78
+ export declare function isBuiltInTopLevelFile(fileName: string): boolean;
79
+ /** Compatibility projection for backend-neutral output while callers move to sync.include. */
80
+ export declare function normalizeSyncFiles(value: unknown): BuiltInSyncFile[];
81
+ /** Compatibility projection for old rendering helpers; v3 persistence never writes this split field. */
82
+ export declare function normalizeExtraFiles(value: unknown): string[];
83
+ export declare const extraFilePathsByLower: typeof customIncludePathsByLower;
84
+ export declare const isSafeExtraFileName: typeof isSafeCustomIncludePath;
85
+ export declare const selectedSyncFileSet: (value: unknown) => Set<"AGENTS.md" | "APPEND_SYSTEM.md" | "extensions" | "keybindings.json" | "models.json" | "prompts" | "settings.json" | "skills" | "themes">;
@@ -0,0 +1,356 @@
1
+ import path from "node:path";
2
+ import { isDeniedPath, toPosix } from "../paths.js";
3
+ import { compileSyncExclude, normalizeSyncExclude, sameSyncExclude } from "./exclude-policy.js";
4
+ export const BUILT_IN_SYNC_ROOTS = [
5
+ "settings.json",
6
+ "keybindings.json",
7
+ "models.json",
8
+ "AGENTS.md",
9
+ "APPEND_SYSTEM.md",
10
+ "skills",
11
+ "prompts",
12
+ "themes",
13
+ "extensions",
14
+ ];
15
+ export const DEFAULT_SYNC_INCLUDE = [...BUILT_IN_SYNC_ROOTS];
16
+ const MAX_SYNC_INCLUDE_ITEMS = 1_024;
17
+ const MAX_SYNC_INCLUDE_PATH_BYTES = 4_096;
18
+ const MAX_SYNC_INCLUDE_TOTAL_BYTES = 256 * 1_024;
19
+ const BUILT_IN_BY_LOWER = new Map(BUILT_IN_SYNC_ROOTS.map((fileName) => [fileName.toLowerCase(), fileName]));
20
+ const TOP_LEVEL_FILE_PATHS = new Map(BUILT_IN_SYNC_ROOTS.filter((fileName) => fileName.includes(".")).map((fileName) => [
21
+ fileName.toLowerCase(),
22
+ fileName,
23
+ ]));
24
+ const TOP_LEVEL_DIRS = new Set(BUILT_IN_SYNC_ROOTS.filter((fileName) => !fileName.includes(".")));
25
+ const RESERVED_TOP_LEVEL_NAMES = new Set([...BUILT_IN_BY_LOWER.keys(), "sessions"]);
26
+ export function normalizeSyncInclude(value) {
27
+ if (!Array.isArray(value)) {
28
+ throw new Error("Invalid pi-sync settings: sync.include must be an array.");
29
+ }
30
+ if (value.length > MAX_SYNC_INCLUDE_ITEMS) {
31
+ throw new Error(`Invalid pi-sync settings: sync.include has too many items; limit: ${MAX_SYNC_INCLUDE_ITEMS}.`);
32
+ }
33
+ const result = [];
34
+ const seen = new Set();
35
+ const pathRoot = { children: new Map() };
36
+ let totalBytes = 0;
37
+ for (const item of value) {
38
+ if (typeof item !== "string") {
39
+ throw new Error("Invalid pi-sync settings: sync.include items must be strings.");
40
+ }
41
+ const itemBytes = Buffer.byteLength(item, "utf8");
42
+ if (itemBytes > MAX_SYNC_INCLUDE_PATH_BYTES) {
43
+ throw new Error(`Invalid pi-sync settings: sync.include item is too long; limit: ${MAX_SYNC_INCLUDE_PATH_BYTES} bytes.`);
44
+ }
45
+ totalBytes += itemBytes;
46
+ if (totalBytes > MAX_SYNC_INCLUDE_TOTAL_BYTES) {
47
+ throw new Error(`Invalid pi-sync settings: sync.include is too large; limit: ${MAX_SYNC_INCLUDE_TOTAL_BYTES} bytes.`);
48
+ }
49
+ const trimmed = item.trim();
50
+ const builtIn = BUILT_IN_BY_LOWER.get(trimmed.toLowerCase());
51
+ const normalized = builtIn ?? (trimmed.toLowerCase() === "sessions" ? "sessions" : trimmed);
52
+ if (!builtIn && normalized !== "sessions")
53
+ validateAgentRelativeInclude(normalized);
54
+ const identity = normalized.toLowerCase();
55
+ if (seen.has(identity)) {
56
+ throw new Error(`Invalid pi-sync settings: duplicate sync.include item: ${item}`);
57
+ }
58
+ addIncludePath(pathRoot, identity, item);
59
+ seen.add(identity);
60
+ result.push(normalized);
61
+ }
62
+ return result;
63
+ }
64
+ function addIncludePath(root, identity, source) {
65
+ let node = root;
66
+ for (const segment of identity.split("/")) {
67
+ if (node.selected !== undefined)
68
+ throwOverlappingInclude(source);
69
+ let child = node.children.get(segment);
70
+ if (!child) {
71
+ child = { children: new Map() };
72
+ node.children.set(segment, child);
73
+ }
74
+ node = child;
75
+ }
76
+ if (node.children.size > 0)
77
+ throwOverlappingInclude(source);
78
+ node.selected = identity;
79
+ }
80
+ function throwOverlappingInclude(item) {
81
+ throw new Error(`Invalid pi-sync settings: overlapping sync.include items are ambiguous: ${item}`);
82
+ }
83
+ function validateAgentRelativeInclude(value) {
84
+ const normalized = toPosix(value);
85
+ const topLevel = normalized.split("/")[0]?.toLowerCase();
86
+ if (!normalized ||
87
+ normalized === "." ||
88
+ normalized === ".." ||
89
+ normalized.startsWith("../") ||
90
+ path.posix.isAbsolute(normalized) ||
91
+ normalized.includes("\\") ||
92
+ path.posix.normalize(normalized) !== normalized ||
93
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Include paths cannot contain controls.
94
+ /[\u0000-\u001f\u007f-\u009f]/u.test(normalized)) {
95
+ throw new Error(`Invalid pi-sync settings: sync.include item must be a safe agent-relative path: ${value}`);
96
+ }
97
+ if (isDeniedPath(normalized)) {
98
+ throw new Error(`Invalid pi-sync settings: ${value} cannot be synced.`);
99
+ }
100
+ if (topLevel && RESERVED_TOP_LEVEL_NAMES.has(topLevel)) {
101
+ throw new Error(`Invalid pi-sync settings: use the canonical ${topLevel} root instead of a nested sync.include path.`);
102
+ }
103
+ }
104
+ export function portableSnapshotSelection(value) {
105
+ const selection = value;
106
+ if (!selection ||
107
+ typeof selection !== "object" ||
108
+ Array.isArray(selection) ||
109
+ (selection.version !== 1 && selection.version !== 2) ||
110
+ !Object.hasOwn(selection, "include") ||
111
+ (selection.version === 2 && !Object.hasOwn(selection, "exclude")) ||
112
+ Object.keys(selection).some((key) => key !== "version" && key !== "include" && !(selection.version === 2 && key === "exclude")))
113
+ throw new Error("Invalid snapshot selection policy.");
114
+ const include = normalizeSyncInclude(selection.include);
115
+ if (selection.version === 1)
116
+ return { version: 1, include };
117
+ if (!Array.isArray(selection.exclude))
118
+ throw new Error("Invalid snapshot exclude policy.");
119
+ return { version: 2, include, exclude: normalizeSyncExclude(selection.exclude) };
120
+ }
121
+ export function snapshotSelectionInclude(snapshot) {
122
+ return snapshot.selection === undefined ? undefined : portableSnapshotSelection(snapshot.selection).include;
123
+ }
124
+ export function snapshotSelectionExclude(snapshot) {
125
+ return snapshot.selection === undefined ? undefined : portableSnapshotSelection(snapshot.selection).exclude;
126
+ }
127
+ export function selectionForSnapshot(include, exclude) {
128
+ const normalized = normalizeSyncInclude(include);
129
+ return exclude === undefined
130
+ ? { version: 1, include: normalized }
131
+ : { version: 2, include: normalized, exclude: normalizeSyncExclude(exclude) };
132
+ }
133
+ /** Metadata equality, not policy compatibility: bind the whole projection to its immutable image. */
134
+ export function sameSnapshotSelection(left, right) {
135
+ return (JSON.stringify(left === undefined ? null : portableSnapshotSelection(left)) ===
136
+ JSON.stringify(right === undefined ? null : portableSnapshotSelection(right)));
137
+ }
138
+ export function validateSnapshotSelection(snapshot) {
139
+ const selection = snapshot.selection === undefined ? undefined : portableSnapshotSelection(snapshot.selection);
140
+ if ((snapshot.version === 4) !== (selection?.version === 2))
141
+ throw new Error("Exclude policy requires snapshot version 4 and selection version 2.");
142
+ }
143
+ export function sameSyncInclude(left, right) {
144
+ const normalizedLeft = normalizeSyncInclude(left);
145
+ const normalizedRight = normalizeSyncInclude(right);
146
+ return (normalizedLeft.length === normalizedRight.length &&
147
+ normalizedLeft.every((item, index) => item === normalizedRight[index]));
148
+ }
149
+ export function compareSyncInclude(local, remote) {
150
+ const localInclude = normalizeSyncInclude(local);
151
+ const remoteInclude = normalizeSyncInclude(remote);
152
+ const localSet = new Set(localInclude);
153
+ const remoteSet = new Set(remoteInclude);
154
+ return {
155
+ same: sameSyncInclude(localInclude, remoteInclude),
156
+ remoteOnly: remoteInclude.filter((item) => !localSet.has(item)),
157
+ localOnly: localInclude.filter((item) => !remoteSet.has(item)),
158
+ };
159
+ }
160
+ export function inspectRemoteSelection(localInclude, snapshot, localExclude) {
161
+ const remoteInclude = snapshotSelectionInclude(snapshot);
162
+ if (!remoteInclude)
163
+ return { kind: "legacy", discovered: discoverLegacySnapshotInclude(snapshot) };
164
+ const exclude = snapshotSelectionExclude(snapshot);
165
+ const comparison = compareSyncInclude(localInclude, remoteInclude);
166
+ const rules = exclude === undefined ? {} : { exclude };
167
+ return comparison.same && sameSyncExclude(localExclude, exclude)
168
+ ? { kind: "same", include: remoteInclude, ...rules }
169
+ : {
170
+ kind: "different",
171
+ include: remoteInclude,
172
+ ...comparison,
173
+ ...rules,
174
+ ...(!sameSyncExclude(localExclude, exclude) ? { excludeChanged: true } : {}),
175
+ };
176
+ }
177
+ export class RemoteSelectionMismatchError extends Error {
178
+ decision;
179
+ setupName;
180
+ localInclude;
181
+ remoteInclude;
182
+ constructor(setupName, localInclude, remoteInclude, configIdentity = JSON.stringify([setupName, normalizeSyncInclude(localInclude)]), localExclude, remoteExclude) {
183
+ const local = normalizeSyncInclude(localInclude);
184
+ const remote = normalizeSyncInclude(remoteInclude);
185
+ super(formatRemoteSelectionMismatch(setupName, local, remote, localExclude, remoteExclude));
186
+ this.name = "RemoteSelectionMismatchError";
187
+ this.setupName = setupName;
188
+ this.localInclude = local;
189
+ this.remoteInclude = remote;
190
+ this.decision = {
191
+ setupName,
192
+ configIdentity,
193
+ localInclude: [...local],
194
+ remoteInclude: [...remote],
195
+ ...(localExclude === undefined ? {} : { localExclude: normalizeSyncExclude(localExclude) }),
196
+ ...(remoteExclude === undefined ? {} : { remoteExclude: normalizeSyncExclude(remoteExclude) }),
197
+ };
198
+ }
199
+ }
200
+ export function remoteSelectionMismatch(config, remoteInclude, configIdentity, remoteExclude) {
201
+ return new RemoteSelectionMismatchError(config.setupName, config.include, remoteInclude, configIdentity, config.exclude, remoteExclude);
202
+ }
203
+ export function formatRemoteSelectionMismatch(setupName, localInclude, remoteInclude, localExclude, remoteExclude) {
204
+ const comparison = compareSyncInclude(localInclude, remoteInclude);
205
+ const lines = [
206
+ `Synced content differs for sync setup “${stripTerminalControls(setupName)}”.`,
207
+ `Remote-only: ${comparison.remoteOnly.join(", ") || "none"}`,
208
+ `This-device-only: ${comparison.localOnly.join(", ") || "none"}`,
209
+ ];
210
+ if (!sameSyncExclude(localExclude, remoteExclude)) {
211
+ lines.push(`Remote excluded paths: ${normalizeSyncExclude(remoteExclude).join(", ") || "none"}`, `This device excluded paths: ${normalizeSyncExclude(localExclude).join(", ") || "none"}`);
212
+ }
213
+ else if (comparison.remoteOnly.length === 0 && comparison.localOnly.length === 0) {
214
+ lines.push("Only ordering differs.", `Remote order: ${remoteInclude.join(", ") || "none"}`, `This device order: ${localInclude.join(", ") || "none"}`);
215
+ }
216
+ lines.push("Run /sync in TUI to review both content lists and choose what happens next.");
217
+ return lines.join("\n");
218
+ }
219
+ function stripTerminalControls(value) {
220
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Escape untrusted terminal controls.
221
+ return value.replace(/[\u0000-\u001f\u007f-\u009f]/gu, "?");
222
+ }
223
+ export function discoverLegacySnapshotInclude(snapshot) {
224
+ const builtIns = new Set();
225
+ const custom = new Set();
226
+ let sessions = false;
227
+ for (const file of snapshot.files) {
228
+ const normalized = toPosix(file.path);
229
+ if (!normalized ||
230
+ file.path.includes("\\") ||
231
+ normalized.length > 4096 ||
232
+ normalized.startsWith("../") ||
233
+ path.posix.isAbsolute(normalized) ||
234
+ path.posix.normalize(normalized) !== normalized ||
235
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Ignore unsafe legacy paths.
236
+ /[\u0000-\u001f\u007f-\u009f]/u.test(normalized) ||
237
+ isDeniedPath(normalized)) {
238
+ continue;
239
+ }
240
+ const [topLevel, ...rest] = normalized.split("/");
241
+ if (!topLevel)
242
+ continue;
243
+ if (topLevel === "sessions" && rest.length > 0) {
244
+ sessions = true;
245
+ continue;
246
+ }
247
+ const builtIn = BUILT_IN_BY_LOWER.get(topLevel.toLowerCase());
248
+ if (builtIn &&
249
+ ((TOP_LEVEL_DIRS.has(builtIn) && rest.length > 0) || (!TOP_LEVEL_DIRS.has(builtIn) && rest.length === 0))) {
250
+ builtIns.add(builtIn);
251
+ continue;
252
+ }
253
+ if (isSafeCustomIncludePath(topLevel))
254
+ custom.add(topLevel);
255
+ }
256
+ return [
257
+ ...BUILT_IN_SYNC_ROOTS.filter((item) => builtIns.has(item)),
258
+ ...[...custom].sort((left, right) => left.localeCompare(right)),
259
+ ...(sessions ? ["sessions"] : []),
260
+ ];
261
+ }
262
+ export function syncIncludeSelection(value) {
263
+ const include = normalizeSyncInclude(value);
264
+ const builtIns = include.filter((item) => BUILT_IN_BY_LOWER.has(item.toLowerCase()));
265
+ const custom = include.filter((item) => item !== "sessions" && !BUILT_IN_BY_LOWER.has(item.toLowerCase()));
266
+ return { include, builtIns, custom, sessions: include.includes("sessions") };
267
+ }
268
+ export function customIncludePathsByLower(value) {
269
+ return new Map(syncIncludeSelection(value).custom.map((relativePath) => [relativePath.toLowerCase(), relativePath]));
270
+ }
271
+ export function includeFromSelectionConfig(config) {
272
+ if (config.include !== undefined)
273
+ return normalizeSyncInclude(config.include);
274
+ return [
275
+ ...normalizeSyncFiles(config.syncFiles),
276
+ ...normalizeExtraFiles(config.extraFiles),
277
+ ...(config.syncSessions ? ["sessions"] : []),
278
+ ];
279
+ }
280
+ export function syncSessionsSelected(config) {
281
+ return includeFromSelectionConfig(config).includes("sessions") && !compileSyncExclude(config.exclude)("sessions");
282
+ }
283
+ export function isConfiguredSnapshotPath(relativePath, config, _legacyExtraFiles) {
284
+ return configuredSnapshotPathMatcher(config)(relativePath);
285
+ }
286
+ export function configuredSnapshotPathMatcher(config) {
287
+ const selection = syncIncludeSelection(includeFromSelectionConfig(config));
288
+ const excluded = compileSyncExclude(config.exclude);
289
+ return (relativePath) => {
290
+ const normalized = toPosix(relativePath);
291
+ if (excluded(normalized))
292
+ return false;
293
+ if (normalized.startsWith("sessions/"))
294
+ return selection.sessions;
295
+ const lower = normalized.toLowerCase();
296
+ if (!normalized.includes("/")) {
297
+ const builtIn = BUILT_IN_BY_LOWER.get(lower);
298
+ if (builtIn)
299
+ return selection.builtIns.includes(builtIn) && !TOP_LEVEL_DIRS.has(builtIn);
300
+ }
301
+ const topLevel = normalized.slice(0, normalized.indexOf("/"));
302
+ if (selection.builtIns.includes(topLevel) && TOP_LEVEL_DIRS.has(topLevel))
303
+ return true;
304
+ return selection.custom.some((candidate) => {
305
+ const key = candidate.toLowerCase();
306
+ return lower === key || lower.startsWith(`${key}/`);
307
+ });
308
+ };
309
+ }
310
+ export function canonicalSnapshotPathForConfig(relativePath, includePaths) {
311
+ const normalized = toPosix(relativePath);
312
+ const lower = normalized.toLowerCase();
313
+ return TOP_LEVEL_FILE_PATHS.get(lower) ?? includePaths.get(lower) ?? normalized;
314
+ }
315
+ export function isPreservableUnmanagedSnapshotPath(relativePath) {
316
+ const normalized = toPosix(relativePath);
317
+ if (!normalized || isDeniedPath(normalized))
318
+ return false;
319
+ if (normalized.startsWith("sessions/"))
320
+ return normalized.endsWith(".jsonl");
321
+ if (!normalized.includes("/")) {
322
+ const lower = normalized.toLowerCase();
323
+ return TOP_LEVEL_FILE_PATHS.has(lower) || !RESERVED_TOP_LEVEL_NAMES.has(lower);
324
+ }
325
+ return true;
326
+ }
327
+ export function isSafeCustomIncludePath(relativePath) {
328
+ try {
329
+ validateAgentRelativeInclude(relativePath);
330
+ return true;
331
+ }
332
+ catch {
333
+ return false;
334
+ }
335
+ }
336
+ export function isBuiltInTopLevelFile(fileName) {
337
+ return TOP_LEVEL_FILE_PATHS.has(path.posix.basename(fileName).toLowerCase());
338
+ }
339
+ /** Compatibility projection for backend-neutral output while callers move to sync.include. */
340
+ export function normalizeSyncFiles(value) {
341
+ if (value === undefined)
342
+ return [...DEFAULT_SYNC_INCLUDE];
343
+ if (Array.isArray(value)) {
344
+ return normalizeSyncInclude(value).filter((item) => BUILT_IN_BY_LOWER.has(item.toLowerCase()));
345
+ }
346
+ throw new Error("Invalid pi-sync settings: expected an include array.");
347
+ }
348
+ /** Compatibility projection for old rendering helpers; v3 persistence never writes this split field. */
349
+ export function normalizeExtraFiles(value) {
350
+ if (!Array.isArray(value))
351
+ return [];
352
+ return value.filter((item) => typeof item === "string" && isSafeCustomIncludePath(item));
353
+ }
354
+ export const extraFilePathsByLower = customIncludePathsByLower;
355
+ export const isSafeExtraFileName = isSafeCustomIncludePath;
356
+ export const selectedSyncFileSet = (value) => new Set(normalizeSyncFiles(value));
@@ -0,0 +1,7 @@
1
+ import { type SyncBackendFactory } from "../backends/backend-factory.js";
2
+ import type { CommandOptions } from "../commands/command-types.js";
3
+ import type { EngineContext as ExtensionCommandContext } from "../host.js";
4
+ export declare function status(ctx: ExtensionCommandContext, options: CommandOptions, factory?: SyncBackendFactory): Promise<void>;
5
+ export declare function diff(ctx: ExtensionCommandContext, options: CommandOptions, factory?: SyncBackendFactory): Promise<void>;
6
+ export declare function doctor(ctx: ExtensionCommandContext, options: CommandOptions, factory?: SyncBackendFactory): Promise<void>;
7
+ export declare function history(ctx: ExtensionCommandContext, options: CommandOptions, factory?: SyncBackendFactory): Promise<void>;
@@ -0,0 +1,195 @@
1
+ import { createSyncBackend } from "../backends/backend-factory.js";
2
+ import { loadConfig, syncSessionsWarnings } from "../settings/config.js";
3
+ import { snapshotOptionsForContext } from "../snapshot/session-paths.js";
4
+ import { createSnapshot, scanSnapshot } from "../snapshot/snapshot.js";
5
+ import { inspectLock, isLockGuardHeld, isStaleLock, withLock } from "../state/lock.js";
6
+ import { readStateForConfig } from "../state/sync-state-store.js";
7
+ import { formatDiff, formatSnapshotOnlyDiff, publicationCapabilityDescription } from "../ui/sync-format.js";
8
+ import { setSyncStatus } from "../ui/sync-status.js";
9
+ import { safeTerminalText } from "../ui/terminal-text.js";
10
+ import { portableSnapshot } from "./local-fields.js";
11
+ import { formatRemoteSelectionStatus, readRemoteSnapshot } from "./remote-snapshot.js";
12
+ import { throwIfAborted } from "./signals.js";
13
+ import { errorMessage } from "./sync-errors.js";
14
+ import { inspectSync } from "./sync-inspection.js";
15
+ import { rollback } from "./sync-mutations.js";
16
+ import { syncSessionsSelected } from "./sync-policy.js";
17
+ const DEFAULT_PROFILE = "default";
18
+ export async function status(ctx, options, factory = createSyncBackend) {
19
+ const config = await loadConfig(options.setup);
20
+ throwIfAborted(options.signal);
21
+ setSyncStatus(ctx, `checking ${config.setupName}`, { activity: "checking" });
22
+ const { head, selectionState, localChanged, remoteChanged, localFiles, destination, capability } = await inspectSync(config, snapshotOptionsForContext(ctx, config), options.signal, factory);
23
+ throwIfAborted(options.signal);
24
+ const continuous = config.continuous
25
+ ? await (await import("./continuous-record.js")).continuousStatusLines(config)
26
+ : [];
27
+ throwIfAborted(options.signal);
28
+ const remoteText = head ? `remote: ${head.snapshotId} from ${head.machine} at ${head.createdAt}` : "remote: empty";
29
+ const warnings = syncSessionsWarnings(config);
30
+ setSyncStatus(ctx, undefined);
31
+ ctx.ui.notify([
32
+ `sync setup: ${config.setupName}`,
33
+ `storage connection: ${config.connectionName}`,
34
+ `storage location: ${safeTerminalText(destination)}`,
35
+ `publication safety: ${publicationCapabilityDescription(capability)}`,
36
+ `included content: ${config.include.join(", ") || "none"}`,
37
+ ...(config.exclude === undefined
38
+ ? []
39
+ : [`excluded paths: ${config.exclude.map(safeTerminalText).join(", ") || "none"}`]),
40
+ `sessions: ${syncSessionsSelected(config) ? "included" : "excluded"}`,
41
+ ...continuous,
42
+ remoteText,
43
+ formatRemoteSelectionStatus(selectionState),
44
+ `local files: ${localFiles}`,
45
+ `local changed since last sync: ${localChanged ? "yes" : "no"}`,
46
+ `remote changed since last sync: ${remoteChanged ? "yes" : "no"}`,
47
+ ...warnings,
48
+ ].join("\n"), localChanged || remoteChanged || selectionState?.kind === "different" || warnings.length > 0 ? "warning" : "info");
49
+ }
50
+ export async function diff(ctx, options, factory = createSyncBackend) {
51
+ const config = await loadConfig(options.setup);
52
+ throwIfAborted(options.signal);
53
+ setSyncStatus(ctx, `checking ${config.setupName}`, { activity: "checking" });
54
+ const backend = await factory(config);
55
+ const local = portableSnapshot(await createSnapshot(config.snapshotIdentity, snapshotOptionsForContext(ctx, config)), config.localFields);
56
+ throwIfAborted(options.signal);
57
+ const { snapshot: remote, selectionState } = await readRemoteSnapshot(backend, config, options.signal, {
58
+ allowSelectionDifference: true,
59
+ });
60
+ throwIfAborted(options.signal);
61
+ setSyncStatus(ctx, undefined);
62
+ const warnings = syncSessionsWarnings(config);
63
+ const header = [
64
+ `sync setup: ${config.setupName}`,
65
+ `storage connection: ${config.connectionName}`,
66
+ `storage location: ${safeTerminalText(backend.destination)}`,
67
+ `included content: ${config.include.join(", ") || "none"}`,
68
+ ...(config.exclude === undefined
69
+ ? []
70
+ : [`excluded paths: ${config.exclude.map(safeTerminalText).join(", ") || "none"}`]),
71
+ `sessions: ${syncSessionsSelected(config) ? "included" : "excluded"}`,
72
+ formatRemoteSelectionStatus(selectionState),
73
+ ...warnings,
74
+ ].join("\n");
75
+ const level = warnings.length > 0 || selectionState?.kind === "different" ? "warning" : "info";
76
+ if (!remote) {
77
+ ctx.ui.notify(`${header}\n\n${formatSnapshotOnlyDiff("Remote is empty. Local push would upload", local)}`, level);
78
+ return;
79
+ }
80
+ ctx.ui.notify(`${header}\n\n${formatDiff(local, portableSnapshot(remote, remote.localFields))}`, level);
81
+ }
82
+ export async function doctor(ctx, options, factory = createSyncBackend) {
83
+ const messages = [];
84
+ let level = "info";
85
+ let snapshotOptions = {};
86
+ let profile = DEFAULT_PROFILE;
87
+ let backend;
88
+ let backendSummary = [];
89
+ try {
90
+ const config = await loadConfig(options.setup);
91
+ throwIfAborted(options.signal);
92
+ backend = await factory(config);
93
+ profile = config.snapshotIdentity;
94
+ snapshotOptions = snapshotOptionsForContext(ctx, config);
95
+ messages.push(`config: ok (sync setup ${config.setupName})`, `included content: ${config.include.join(", ") || "none"}`, ...(config.exclude === undefined
96
+ ? []
97
+ : [`excluded paths: ${config.exclude.map(safeTerminalText).join(", ") || "none"}`]), `sessions: ${syncSessionsSelected(config) ? "included" : "excluded"}`);
98
+ backendSummary = [
99
+ `storage location: ${safeTerminalText(backend.destination)}`,
100
+ `publication safety: ${publicationCapabilityDescription(backend.capability)}`,
101
+ ];
102
+ const warnings = syncSessionsWarnings(config);
103
+ if (warnings.length > 0) {
104
+ level = "warning";
105
+ messages.push(...warnings);
106
+ }
107
+ }
108
+ catch (error) {
109
+ throwIfAborted(options.signal);
110
+ level = "warning";
111
+ messages.push(`config: ${errorMessage(error)}`);
112
+ }
113
+ const local = await createSnapshot(profile, snapshotOptions);
114
+ throwIfAborted(options.signal);
115
+ const secrets = scanSnapshot(local);
116
+ if (secrets.length > 0) {
117
+ level = "warning";
118
+ messages.push("secret scan: possible secrets found:");
119
+ messages.push(...secrets.map((secret) => `- ${secret}`));
120
+ }
121
+ else {
122
+ messages.push(`secret scan: ok (${local.files.length} files checked)`);
123
+ }
124
+ const lock = await inspectLock();
125
+ throwIfAborted(options.signal);
126
+ if (lock.status === "valid" && isStaleLock(lock.lock)) {
127
+ level = "warning";
128
+ messages.push(`lock: stale (pid ${lock.lock.pid}); run /sync unlock --stale after verifying no sync is running`);
129
+ }
130
+ else if (lock.status === "valid") {
131
+ messages.push(`lock: held by pid ${lock.lock.pid} since ${lock.lock.startedAt}`);
132
+ }
133
+ else if (lock.status === "unreadable") {
134
+ level = "warning";
135
+ messages.push("lock: unreadable; use /sync unlock --stale only after verifying no sync is running");
136
+ }
137
+ else if (await isLockGuardHeld()) {
138
+ throwIfAborted(options.signal);
139
+ level = "warning";
140
+ messages.push("lock: guard active while metadata is missing or still being initialized");
141
+ }
142
+ else {
143
+ messages.push("lock: free");
144
+ }
145
+ if (backend) {
146
+ messages.push(...backendSummary);
147
+ const diagnostics = await backend.diagnose(options.signal);
148
+ throwIfAborted(options.signal);
149
+ for (const diagnostic of diagnostics) {
150
+ messages.push(diagnostic.message);
151
+ if (diagnostic.level !== "info")
152
+ level = "warning";
153
+ }
154
+ }
155
+ ctx.ui.notify(messages.join("\n"), level);
156
+ }
157
+ export async function history(ctx, options, factory = createSyncBackend) {
158
+ const config = await loadConfig(options.setup);
159
+ throwIfAborted(options.signal);
160
+ const backend = await factory(config);
161
+ const snapshots = (await backend.listHistory(options.signal)).slice(-20).reverse();
162
+ throwIfAborted(options.signal);
163
+ const lastApplied = await readStateForConfig(config)
164
+ .then((state) => state.lastAppliedSnapshot)
165
+ .catch(() => undefined);
166
+ throwIfAborted(options.signal);
167
+ const appliedDetails = lastApplied
168
+ ? `Last applied snapshot ID: ${safeTerminalText(lastApplied)}\nApplication time: unavailable. Snapshot dates are creation times.`
169
+ : "Last applied snapshot ID: unavailable.";
170
+ if (snapshots.length === 0) {
171
+ ctx.ui.notify(`No remote pi-sync history found.\n${appliedDetails}`, "info");
172
+ return;
173
+ }
174
+ const currentSnapshot = snapshots[0]?.snapshotId;
175
+ if (ctx.mode === "tui") {
176
+ const labels = snapshots.map((item, index) => `${index + 1}. ${item.createdAt} · ${safeTerminalText(item.machine)} · ${item.snapshotId}${item.snapshotId === currentSnapshot ? " (current)" : ""}${item.syncSessions ? " · sessions" : ""}`);
177
+ const selected = await ctx.ui.select(`History for sync setup “${safeTerminalText(config.setupName)}”\n\n${appliedDetails}\n\nChoose a snapshot to preview rollback.`, [...labels, "Back"], { signal: options.signal });
178
+ if (!selected || selected === "Back")
179
+ return;
180
+ throwIfAborted(options.signal);
181
+ const index = labels.indexOf(selected);
182
+ const snapshot = snapshots[index];
183
+ if (!snapshot)
184
+ return;
185
+ await withLock("rollback", () => rollback(ctx, { ...options, args: [snapshot.snapshotRef], yes: false }, factory, {
186
+ backendIdentity: backend.identity,
187
+ setup: config.setupName,
188
+ }));
189
+ return;
190
+ }
191
+ ctx.ui.notify([
192
+ appliedDetails,
193
+ ...snapshots.map((item) => `${item.snapshotRef} ${item.createdAt} ${safeTerminalText(item.machine)}`),
194
+ ].join("\n"), "info");
195
+ }