@indigoai-us/hq-cloud 6.15.0 → 6.15.2

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 (329) hide show
  1. package/dist/bin/sync-mutation.d.ts +16 -0
  2. package/dist/bin/sync-mutation.d.ts.map +1 -0
  3. package/dist/bin/sync-mutation.js +60 -0
  4. package/dist/bin/sync-mutation.js.map +1 -0
  5. package/dist/bin/sync-mutation.test.d.ts +2 -0
  6. package/dist/bin/sync-mutation.test.d.ts.map +1 -0
  7. package/dist/bin/sync-mutation.test.js +165 -0
  8. package/dist/bin/sync-mutation.test.js.map +1 -0
  9. package/dist/bin/sync-runner-company.d.ts +8 -0
  10. package/dist/bin/sync-runner-company.d.ts.map +1 -1
  11. package/dist/bin/sync-runner-company.js +16 -0
  12. package/dist/bin/sync-runner-company.js.map +1 -1
  13. package/dist/bin/sync-runner-company.test.d.ts +2 -0
  14. package/dist/bin/sync-runner-company.test.d.ts.map +1 -0
  15. package/dist/bin/sync-runner-company.test.js +36 -0
  16. package/dist/bin/sync-runner-company.test.js.map +1 -0
  17. package/dist/bin/sync-runner-watch-loop.d.ts.map +1 -1
  18. package/dist/bin/sync-runner-watch-loop.js +98 -8
  19. package/dist/bin/sync-runner-watch-loop.js.map +1 -1
  20. package/dist/bin/sync-runner.d.ts +17 -0
  21. package/dist/bin/sync-runner.d.ts.map +1 -1
  22. package/dist/bin/sync-runner.js.map +1 -1
  23. package/dist/bin/sync-runner.test.js +109 -0
  24. package/dist/bin/sync-runner.test.js.map +1 -1
  25. package/dist/cli/conflict-recovery.test.d.ts +2 -0
  26. package/dist/cli/conflict-recovery.test.d.ts.map +1 -0
  27. package/dist/cli/conflict-recovery.test.js +201 -0
  28. package/dist/cli/conflict-recovery.test.js.map +1 -0
  29. package/dist/cli/conflict.d.ts +60 -0
  30. package/dist/cli/conflict.d.ts.map +1 -1
  31. package/dist/cli/conflict.js +333 -0
  32. package/dist/cli/conflict.js.map +1 -1
  33. package/dist/cli/sync.d.ts +35 -0
  34. package/dist/cli/sync.d.ts.map +1 -1
  35. package/dist/cli/sync.js +100 -0
  36. package/dist/cli/sync.js.map +1 -1
  37. package/dist/cli/sync.test.js +85 -1
  38. package/dist/cli/sync.test.js.map +1 -1
  39. package/dist/index.d.ts +2 -0
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +1 -0
  42. package/dist/index.js.map +1 -1
  43. package/dist/skill-telemetry.d.ts +6 -0
  44. package/dist/skill-telemetry.d.ts.map +1 -1
  45. package/dist/skill-telemetry.js +14 -2
  46. package/dist/skill-telemetry.js.map +1 -1
  47. package/dist/skill-telemetry.test.js +79 -0
  48. package/dist/skill-telemetry.test.js.map +1 -1
  49. package/dist/sync/candidate-uploader.d.ts +88 -0
  50. package/dist/sync/candidate-uploader.d.ts.map +1 -0
  51. package/dist/sync/candidate-uploader.js +212 -0
  52. package/dist/sync/candidate-uploader.js.map +1 -0
  53. package/dist/sync/candidate-uploader.test.d.ts +2 -0
  54. package/dist/sync/candidate-uploader.test.d.ts.map +1 -0
  55. package/dist/sync/candidate-uploader.test.js +132 -0
  56. package/dist/sync/candidate-uploader.test.js.map +1 -0
  57. package/dist/sync/delta-client.d.ts +73 -0
  58. package/dist/sync/delta-client.d.ts.map +1 -0
  59. package/dist/sync/delta-client.js +201 -0
  60. package/dist/sync/delta-client.js.map +1 -0
  61. package/dist/sync/delta-client.test.d.ts +2 -0
  62. package/dist/sync/delta-client.test.d.ts.map +1 -0
  63. package/dist/sync/delta-client.test.js +97 -0
  64. package/dist/sync/delta-client.test.js.map +1 -0
  65. package/dist/sync/durable-apply.d.ts +76 -0
  66. package/dist/sync/durable-apply.d.ts.map +1 -0
  67. package/dist/sync/durable-apply.js +530 -0
  68. package/dist/sync/durable-apply.js.map +1 -0
  69. package/dist/sync/durable-apply.test.d.ts +2 -0
  70. package/dist/sync/durable-apply.test.d.ts.map +1 -0
  71. package/dist/sync/durable-apply.test.js +180 -0
  72. package/dist/sync/durable-apply.test.js.map +1 -0
  73. package/dist/sync/event-sync.d.ts +33 -1
  74. package/dist/sync/event-sync.d.ts.map +1 -1
  75. package/dist/sync/event-sync.js +149 -1
  76. package/dist/sync/event-sync.js.map +1 -1
  77. package/dist/sync/event-sync.test.js +142 -1
  78. package/dist/sync/event-sync.test.js.map +1 -1
  79. package/dist/sync/index.d.ts +2 -0
  80. package/dist/sync/index.d.ts.map +1 -1
  81. package/dist/sync/index.js +1 -0
  82. package/dist/sync/index.js.map +1 -1
  83. package/dist/sync/multipart-uploader.d.ts +99 -0
  84. package/dist/sync/multipart-uploader.d.ts.map +1 -0
  85. package/dist/sync/multipart-uploader.js +447 -0
  86. package/dist/sync/multipart-uploader.js.map +1 -0
  87. package/dist/sync/multipart-uploader.test.d.ts +2 -0
  88. package/dist/sync/multipart-uploader.test.d.ts.map +1 -0
  89. package/dist/sync/multipart-uploader.test.js +119 -0
  90. package/dist/sync/multipart-uploader.test.js.map +1 -0
  91. package/dist/sync/mutation-client.d.ts +85 -0
  92. package/dist/sync/mutation-client.d.ts.map +1 -0
  93. package/dist/sync/mutation-client.js +245 -0
  94. package/dist/sync/mutation-client.js.map +1 -0
  95. package/dist/sync/mutation-client.test.d.ts +2 -0
  96. package/dist/sync/mutation-client.test.d.ts.map +1 -0
  97. package/dist/sync/mutation-client.test.js +51 -0
  98. package/dist/sync/mutation-client.test.js.map +1 -0
  99. package/dist/sync/push-receiver.d.ts +45 -0
  100. package/dist/sync/push-receiver.d.ts.map +1 -1
  101. package/dist/sync/push-receiver.js +101 -0
  102. package/dist/sync/push-receiver.js.map +1 -1
  103. package/dist/sync/push-receiver.test.js +54 -2
  104. package/dist/sync/push-receiver.test.js.map +1 -1
  105. package/dist/sync/scope-inventory-client.d.ts +69 -0
  106. package/dist/sync/scope-inventory-client.d.ts.map +1 -0
  107. package/dist/sync/scope-inventory-client.js +210 -0
  108. package/dist/sync/scope-inventory-client.js.map +1 -0
  109. package/dist/sync/scope-inventory-client.test.d.ts +2 -0
  110. package/dist/sync/scope-inventory-client.test.d.ts.map +1 -0
  111. package/dist/sync/scope-inventory-client.test.js +94 -0
  112. package/dist/sync/scope-inventory-client.test.js.map +1 -0
  113. package/dist/sync/snapshot-client.d.ts +98 -0
  114. package/dist/sync/snapshot-client.d.ts.map +1 -0
  115. package/dist/sync/snapshot-client.js +402 -0
  116. package/dist/sync/snapshot-client.js.map +1 -0
  117. package/dist/sync/snapshot-client.test.d.ts +2 -0
  118. package/dist/sync/snapshot-client.test.d.ts.map +1 -0
  119. package/dist/sync/snapshot-client.test.js +169 -0
  120. package/dist/sync/snapshot-client.test.js.map +1 -0
  121. package/dist/sync/uploader-finalization.d.ts +97 -0
  122. package/dist/sync/uploader-finalization.d.ts.map +1 -0
  123. package/dist/sync/uploader-finalization.js +273 -0
  124. package/dist/sync/uploader-finalization.js.map +1 -0
  125. package/dist/sync/uploader-finalization.test.d.ts +2 -0
  126. package/dist/sync/uploader-finalization.test.d.ts.map +1 -0
  127. package/dist/sync/uploader-finalization.test.js +92 -0
  128. package/dist/sync/uploader-finalization.test.js.map +1 -0
  129. package/dist/telemetry.d.ts +11 -1
  130. package/dist/telemetry.d.ts.map +1 -1
  131. package/dist/telemetry.js +21 -2
  132. package/dist/telemetry.js.map +1 -1
  133. package/dist/telemetry.test.js +80 -0
  134. package/dist/telemetry.test.js.map +1 -1
  135. package/package.json +6 -1
  136. package/.claude/policies/hq-cloud-esm-cannot-spy-fs-builtins.md +0 -30
  137. package/.claude/policies/hq-cloud-strip-types-no-parameter-properties.md +0 -22
  138. package/.github/workflows/ci.yml +0 -84
  139. package/.github/workflows/publish.yml +0 -56
  140. package/.github/workflows/unreleased-commits-nag.yml +0 -256
  141. package/eslint.config.js +0 -67
  142. package/pnpm-workspace.yaml +0 -2
  143. package/scripts/presign-transport-e2e.mjs +0 -250
  144. package/scripts/vault-rebaseline.sh +0 -323
  145. package/scripts/vault-rescue.sh +0 -332
  146. package/src/active-company.test.ts +0 -188
  147. package/src/active-company.ts +0 -168
  148. package/src/agent-codex-instructions.test.ts +0 -332
  149. package/src/agent-codex-instructions.ts +0 -309
  150. package/src/auth.ts +0 -146
  151. package/src/backup-prune.test.ts +0 -98
  152. package/src/backup-prune.ts +0 -182
  153. package/src/bin/backup-prune-runner.ts +0 -33
  154. package/src/bin/rescue-runner.ts +0 -25
  155. package/src/bin/sync-runner-company.ts +0 -695
  156. package/src/bin/sync-runner-events.test.ts +0 -143
  157. package/src/bin/sync-runner-events.ts +0 -55
  158. package/src/bin/sync-runner-planning.test.ts +0 -311
  159. package/src/bin/sync-runner-planning.ts +0 -258
  160. package/src/bin/sync-runner-rollup.test.ts +0 -37
  161. package/src/bin/sync-runner-rollup.ts +0 -97
  162. package/src/bin/sync-runner-telemetry.ts +0 -15
  163. package/src/bin/sync-runner-watch-loop.ts +0 -1235
  164. package/src/bin/sync-runner-watch-routes.test.ts +0 -71
  165. package/src/bin/sync-runner-watch-routes.ts +0 -184
  166. package/src/bin/sync-runner.test.ts +0 -8767
  167. package/src/bin/sync-runner.ts +0 -2190
  168. package/src/cli/accept.ts +0 -124
  169. package/src/cli/conflict.ts +0 -119
  170. package/src/cli/doctor.test.ts +0 -581
  171. package/src/cli/doctor.ts +0 -642
  172. package/src/cli/index.ts +0 -49
  173. package/src/cli/invite.test.ts +0 -250
  174. package/src/cli/invite.ts +0 -214
  175. package/src/cli/promote.ts +0 -157
  176. package/src/cli/reindex-knowledge.test.ts +0 -307
  177. package/src/cli/reindex-knowledge.ts +0 -450
  178. package/src/cli/reindex.test.ts +0 -957
  179. package/src/cli/reindex.ts +0 -979
  180. package/src/cli/rescue-classify-ordering.test.ts +0 -548
  181. package/src/cli/rescue-clone-diagnostics.test.ts +0 -120
  182. package/src/cli/rescue-core.ts +0 -3011
  183. package/src/cli/rescue-drift-reconcile.test.ts +0 -179
  184. package/src/cli/rescue-drop-dir-symlink.test.ts +0 -224
  185. package/src/cli/rescue-exec-bit-preserve.test.ts +0 -187
  186. package/src/cli/rescue-hq-root-guard.test.ts +0 -232
  187. package/src/cli/rescue-journal-reconcile.test.ts +0 -215
  188. package/src/cli/rescue-mtime-preserve.test.ts +0 -203
  189. package/src/cli/rescue-settings-reconcile.test.ts +0 -637
  190. package/src/cli/rescue-snapshot.test.ts +0 -57
  191. package/src/cli/rescue-snapshot.ts +0 -51
  192. package/src/cli/rescue.reindex.test.ts +0 -63
  193. package/src/cli/rescue.test.ts +0 -131
  194. package/src/cli/rescue.ts +0 -182
  195. package/src/cli/share.test.ts +0 -7843
  196. package/src/cli/share.ts +0 -3663
  197. package/src/cli/sync-scope.test.ts +0 -652
  198. package/src/cli/sync.test.ts +0 -5207
  199. package/src/cli/sync.ts +0 -3470
  200. package/src/cli/tombstones.ts +0 -106
  201. package/src/cli/watch-event-push-conflict.test.ts +0 -234
  202. package/src/client-info.test.ts +0 -214
  203. package/src/client-info.ts +0 -121
  204. package/src/cognito-auth.test.ts +0 -712
  205. package/src/cognito-auth.ts +0 -1422
  206. package/src/company-resolver.test.ts +0 -618
  207. package/src/company-resolver.ts +0 -521
  208. package/src/context.test.ts +0 -583
  209. package/src/context.ts +0 -378
  210. package/src/daemon-worker.ts +0 -26
  211. package/src/daemon.ts +0 -99
  212. package/src/entity-resolver.test.ts +0 -315
  213. package/src/entity-resolver.ts +0 -180
  214. package/src/ignore.test.ts +0 -466
  215. package/src/ignore.ts +0 -469
  216. package/src/index.ts +0 -439
  217. package/src/journal.test.ts +0 -968
  218. package/src/journal.ts +0 -765
  219. package/src/lib/cloud-authoritative.test.ts +0 -45
  220. package/src/lib/cloud-authoritative.ts +0 -59
  221. package/src/lib/conflict-file.ts +0 -86
  222. package/src/lib/conflict-index.ts +0 -289
  223. package/src/lib/conflict.test.ts +0 -348
  224. package/src/lib/describe-error.test.ts +0 -100
  225. package/src/lib/describe-error.ts +0 -58
  226. package/src/lib/exit-codes.ts +0 -24
  227. package/src/lib/machine-id.test.ts +0 -231
  228. package/src/lib/machine-id.ts +0 -175
  229. package/src/lib/net-errors.test.ts +0 -65
  230. package/src/lib/net-errors.ts +0 -86
  231. package/src/lib/readlink-safe.test.ts +0 -43
  232. package/src/lib/readlink-safe.ts +0 -29
  233. package/src/local-path-codec.test.ts +0 -138
  234. package/src/local-path-codec.ts +0 -161
  235. package/src/machine-auth.test.ts +0 -1323
  236. package/src/manifest-reconcile.test.ts +0 -1123
  237. package/src/manifest-reconcile.ts +0 -518
  238. package/src/object-io.test.ts +0 -1221
  239. package/src/object-io.ts +0 -1306
  240. package/src/operation-lock.test.ts +0 -484
  241. package/src/operation-lock.ts +0 -680
  242. package/src/outcome-telemetry.test.ts +0 -498
  243. package/src/outcome-telemetry.ts +0 -639
  244. package/src/personal-vault-exclusions.test.ts +0 -308
  245. package/src/personal-vault-exclusions.ts +0 -354
  246. package/src/personal-vault.test.ts +0 -756
  247. package/src/personal-vault.ts +0 -496
  248. package/src/prefix-coalesce.test.ts +0 -240
  249. package/src/prefix-coalesce.ts +0 -273
  250. package/src/public-surface.test.ts +0 -117
  251. package/src/qmd-reindex.test.ts +0 -877
  252. package/src/qmd-reindex.ts +0 -842
  253. package/src/read-only-state-dir.test.ts +0 -188
  254. package/src/remote-pull.test.ts +0 -1130
  255. package/src/remote-pull.ts +0 -618
  256. package/src/s3.symlink-materialize.test.ts +0 -492
  257. package/src/s3.test.ts +0 -1789
  258. package/src/s3.ts +0 -1532
  259. package/src/schemas/signal-types.test.ts +0 -82
  260. package/src/schemas/signal-types.ts +0 -38
  261. package/src/schemas/source-channels.test.ts +0 -82
  262. package/src/schemas/source-channels.ts +0 -53
  263. package/src/scope-shrink.test.ts +0 -633
  264. package/src/scope-shrink.ts +0 -481
  265. package/src/signals/get.test.ts +0 -310
  266. package/src/signals/get.ts +0 -75
  267. package/src/signals/internals.ts +0 -195
  268. package/src/signals/list.test.ts +0 -420
  269. package/src/signals/list.ts +0 -79
  270. package/src/signals/parse.ts +0 -8
  271. package/src/signals/types.ts +0 -91
  272. package/src/skill-telemetry.test.ts +0 -1825
  273. package/src/skill-telemetry.ts +0 -1439
  274. package/src/sources/get.test.ts +0 -293
  275. package/src/sources/get.ts +0 -66
  276. package/src/sources/internals.ts +0 -198
  277. package/src/sources/list.test.ts +0 -402
  278. package/src/sources/list.ts +0 -84
  279. package/src/sources/parse.ts +0 -43
  280. package/src/sources/types.ts +0 -84
  281. package/src/sync/event-sync.test.ts +0 -594
  282. package/src/sync/event-sync.ts +0 -545
  283. package/src/sync/feature-flags.test.ts +0 -378
  284. package/src/sync/feature-flags.ts +0 -62
  285. package/src/sync/index.ts +0 -76
  286. package/src/sync/lease-client.test.ts +0 -128
  287. package/src/sync/lease-client.ts +0 -207
  288. package/src/sync/logger.test.ts +0 -242
  289. package/src/sync/logger.ts +0 -79
  290. package/src/sync/metrics.test.ts +0 -462
  291. package/src/sync/metrics.ts +0 -213
  292. package/src/sync/pull-scope.ts +0 -265
  293. package/src/sync/push-event.test.ts +0 -266
  294. package/src/sync/push-event.ts +0 -224
  295. package/src/sync/push-receiver.test.ts +0 -566
  296. package/src/sync/push-receiver.ts +0 -1048
  297. package/src/sync/push-transport.ts +0 -231
  298. package/src/sync/realtime-rollout.test.ts +0 -86
  299. package/src/sync/realtime-rollout.ts +0 -262
  300. package/src/sync/state-store.test.ts +0 -194
  301. package/src/sync/state-store.ts +0 -727
  302. package/src/sync-core.ts +0 -58
  303. package/src/sync-progress.test.ts +0 -94
  304. package/src/sync-progress.ts +0 -140
  305. package/src/telemetry-events.test.ts +0 -88
  306. package/src/telemetry-events.ts +0 -205
  307. package/src/telemetry.test.ts +0 -1280
  308. package/src/telemetry.ts +0 -1109
  309. package/src/types.ts +0 -314
  310. package/src/vault-client.test.ts +0 -1380
  311. package/src/vault-client.ts +0 -1694
  312. package/src/version.ts +0 -24
  313. package/src/watch-roots.test.ts +0 -278
  314. package/src/watch-roots.ts +0 -162
  315. package/src/watcher-event-gate.test.ts +0 -212
  316. package/src/watcher.test.ts +0 -1079
  317. package/src/watcher.ts +0 -1741
  318. package/test/e2e/sync/cross-tenant-isolation.test.ts +0 -630
  319. package/test/e2e/sync/skill-telemetry-oversized-transcript.test.ts +0 -124
  320. package/test/e2e/sync/transient-company-leg.test.ts +0 -384
  321. package/test/e2e/sync/windows-unreadable-link-leg.test.ts +0 -191
  322. package/test/e2e/watcher-real-chokidar.test.ts +0 -165
  323. package/test/e2e/watcher-recursive-backend.test.ts +0 -181
  324. package/test/e2e/watcher-scoped-coverage.test.ts +0 -381
  325. package/test/invite-flow.integration.test.ts +0 -244
  326. package/test/joiner-manifest-reconcile.integration.test.ts +0 -322
  327. package/test/share-sync.integration.test.ts +0 -213
  328. package/tsconfig.json +0 -19
  329. package/vitest.config.ts +0 -22
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=conflict-recovery.test.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conflict-recovery.test.d.ts","sourceRoot":"","sources":["../../src/cli/conflict-recovery.test.ts"],"names":[],"mappings":""}
@@ -0,0 +1,201 @@
1
+ import { createHash } from "node:crypto";
2
+ import * as fs from "node:fs";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ import { afterEach, describe, expect, it, vi } from "vitest";
6
+ import { preserveRealtimeConflict, realtimeConflictSiblingPath, } from "./conflict.js";
7
+ const directories = [];
8
+ afterEach(() => {
9
+ for (const directory of directories.splice(0)) {
10
+ fs.rmSync(directory, { recursive: true, force: true });
11
+ }
12
+ });
13
+ function root() {
14
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), "hq-u55-conflict-"));
15
+ directories.push(directory);
16
+ return directory;
17
+ }
18
+ function digest(bytes) {
19
+ return `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
20
+ }
21
+ function authorization() {
22
+ return {
23
+ bearer: "bearer",
24
+ deviceId: "device-a",
25
+ capabilityVector: { hqCloud: "1.0.0", hqDesktop: "1.0.0", protocol: 2, journal: 3, durableApply: 1 },
26
+ lease: { lease: "lease", issuedAt: "2030-01-01T00:00:00.000Z", expiresAt: "2030-01-01T00:01:00.000Z", authorizationEpoch: "epoch-1" },
27
+ };
28
+ }
29
+ function ackFetch(status, duringAck) {
30
+ return vi.fn(async () => {
31
+ duringAck?.();
32
+ return {
33
+ ok: status >= 200 && status < 300,
34
+ status,
35
+ headers: { get: () => null },
36
+ body: null,
37
+ text: async () => "ack response",
38
+ };
39
+ });
40
+ }
41
+ describe("realtime conflict sibling vectors", () => {
42
+ it("uses NFC plus the protocol's lower-case RFC4648 suffix golden", () => {
43
+ expect(realtimeConflictSiblingPath({
44
+ scopeUid: "prs_demo",
45
+ canonicalPath: "notes/cafe\u0301.md",
46
+ attemptId: "attempt-01",
47
+ })).toBe("notes/café.conflict-gh3wpjyej2j7lqaz3bo5xfgsbu.md");
48
+ });
49
+ it("keeps leading-dot and trailing-dot filenames extensionless", () => {
50
+ expect(realtimeConflictSiblingPath({ scopeUid: "prs_demo", canonicalPath: ".env", attemptId: "attempt-01" }))
51
+ .toBe(".env.conflict-ctwymj4ik6slm4yebxhtmykqjg");
52
+ expect(realtimeConflictSiblingPath({ scopeUid: "prs_demo", canonicalPath: "report.", attemptId: "attempt-01" }))
53
+ .toBe("report..conflict-7bkmwiyxxbpvkbnplv6vplbkue");
54
+ });
55
+ it("truncates only at a complete UTF-8 code point and preserves the extension", () => {
56
+ const sibling = realtimeConflictSiblingPath({
57
+ scopeUid: "prs_demo",
58
+ canonicalPath: `${"😀".repeat(54)}.md`,
59
+ attemptId: "attempt-01",
60
+ });
61
+ const component = sibling.split("/").at(-1);
62
+ expect(Buffer.byteLength(component, "utf8")).toBe(255);
63
+ expect(component).toMatch(/\.conflict-[a-z2-7]{26}\.md$/);
64
+ expect(component.startsWith("😀")).toBe(true);
65
+ expect(component.includes("\ufffd")).toBe(false);
66
+ });
67
+ });
68
+ describe("creator-candidate conflict recovery", () => {
69
+ it("preserves exact fsynced spool bytes before sending conflict-sibling acknowledgement", async () => {
70
+ const directory = root();
71
+ const bytes = Buffer.from([0, 255, 1, 2, 3]);
72
+ const expectedSha256 = digest(bytes);
73
+ const spool = path.join(directory, "attempt.spool");
74
+ fs.writeFileSync(spool, bytes);
75
+ const expectedSibling = realtimeConflictSiblingPath({ scopeUid: "prs_demo", canonicalPath: "notes/lost.bin", attemptId: "attempt-01" });
76
+ const order = [];
77
+ const fetchImpl = ackFetch(204, () => {
78
+ expect(order).toEqual(["recorded"]);
79
+ expect(fs.readFileSync(path.join(directory, expectedSibling))).toEqual(bytes);
80
+ });
81
+ const result = await preserveRealtimeConflict({
82
+ root: directory,
83
+ scopeUid: "prs_demo",
84
+ canonicalPath: "notes/lost.bin",
85
+ attemptId: "attempt-01",
86
+ expectedSha256,
87
+ expectedSize: bytes.byteLength,
88
+ spoolPath: spool,
89
+ caseInsensitiveFilesystem: false,
90
+ recordConflictPreserved: async () => { order.push("recorded"); },
91
+ creatorCandidate: { apiUrl: "https://sync.example.test", authorization: authorization(), fetchImpl },
92
+ });
93
+ expect(result.source).toBe("local-attempt-spool");
94
+ expect(fs.readFileSync(path.join(directory, result.siblingPath))).toEqual(bytes);
95
+ expect(fetchImpl).toHaveBeenCalledWith("https://sync.example.test/v2/sync/mutations/attempt-01/candidate-ack", expect.objectContaining({
96
+ method: "POST",
97
+ body: JSON.stringify({ evidence: { kind: "conflict-sibling", sha256: expectedSha256 } }),
98
+ }));
99
+ });
100
+ it("recovers exact bytes from the creator-only exact candidate when the spool is absent", async () => {
101
+ const directory = root();
102
+ const bytes = Buffer.from("candidate-only bytes\u0000", "utf8");
103
+ const expectedSha256 = digest(bytes);
104
+ const candidateReader = {
105
+ openCandidate: vi.fn(async () => ({
106
+ url: "https://s3.example.test/exact-version",
107
+ expiresAt: "2030-01-01T00:01:00.000Z",
108
+ versionId: "candidate-v7",
109
+ sha256: expectedSha256,
110
+ size: bytes.byteLength,
111
+ body: (async function* () { yield bytes; })(),
112
+ })),
113
+ };
114
+ const fetchImpl = ackFetch(204);
115
+ const result = await preserveRealtimeConflict({
116
+ root: directory,
117
+ scopeUid: "prs_demo",
118
+ canonicalPath: "notes/lost.bin",
119
+ attemptId: "attempt-02",
120
+ expectedSha256,
121
+ expectedSize: bytes.byteLength,
122
+ spoolPath: path.join(directory, "missing.spool"),
123
+ caseInsensitiveFilesystem: false,
124
+ recordConflictPreserved: async () => undefined,
125
+ creatorCandidate: {
126
+ apiUrl: "https://sync.example.test",
127
+ authorization: authorization(),
128
+ fetchImpl,
129
+ candidateReader,
130
+ },
131
+ });
132
+ expect(result.source).toBe("creator-candidate");
133
+ expect(candidateReader.openCandidate).toHaveBeenCalledTimes(1);
134
+ expect(fs.readFileSync(path.join(directory, result.siblingPath))).toEqual(bytes);
135
+ });
136
+ it("refuses a case-fold collision without acknowledging or overwriting either path", async () => {
137
+ const directory = root();
138
+ fs.mkdirSync(path.join(directory, "Notes"));
139
+ const bytes = Buffer.from("losing bytes");
140
+ const fetchImpl = ackFetch(204);
141
+ await expect(preserveRealtimeConflict({
142
+ root: directory,
143
+ scopeUid: "prs_demo",
144
+ canonicalPath: "notes/lost.txt",
145
+ attemptId: "attempt-03",
146
+ expectedSha256: digest(bytes),
147
+ expectedSize: bytes.byteLength,
148
+ spoolPath: (() => { const spool = path.join(directory, "attempt.spool"); fs.writeFileSync(spool, bytes); return spool; })(),
149
+ caseInsensitiveFilesystem: true,
150
+ recordConflictPreserved: async () => undefined,
151
+ creatorCandidate: { apiUrl: "https://sync.example.test", authorization: authorization(), fetchImpl },
152
+ })).rejects.toMatchObject({ code: "CASE_COLLISION" });
153
+ expect(fs.existsSync(path.join(directory, "Notes"))).toBe(true);
154
+ expect(fetchImpl).not.toHaveBeenCalled();
155
+ });
156
+ it("retains the durable sibling when acknowledgement fails, so candidate cleanup remains blocked", async () => {
157
+ const directory = root();
158
+ const bytes = Buffer.from("must survive failed acknowledgement");
159
+ const expectedSha256 = digest(bytes);
160
+ const spool = path.join(directory, "attempt.spool");
161
+ fs.writeFileSync(spool, bytes);
162
+ const sibling = realtimeConflictSiblingPath({ scopeUid: "prs_demo", canonicalPath: "notes/lost.txt", attemptId: "attempt-04" });
163
+ await expect(preserveRealtimeConflict({
164
+ root: directory,
165
+ scopeUid: "prs_demo",
166
+ canonicalPath: "notes/lost.txt",
167
+ attemptId: "attempt-04",
168
+ expectedSha256,
169
+ expectedSize: bytes.byteLength,
170
+ spoolPath: spool,
171
+ caseInsensitiveFilesystem: false,
172
+ recordConflictPreserved: async () => undefined,
173
+ creatorCandidate: { apiUrl: "https://sync.example.test", authorization: authorization(), fetchImpl: ackFetch(503) },
174
+ })).rejects.toMatchObject({ code: "CANDIDATE_UNAVAILABLE" });
175
+ expect(fs.readFileSync(path.join(directory, sibling))).toEqual(bytes);
176
+ });
177
+ it("withholds acknowledgement when the conflict-preserved record is not durable", async () => {
178
+ const directory = root();
179
+ const bytes = Buffer.from("record failure must retain recovery material");
180
+ const expectedSha256 = digest(bytes);
181
+ const spool = path.join(directory, "attempt.spool");
182
+ fs.writeFileSync(spool, bytes);
183
+ const fetchImpl = ackFetch(204);
184
+ const sibling = realtimeConflictSiblingPath({ scopeUid: "prs_demo", canonicalPath: "notes/record.txt", attemptId: "attempt-05" });
185
+ await expect(preserveRealtimeConflict({
186
+ root: directory,
187
+ scopeUid: "prs_demo",
188
+ canonicalPath: "notes/record.txt",
189
+ attemptId: "attempt-05",
190
+ expectedSha256,
191
+ expectedSize: bytes.byteLength,
192
+ spoolPath: spool,
193
+ caseInsensitiveFilesystem: false,
194
+ recordConflictPreserved: async () => { throw new Error("WAL unavailable"); },
195
+ creatorCandidate: { apiUrl: "https://sync.example.test", authorization: authorization(), fetchImpl },
196
+ })).rejects.toThrow("WAL unavailable");
197
+ expect(fetchImpl).not.toHaveBeenCalled();
198
+ expect(fs.readFileSync(path.join(directory, sibling))).toEqual(bytes);
199
+ });
200
+ });
201
+ //# sourceMappingURL=conflict-recovery.test.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"conflict-recovery.test.js","sourceRoot":"","sources":["../../src/cli/conflict-recovery.test.ts"],"names":[],"mappings":"AAAA,OAAO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CAAC;YAC5E,gBAAgB,EAAE,EAAE,MAAM,EAAE,2BAA2B,EAAE,aAAa,EAAE,aAAa,EAAE,EAAE,SAAS,EAAE;SACrG,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,CAAC,iBAAiB,CAAC,CAAC;QAEvC,MAAM,CAAC,SAAS,CAAC,CAAC,GAAG,CAAC,gBAAgB,EAAE,CAAC;QACzC,MAAM,CAAC,EAAE,CAAC,YAAY,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,CAAC;IACxE,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC"}
@@ -4,6 +4,66 @@
4
4
  * Interactive prompts in terminal mode; deterministic resolution via
5
5
  * --on-conflict flag for worker/skill callers.
6
6
  */
7
+ import { CandidateUploader, type CandidateFetch, type CandidateTransportAuthorization } from "../sync/candidate-uploader.js";
8
+ export declare class RealtimeConflictError extends Error {
9
+ readonly code: "INVALID_PATH" | "CASE_COLLISION" | "CONFLICT_NAME_COLLISION" | "CANDIDATE_UNAVAILABLE";
10
+ constructor(code: "INVALID_PATH" | "CASE_COLLISION" | "CONFLICT_NAME_COLLISION" | "CANDIDATE_UNAVAILABLE", message?: string, options?: ErrorOptions);
11
+ }
12
+ export interface RealtimeConflictPathInput {
13
+ scopeUid: string;
14
+ canonicalPath: string;
15
+ attemptId: string;
16
+ }
17
+ export interface CreatorCandidateRecovery {
18
+ apiUrl: string;
19
+ authorization: CandidateTransportAuthorization;
20
+ fetchImpl?: CandidateFetch;
21
+ /** Injectable only so recovery can share the already-bound candidate reader. */
22
+ candidateReader?: Pick<CandidateUploader, "openCandidate">;
23
+ }
24
+ export interface PreserveRealtimeConflictInput extends RealtimeConflictPathInput {
25
+ /** Root of the scope; the conflict sibling is always contained beneath it. */
26
+ root: string;
27
+ /** SHA-256 from the immutable attempt request, never a best-effort local hash. */
28
+ expectedSha256: `sha256:${string}`;
29
+ expectedSize: number;
30
+ /** Preferred exact source: the fsynced immutable local attempt spool. */
31
+ spoolPath?: string;
32
+ /** Used only when the local spool is unavailable or fails exact verification. */
33
+ creatorCandidate?: CreatorCandidateRecovery;
34
+ /** Must be set by a caller operating on a case-insensitive filesystem. */
35
+ caseInsensitiveFilesystem: boolean;
36
+ /** Mirrors the platform's actual folding rule and makes that rule testable. */
37
+ caseFold?: (value: string) => string;
38
+ /**
39
+ * Appends the `conflict-preserved` WAL/state-store fact. It must not resolve
40
+ * until that fact is durable; acknowledgement is intentionally after it.
41
+ */
42
+ recordConflictPreserved(record: PreservedRealtimeConflict): Promise<void>;
43
+ }
44
+ export interface PreservedRealtimeConflict {
45
+ canonicalPath: string;
46
+ siblingPath: string;
47
+ sha256: `sha256:${string}`;
48
+ source: "local-attempt-spool" | "creator-candidate";
49
+ }
50
+ /** Exact V2 canonical path contract, duplicated here so recovery has no V1 path dependency. */
51
+ export declare function canonicalizeRealtimeConflictPath(rawPath: string): string;
52
+ /** RFC 4648 lower-case Base32 without padding, as frozen by protocol v2. */
53
+ export declare function lowercaseBase32NoPadding(bytes: Uint8Array): string;
54
+ /**
55
+ * The stable sibling name for a losing V2 mutation. It deliberately includes
56
+ * no clock, hostname, ETag, or local filesystem fact.
57
+ */
58
+ export declare function realtimeConflictSiblingPath(input: RealtimeConflictPathInput): string;
59
+ /** Acknowledgement is sent only after sibling bytes and its containing directory are fsynced. */
60
+ export declare function acknowledgeCreatorCandidate(recovery: CreatorCandidateRecovery, attemptId: string, checksum: `sha256:${string}`): Promise<void>;
61
+ /**
62
+ * Recovers a losing mutation from the immutable spool or creator-only exact
63
+ * candidate, publishes its deterministic sibling, then releases server-side
64
+ * candidate retention with a monotonic acknowledgement.
65
+ */
66
+ export declare function preserveRealtimeConflict(input: PreserveRealtimeConflictInput): Promise<PreservedRealtimeConflict>;
7
67
  export type ConflictStrategy = "overwrite" | "keep" | "abort";
8
68
  export interface ConflictInfo {
9
69
  path: string;
@@ -1 +1 @@
1
- {"version":3,"file":"conflict.d.ts","sourceRoot":"","sources":["../../src/cli/conflict.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAKH,MAAM,MAAM,gBAAgB,GAAG,WAAW,GAAG,MAAM,GAAG,OAAO,CAAC;AAE9D,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,IAAI,CAAC;IACrB,cAAc,CAAC,EAAE,IAAI,CAAC;IACtB,SAAS,EAAE,MAAM,GAAG,MAAM,CAAC;CAC5B;AAED,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;AAElF;;;;;;;;;GASG;AACH,wBAAsB,eAAe,CACnC,QAAQ,EAAE,YAAY,EACtB,QAAQ,CAAC,EAAE,gBAAgB,GAC1B,OAAO,CAAC,kBAAkB,CAAC,CAM7B;AAuDD;;;GAGG;AACH,wBAAgB,QAAQ,CACtB,SAAS,EAAE,MAAM,EACjB,aAAa,EAAE,MAAM,GACpB,IAAI,CAcN"}
1
+ {"version":3,"file":"conflict.d.ts","sourceRoot":"","sources":["../../src/cli/conflict.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAOH,OAAO,EACL,iBAAiB,EACjB,KAAK,cAAc,EACnB,KAAK,+BAA+B,EAErC,MAAM,+BAA+B,CAAC;AAMvC,qBAAa,qBAAsB,SAAQ,KAAK;IAE5C,QAAQ,CAAC,IAAI,EAAE,cAAc,GAAG,gBAAgB,GAAG,yBAAyB,GAAG,uBAAuB;gBAA7F,IAAI,EAAE,cAAc,GAAG,gBAAgB,GAAG,yBAAyB,GAAG,uBAAuB,EACtG,OAAO,GAAE,MAAa,EACtB,OAAO,CAAC,EAAE,YAAY;CAKzB;AAED,MAAM,WAAW,yBAAyB;IACxC,QAAQ,EAAE,MAAM,CAAC;IACjB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G,wBAAsB,2BAA2B,CAC/C,QAAQ,EAAE,wBAAwB,EAClC,SAAS,EAAE,MAAM,EACjB,QAAQ,EAAE,UAAU,MAAM,EAAE,GAC3B,OAAO,CAAC,IAAI,CAAC,CAkCf;AAED;;;;GAIG;AACH,wBAAsB,wBAAwB,CAAC,KAAK,EAAE,6BAA6B,GAAG,OAAO,CAAC,yBAAyB,CAAC,CA+CvH;AAED,MAAM,MAAM,gBAAgB,GAAG,WAAW,GAAG,MAAM,GAAG,OAAO,CAAC;AAE9D,MAAM,WAAW,YAAY;IAC3B,IAAI,EAAE,MAAM,CAAC;IACb,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,aAAa,CAAC,EAAE,IAAI,CAAC;IACrB,cAAc,CAAC,EAAE,IAAI,CAAC;IACtB,SAAS,EAAE,MAAM,GAAG,MAAM,CAAC;CAC5B;AAED,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,GAAG,OAAO,CAAC;AAElF;;;;;;;;;GASG;AACH,wBAAsB,eAAe,CACnC,QAAQ,EAAE,YAAY,EACtB,QAAQ,CAAC,EAAE,gBAAgB,GAC1B,OAAO,CAAC,kBAAkB,CAAC,CAM7B;AAuDD;;;GAGG;AACH,wBAAgB,QAAQ,CACtB,SAAS,EAAE,MAAM,EACjB,aAAa,EAAE,MAAM,GACpB,IAAI,CAcN"}
@@ -5,7 +5,340 @@
5
5
  * --on-conflict flag for worker/skill callers.
6
6
  */
7
7
  import * as fs from "fs";
8
+ import { createHash } from "node:crypto";
9
+ import * as pathModule from "node:path";
8
10
  import * as readline from "readline";
11
+ import { CandidateUploader, } from "../sync/candidate-uploader.js";
12
+ const REALTIME_OPAQUE_ID = /^[A-Za-z0-9._~-]{1,512}$/;
13
+ const REALTIME_SHA256 = /^sha256:[a-f0-9]{64}$/;
14
+ const BASE32_LOWER = "abcdefghijklmnopqrstuvwxyz234567";
15
+ export class RealtimeConflictError extends Error {
16
+ code;
17
+ constructor(code, message = code, options) {
18
+ super(message, options);
19
+ this.code = code;
20
+ this.name = "RealtimeConflictError";
21
+ }
22
+ }
23
+ function assertScalarUnicode(value, label) {
24
+ for (let index = 0; index < value.length; index += 1) {
25
+ const code = value.charCodeAt(index);
26
+ if (code >= 0xd800 && code <= 0xdbff) {
27
+ const next = value.charCodeAt(index + 1);
28
+ if (next < 0xdc00 || next > 0xdfff) {
29
+ throw new RealtimeConflictError("INVALID_PATH", `${label} contains an unpaired surrogate`);
30
+ }
31
+ index += 1;
32
+ }
33
+ else if (code >= 0xdc00 && code <= 0xdfff) {
34
+ throw new RealtimeConflictError("INVALID_PATH", `${label} contains an unpaired surrogate`);
35
+ }
36
+ }
37
+ }
38
+ function containsControlCharacter(value) {
39
+ for (let index = 0; index < value.length; index += 1) {
40
+ const codePoint = value.codePointAt(index);
41
+ if (codePoint !== undefined && ((codePoint >= 0x00 && codePoint <= 0x1f) ||
42
+ (codePoint >= 0x7f && codePoint <= 0x9f)))
43
+ return true;
44
+ }
45
+ return false;
46
+ }
47
+ /** Exact V2 canonical path contract, duplicated here so recovery has no V1 path dependency. */
48
+ export function canonicalizeRealtimeConflictPath(rawPath) {
49
+ assertScalarUnicode(rawPath, "path");
50
+ const canonicalPath = rawPath.normalize("NFC");
51
+ if (!canonicalPath || containsControlCharacter(canonicalPath) || canonicalPath.startsWith("/") ||
52
+ canonicalPath.endsWith("/") || canonicalPath.startsWith(".hq-control/") ||
53
+ Buffer.byteLength(canonicalPath, "utf8") > 1024)
54
+ throw new RealtimeConflictError("INVALID_PATH");
55
+ for (const component of canonicalPath.split("/")) {
56
+ if (!component || component === "." || component === ".." || Buffer.byteLength(component, "utf8") > 255) {
57
+ throw new RealtimeConflictError("INVALID_PATH");
58
+ }
59
+ }
60
+ return canonicalPath;
61
+ }
62
+ /** RFC 4648 lower-case Base32 without padding, as frozen by protocol v2. */
63
+ export function lowercaseBase32NoPadding(bytes) {
64
+ let result = "";
65
+ let buffer = 0;
66
+ let bits = 0;
67
+ for (const byte of bytes) {
68
+ buffer = (buffer << 8) | byte;
69
+ bits += 8;
70
+ while (bits >= 5) {
71
+ result += BASE32_LOWER[(buffer >>> (bits - 5)) & 31];
72
+ bits -= 5;
73
+ }
74
+ }
75
+ if (bits > 0)
76
+ result += BASE32_LOWER[(buffer << (5 - bits)) & 31];
77
+ return result;
78
+ }
79
+ function splitStemAndExtension(fileName) {
80
+ if (fileName.startsWith(".") || fileName.endsWith("."))
81
+ return { stem: fileName, extension: "" };
82
+ const lastDot = fileName.lastIndexOf(".");
83
+ return lastDot === -1
84
+ ? { stem: fileName, extension: "" }
85
+ : { stem: fileName.slice(0, lastDot), extension: fileName.slice(lastDot) };
86
+ }
87
+ function truncateUtf8(value, maxBytes) {
88
+ let end = value.length;
89
+ while (end > 0 && Buffer.byteLength(value.slice(0, end), "utf8") > maxBytes) {
90
+ end -= 1;
91
+ const code = value.charCodeAt(end);
92
+ if (code >= 0xdc00 && code <= 0xdfff)
93
+ end -= 1;
94
+ }
95
+ return value.slice(0, end);
96
+ }
97
+ /**
98
+ * The stable sibling name for a losing V2 mutation. It deliberately includes
99
+ * no clock, hostname, ETag, or local filesystem fact.
100
+ */
101
+ export function realtimeConflictSiblingPath(input) {
102
+ if (!REALTIME_OPAQUE_ID.test(input.scopeUid) || !REALTIME_OPAQUE_ID.test(input.attemptId)) {
103
+ throw new RealtimeConflictError("INVALID_PATH", "scopeUid or attemptId is invalid");
104
+ }
105
+ const canonicalPath = canonicalizeRealtimeConflictPath(input.canonicalPath);
106
+ const slash = canonicalPath.lastIndexOf("/");
107
+ const directory = slash === -1 ? "" : canonicalPath.slice(0, slash + 1);
108
+ const fileName = canonicalPath.slice(slash + 1);
109
+ const suffix = lowercaseBase32NoPadding(createHash("sha256").update(`${input.scopeUid}\0${canonicalPath}\0${input.attemptId}`, "utf8").digest()).slice(0, 26);
110
+ const { stem, extension } = splitStemAndExtension(fileName);
111
+ const fixed = `.conflict-${suffix}${extension}`;
112
+ if (Buffer.byteLength(fixed, "utf8") > 255) {
113
+ throw new RealtimeConflictError("CONFLICT_NAME_COLLISION", "conflict suffix and extension exceed one component");
114
+ }
115
+ return canonicalizeRealtimeConflictPath(`${directory}${truncateUtf8(stem, 255 - Buffer.byteLength(fixed, "utf8"))}${fixed}`);
116
+ }
117
+ function sha256(bytes) {
118
+ return `sha256:${createHash("sha256").update(bytes).digest("hex")}`;
119
+ }
120
+ function fsyncDirectory(directory) {
121
+ const descriptor = fs.openSync(directory, "r");
122
+ try {
123
+ fs.fsyncSync(descriptor);
124
+ }
125
+ finally {
126
+ fs.closeSync(descriptor);
127
+ }
128
+ }
129
+ function containedPath(root, canonicalPath) {
130
+ const resolvedRoot = pathModule.resolve(root);
131
+ const target = pathModule.resolve(resolvedRoot, ...canonicalPath.split("/"));
132
+ if (target !== resolvedRoot && !target.startsWith(`${resolvedRoot}${pathModule.sep}`)) {
133
+ throw new RealtimeConflictError("INVALID_PATH", "conflict path escapes its scope root");
134
+ }
135
+ return target;
136
+ }
137
+ function assertNoCaseCollision(root, canonicalPath, caseFold) {
138
+ let parent = pathModule.resolve(root);
139
+ for (const component of canonicalPath.split("/")) {
140
+ if (!fs.existsSync(parent))
141
+ return;
142
+ let entries;
143
+ try {
144
+ entries = fs.readdirSync(parent, { withFileTypes: true });
145
+ }
146
+ catch (error) {
147
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", `cannot inspect conflict parent ${parent}`, { cause: error });
148
+ }
149
+ const colliding = entries.find((entry) => entry.name !== component && caseFold(entry.name.normalize("NFC")) === caseFold(component));
150
+ if (colliding) {
151
+ throw new RealtimeConflictError("CASE_COLLISION", `case collision between ${component} and ${colliding.name}`);
152
+ }
153
+ parent = pathModule.join(parent, component);
154
+ }
155
+ }
156
+ function ensureSafeSiblingParent(root, siblingPath) {
157
+ let current = pathModule.resolve(root);
158
+ const rootStat = fs.lstatSync(current);
159
+ if (!rootStat.isDirectory() || rootStat.isSymbolicLink()) {
160
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", "conflict scope root is not a directory");
161
+ }
162
+ const parentComponents = siblingPath.split("/").slice(0, -1);
163
+ for (const component of parentComponents) {
164
+ current = pathModule.join(current, component);
165
+ if (!fs.existsSync(current)) {
166
+ fs.mkdirSync(current, { mode: 0o700 });
167
+ fsyncDirectory(pathModule.dirname(current));
168
+ }
169
+ const stat = fs.lstatSync(current);
170
+ if (!stat.isDirectory() || stat.isSymbolicLink()) {
171
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", `conflict parent ${current} is not a real directory`);
172
+ }
173
+ }
174
+ }
175
+ function writeSiblingExactly(destination, bytes, expectedSha256) {
176
+ const directory = pathModule.dirname(destination);
177
+ const temporary = pathModule.join(directory, `.${pathModule.basename(destination)}.${process.pid}.${cryptoRandomSuffix()}.tmp`);
178
+ let descriptor;
179
+ try {
180
+ fsyncDirectory(directory);
181
+ descriptor = fs.openSync(temporary, "wx", 0o600);
182
+ let offset = 0;
183
+ while (offset < bytes.byteLength)
184
+ offset += fs.writeSync(descriptor, bytes, offset, bytes.byteLength - offset);
185
+ fs.fsyncSync(descriptor);
186
+ fs.closeSync(descriptor);
187
+ descriptor = undefined;
188
+ try {
189
+ // link is publication without rename's replacement semantics.
190
+ fs.linkSync(temporary, destination);
191
+ fs.unlinkSync(temporary);
192
+ fsyncDirectory(directory);
193
+ return;
194
+ }
195
+ catch (error) {
196
+ if (error.code !== "EEXIST")
197
+ throw error;
198
+ const existing = fs.readFileSync(destination);
199
+ if (sha256(existing) !== expectedSha256) {
200
+ throw new RealtimeConflictError("CONFLICT_NAME_COLLISION", `different bytes already occupy ${destination}`);
201
+ }
202
+ fs.unlinkSync(temporary);
203
+ // The existing sibling is the durable idempotent publication.
204
+ fsyncDirectory(directory);
205
+ return;
206
+ }
207
+ }
208
+ catch (error) {
209
+ if (descriptor !== undefined)
210
+ fs.closeSync(descriptor);
211
+ if (fs.existsSync(temporary))
212
+ fs.unlinkSync(temporary);
213
+ if (error instanceof RealtimeConflictError)
214
+ throw error;
215
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", `unable to durably preserve conflict sibling`, { cause: error });
216
+ }
217
+ }
218
+ function cryptoRandomSuffix() {
219
+ return createHash("sha256").update(`${process.pid}:${Date.now()}:${Math.random()}`).digest("hex").slice(0, 16);
220
+ }
221
+ async function readExactCandidate(reader, authorization, attemptId, expectedSha256, expectedSize) {
222
+ const candidate = await reader.openCandidate(authorization, attemptId);
223
+ if (candidate.sha256 !== expectedSha256 || candidate.size !== expectedSize || !candidate.body) {
224
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", "creator candidate does not match the immutable losing attempt");
225
+ }
226
+ const chunks = [];
227
+ let size = 0;
228
+ for await (const chunk of candidate.body) {
229
+ size += chunk.byteLength;
230
+ if (size > expectedSize)
231
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", "creator candidate exceeded its declared size");
232
+ chunks.push(chunk);
233
+ }
234
+ const bytes = Buffer.concat(chunks.map((chunk) => Buffer.from(chunk)), size);
235
+ if (bytes.byteLength !== expectedSize || sha256(bytes) !== expectedSha256) {
236
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", "creator candidate bytes do not match the losing attempt");
237
+ }
238
+ return bytes;
239
+ }
240
+ function controlHeaders(authorization) {
241
+ return {
242
+ Authorization: `Bearer ${authorization.bearer}`,
243
+ Accept: "application/json",
244
+ "Content-Type": "application/json",
245
+ "X-HQ-Sync-Contract": "2",
246
+ "X-HQ-Device-ID": authorization.deviceId,
247
+ "X-HQ-Cloud-Version": authorization.capabilityVector.hqCloud,
248
+ "X-HQ-Desktop-Version": authorization.capabilityVector.hqDesktop,
249
+ "X-HQ-Sync-Lease": authorization.lease.lease,
250
+ };
251
+ }
252
+ /** Acknowledgement is sent only after sibling bytes and its containing directory are fsynced. */
253
+ export async function acknowledgeCreatorCandidate(recovery, attemptId, checksum) {
254
+ if (!REALTIME_OPAQUE_ID.test(attemptId) || !REALTIME_SHA256.test(checksum)) {
255
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", "candidate acknowledgement identity is invalid");
256
+ }
257
+ if (Date.parse(recovery.authorization.lease.expiresAt) <= Date.now()) {
258
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", "lease expired before candidate acknowledgement");
259
+ }
260
+ const fetchImpl = recovery.fetchImpl ?? globalThis.fetch;
261
+ const controller = new AbortController();
262
+ const timer = setTimeout(() => controller.abort(), 15_000);
263
+ let response;
264
+ try {
265
+ response = await fetchImpl(`${recovery.apiUrl.replace(/\/+$/, "")}/v2/sync/mutations/${encodeURIComponent(attemptId)}/candidate-ack`, {
266
+ method: "POST",
267
+ headers: controlHeaders(recovery.authorization),
268
+ body: JSON.stringify({ evidence: { kind: "conflict-sibling", sha256: checksum } }),
269
+ signal: controller.signal,
270
+ });
271
+ }
272
+ catch (error) {
273
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", "candidate acknowledgement request failed", { cause: error });
274
+ }
275
+ finally {
276
+ clearTimeout(timer);
277
+ }
278
+ if (response.status === 204)
279
+ return;
280
+ let detail;
281
+ try {
282
+ detail = await response.text();
283
+ }
284
+ catch (error) {
285
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", "candidate acknowledgement response is unreadable", { cause: error });
286
+ }
287
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", `candidate acknowledgement failed (${response.status}): ${detail.slice(0, 300)}`);
288
+ }
289
+ /**
290
+ * Recovers a losing mutation from the immutable spool or creator-only exact
291
+ * candidate, publishes its deterministic sibling, then releases server-side
292
+ * candidate retention with a monotonic acknowledgement.
293
+ */
294
+ export async function preserveRealtimeConflict(input) {
295
+ if (!REALTIME_SHA256.test(input.expectedSha256) || !Number.isSafeInteger(input.expectedSize) || input.expectedSize < 0) {
296
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", "losing attempt metadata is invalid");
297
+ }
298
+ const canonicalPath = canonicalizeRealtimeConflictPath(input.canonicalPath);
299
+ const siblingPath = realtimeConflictSiblingPath({ ...input, canonicalPath });
300
+ const siblingAbsolutePath = containedPath(input.root, siblingPath);
301
+ if (input.caseInsensitiveFilesystem) {
302
+ assertNoCaseCollision(input.root, canonicalPath, input.caseFold ?? ((value) => value.toLowerCase()));
303
+ assertNoCaseCollision(input.root, siblingPath, input.caseFold ?? ((value) => value.toLowerCase()));
304
+ }
305
+ ensureSafeSiblingParent(input.root, siblingPath);
306
+ let bytes;
307
+ let source;
308
+ if (input.spoolPath && fs.existsSync(input.spoolPath)) {
309
+ try {
310
+ const candidate = fs.readFileSync(input.spoolPath);
311
+ if (candidate.byteLength === input.expectedSize && sha256(candidate) === input.expectedSha256) {
312
+ bytes = candidate;
313
+ source = "local-attempt-spool";
314
+ }
315
+ }
316
+ catch (error) {
317
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", "unable to read local attempt spool", { cause: error });
318
+ }
319
+ }
320
+ if (!bytes) {
321
+ if (!input.creatorCandidate) {
322
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", "no verified local spool or creator candidate is available");
323
+ }
324
+ const reader = input.creatorCandidate.candidateReader ?? new CandidateUploader({
325
+ apiUrl: input.creatorCandidate.apiUrl,
326
+ fetchImpl: input.creatorCandidate.fetchImpl,
327
+ });
328
+ bytes = await readExactCandidate(reader, input.creatorCandidate.authorization, input.attemptId, input.expectedSha256, input.expectedSize);
329
+ source = "creator-candidate";
330
+ }
331
+ if (!source) {
332
+ throw new RealtimeConflictError("CANDIDATE_UNAVAILABLE", "conflict source was not established");
333
+ }
334
+ writeSiblingExactly(siblingAbsolutePath, bytes, input.expectedSha256);
335
+ const preserved = { canonicalPath, siblingPath, sha256: input.expectedSha256, source };
336
+ await input.recordConflictPreserved(preserved);
337
+ if (input.creatorCandidate) {
338
+ await acknowledgeCreatorCandidate(input.creatorCandidate, input.attemptId, input.expectedSha256);
339
+ }
340
+ return preserved;
341
+ }
9
342
  /**
10
343
  * Resolve a conflict interactively or via strategy flag.
11
344
  *