@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,79 @@
1
+ import path from "node:path";
2
+ import { Minimatch } from "minimatch";
3
+ const MAX_RULES = 1_024;
4
+ const MAX_RULE_BYTES = 4_096;
5
+ const MAX_TOTAL_BYTES = 256 * 1_024;
6
+ /** Exclusions are a set; keep spelling for exact reviews, not filesystem lookup. */
7
+ export function normalizeSyncExclude(value) {
8
+ if (value === undefined)
9
+ return [];
10
+ if (!Array.isArray(value))
11
+ throw new Error("Invalid pi-sync settings: sync.exclude must be an array.");
12
+ if (value.length > MAX_RULES)
13
+ throw new Error(`sync.exclude exceeds ${MAX_RULES} rules.`);
14
+ const seen = new Set();
15
+ let total = 0;
16
+ const rules = value.map((item) => {
17
+ if (typeof item !== "string")
18
+ throw new Error("sync.exclude rules must be strings.");
19
+ const bytes = Buffer.byteLength(item, "utf8");
20
+ total += bytes;
21
+ if (bytes > MAX_RULE_BYTES || total > MAX_TOTAL_BYTES)
22
+ throw new Error("sync.exclude exceeds its byte limit.");
23
+ const rule = item.trim();
24
+ const segments = rule.split("/");
25
+ if (!rule ||
26
+ path.posix.isAbsolute(rule) ||
27
+ path.win32.isAbsolute(rule) ||
28
+ /^[a-z]:/iu.test(rule) ||
29
+ rule.includes("\\") ||
30
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Reject untrusted terminal controls.
31
+ /[\u0000-\u001f\u007f-\u009f]/u.test(item) ||
32
+ /^[!#]/u.test(rule) ||
33
+ /[[\]{}()]/u.test(rule) ||
34
+ segments.some((segment) => !segment || segment === "." || segment === ".." || (segment.includes("**") && segment !== "**")))
35
+ throw new Error("Invalid sync.exclude rule: use a safe relative path with only *, ?, and whole-segment ** globs.");
36
+ const key = rule.toLowerCase();
37
+ if (seen.has(key))
38
+ throw new Error("Duplicate sync.exclude rule (case-insensitive).");
39
+ seen.add(key);
40
+ return rule;
41
+ });
42
+ return rules.sort((left, right) => {
43
+ const a = left.toLowerCase();
44
+ const b = right.toLowerCase();
45
+ return a < b ? -1 : a > b ? 1 : 0;
46
+ });
47
+ }
48
+ export function sameSyncExclude(left, right) {
49
+ return (JSON.stringify(normalizeSyncExclude(left).map((rule) => rule.toLowerCase())) ===
50
+ JSON.stringify(normalizeSyncExclude(right).map((rule) => rule.toLowerCase())));
51
+ }
52
+ /** Compile at the operation boundary and reuse for every file/directory. */
53
+ export function compileSyncExclude(value) {
54
+ const matchers = normalizeSyncExclude(value).map((rule) =>
55
+ // A trailing globstar also matches zero segments; ancestor matching owns its subtree.
56
+ new Minimatch(rule.replace(/(?:\/\*\*)+$/u, ""), {
57
+ dot: true,
58
+ nocase: true,
59
+ nonegate: true,
60
+ nocomment: true,
61
+ nobrace: true,
62
+ noext: true,
63
+ platform: "linux",
64
+ optimizationLevel: 0,
65
+ }));
66
+ return (relativePath) => {
67
+ if (matchers.length === 0)
68
+ return false;
69
+ for (let candidate = relativePath; candidate;) {
70
+ if (matchers.some((matcher) => matcher.match(candidate)))
71
+ return true;
72
+ const slash = candidate.lastIndexOf("/");
73
+ if (slash < 0)
74
+ break;
75
+ candidate = candidate.slice(0, slash);
76
+ }
77
+ return false;
78
+ };
79
+ }
@@ -0,0 +1,5 @@
1
+ import type { EngineContext as ExtensionContext } from "../host.js";
2
+ import type { AnySyncConfig } from "../settings/settings-types.js";
3
+ import type { Snapshot } from "../snapshot/snapshot-types.js";
4
+ import type { SyncState } from "../state/state-types.js";
5
+ export declare function confirmFieldMigration(ctx: ExtensionContext, config: AnySyncConfig, state: SyncState, remote: Snapshot | undefined, force: boolean, signal?: AbortSignal): Promise<boolean>;
@@ -0,0 +1,20 @@
1
+ import { safeTerminalText } from "../ui/terminal-text.js";
2
+ import { sameLocalFields } from "./local-fields.js";
3
+ import { captureMutationOwner } from "./sync-local.js";
4
+ export async function confirmFieldMigration(ctx, config, state, remote, force, signal) {
5
+ if (remote?.localFields !== undefined && config.localFields === undefined)
6
+ throw new Error("Portable snapshots require settings version 4 and explicit localFields rules on this machine; older policy must not replace local-only values.");
7
+ const changed = (Boolean(state.lastAppliedSnapshot) && !sameLocalFields(state.localFields, config.localFields)) ||
8
+ (remote !== undefined && !sameLocalFields(remote.localFields, config.localFields));
9
+ if (!changed)
10
+ return true;
11
+ if (!force)
12
+ throw new Error("Local-field policy changed; review an explicit push --force or pull --force migration. Old remote history is not erased.");
13
+ const validate = captureMutationOwner(ctx, signal);
14
+ if (!ctx.hasUI)
15
+ throw new Error("Local-field migration requires observable TUI/RPC confirmation.");
16
+ validate();
17
+ const confirmed = await ctx.ui.confirm("Migrate portable settings policy?", `New machine-local fields: ${(config.localFields ?? []).map(safeTerminalText).join(", ") || "none"}. Additions remove fields from future snapshots, not old history. Removals make local-only values portable again and a pull may replace them. The selected direction is authoritative; inspect /sync diff first. This confirmation is required even with --yes.`, { signal });
18
+ validate();
19
+ return confirmed;
20
+ }
@@ -0,0 +1,36 @@
1
+ import type { SnapshotFile } from "../snapshot/snapshot-types.js";
2
+ /** Absence and an empty file are different states. A missing ancestor is not absence. */
3
+ export type FileVersion = SnapshotFile | undefined;
4
+ export type FileMergeDecision = {
5
+ kind: "accepted";
6
+ path: string;
7
+ source: "equal" | "local" | "remote" | "merged";
8
+ file: FileVersion;
9
+ } | {
10
+ kind: "conflict";
11
+ path: string;
12
+ reason: "both-changed" | "protected-session" | "path-collision";
13
+ };
14
+ export type FileMergePlan = {
15
+ kind: "review";
16
+ reason: "missing-baseline" | "selection-changed";
17
+ } | {
18
+ kind: "planned";
19
+ decisions: FileMergeDecision[];
20
+ conflicts: Extract<FileMergeDecision, {
21
+ kind: "conflict";
22
+ }>[];
23
+ };
24
+ export interface FileMergeInput {
25
+ /** Undefined means unavailable; an empty map is an established empty baseline. */
26
+ baseline: Readonly<Record<string, string>> | undefined;
27
+ local: readonly SnapshotFile[];
28
+ remote: readonly SnapshotFile[];
29
+ selectionCompatible: boolean;
30
+ protectedPaths?: ReadonlySet<string>;
31
+ }
32
+ /** Pure, deterministic decisions only. This does not authorize publication or mutation. */
33
+ export declare function planFileMerge(input: FileMergeInput): FileMergePlan;
34
+ export declare function mergePathIdentity(filePath: string): string;
35
+ /** Conservative dependency groups: never accept a case or file/directory transition independently. */
36
+ export declare function collidingPaths(paths: readonly string[]): Set<string>;
@@ -0,0 +1,123 @@
1
+ import { createHash } from "node:crypto";
2
+ import path from "node:path";
3
+ import { isDeniedPath } from "../paths.js";
4
+ /** Pure, deterministic decisions only. This does not authorize publication or mutation. */
5
+ export function planFileMerge(input) {
6
+ if (!input.selectionCompatible)
7
+ return { kind: "review", reason: "selection-changed" };
8
+ if (input.baseline === undefined)
9
+ return { kind: "review", reason: "missing-baseline" };
10
+ const local = indexFiles(input.local);
11
+ const remote = indexFiles(input.remote);
12
+ const baseline = input.baseline;
13
+ for (const [filePath, hash] of Object.entries(baseline)) {
14
+ validatePath(filePath);
15
+ if (!/^[a-f0-9]{64}$/u.test(hash))
16
+ throw new Error("Invalid merge baseline hash.");
17
+ }
18
+ const paths = [...new Set([...Object.keys(baseline), ...local.keys(), ...remote.keys()])].sort();
19
+ const collisions = collidingPaths(paths);
20
+ const protectedKeys = new Set([...(input.protectedPaths ?? [])].map(mergePathIdentity));
21
+ const decisions = paths.map((filePath) => {
22
+ if (collisions.has(filePath))
23
+ return { kind: "conflict", path: filePath, reason: "path-collision" };
24
+ const left = local.get(filePath);
25
+ const right = remote.get(filePath);
26
+ const ancestor = Object.hasOwn(baseline, filePath) ? baseline[filePath] : undefined;
27
+ let source;
28
+ let file;
29
+ if (left?.sha256 === right?.sha256) {
30
+ source = "equal";
31
+ file = left;
32
+ }
33
+ else if (right?.sha256 === ancestor) {
34
+ source = "local";
35
+ file = left;
36
+ }
37
+ else if (left?.sha256 === ancestor) {
38
+ source = "remote";
39
+ file = right;
40
+ }
41
+ else {
42
+ return { kind: "conflict", path: filePath, reason: "both-changed" };
43
+ }
44
+ if (source === "remote" && protectedKeys.has(mergePathIdentity(filePath))) {
45
+ return { kind: "conflict", path: filePath, reason: "protected-session" };
46
+ }
47
+ return { kind: "accepted", path: filePath, source, file };
48
+ });
49
+ return {
50
+ kind: "planned",
51
+ decisions,
52
+ conflicts: decisions.filter((decision) => decision.kind === "conflict"),
53
+ };
54
+ }
55
+ function indexFiles(files) {
56
+ const result = new Map();
57
+ for (const file of files) {
58
+ validatePath(file.path);
59
+ if (result.has(file.path))
60
+ throw new Error("Duplicate merge path.");
61
+ if (!/^[A-Za-z0-9+/]*={0,2}$/u.test(file.contentBase64) ||
62
+ file.contentBase64.length % 4 !== 0 ||
63
+ Buffer.from(file.contentBase64, "base64").toString("base64") !== file.contentBase64 ||
64
+ createHash("sha256").update(Buffer.from(file.contentBase64, "base64")).digest("hex") !== file.sha256) {
65
+ throw new Error("Invalid merge file content or checksum.");
66
+ }
67
+ result.set(file.path, file);
68
+ }
69
+ return result;
70
+ }
71
+ function validatePath(filePath) {
72
+ if (!filePath ||
73
+ filePath === "." ||
74
+ filePath === ".." ||
75
+ filePath.startsWith("../") ||
76
+ path.posix.isAbsolute(filePath) ||
77
+ filePath.includes("\\") ||
78
+ (process.platform === "win32" &&
79
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Native Windows filename restrictions.
80
+ (/[<>:"|?*\u0001-\u001f]/u.test(filePath) ||
81
+ filePath
82
+ .split("/")
83
+ .some((segment) => /[ .]$/u.test(segment) || /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/iu.test(segment)))) ||
84
+ path.posix.normalize(filePath) !== filePath ||
85
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: Reject unsafe snapshot paths.
86
+ /[\u0000\ud800-\udfff]/u.test(filePath) ||
87
+ isDeniedPath(filePath) ||
88
+ (filePath.startsWith("sessions/") && !filePath.endsWith(".jsonl"))) {
89
+ throw new Error("Unsafe merge path.");
90
+ }
91
+ }
92
+ export function mergePathIdentity(filePath) {
93
+ // Node path strings encode invalid UTF-16 as U+FFFD; context paths can still contain it.
94
+ return Buffer.from(filePath, "utf8").toString("utf8").normalize("NFC").toLowerCase();
95
+ }
96
+ /** Conservative dependency groups: never accept a case or file/directory transition independently. */
97
+ export function collidingPaths(paths) {
98
+ const byLower = new Map();
99
+ for (const filePath of paths) {
100
+ const lower = mergePathIdentity(filePath);
101
+ const variants = byLower.get(lower) ?? [];
102
+ variants.push(filePath);
103
+ byLower.set(lower, variants);
104
+ }
105
+ const result = new Set();
106
+ for (const variants of byLower.values()) {
107
+ if (variants.length > 1)
108
+ for (const variant of variants)
109
+ result.add(variant);
110
+ }
111
+ for (const filePath of paths) {
112
+ const segments = mergePathIdentity(filePath).split("/");
113
+ for (let length = 1; length < segments.length; length += 1) {
114
+ const ancestors = byLower.get(segments.slice(0, length).join("/"));
115
+ if (ancestors) {
116
+ result.add(filePath);
117
+ for (const ancestor of ancestors)
118
+ result.add(ancestor);
119
+ }
120
+ }
121
+ }
122
+ return result;
123
+ }
@@ -0,0 +1,12 @@
1
+ import type { EngineContext } from "../host.js";
2
+ import { type StartupTimingPublisher } from "./startup-timings.js";
3
+ /** Shared engine initialization; the caller establishes process handover before recovery. */
4
+ export declare function initializeSync(ctx: EngineContext, signal: AbortSignal, publish?: StartupTimingPublisher): Promise<{
5
+ debug: boolean;
6
+ settings: import("../types.js").PiSyncSettingsV3 | undefined;
7
+ config?: undefined;
8
+ } | {
9
+ debug: boolean;
10
+ settings: import("../types.js").PiSyncSettingsV3 | undefined;
11
+ config: import("../types.js").AnySyncConfig;
12
+ }>;
@@ -0,0 +1,75 @@
1
+ import { loadConfig } from "../settings/config.js";
2
+ import { isMissingConfigError } from "../settings/config-errors.js";
3
+ import { consumeLocalConfigMigrationNotice } from "../settings/config-file.js";
4
+ import { readLocalConfigObject } from "../settings/settings-store.js";
5
+ import { sessionDirFromContext } from "../snapshot/session-paths.js";
6
+ import { pendingTransactionEntries } from "../snapshot/snapshot-transaction-directory.js";
7
+ import { stateDirectoryMigrationNotice, withStateDirectoryAccess } from "../state/state-directory.js";
8
+ import { captureMutationOwner } from "./mutation-owner.js";
9
+ import { createStartupTimings } from "./startup-timings.js";
10
+ import { errorMessage } from "./sync-errors.js";
11
+ /** Shared engine initialization; the caller establishes process handover before recovery. */
12
+ export async function initializeSync(ctx, signal, publish) {
13
+ return withStateDirectoryAccess(async () => {
14
+ const timings = createStartupTimings(publish);
15
+ let debug = false;
16
+ let outcome = "stopped";
17
+ try {
18
+ const validate = captureMutationOwner(ctx, signal);
19
+ validate();
20
+ const stateNotice = stateDirectoryMigrationNotice();
21
+ if (stateNotice && ctx.hasUI)
22
+ ctx.ui.notify(stateNotice, "warning");
23
+ await timings.measure("transaction recovery", async () => {
24
+ const pending = await pendingTransactionEntries();
25
+ validate();
26
+ if (!pending.some((entry) => entry.isDirectory()))
27
+ return;
28
+ const { recoverSnapshotTransactionsOnStartup } = await import("../snapshot/snapshot-transaction.js");
29
+ validate();
30
+ const settings = await readLocalConfigObject();
31
+ validate();
32
+ const setup = settings?.activeSyncSetup;
33
+ const current = ctx.sessionManager.getSessionFile?.();
34
+ await recoverSnapshotTransactionsOnStartup({
35
+ exclude: setup ? settings.syncSetups[setup]?.sync.exclude : undefined,
36
+ signal,
37
+ sessionDir: sessionDirFromContext(ctx),
38
+ protectedTargets: [...(ctx.protectedSessionFiles ?? []), ...(current ? [current] : [])],
39
+ validateMutation: validate,
40
+ });
41
+ });
42
+ validate();
43
+ let settings;
44
+ try {
45
+ settings = await timings.measure("settings read", () => readLocalConfigObject());
46
+ validate();
47
+ debug = settings?.debug ?? false;
48
+ }
49
+ catch {
50
+ validate();
51
+ }
52
+ const notice = consumeLocalConfigMigrationNotice();
53
+ if (notice && ctx.hasUI)
54
+ ctx.ui.notify(notice, "warning");
55
+ validate();
56
+ if (!ctx.hasUI)
57
+ return { debug, settings };
58
+ try {
59
+ const config = await timings.measure("config resolution", () => loadConfig());
60
+ validate();
61
+ outcome = "completed";
62
+ return { debug, settings, config };
63
+ }
64
+ catch (error) {
65
+ validate();
66
+ if (!isMissingConfigError(error))
67
+ ctx.ui.notify(`pi-sync startup check skipped: ${errorMessage(error)}`, "warning");
68
+ }
69
+ return { debug, settings };
70
+ }
71
+ finally {
72
+ timings.publish(ctx, debug, signal, "local initialization", outcome);
73
+ }
74
+ });
75
+ }
@@ -0,0 +1,29 @@
1
+ export type JsonValue = null | boolean | number | string | JsonValue[] | JsonObject;
2
+ export interface JsonObject {
3
+ [key: string]: JsonValue;
4
+ }
5
+ export interface JsonNode {
6
+ value: JsonValue;
7
+ start: number;
8
+ end: number;
9
+ members?: Map<string, {
10
+ start: number;
11
+ end: number;
12
+ node: JsonNode;
13
+ }>;
14
+ }
15
+ export interface JsonDocument {
16
+ text: string;
17
+ root: JsonNode & {
18
+ members: NonNullable<JsonNode["members"]>;
19
+ };
20
+ }
21
+ /** Strict UTF-8 JSON, with Pi's supported BOM; duplicates and prototype hazards require review. */
22
+ export declare function parseSettingsDocument(bytes: Buffer): JsonDocument;
23
+ export declare function parseJsonObjectDocument(bytes: Buffer): JsonDocument;
24
+ export declare function jsonEqual(left: JsonValue | undefined, right: JsonValue | undefined): boolean;
25
+ /** Preserve the local prefix/suffix, order, unchanged member bytes, and every chosen value's spelling. */
26
+ export declare function renderSettingsMembers(local: JsonDocument, selected: Map<string, {
27
+ document: JsonDocument;
28
+ node: JsonNode;
29
+ }>): Buffer;
@@ -0,0 +1,172 @@
1
+ import { SettingsManager } from "@earendil-works/pi-coding-agent";
2
+ /** Strict UTF-8 JSON, with Pi's supported BOM; duplicates and prototype hazards require review. */
3
+ export function parseSettingsDocument(bytes) {
4
+ try {
5
+ return parseDocument(bytes);
6
+ }
7
+ catch {
8
+ throw new Error("Unsupported settings JSON syntax, encoding, migration or structure; review without modifying the original file.");
9
+ }
10
+ }
11
+ export function parseJsonObjectDocument(bytes) {
12
+ try {
13
+ return parseDocument(bytes, false);
14
+ }
15
+ catch {
16
+ throw new Error("Unsupported JSON object syntax, encoding or structure; preserve original bytes.");
17
+ }
18
+ }
19
+ function parseDocument(bytes, checkSettingsMigration = true) {
20
+ if (bytes.length > 1024 * 1024)
21
+ throw new Error("Settings merge input exceeds 1 MiB.");
22
+ const text = bytes.toString("utf8");
23
+ if (!Buffer.from(text).equals(bytes))
24
+ throw new Error("Settings merge requires valid UTF-8.");
25
+ let position = text.startsWith("\uFEFF") ? 1 : 0;
26
+ let nodes = 0;
27
+ JSON.parse(text.slice(position));
28
+ const whitespace = () => {
29
+ while (/^[\t\n\r ]$/.test(text[position] ?? ""))
30
+ position++;
31
+ };
32
+ const stringEnd = () => {
33
+ position++;
34
+ while (position < text.length) {
35
+ const character = text[position++];
36
+ if (character === "\\")
37
+ position++;
38
+ else if (character === '"')
39
+ return;
40
+ }
41
+ throw new Error("Invalid JSON string.");
42
+ };
43
+ const parse = (depth) => {
44
+ if (depth > 64 || ++nodes > 16_384)
45
+ throw new Error("Settings merge structure exceeds its bound.");
46
+ whitespace();
47
+ const start = position;
48
+ let members;
49
+ if (text[position] === "{") {
50
+ position++;
51
+ members = new Map();
52
+ whitespace();
53
+ while (text[position] !== "}") {
54
+ const memberStart = position;
55
+ stringEnd();
56
+ const key = JSON.parse(text.slice(memberStart, position));
57
+ if (members.has(key) || ["__proto__", "constructor", "prototype"].includes(key))
58
+ throw new Error("Duplicate or prototype-sensitive JSON key; review required.");
59
+ whitespace();
60
+ position++; // Colon: whole-document JSON.parse already validated grammar.
61
+ const node = parse(depth + 1);
62
+ members.set(key, { start: memberStart, end: position, node });
63
+ whitespace();
64
+ if (text[position] !== ",")
65
+ break;
66
+ position++;
67
+ whitespace();
68
+ }
69
+ position++;
70
+ }
71
+ else if (text[position] === "[") {
72
+ position++;
73
+ whitespace();
74
+ while (text[position] !== "]") {
75
+ parse(depth + 1);
76
+ whitespace();
77
+ if (text[position] !== ",")
78
+ break;
79
+ position++;
80
+ }
81
+ position++;
82
+ }
83
+ else if (text[position] === '"')
84
+ stringEnd();
85
+ else
86
+ while (position < text.length && !/[\s,\]}]/u.test(text.charAt(position)))
87
+ position++;
88
+ const source = text.slice(start, position);
89
+ const value = JSON.parse(source);
90
+ if (typeof value === "number" &&
91
+ (!Number.isFinite(value) ||
92
+ (Number.isInteger(value) && !Number.isSafeInteger(value)) ||
93
+ decimalIdentity(source) !== decimalIdentity(String(value))))
94
+ throw new Error("Numeric settings value cannot round-trip without loss; review required.");
95
+ return { start, end: position, value, ...(members ? { members } : {}) };
96
+ };
97
+ const root = parse(0);
98
+ if (!root.members)
99
+ throw new Error("Settings merge requires a JSON object.");
100
+ // Use the public API rather than reproducing private migration branches. Migrating input
101
+ // is withheld, including legacy queue/transport/skills and retry-delay formats.
102
+ if (checkSettingsMigration) {
103
+ const migrated = SettingsManager.inMemory(root.value).getGlobalSettings();
104
+ if (!jsonEqual(root.value, migrated))
105
+ throw new Error("Legacy settings migration requires review before content merge.");
106
+ }
107
+ return { text, root: { ...root, members: root.members } };
108
+ }
109
+ /** Compare decimal literals without expanding exponents or rounding through Number. */
110
+ function decimalIdentity(source) {
111
+ const match = /^(-?)(\d+)(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/u.exec(source);
112
+ if (!match)
113
+ throw new Error("Invalid numeric token.");
114
+ const fraction = match[3] ?? "";
115
+ const digits = `${match[2]}${fraction}`.replace(/^0+/u, "");
116
+ if (!digits)
117
+ return "0";
118
+ const coefficient = digits.replace(/0+$/u, "");
119
+ const exponent = Number(match[4] ?? 0) - fraction.length + digits.length - coefficient.length;
120
+ if (!Number.isSafeInteger(exponent))
121
+ throw new Error("Unsupported numeric exponent.");
122
+ return `${match[1]}${coefficient}e${exponent}`;
123
+ }
124
+ export function jsonEqual(left, right) {
125
+ if (left === right)
126
+ return true;
127
+ if (left === undefined || right === undefined || left === null || right === null)
128
+ return false;
129
+ if (Array.isArray(left) || Array.isArray(right))
130
+ return (Array.isArray(left) &&
131
+ Array.isArray(right) &&
132
+ left.length === right.length &&
133
+ left.every((value, index) => jsonEqual(value, right[index])));
134
+ if (typeof left !== "object" || typeof right !== "object")
135
+ return false;
136
+ const keys = Object.keys(left);
137
+ return (keys.length === Object.keys(right).length &&
138
+ keys.every((key) => Object.hasOwn(right, key) && jsonEqual(left[key], right[key])));
139
+ }
140
+ /** Preserve the local prefix/suffix, order, unchanged member bytes, and every chosen value's spelling. */
141
+ export function renderSettingsMembers(local, selected) {
142
+ const members = local.root.members;
143
+ const keys = [...members.keys(), ...[...selected.keys()].filter((key) => !members.has(key))].filter((key) => selected.has(key));
144
+ const opening = local.text.slice(local.root.start, members.values().next().value?.start ?? local.root.end - 1);
145
+ const last = [...members.values()].at(-1);
146
+ const closing = last ? local.text.slice(last.end, local.root.end) : "}";
147
+ const separator = /\r\n/.test(local.text) ? "\r\n" : "\n";
148
+ const indent = local.text.match(/\n([\t ]+)"/)?.[1] ?? " ";
149
+ const multiline = opening.includes("\n") || closing.includes("\n");
150
+ const originalSeparators = new Map();
151
+ let previous;
152
+ for (const [key, member] of members) {
153
+ if (previous)
154
+ originalSeparators.set(key, local.text.slice(previous.end, member.start));
155
+ previous = member;
156
+ }
157
+ const newSeparator = multiline ? `,${separator}${indent}` : ", ";
158
+ const rendered = keys
159
+ .map((key, index) => {
160
+ const choice = selected.get(key);
161
+ if (!choice)
162
+ throw new Error("Missing selected settings member.");
163
+ const existing = members.get(key);
164
+ const prefix = existing ? local.text.slice(existing.start, existing.node.start) : `${JSON.stringify(key)}: `;
165
+ const gap = index ? (originalSeparators.get(key) ?? newSeparator) : "";
166
+ return gap + prefix + choice.document.text.slice(choice.node.start, choice.node.end);
167
+ })
168
+ .join("");
169
+ const result = Buffer.from(local.text.slice(0, local.root.start) + opening + rendered + closing + local.text.slice(local.root.end));
170
+ parseSettingsDocument(result);
171
+ return result;
172
+ }
@@ -0,0 +1,2 @@
1
+ /** Initial rules select whole root fields of the global settings.json only. */
2
+ export declare function normalizeLocalFields(value: unknown): string[];
@@ -0,0 +1,26 @@
1
+ /** Initial rules select whole root fields of the global settings.json only. */
2
+ export function normalizeLocalFields(value) {
3
+ if (value === undefined)
4
+ return [];
5
+ if (!Array.isArray(value) ||
6
+ value.length > 128 ||
7
+ value.some((field) => typeof field !== "string" ||
8
+ !field ||
9
+ field.length > 128 ||
10
+ /[\p{Cc}\p{Cf}\p{Cs}]/u.test(field) ||
11
+ ["__proto__", "constructor", "prototype"].includes(field)))
12
+ throw new Error("localFields must be at most 128 safe settings.json root field names.");
13
+ if (new Set(value).size !== value.length)
14
+ throw new Error("Duplicate localFields rule.");
15
+ for (const [first, second] of [
16
+ ["defaultProvider", "defaultModel"],
17
+ ["skills", "enableSkillCommands"],
18
+ ["queueMode", "steeringMode"],
19
+ ["websockets", "transport"],
20
+ ["enableAnalytics", "trackingId"],
21
+ ]) {
22
+ if (value.includes(first) !== value.includes(second))
23
+ throw new Error("Coupled settings fields must be excluded together.");
24
+ }
25
+ return [...value].sort();
26
+ }
@@ -0,0 +1,9 @@
1
+ import type { Snapshot } from "../snapshot/snapshot-types.js";
2
+ export { normalizeLocalFields } from "./local-field-policy.js";
3
+ /** Shared transport contract: older snapshots cannot carry portable policy metadata. */
4
+ export declare function validateSnapshotFieldPolicy(snapshot: Pick<Snapshot, "version" | "localFields">): void;
5
+ /** Portable transport images must not carry values declared machine-local. Physical journal images are different. */
6
+ export declare function validatePortableSnapshot(snapshot: Snapshot): void;
7
+ export declare function sameLocalFields(left: unknown, right: unknown): boolean;
8
+ export declare function portableSnapshot(snapshot: Snapshot, fields: string[] | undefined): Snapshot;
9
+ export declare function overlayLocalFields(portable: Snapshot, local: Snapshot, fields: string[] | undefined): Snapshot;