@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,4 @@
1
+ import type { AnySyncConfig } from "../settings/settings-types.js";
2
+ import { type CreatedConflictArtifact } from "./conflict-artifacts.js";
3
+ /** Attempt-owned cleanup only: unknown evidence remains the retention policy's responsibility. */
4
+ export declare function releaseConflictArtifacts(config: AnySyncConfig, statePath: string, created: readonly CreatedConflictArtifact[]): Promise<void>;
@@ -0,0 +1,53 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { syncDirectory } from "../state/json-file.js";
4
+ import { readStateForConfig, statePathForConfig } from "../state/sync-state-store.js";
5
+ import { conflictArtifactFingerprint, conflictDirectory, } from "./conflict-artifacts.js";
6
+ import { readMergeJournal } from "./merge-journal.js";
7
+ /** Attempt-owned cleanup only: unknown evidence remains the retention policy's responsibility. */
8
+ export async function releaseConflictArtifacts(config, statePath, created) {
9
+ if (!created.length || statePathForConfig(config) !== statePath)
10
+ return;
11
+ try {
12
+ const state = await readStateForConfig(config);
13
+ if (statePathForConfig(config) !== statePath)
14
+ return;
15
+ const journal = await readMergeJournal(config);
16
+ if (statePathForConfig(config) !== statePath)
17
+ return;
18
+ const referenced = new Set([
19
+ ...(state.unresolved ?? []).map((group) => group.artifact),
20
+ ...(journal?.progress?.groups ?? []).map((group) => group.artifact),
21
+ ]);
22
+ for (const lease of created) {
23
+ if (referenced.has(lease.token) || lease.target !== path.join(conflictDirectory(config), `${lease.token}.json`))
24
+ continue;
25
+ try {
26
+ const stat = await fs.lstat(lease.target);
27
+ if (!stat.isFile() ||
28
+ stat.nlink !== 1 ||
29
+ stat.dev !== lease.dev ||
30
+ stat.ino !== lease.ino ||
31
+ stat.size !== lease.size)
32
+ continue;
33
+ const artifact = JSON.parse(await fs.readFile(lease.target, "utf8"));
34
+ if (conflictArtifactFingerprint(artifact) !== lease.fingerprint || statePathForConfig(config) !== statePath)
35
+ continue;
36
+ const latest = await fs.lstat(lease.target);
37
+ if (latest.dev !== lease.dev ||
38
+ latest.ino !== lease.ino ||
39
+ latest.nlink !== 1 ||
40
+ statePathForConfig(config) !== statePath)
41
+ continue;
42
+ await fs.unlink(lease.target);
43
+ await syncDirectory(path.dirname(lease.target));
44
+ }
45
+ catch {
46
+ /* Missing, replaced or unreadable evidence is not ours to delete. */
47
+ }
48
+ }
49
+ }
50
+ catch {
51
+ /* Invalid state/journal or unavailable storage cannot prove lack of references. */
52
+ }
53
+ }
@@ -0,0 +1,32 @@
1
+ import type { AnySyncConfig } from "../settings/settings-types.js";
2
+ import type { Snapshot, SnapshotFile } from "../snapshot/snapshot-types.js";
3
+ import type { SyncState } from "../state/state-types.js";
4
+ export { conflictGroups } from "./conflict-groups.js";
5
+ export interface ConflictArtifact {
6
+ version: 1;
7
+ identity: string;
8
+ ancestors?: SnapshotFile[];
9
+ state: SyncState;
10
+ local: Snapshot;
11
+ remote: Snapshot;
12
+ groups: {
13
+ paths: string[];
14
+ reasons: string[];
15
+ }[];
16
+ observed: {
17
+ snapshotId: string;
18
+ revision: string;
19
+ };
20
+ }
21
+ export declare function conflictArtifactFingerprint(artifact: ConflictArtifact): string;
22
+ export declare function conflictDirectory(config: AnySyncConfig): string;
23
+ export interface CreatedConflictArtifact {
24
+ token: string;
25
+ target: string;
26
+ dev: number;
27
+ ino: number;
28
+ size: number;
29
+ fingerprint: string;
30
+ }
31
+ export declare function saveConflictArtifact(config: AnySyncConfig, backend: string, artifact: Omit<ConflictArtifact, "version" | "identity">, validate: () => void, onCreated?: (created: CreatedConflictArtifact) => void): Promise<string>;
32
+ export declare function readConflictArtifact(config: AnySyncConfig, backend: string, token: string): Promise<ConflictArtifact>;
@@ -0,0 +1,158 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import fs from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { syncDirectory, writeJson } from "../state/json-file.js";
5
+ import { statePathForConfig, syncStateFingerprint } from "../state/sync-state-store.js";
6
+ import { planFileMerge } from "./file-merge-planner.js";
7
+ export { conflictGroups } from "./conflict-groups.js";
8
+ import { mergeJournalIdentity } from "./merge-journal.js";
9
+ const LIMIT = 192 * 1024 * 1024;
10
+ export function conflictArtifactFingerprint(artifact) {
11
+ return createHash("sha256").update(JSON.stringify(artifact)).digest("hex");
12
+ }
13
+ export function conflictDirectory(config) {
14
+ return `${statePathForConfig(config)}.conflicts`;
15
+ }
16
+ async function directory(config, create = false) {
17
+ const target = conflictDirectory(config);
18
+ if (create)
19
+ await fs.mkdir(target, { recursive: true, mode: 0o700 });
20
+ const stat = await fs.lstat(target);
21
+ if (!stat.isDirectory() || stat.isSymbolicLink() || (process.platform !== "win32" && (stat.mode & 0o077) !== 0))
22
+ throw new Error("Unsafe private conflict directory.");
23
+ return target;
24
+ }
25
+ function tokenPath(config, token) {
26
+ if (!/^[a-f0-9-]{36}$/u.test(token))
27
+ throw new Error("Invalid conflict token.");
28
+ return path.join(conflictDirectory(config), `${token}.json`);
29
+ }
30
+ export async function saveConflictArtifact(config, backend, artifact, validate, onCreated) {
31
+ validate();
32
+ const identity = mergeJournalIdentity(config, backend);
33
+ const local = Object.fromEntries(artifact.local.files.map((file) => [file.path, file.sha256]));
34
+ const remote = Object.fromEntries(artifact.remote.files.map((file) => [file.path, file.sha256]));
35
+ const fingerprint = createHash("sha256")
36
+ .update(JSON.stringify([
37
+ identity,
38
+ artifact.groups.map((group) => group.paths.map((filePath) => [
39
+ filePath,
40
+ artifact.state.lastFileHashes[filePath] ?? null,
41
+ local[filePath] ?? null,
42
+ remote[filePath] ?? null,
43
+ ])),
44
+ ]))
45
+ .digest("hex")
46
+ .slice(0, 32);
47
+ const token = `${fingerprint.slice(0, 8)}-${fingerprint.slice(8, 12)}-${fingerprint.slice(12, 16)}-${fingerprint.slice(16, 20)}-${fingerprint.slice(20)}`;
48
+ await directory(config, true);
49
+ validate();
50
+ const reuse = async () => {
51
+ const existing = await readConflictArtifact(config, backend, token);
52
+ validate();
53
+ const oldLocal = Object.fromEntries(existing.local.files.map((file) => [file.path, file.sha256]));
54
+ const oldRemote = Object.fromEntries(existing.remote.files.map((file) => [file.path, file.sha256]));
55
+ if (JSON.stringify(existing.groups.map((group) => group.paths)) !==
56
+ JSON.stringify(artifact.groups.map((group) => group.paths)) ||
57
+ artifact.groups.some((group) => group.paths.some((filePath) => existing.state.lastFileHashes[filePath] !== artifact.state.lastFileHashes[filePath] ||
58
+ oldLocal[filePath] !== local[filePath] ||
59
+ oldRemote[filePath] !== remote[filePath])))
60
+ throw new Error("Conflict identity does not match retained immutable evidence.");
61
+ return token;
62
+ };
63
+ const target = tokenPath(config, token);
64
+ try {
65
+ await fs.lstat(target);
66
+ validate();
67
+ return await reuse();
68
+ }
69
+ catch (error) {
70
+ if (error.code !== "ENOENT")
71
+ throw error;
72
+ }
73
+ const temporary = `${target}.${randomUUID()}.pending`;
74
+ const candidate = { version: 1, identity, ...artifact };
75
+ try {
76
+ await writeJson(temporary, candidate, { maxBytes: LIMIT });
77
+ validate();
78
+ const stat = await fs.lstat(temporary);
79
+ validate();
80
+ try {
81
+ // Publish immutable evidence without replacing a concurrent/pre-existing owner.
82
+ await fs.link(temporary, target);
83
+ }
84
+ catch (error) {
85
+ if (error.code !== "EEXIST")
86
+ throw error;
87
+ validate();
88
+ return await reuse();
89
+ }
90
+ // Register ownership before any cancellation or durability await can fail.
91
+ onCreated?.({
92
+ token,
93
+ target,
94
+ dev: stat.dev,
95
+ ino: stat.ino,
96
+ size: stat.size,
97
+ fingerprint: conflictArtifactFingerprint(candidate),
98
+ });
99
+ validate();
100
+ await syncDirectory(path.dirname(target));
101
+ validate();
102
+ await syncDirectory(path.dirname(conflictDirectory(config)));
103
+ validate();
104
+ return token;
105
+ }
106
+ finally {
107
+ await fs.rm(temporary, { force: true });
108
+ }
109
+ }
110
+ export async function readConflictArtifact(config, backend, token) {
111
+ try {
112
+ await directory(config);
113
+ const target = tokenPath(config, token);
114
+ const stat = await fs.lstat(target);
115
+ if (!stat.isFile() || stat.size > LIMIT || (process.platform !== "win32" && (stat.mode & 0o077) !== 0))
116
+ throw new Error("Unsafe conflict artifact.");
117
+ const artifact = JSON.parse(await fs.readFile(target, "utf8"));
118
+ if (artifact.version !== 1 ||
119
+ artifact.identity !== mergeJournalIdentity(config, backend) ||
120
+ !Array.isArray(artifact.groups) ||
121
+ artifact.groups.length > 16_384 ||
122
+ artifact.groups.some((group) => !Array.isArray(group.paths) ||
123
+ !group.paths.length ||
124
+ group.paths.length > 16_384 ||
125
+ !Array.isArray(group.reasons)))
126
+ throw new Error("Invalid conflict artifact.");
127
+ const plan = planFileMerge({
128
+ baseline: artifact.state.lastFileHashes,
129
+ local: artifact.local.files,
130
+ remote: artifact.remote.files,
131
+ selectionCompatible: true,
132
+ });
133
+ if (plan.kind !== "planned")
134
+ throw new Error("Invalid conflict versions.");
135
+ const known = new Set(plan.decisions.map((item) => item.path));
136
+ if (artifact.groups.some((group) => group.paths.some((value) => !known.has(value))))
137
+ throw new Error("Invalid conflict paths.");
138
+ if (artifact.ancestors) {
139
+ if (!Array.isArray(artifact.ancestors) ||
140
+ artifact.ancestors.length > 16_384 ||
141
+ artifact.ancestors.some((file) => artifact.state.lastFileHashes[file.path] !== file.sha256))
142
+ throw new Error("Invalid artifact ancestor.");
143
+ const basePlan = planFileMerge({
144
+ baseline: {},
145
+ local: artifact.ancestors,
146
+ remote: [],
147
+ selectionCompatible: true,
148
+ });
149
+ if (basePlan.kind !== "planned" || basePlan.conflicts.length)
150
+ throw new Error("Invalid ancestor bytes.");
151
+ }
152
+ syncStateFingerprint(artifact.state);
153
+ return artifact;
154
+ }
155
+ catch {
156
+ throw new Error("Cannot verify private conflict artifact; preserve evidence and review a fresh sync.");
157
+ }
158
+ }
@@ -0,0 +1,9 @@
1
+ import type { AnySyncConfig } from "../settings/settings-types.js";
2
+ import { type FileMergePlan } from "./file-merge-planner.js";
3
+ /** Indexed connected closure; path relationships are identical to the conservative merge policy. */
4
+ export declare function conflictGroups(plan: Extract<FileMergePlan, {
5
+ kind: "planned";
6
+ }>, config: AnySyncConfig): {
7
+ reasons: string[];
8
+ paths: string[];
9
+ }[];
@@ -0,0 +1,76 @@
1
+ import { mergePathIdentity } from "./file-merge-planner.js";
2
+ /** Indexed connected closure; path relationships are identical to the conservative merge policy. */
3
+ export function conflictGroups(plan, config) {
4
+ const paths = plan.decisions.map((item) => item.path);
5
+ const parents = paths.map((_, index) => index);
6
+ const ranks = paths.map(() => 0);
7
+ const find = (index) => {
8
+ while (parents[index] !== index) {
9
+ parents[index] = parents[parents[index] ?? index] ?? index;
10
+ index = parents[index] ?? index;
11
+ }
12
+ return index;
13
+ };
14
+ const join = (left, right) => {
15
+ let a = find(left);
16
+ let b = find(right);
17
+ if (a === b)
18
+ return;
19
+ if ((ranks[a] ?? 0) < (ranks[b] ?? 0))
20
+ [a, b] = [b, a];
21
+ parents[b] = a;
22
+ if (ranks[a] === ranks[b])
23
+ ranks[a] = (ranks[a] ?? 0) + 1;
24
+ };
25
+ const identities = paths.map(mergePathIdentity);
26
+ const byIdentity = new Map();
27
+ const byPath = new Map(paths.map((value, index) => [value, index]));
28
+ identities.forEach((value, index) => {
29
+ const previous = byIdentity.get(value);
30
+ if (previous !== undefined)
31
+ join(index, previous);
32
+ else
33
+ byIdentity.set(value, index);
34
+ });
35
+ const includes = new Set(config.include
36
+ .filter((value) => !["settings.json", "AGENTS.md", "sessions"].includes(value))
37
+ .map(mergePathIdentity));
38
+ const buckets = new Map();
39
+ const bucket = (key, index) => {
40
+ const previous = buckets.get(key);
41
+ if (previous === undefined)
42
+ buckets.set(key, index);
43
+ else
44
+ join(index, previous);
45
+ };
46
+ paths.forEach((value, index) => {
47
+ const root = value.split("/")[0] ?? "";
48
+ if (["extensions", "themes", "skills", "prompts"].includes(root))
49
+ bucket(`resource:${root}`, index);
50
+ const segments = (identities[index] ?? "").split("/");
51
+ let ancestor = "";
52
+ for (let length = 0; length < segments.length - 1; length++) {
53
+ ancestor = ancestor ? `${ancestor}/${segments[length]}` : (segments[length] ?? "");
54
+ const parent = byIdentity.get(ancestor);
55
+ if (parent !== undefined)
56
+ join(index, parent);
57
+ if (includes.has(ancestor))
58
+ bucket(`include:${ancestor}`, index);
59
+ }
60
+ });
61
+ const groups = new Map();
62
+ for (const conflict of plan.conflicts) {
63
+ const index = byPath.get(conflict.path);
64
+ if (index === undefined)
65
+ throw new Error("Conflict is missing from managed decisions.");
66
+ const key = find(index);
67
+ const group = groups.get(key) ?? { paths: [], reasons: [] };
68
+ if (!group.reasons.includes(conflict.reason))
69
+ group.reasons.push(conflict.reason);
70
+ groups.set(key, group);
71
+ }
72
+ paths.forEach((value, index) => {
73
+ groups.get(find(index))?.paths.push(value);
74
+ });
75
+ return [...groups.values()].map((group) => ({ ...group, paths: group.paths.sort() }));
76
+ }
@@ -0,0 +1,4 @@
1
+ import type { ConflictArtifact } from "./conflict-artifacts.js";
2
+ export declare const CONFLICT_DISPLAY_BYTES: number;
3
+ /** Index once and refuse a version before decoding if it cannot fit the remaining display budget. */
4
+ export declare function conflictPreview(artifact: ConflictArtifact, paths: readonly string[], destination: string): string;
@@ -0,0 +1,53 @@
1
+ import { safeTerminalText } from "../ui/terminal-text.js";
2
+ export const CONFLICT_DISPLAY_BYTES = 2 * 1024 * 1024;
3
+ const tooLarge = () => new Error("Conflict review exceeds the 2 MiB display bound; inspect private evidence and use a reviewed explicit direction.");
4
+ /** Index once and refuse a version before decoding if it cannot fit the remaining display budget. */
5
+ export function conflictPreview(artifact, paths, destination) {
6
+ const index = (files) => new Map(files.map((file) => [file.path, file]));
7
+ const ancestors = index(artifact.ancestors ?? []);
8
+ const local = index(artifact.local.files);
9
+ const remote = index(artifact.remote.files);
10
+ const parts = [];
11
+ let size = 0;
12
+ const remaining = () => CONFLICT_DISPLAY_BYTES - size - (parts.length ? 1 : 0);
13
+ const append = (value, prefix = "") => {
14
+ if (Buffer.byteLength(value) + Buffer.byteLength(prefix) > remaining())
15
+ throw tooLarge();
16
+ // Sanitize at the display boundary, retaining line endings and raw evidence unchanged.
17
+ parts.push(prefix + value.split("\n").map(safeTerminalText).join("\n"));
18
+ size += Buffer.byteLength(prefix) + Buffer.byteLength(value) + (parts.length > 1 ? 1 : 0);
19
+ };
20
+ const version = (files, filePath) => {
21
+ const file = files.get(filePath);
22
+ if (!file)
23
+ return append("(absent)");
24
+ append(file.sha256, "sha256: ");
25
+ if (Buffer.byteLength(file.contentBase64, "base64") > remaining())
26
+ throw tooLarge();
27
+ const bytes = Buffer.from(file.contentBase64, "base64");
28
+ let value;
29
+ try {
30
+ value = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes);
31
+ }
32
+ catch {
33
+ return append(file.contentBase64, "base64: ");
34
+ }
35
+ append(value);
36
+ };
37
+ append(safeTerminalText(destination), "Storage: ");
38
+ append("Private conflict versions. Historical artifact is not authority for changed bytes/head. No automatic activation.");
39
+ for (const filePath of paths) {
40
+ append(safeTerminalText(filePath), "Path: ");
41
+ append("Base:");
42
+ const hash = artifact.state.lastFileHashes[filePath];
43
+ if (hash && !ancestors.has(filePath))
44
+ append(`(verified ancestor unavailable; sha256: ${hash})`);
45
+ else
46
+ version(ancestors, filePath);
47
+ append("Local:");
48
+ version(local, filePath);
49
+ append("Remote:");
50
+ version(remote, filePath);
51
+ }
52
+ return parts.join("\n");
53
+ }
@@ -0,0 +1,13 @@
1
+ import type { RemoteHead, SyncBackend } from "../backends/sync-backend.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
+ import { type FileMergePlan } from "./file-merge-planner.js";
6
+ export interface ConflictResolution {
7
+ token: string;
8
+ group: number;
9
+ source: "local" | "remote";
10
+ stateIdentity: string;
11
+ artifactIdentity: string;
12
+ }
13
+ export declare function resolveReviewedGroup(config: AnySyncConfig, backend: SyncBackend, state: SyncState, local: Snapshot, remote: Snapshot, head: RemoteHead, plan: FileMergePlan, resolution: ConflictResolution, protectedPaths: ReadonlySet<string>): Promise<FileMergePlan>;
@@ -0,0 +1,53 @@
1
+ import { syncStateFingerprint } from "../state/sync-state-store.js";
2
+ import { conflictArtifactFingerprint, readConflictArtifact } from "./conflict-artifacts.js";
3
+ import { mergePathIdentity, planFileMerge } from "./file-merge-planner.js";
4
+ import { fileHashMap } from "./sync-state.js";
5
+ export async function resolveReviewedGroup(config, backend, state, local, remote, head, plan, resolution, protectedPaths) {
6
+ const artifact = await readConflictArtifact(config, backend.identity, resolution.token);
7
+ const group = artifact.groups[resolution.group];
8
+ if (conflictArtifactFingerprint(artifact) !== resolution.artifactIdentity ||
9
+ !group ||
10
+ plan.kind !== "planned" ||
11
+ !state.unresolved?.some((item) => item.artifact === resolution.token && JSON.stringify(item.paths) === JSON.stringify(group.paths)) ||
12
+ syncStateFingerprint(state) !== resolution.stateIdentity ||
13
+ state.lastObservedSnapshot !== head.snapshotId ||
14
+ !state.lastObservedRevision ||
15
+ !backend.sameRevision(state.lastObservedRevision, head.revision))
16
+ throw new Error("Conflict review is stale; refresh sync and review again.");
17
+ const ours = fileHashMap(local);
18
+ const theirs = fileHashMap(remote);
19
+ const oldOurs = fileHashMap(artifact.local);
20
+ const oldTheirs = fileHashMap(artifact.remote);
21
+ if (group.paths.some((filePath) => ours[filePath] !== oldOurs[filePath] ||
22
+ theirs[filePath] !== oldTheirs[filePath] ||
23
+ state.lastFileHashes[filePath] !== artifact.state.lastFileHashes[filePath]))
24
+ throw new Error("Conflict versions changed; no resolution was applied.");
25
+ if (group.paths.some((filePath) => [...protectedPaths].some((value) => mergePathIdentity(value) === mergePathIdentity(filePath))))
26
+ throw new Error("Current session conflict cannot be resolved from the loaded session; preserve evidence and close Pi.");
27
+ const selected = resolution.source === "local" ? local : remote;
28
+ const paths = new Set(group.paths);
29
+ for (const snapshot of [selected, local]) {
30
+ const layout = planFileMerge({
31
+ baseline: {},
32
+ local: snapshot.files.filter((file) => paths.has(file.path)),
33
+ remote: [],
34
+ selectionCompatible: true,
35
+ });
36
+ if (layout.kind !== "planned" || layout.conflicts.length)
37
+ throw new Error("Selected/current local group still has path collisions; preserve evidence, repair the layout manually and refresh sync.");
38
+ }
39
+ const selectedFiles = new Map(selected.files.map((file) => [file.path, file]));
40
+ const decisions = plan.decisions.map((item) => paths.has(item.path)
41
+ ? {
42
+ kind: "accepted",
43
+ path: item.path,
44
+ source: resolution.source,
45
+ file: selectedFiles.get(item.path),
46
+ }
47
+ : item);
48
+ return {
49
+ kind: "planned",
50
+ decisions,
51
+ conflicts: decisions.filter((item) => item.kind === "conflict"),
52
+ };
53
+ }
@@ -0,0 +1,5 @@
1
+ import type { AnySyncConfig } from "../settings/settings-types.js";
2
+ import type { Snapshot } from "../snapshot/snapshot-types.js";
3
+ import type { SyncState } from "../state/state-types.js";
4
+ /** Only after accepted state and journal retirement, under the operation lock. Unknown/unresolved evidence is never pruned. */
5
+ export declare function pruneCompletedConflicts(config: AnySyncConfig, backend: string, state: SyncState, local: Snapshot, remote: Snapshot, validate: () => void): Promise<void>;
@@ -0,0 +1,61 @@
1
+ import fs from "node:fs/promises";
2
+ import path from "node:path";
3
+ import { syncDirectory } from "../state/json-file.js";
4
+ import { conflictDirectory, readConflictArtifact } from "./conflict-artifacts.js";
5
+ import { fileHashMap } from "./sync-state.js";
6
+ /** Only after accepted state and journal retirement, under the operation lock. Unknown/unresolved evidence is never pruned. */
7
+ export async function pruneCompletedConflicts(config, backend, state, local, remote, validate) {
8
+ validate();
9
+ const directory = conflictDirectory(config);
10
+ let names;
11
+ try {
12
+ const stat = await fs.lstat(directory);
13
+ validate();
14
+ if (!stat.isDirectory() || stat.isSymbolicLink())
15
+ throw new Error("Unsafe conflict retention directory.");
16
+ names = await fs.readdir(directory);
17
+ validate();
18
+ }
19
+ catch (error) {
20
+ if (error.code === "ENOENT")
21
+ return;
22
+ throw error;
23
+ }
24
+ const pinned = new Set(state.unresolved?.map((group) => group.artifact) ?? []);
25
+ const ours = fileHashMap(local);
26
+ const theirs = fileHashMap(remote);
27
+ const completed = [];
28
+ for (const name of names) {
29
+ validate();
30
+ const token = name.replace(/\.json$/u, "");
31
+ if (!/^[a-f0-9-]{36}\.json$/u.test(name) || pinned.has(token))
32
+ continue;
33
+ try {
34
+ const artifact = await readConflictArtifact(config, backend, token);
35
+ validate();
36
+ const originalLocal = fileHashMap(artifact.local);
37
+ const originalRemote = fileHashMap(artifact.remote);
38
+ if (!artifact.groups.every((group) => group.paths.every((filePath) => state.lastFileHashes[filePath] === ours[filePath] &&
39
+ ours[filePath] === theirs[filePath] &&
40
+ (ours[filePath] === originalLocal[filePath] || ours[filePath] === originalRemote[filePath]))))
41
+ continue;
42
+ const stat = await fs.lstat(path.join(directory, name));
43
+ validate();
44
+ if (stat.isFile())
45
+ completed.push({ token, modified: stat.mtimeMs });
46
+ }
47
+ catch {
48
+ validate(); /* Corrupt/unknown evidence remains. */
49
+ }
50
+ }
51
+ completed.sort((left, right) => right.modified - left.modified || left.token.localeCompare(right.token));
52
+ for (const entry of completed.slice(32)) {
53
+ validate();
54
+ await fs.rm(path.join(directory, `${entry.token}.json`));
55
+ validate();
56
+ }
57
+ if (completed.length > 32) {
58
+ await syncDirectory(directory);
59
+ validate();
60
+ }
61
+ }
@@ -0,0 +1,4 @@
1
+ import { type SyncBackendFactory } from "../backends/backend-factory.js";
2
+ import type { CommandOptions } from "../commands/command-types.js";
3
+ import type { EngineContext as ExtensionContext } from "../host.js";
4
+ export declare function showConflicts(ctx: ExtensionContext, options: CommandOptions, factory?: SyncBackendFactory): Promise<void>;
@@ -0,0 +1,73 @@
1
+ import { truncateToWidth } from "@earendil-works/pi-tui";
2
+ import { createSyncBackend } from "../backends/backend-factory.js";
3
+ import { loadConfig, syncCheckConfigFingerprint } from "../settings/config.js";
4
+ import { readStateForConfig, syncStateFingerprint } from "../state/sync-state-store.js";
5
+ import { confirmMergeReview } from "../ui/merge-review.js";
6
+ import { safeTerminalText } from "../ui/terminal-text.js";
7
+ import { conflictArtifactFingerprint, readConflictArtifact } from "./conflict-artifacts.js";
8
+ import { conflictPreview } from "./conflict-preview.js";
9
+ import { mergeSync } from "./merged-sync.js";
10
+ import { captureMutationOwner } from "./sync-local.js";
11
+ export async function showConflicts(ctx, options, factory = createSyncBackend) {
12
+ const validate = captureMutationOwner(ctx, options.signal);
13
+ const config = await loadConfig(options.setup);
14
+ validate();
15
+ const state = await readStateForConfig(config);
16
+ validate();
17
+ if (!state.unresolved?.length) {
18
+ ctx.ui.notify("No recorded unresolved conflict groups.", "info");
19
+ return;
20
+ }
21
+ if (!ctx.hasUI) {
22
+ ctx.ui.notify(`${state.unresolved.length} conflict groups remain unresolved. Review with TUI/RPC; no transfer performed.`, "warning");
23
+ return;
24
+ }
25
+ const backend = await factory(config);
26
+ validate();
27
+ const labels = state.unresolved.map((group, index) => `${index + 1}: ${group.paths.length} paths · ${group.paths
28
+ .slice(0, 3)
29
+ .map((value) => truncateToWidth(safeTerminalText(value), 80))
30
+ .join(", ")}${group.paths.length > 3 ? ", …" : ""}`);
31
+ const choice = await ctx.ui.select("Review unresolved dependency group", [...labels, "Keep all unresolved"], {
32
+ signal: options.signal,
33
+ });
34
+ validate();
35
+ const index = labels.indexOf(choice ?? "");
36
+ if (index < 0)
37
+ return;
38
+ const reference = state.unresolved[index];
39
+ if (!reference)
40
+ return;
41
+ const artifact = await readConflictArtifact(config, backend.identity, reference.artifact);
42
+ validate();
43
+ const groupIndex = artifact.groups.findIndex((group) => JSON.stringify(group.paths) === JSON.stringify(reference.paths));
44
+ if (groupIndex < 0)
45
+ throw new Error("Conflict reference is stale; refresh sync.");
46
+ const body = conflictPreview(artifact, reference.paths, backend.destination);
47
+ if (!(await confirmMergeReview(ctx, "Review private conflict versions", body, options.signal, () => {
48
+ try {
49
+ validate();
50
+ return true;
51
+ }
52
+ catch {
53
+ return false;
54
+ }
55
+ }, "Continue to resolution choices")))
56
+ return;
57
+ validate();
58
+ const decision = await ctx.ui.select("Resolve the entire reviewed group", ["Keep unresolved", "Use local group", "Use remote group"], { signal: options.signal });
59
+ validate();
60
+ if (decision !== "Use local group" && decision !== "Use remote group")
61
+ return;
62
+ if (syncCheckConfigFingerprint(config) !== syncCheckConfigFingerprint(await loadConfig(options.setup)))
63
+ throw new Error("Settings changed during conflict review.");
64
+ validate();
65
+ await mergeSync(ctx, { ...options, yes: false, auto: false }, factory, {
66
+ token: reference.artifact,
67
+ group: groupIndex,
68
+ source: decision === "Use local group" ? "local" : "remote",
69
+ stateIdentity: syncStateFingerprint(state),
70
+ artifactIdentity: conflictArtifactFingerprint(artifact),
71
+ });
72
+ validate();
73
+ }
@@ -0,0 +1,10 @@
1
+ import type { AnySyncConfig } from "../settings/settings-types.js";
2
+ import type { Snapshot, SnapshotFile } from "../snapshot/snapshot-types.js";
3
+ import type { SyncState } from "../state/state-types.js";
4
+ import { type FileMergePlan } from "./file-merge-planner.js";
5
+ import { type TextMergeBudget } from "./text-merge.js";
6
+ export declare function snapshotFile(filePath: string, bytes: Buffer): SnapshotFile;
7
+ export declare function resolveContentConflicts(config: AnySyncConfig, state: SyncState, local: Snapshot, remote: Snapshot, plan: FileMergePlan, protectedPaths: ReadonlySet<string>, options?: {
8
+ textBudget?: TextMergeBudget;
9
+ signal?: AbortSignal;
10
+ }): Promise<FileMergePlan>;