@indigoai-us/hq-cloud 6.16.53-alpha.0 → 6.16.53

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 (179) hide show
  1. package/dist/backup-prune.d.ts +23 -1
  2. package/dist/backup-prune.d.ts.map +1 -1
  3. package/dist/backup-prune.js +92 -8
  4. package/dist/backup-prune.js.map +1 -1
  5. package/dist/backup-prune.test.js +36 -0
  6. package/dist/backup-prune.test.js.map +1 -1
  7. package/dist/bin/rescue-runner.js +2 -1
  8. package/dist/bin/rescue-runner.js.map +1 -1
  9. package/dist/bin/sync-runner-company.d.ts +0 -6
  10. package/dist/bin/sync-runner-company.d.ts.map +1 -1
  11. package/dist/bin/sync-runner-company.js +1 -30
  12. package/dist/bin/sync-runner-company.js.map +1 -1
  13. package/dist/bin/sync-runner-company.test.js +126 -57
  14. package/dist/bin/sync-runner-company.test.js.map +1 -1
  15. package/dist/bin/sync-runner-planning.d.ts +3 -12
  16. package/dist/bin/sync-runner-planning.d.ts.map +1 -1
  17. package/dist/bin/sync-runner-planning.js +3 -65
  18. package/dist/bin/sync-runner-planning.js.map +1 -1
  19. package/dist/bin/sync-runner-planning.test.js +1 -108
  20. package/dist/bin/sync-runner-planning.test.js.map +1 -1
  21. package/dist/bin/sync-runner-watch-loop.d.ts +2 -48
  22. package/dist/bin/sync-runner-watch-loop.d.ts.map +1 -1
  23. package/dist/bin/sync-runner-watch-loop.js +120 -318
  24. package/dist/bin/sync-runner-watch-loop.js.map +1 -1
  25. package/dist/bin/sync-runner.d.ts +5 -33
  26. package/dist/bin/sync-runner.d.ts.map +1 -1
  27. package/dist/bin/sync-runner.js +4 -34
  28. package/dist/bin/sync-runner.js.map +1 -1
  29. package/dist/bin/sync-runner.test.js +79 -1079
  30. package/dist/bin/sync-runner.test.js.map +1 -1
  31. package/dist/cli/rescue-breaker.test.d.ts +2 -0
  32. package/dist/cli/rescue-breaker.test.d.ts.map +1 -0
  33. package/dist/cli/rescue-breaker.test.js +334 -0
  34. package/dist/cli/rescue-breaker.test.js.map +1 -0
  35. package/dist/cli/rescue-core.d.ts +40 -0
  36. package/dist/cli/rescue-core.d.ts.map +1 -1
  37. package/dist/cli/rescue-core.js +1454 -162
  38. package/dist/cli/rescue-core.js.map +1 -1
  39. package/dist/cli/rescue-realpath.test.d.ts +2 -0
  40. package/dist/cli/rescue-realpath.test.d.ts.map +1 -0
  41. package/dist/cli/rescue-realpath.test.js +109 -0
  42. package/dist/cli/rescue-realpath.test.js.map +1 -0
  43. package/dist/cli/rescue-rsync-preflight.test.js +256 -4
  44. package/dist/cli/rescue-rsync-preflight.test.js.map +1 -1
  45. package/dist/cli/rescue-snapshot-copy.test.d.ts +2 -0
  46. package/dist/cli/rescue-snapshot-copy.test.d.ts.map +1 -0
  47. package/dist/cli/rescue-snapshot-copy.test.js +627 -0
  48. package/dist/cli/rescue-snapshot-copy.test.js.map +1 -0
  49. package/dist/cli/rescue-snapshot-recovery.test.d.ts +2 -0
  50. package/dist/cli/rescue-snapshot-recovery.test.d.ts.map +1 -0
  51. package/dist/cli/rescue-snapshot-recovery.test.js +260 -0
  52. package/dist/cli/rescue-snapshot-recovery.test.js.map +1 -0
  53. package/dist/cli/rescue-source-switch-floor.test.d.ts +2 -0
  54. package/dist/cli/rescue-source-switch-floor.test.d.ts.map +1 -0
  55. package/dist/cli/rescue-source-switch-floor.test.js +210 -0
  56. package/dist/cli/rescue-source-switch-floor.test.js.map +1 -0
  57. package/dist/cli/rescue.d.ts +4 -0
  58. package/dist/cli/rescue.d.ts.map +1 -1
  59. package/dist/cli/rescue.js +20 -1
  60. package/dist/cli/rescue.js.map +1 -1
  61. package/dist/cli/rescue.test.js +16 -1
  62. package/dist/cli/rescue.test.js.map +1 -1
  63. package/dist/cli/share-presign-transport.test.js +2 -0
  64. package/dist/cli/share-presign-transport.test.js.map +1 -1
  65. package/dist/cli/share.d.ts +0 -19
  66. package/dist/cli/share.d.ts.map +1 -1
  67. package/dist/cli/share.js +467 -150
  68. package/dist/cli/share.js.map +1 -1
  69. package/dist/cli/share.test.js +608 -95
  70. package/dist/cli/share.test.js.map +1 -1
  71. package/dist/cli/sync-scope.test.js +0 -8
  72. package/dist/cli/sync-scope.test.js.map +1 -1
  73. package/dist/cli/sync.d.ts +15 -13
  74. package/dist/cli/sync.d.ts.map +1 -1
  75. package/dist/cli/sync.js +118 -226
  76. package/dist/cli/sync.js.map +1 -1
  77. package/dist/cli/sync.test.js +2 -215
  78. package/dist/cli/sync.test.js.map +1 -1
  79. package/dist/cli/watch-event-push-conflict.test.js +2 -0
  80. package/dist/cli/watch-event-push-conflict.test.js.map +1 -1
  81. package/dist/cognito-auth.d.ts +30 -0
  82. package/dist/cognito-auth.d.ts.map +1 -1
  83. package/dist/cognito-auth.js +175 -0
  84. package/dist/cognito-auth.js.map +1 -1
  85. package/dist/index.d.ts +2 -2
  86. package/dist/index.d.ts.map +1 -1
  87. package/dist/index.js +1 -1
  88. package/dist/index.js.map +1 -1
  89. package/dist/journal-row-store.d.ts +5 -9
  90. package/dist/journal-row-store.d.ts.map +1 -1
  91. package/dist/journal-row-store.js +10 -70
  92. package/dist/journal-row-store.js.map +1 -1
  93. package/dist/journal-snapshot-v4.d.ts.map +1 -1
  94. package/dist/journal-snapshot-v4.js +6 -11
  95. package/dist/journal-snapshot-v4.js.map +1 -1
  96. package/dist/journal-store.test.js +7 -259
  97. package/dist/journal-store.test.js.map +1 -1
  98. package/dist/journal.d.ts +15 -43
  99. package/dist/journal.d.ts.map +1 -1
  100. package/dist/journal.js +79 -297
  101. package/dist/journal.js.map +1 -1
  102. package/dist/lib/describe-error.d.ts.map +1 -1
  103. package/dist/lib/describe-error.js +7 -0
  104. package/dist/lib/describe-error.js.map +1 -1
  105. package/dist/lib/describe-error.test.js +11 -0
  106. package/dist/lib/describe-error.test.js.map +1 -1
  107. package/dist/lib/exit-codes.d.ts +0 -15
  108. package/dist/lib/exit-codes.d.ts.map +1 -1
  109. package/dist/lib/exit-codes.js +0 -15
  110. package/dist/lib/exit-codes.js.map +1 -1
  111. package/dist/machine-auth.test.js +295 -0
  112. package/dist/machine-auth.test.js.map +1 -1
  113. package/dist/object-io.d.ts +2 -2
  114. package/dist/object-io.d.ts.map +1 -1
  115. package/dist/object-io.js +18 -3
  116. package/dist/object-io.js.map +1 -1
  117. package/dist/personal-vault.d.ts.map +1 -1
  118. package/dist/personal-vault.js +3 -10
  119. package/dist/personal-vault.js.map +1 -1
  120. package/dist/personal-vault.test.js +0 -35
  121. package/dist/personal-vault.test.js.map +1 -1
  122. package/dist/remote-pull.d.ts.map +1 -1
  123. package/dist/remote-pull.js +2 -9
  124. package/dist/remote-pull.js.map +1 -1
  125. package/dist/remote-pull.test.js +2 -59
  126. package/dist/remote-pull.test.js.map +1 -1
  127. package/dist/s3.d.ts +18 -1
  128. package/dist/s3.d.ts.map +1 -1
  129. package/dist/s3.js +47 -24
  130. package/dist/s3.js.map +1 -1
  131. package/dist/s3.test.js +27 -1
  132. package/dist/s3.test.js.map +1 -1
  133. package/dist/sync/area-ledger.js +4 -4
  134. package/dist/sync/area-ledger.js.map +1 -1
  135. package/dist/sync/parallel-sync-coordinator.test.js +0 -29
  136. package/dist/sync/parallel-sync-coordinator.test.js.map +1 -1
  137. package/dist/sync/realtime-telemetry.d.ts +1 -1
  138. package/dist/sync/realtime-telemetry.d.ts.map +1 -1
  139. package/dist/sync/realtime-telemetry.js +6 -14
  140. package/dist/sync/realtime-telemetry.js.map +1 -1
  141. package/dist/sync/realtime-telemetry.test.js +16 -136
  142. package/dist/sync/realtime-telemetry.test.js.map +1 -1
  143. package/dist/sync-core.d.ts +6 -4
  144. package/dist/sync-core.d.ts.map +1 -1
  145. package/dist/sync-core.js +10 -4
  146. package/dist/sync-core.js.map +1 -1
  147. package/dist/sync-core.test.js +25 -1
  148. package/dist/sync-core.test.js.map +1 -1
  149. package/dist/vault-client.d.ts +26 -5
  150. package/dist/vault-client.d.ts.map +1 -1
  151. package/dist/vault-client.js +43 -20
  152. package/dist/vault-client.js.map +1 -1
  153. package/dist/vault-client.test.js +32 -0
  154. package/dist/vault-client.test.js.map +1 -1
  155. package/package.json +1 -2
  156. package/dist/cli/onepass-pull-planner-regressions.test.d.ts +0 -2
  157. package/dist/cli/onepass-pull-planner-regressions.test.d.ts.map +0 -1
  158. package/dist/cli/onepass-pull-planner-regressions.test.js +0 -300
  159. package/dist/cli/onepass-pull-planner-regressions.test.js.map +0 -1
  160. package/dist/cli/onepass-pull-planner.test.d.ts +0 -2
  161. package/dist/cli/onepass-pull-planner.test.d.ts.map +0 -1
  162. package/dist/cli/onepass-pull-planner.test.js +0 -266
  163. package/dist/cli/onepass-pull-planner.test.js.map +0 -1
  164. package/dist/cli/streaming-pull-planner.bench.test.d.ts +0 -15
  165. package/dist/cli/streaming-pull-planner.bench.test.d.ts.map +0 -1
  166. package/dist/cli/streaming-pull-planner.bench.test.js +0 -273
  167. package/dist/cli/streaming-pull-planner.bench.test.js.map +0 -1
  168. package/dist/s3.list-cost.test.d.ts +0 -2
  169. package/dist/s3.list-cost.test.d.ts.map +0 -1
  170. package/dist/s3.list-cost.test.js +0 -51
  171. package/dist/s3.list-cost.test.js.map +0 -1
  172. package/dist/sync/remote-file-spool.d.ts +0 -16
  173. package/dist/sync/remote-file-spool.d.ts.map +0 -1
  174. package/dist/sync/remote-file-spool.js +0 -91
  175. package/dist/sync/remote-file-spool.js.map +0 -1
  176. package/dist/sync/remote-file-spool.test.d.ts +0 -2
  177. package/dist/sync/remote-file-spool.test.d.ts.map +0 -1
  178. package/dist/sync/remote-file-spool.test.js +0 -77
  179. package/dist/sync/remote-file-spool.test.js.map +0 -1
@@ -30,6 +30,8 @@ vi.mock("../s3.js", async (importOriginal) => {
30
30
  readVerifiedRemoteSymlinkTarget: vi.fn().mockResolvedValue(null),
31
31
  primeObjectTransport: vi.fn().mockResolvedValue(undefined),
32
32
  primeUploads: vi.fn().mockResolvedValue(undefined),
33
+ publishedContentHash: actual.publishedContentHash,
34
+ setUploadContentHash: actual.setUploadContentHash,
33
35
  // Real exports share.ts now imports for the HQ-DESKTOP-54 privilege skip.
34
36
  WINDOWS_SYMLINK_PRIVILEGE_REMEDY: "Enable Windows Developer Mode (Settings > Privacy & security > For developers) or run HQ sync once from an elevated terminal, then sync again.",
35
37
  WindowsSymlinkPrivilegeError: class WindowsSymlinkPrivilegeError extends Error {
@@ -62,14 +64,13 @@ vi.mock("readline", () => ({
62
64
  })),
63
65
  }));
64
66
  import * as readline from "readline";
65
- import { share, ServerOwnedPushPathsError, UnreachablePushPathsError, UnregisteredCompanySkillError, currentUploadBytes, FULL_PUSH_COOPERATIVE_CHECKPOINT_BATCH_SIZE, parseRegisteredCompanySkillUid, _testing as shareTesting, } from "./share.js";
67
+ import { share, ServerOwnedPushPathsError, UnreachablePushPathsError, UnregisteredCompanySkillError, currentUploadBytes, parseRegisteredCompanySkillUid, _testing as shareTesting, } from "./share.js";
66
68
  import { deleteRemoteFile, downloadFile, headRemoteFile, primeObjectTransport, primeUploads, uploadFile, uploadSymlink, WindowsSymlinkPrivilegeError, } from "../s3.js";
67
- import { VaultAuthError, VaultClientError, VaultPermissionDeniedError, } from "../vault-client.js";
69
+ import { VaultAuthError, VaultClientError, VaultConflictError, VaultPermissionDeniedError, } from "../vault-client.js";
68
70
  import { CognitoRefreshError } from "../cognito-auth.js";
69
71
  import { AreaLedgerMigration, closeCachedAreaJournalMigration, hashFile, openJournalStateStoreForMigration, readJournal, readJournalScoped, setAreaLedgerMigrationTestHooksForTest, writeJournal, } from "../journal.js";
70
72
  import { ReconcileCursorStore } from "../sync/reconcile-cursor.js";
71
73
  import { AreaResolver } from "../sync/area-resolver.js";
72
- import { CooperativePassScheduler } from "../bin/sync-runner-watch-loop.js";
73
74
  /**
74
75
  * Read a journal the way production does.
75
76
  *
@@ -200,6 +201,20 @@ describe("company skill identity preflight", () => {
200
201
  skill: { name: "Call Prep", description: "Prepare calls", tags: [] },
201
202
  };
202
203
  }
204
+ // A non-landed register of a stamped copy: the server mints a fresh identity
205
+ // for THIS path and returns the re-stamped bytes (the `forked` classification).
206
+ function forkedRegistration(input, newUid = "skl_FORKED1") {
207
+ return {
208
+ ok: true,
209
+ skillUid: newUid,
210
+ path: input.path,
211
+ vaultPath: input.path,
212
+ content: input.content.replace(/skill_uid:[^\n]*/, `skill_uid: ${newUid}`),
213
+ action: "forked",
214
+ accessPolicy: "open",
215
+ skill: { name: "Copied", description: "Copied skill", tags: [] },
216
+ };
217
+ }
203
218
  it("registers and atomically stamps an unstamped canonical skill before upload", async () => {
204
219
  const file = createSkill("call-prep", "---\nname: Call Prep\ndescription: Prepare calls\n---\n\nDo the work.\n");
205
220
  const registrar = vi.fn(async (input) => registered(input));
@@ -382,8 +397,16 @@ describe("company skill identity preflight", () => {
382
397
  registerCompanySkill: registrar,
383
398
  onEvent: (event) => events.push(event),
384
399
  });
385
- expect(registrar).toHaveBeenCalledOnce();
386
- expect(registrar).toHaveBeenCalledWith({
400
+ // A stamped skill at a path this journal has never seen reserves its
401
+ // identity for the path BEFORE upload (the rename / copy backstop), then
402
+ // reconciles metadata after the bytes land.
403
+ expect(registrar).toHaveBeenCalledTimes(2);
404
+ expect(registrar).toHaveBeenNthCalledWith(1, {
405
+ companySlug: "acme",
406
+ path: "skills/existing/SKILL.md",
407
+ content: expect.stringContaining("skill_uid: skl_EXISTING1"),
408
+ });
409
+ expect(registrar).toHaveBeenLastCalledWith({
387
410
  companySlug: "acme",
388
411
  path: "skills/existing/SKILL.md",
389
412
  content: expect.stringContaining("skill_uid: skl_EXISTING1"),
@@ -392,6 +415,237 @@ describe("company skill identity preflight", () => {
392
415
  expect(result.filesUploaded).toBe(1);
393
416
  expect(events.some((event) => event.type === "not-shipped")).toBe(false);
394
417
  });
418
+ it("does not re-reserve a stamped skill the journal already knows at its path", async () => {
419
+ const file = createSkill("existing", "---\nname: Existing\ndescription: Ready\nskill_uid: skl_EXISTING1\n---\n");
420
+ const registrar = vi.fn(async (input) => registered(input, "skl_EXISTING1"));
421
+ await share({
422
+ paths: [file],
423
+ hqRoot,
424
+ entityContext: makeEntityContext(),
425
+ registerCompanySkill: registrar,
426
+ });
427
+ registrar.mockClear();
428
+ vi.mocked(uploadFile).mockClear();
429
+ fs.writeFileSync(file, fs.readFileSync(file, "utf8") + "\nEdited.\n");
430
+ const result = await share({
431
+ paths: [file],
432
+ hqRoot,
433
+ entityContext: makeEntityContext(),
434
+ registerCompanySkill: registrar,
435
+ skipUnchanged: true,
436
+ });
437
+ // Journal row exists → no pre-upload reservation; only the landed
438
+ // reconciliation after the edited bytes upload.
439
+ expect(result.filesUploaded).toBe(1);
440
+ expect(registrar).toHaveBeenCalledOnce();
441
+ expect(registrar).toHaveBeenCalledWith(expect.objectContaining({ landed: true }));
442
+ });
443
+ it("re-stamps a renamed skill folder when the service forks or moves its identity", async () => {
444
+ // The file carries an identity the vault registers for ANOTHER path (the
445
+ // folder was renamed locally). Registration hands back bytes stamped with
446
+ // the identity that governs the new path; those bytes must be what
447
+ // uploads, and the landed reconciliation must carry the new identity.
448
+ const file = createSkill("workflow-preflight", "---\nname: Preflight\ndescription: Renamed\nskill_uid: skl_OLDPATH01\n---\n\nBody.\n");
449
+ const registrar = vi.fn(async (input) => {
450
+ if (input.landed)
451
+ return registered(input, "skl_NEWPATH01");
452
+ return {
453
+ ...registered(input, "skl_NEWPATH01"),
454
+ content: input.content.replace("skl_OLDPATH01", "skl_NEWPATH01"),
455
+ action: "forked",
456
+ };
457
+ });
458
+ const events = [];
459
+ const result = await share({
460
+ paths: [file],
461
+ hqRoot,
462
+ entityContext: makeEntityContext(),
463
+ registerCompanySkill: registrar,
464
+ onEvent: (event) => events.push(event),
465
+ });
466
+ expect(result.filesUploaded).toBe(1);
467
+ expect(parseRegisteredCompanySkillUid(fs.readFileSync(file, "utf8"))).toBe("skl_NEWPATH01");
468
+ expect(registrar).toHaveBeenLastCalledWith({
469
+ companySlug: "acme",
470
+ path: "skills/workflow-preflight/SKILL.md",
471
+ content: expect.stringContaining("skill_uid: skl_NEWPATH01"),
472
+ landed: true,
473
+ });
474
+ expect(events.some((event) => event.type === "not-shipped")).toBe(false);
475
+ expect(events.some((event) => event.type === "error")).toBe(false);
476
+ });
477
+ it("keeps uploading a stamped skill when its pre-upload reservation fails transiently", async () => {
478
+ const file = createSkill("existing", "---\nname: Existing\ndescription: Ready\nskill_uid: skl_EXISTING1\n---\n");
479
+ const registrar = vi.fn(async (input) => {
480
+ if (!input.landed)
481
+ throw new Error("registry temporarily unavailable");
482
+ return registered(input, "skl_EXISTING1");
483
+ });
484
+ const events = [];
485
+ const result = await share({
486
+ paths: [file],
487
+ hqRoot,
488
+ entityContext: makeEntityContext(),
489
+ registerCompanySkill: registrar,
490
+ onEvent: (event) => events.push(event),
491
+ });
492
+ // Reservation is the fast path, not a gate: the upload still happens and
493
+ // the landed reconciliation owns the outcome.
494
+ expect(result.filesUploaded).toBe(1);
495
+ expect(registrar).toHaveBeenLastCalledWith(expect.objectContaining({ landed: true }));
496
+ expect(events.some((event) => event.type === "not-shipped")).toBe(false);
497
+ });
498
+ it("heals a landed identity refusal by re-registering and re-stamping instead of aborting", async () => {
499
+ // Reproduces the undrdog 2026-09-11 wedge: the file at the new path
500
+ // carries the OLD identity, the vault registers the path under a
501
+ // placeholder, and the landed reconciliation refuses with 409. The
502
+ // engine must re-register, re-stamp the file, and complete the pass; the
503
+ // next pass uploads the re-stamped bytes and reconciles cleanly.
504
+ const original = "---\nname: Preflight\ndescription: Renamed\nskill_uid: skl_OLDPATH01\n---\n\nBody.\n";
505
+ const file = createSkill("workflow-preflight", original);
506
+ // Pass 1: an old client uploaded the file already — simulate by letting
507
+ // the reservation call fail transiently, so the bytes upload with the old
508
+ // identity and the landed call is refused.
509
+ const wedgingRegistrar = vi.fn(async (input) => {
510
+ if (!input.landed)
511
+ throw new Error("registry temporarily unavailable");
512
+ throw new VaultConflictError("The landed skill does not carry the registered identity for this path", { code: "SKILL_REGISTER_LANDED_IDENTITY_MISMATCH", path: input.path });
513
+ });
514
+ const first = await share({
515
+ paths: [file],
516
+ hqRoot,
517
+ entityContext: makeEntityContext(),
518
+ registerCompanySkill: wedgingRegistrar,
519
+ });
520
+ expect(first.filesUploaded).toBe(1);
521
+ expect(readJournal("acme").files["skills/workflow-preflight/SKILL.md"])
522
+ .toMatchObject({ skillMetadataPending: true });
523
+ // Pass 2: the service still refuses the landed bytes, but a plain
524
+ // registration converges on the identity governing the path.
525
+ vi.mocked(uploadFile).mockClear();
526
+ vi.mocked(headRemoteFile).mockResolvedValue({
527
+ lastModified: new Date(),
528
+ etag: '"upload-etag"',
529
+ size: fs.statSync(file).size,
530
+ });
531
+ const healingRegistrar = vi.fn(async (input) => {
532
+ const localUid = parseRegisteredCompanySkillUid(input.content);
533
+ if (input.landed && localUid !== "skl_NEWPATH01") {
534
+ throw new VaultConflictError("The landed skill does not carry the registered identity for this path", { code: "SKILL_REGISTER_LANDED_IDENTITY_MISMATCH", path: input.path });
535
+ }
536
+ return {
537
+ ...registered(input, "skl_NEWPATH01"),
538
+ content: input.content.replace("skl_OLDPATH01", "skl_NEWPATH01"),
539
+ action: "reused",
540
+ };
541
+ });
542
+ const events = [];
543
+ const second = await share({
544
+ paths: [file],
545
+ hqRoot,
546
+ entityContext: makeEntityContext(),
547
+ registerCompanySkill: healingRegistrar,
548
+ skipUnchanged: true,
549
+ onEvent: (event) => events.push(event),
550
+ });
551
+ // The pass completed (no throw), the file was re-stamped, and the
552
+ // re-stamped bytes uploaded on the SAME pass with a clean landed
553
+ // reconciliation.
554
+ expect(parseRegisteredCompanySkillUid(fs.readFileSync(file, "utf8"))).toBe("skl_NEWPATH01");
555
+ expect(second.filesUploaded).toBe(1);
556
+ expect(uploadFile).toHaveBeenCalledOnce();
557
+ expect(healingRegistrar).toHaveBeenLastCalledWith(expect.objectContaining({
558
+ landed: true,
559
+ content: expect.stringContaining("skill_uid: skl_NEWPATH01"),
560
+ }));
561
+ expect(events.some((event) => event.type === "not-shipped")).toBe(false);
562
+ expect(events.some((event) => event.type === "error")).toBe(false);
563
+ expect(readJournal("acme").files["skills/workflow-preflight/SKILL.md"]
564
+ ?.skillMetadataPending).toBeUndefined();
565
+ });
566
+ it("skips one skill whose pending reconciliation fails outside the 409 path and completes the rest of the pass", async () => {
567
+ // The guarantee behind this fix: a single skill's registration failure
568
+ // never aborts the company leg — whatever the failure is. A 409 has its
569
+ // own recovery (recoverLandedSkillConflict); everything else (here a 5xx)
570
+ // is contained per skill: other files upload, the pass completes, and the
571
+ // failing skill keeps its retry marker for the next pass.
572
+ const skill = createSkill("existing", "---\nname: Existing\ndescription: Ready\nskill_uid: skl_EXISTING1\n---\n");
573
+ const other = path.join(hqRoot, "companies", "acme", "knowledge", "note.md");
574
+ fs.mkdirSync(path.dirname(other), { recursive: true });
575
+ fs.writeFileSync(other, "# note\n");
576
+ await share({
577
+ paths: [skill],
578
+ hqRoot,
579
+ entityContext: makeEntityContext(),
580
+ registerCompanySkill: vi.fn(async () => {
581
+ throw new Error("registry temporarily unavailable");
582
+ }),
583
+ });
584
+ expect(readJournal("acme").files["skills/existing/SKILL.md"])
585
+ .toMatchObject({ skillMetadataPending: true });
586
+ vi.mocked(uploadFile).mockClear();
587
+ // Only the skill exists remotely; the note is genuinely new.
588
+ vi.mocked(headRemoteFile).mockImplementation(async (_ctx, key) => key === "skills/existing/SKILL.md"
589
+ ? {
590
+ lastModified: new Date(),
591
+ etag: '"upload-etag"',
592
+ size: fs.statSync(skill).size,
593
+ }
594
+ : null);
595
+ const stuckRegistrar = vi.fn(async (input) => {
596
+ throw new VaultClientError("Skill registry unavailable", 503, undefined, { code: "SKILL_REGISTRY_UNAVAILABLE", path: input.path });
597
+ });
598
+ const events = [];
599
+ const result = await share({
600
+ paths: [skill, other],
601
+ hqRoot,
602
+ entityContext: makeEntityContext(),
603
+ registerCompanySkill: stuckRegistrar,
604
+ skipUnchanged: true,
605
+ onEvent: (event) => events.push(event),
606
+ });
607
+ expect(result.filesUploaded).toBe(1);
608
+ expect(uploadFile).toHaveBeenCalledWith(expect.anything(), other, "knowledge/note.md", undefined, expect.anything());
609
+ const notShipped = events.find((event) => event.type === "not-shipped");
610
+ expect(notShipped).toMatchObject({
611
+ reason: "skill-registration-failed",
612
+ count: 1,
613
+ samplePaths: ["skills/existing/SKILL.md"],
614
+ });
615
+ expect(notShipped?.message).toContain("path=skills/existing/SKILL.md");
616
+ expect(notShipped?.message).toContain("code=SKILL_REGISTRY_UNAVAILABLE");
617
+ expect(events.some((event) => event.type === "error")).toBe(false);
618
+ // Marker kept: the next pass retries this one skill.
619
+ expect(readJournal("acme").files["skills/existing/SKILL.md"])
620
+ .toMatchObject({ skillMetadataPending: true });
621
+ });
622
+ it("still aborts the pass on a run-level failure inside the pending reconciliation", async () => {
623
+ // Containment must never swallow an expired session: that is a fact
624
+ // about the run, and every company leg would fail the same way.
625
+ const skill = createSkill("existing", "---\nname: Existing\ndescription: Ready\nskill_uid: skl_EXISTING1\n---\n");
626
+ await share({
627
+ paths: [skill],
628
+ hqRoot,
629
+ entityContext: makeEntityContext(),
630
+ registerCompanySkill: vi.fn(async () => {
631
+ throw new Error("registry temporarily unavailable");
632
+ }),
633
+ });
634
+ vi.mocked(headRemoteFile).mockResolvedValue({
635
+ lastModified: new Date(),
636
+ etag: '"upload-etag"',
637
+ size: fs.statSync(skill).size,
638
+ });
639
+ await expect(share({
640
+ paths: [skill],
641
+ hqRoot,
642
+ entityContext: makeEntityContext(),
643
+ registerCompanySkill: vi.fn(async () => {
644
+ throw new VaultAuthError("session expired");
645
+ }),
646
+ skipUnchanged: true,
647
+ })).rejects.toBeInstanceOf(VaultAuthError);
648
+ });
395
649
  it("does not reconcile bytes edited while the upload is in flight", async () => {
396
650
  const original = "---\nname: Existing\ndescription: Ready\nskill_uid: skl_EXISTING1\ntags: [sales]\n---\n";
397
651
  const file = createSkill("existing", original);
@@ -407,7 +661,10 @@ describe("company skill identity preflight", () => {
407
661
  registerCompanySkill: registrar,
408
662
  });
409
663
  expect(result.filesUploaded).toBe(1);
410
- expect(registrar).not.toHaveBeenCalled();
664
+ // Only the pre-upload reservation ran; the landed reconciliation was
665
+ // skipped because the bytes changed under the upload.
666
+ expect(registrar).toHaveBeenCalledOnce();
667
+ expect(registrar).toHaveBeenCalledWith(expect.not.objectContaining({ landed: true }));
411
668
  });
412
669
  it("retries a failed post-upload metadata reconciliation without re-uploading", async () => {
413
670
  const file = createSkill("existing", "---\nname: Existing\ndescription: Ready\nskill_uid: skl_EXISTING1\ntags: [sales]\n---\n");
@@ -483,7 +740,10 @@ describe("company skill identity preflight", () => {
483
740
  entityContext: makeEntityContext(),
484
741
  registerCompanySkill: registrar,
485
742
  });
486
- expect(registrar).toHaveBeenCalledOnce();
743
+ // Reservation before upload, then the landed reconciliation; the marker
744
+ // is durable by the time the landed call runs.
745
+ expect(registrar).toHaveBeenCalledTimes(2);
746
+ expect(registrar).toHaveBeenLastCalledWith(expect.objectContaining({ landed: true }));
487
747
  expect(pendingAtReconcile)
488
748
  .toMatchObject({ skillMetadataPending: true, remoteEtag: "upload-etag" });
489
749
  });
@@ -555,8 +815,10 @@ describe("company skill identity preflight", () => {
555
815
  }
556
816
  expect(result.filesUploaded).toBe(1);
557
817
  expect(uploadFile).toHaveBeenCalledOnce();
558
- expect(registrar).toHaveBeenCalledOnce();
559
- expect(registrar).toHaveBeenCalledWith(expect.objectContaining({
818
+ // One pre-upload reservation (fresh journal) plus one landed
819
+ // reconciliation carrying the changed bytes.
820
+ expect(registrar).toHaveBeenCalledTimes(2);
821
+ expect(registrar).toHaveBeenLastCalledWith(expect.objectContaining({
560
822
  content: changed,
561
823
  landed: true,
562
824
  }));
@@ -627,13 +889,24 @@ describe("company skill identity preflight", () => {
627
889
  size: fs.statSync(file).size,
628
890
  });
629
891
  vi.mocked(downloadFile).mockRejectedValueOnce(new Error("download failed"));
892
+ // The recovery failure is contained to this one skill: the pass completes
893
+ // (no throw), the skill is reported as not shipped, and the stale
894
+ // baseline is still invalidated so the next pass sees a real divergence.
895
+ const events = [];
630
896
  await expect(share({
631
897
  paths: [file],
632
898
  hqRoot,
633
899
  entityContext: makeEntityContext(),
634
900
  registerCompanySkill: vi.fn(async (input) => registered(input, "skl_EXISTING1")),
635
901
  skipUnchanged: true,
636
- })).rejects.toThrow("download failed");
902
+ onEvent: (event) => events.push(event),
903
+ })).resolves.toMatchObject({ filesUploaded: 0 });
904
+ expect(events).toContainEqual(expect.objectContaining({
905
+ type: "not-shipped",
906
+ reason: "skill-registration-failed",
907
+ samplePaths: ["skills/existing/SKILL.md"],
908
+ message: expect.stringContaining("download failed"),
909
+ }));
637
910
  expect(readJournal("acme").files["skills/existing/SKILL.md"])
638
911
  .toBeUndefined();
639
912
  });
@@ -691,6 +964,241 @@ describe("company skill identity preflight", () => {
691
964
  expect(fs.readFileSync(file, "utf8")).toBe(original);
692
965
  expect(uploadFile).not.toHaveBeenCalled();
693
966
  });
967
+ it("HQ-DESKTOP-64: a landed 409 on a copied skill forks via a non-landed fallback, re-stamps atomically and clears the marker", async () => {
968
+ // A skill copied from another directory carries the SOURCE path's identity.
969
+ const copied = "---\nname: Copied\ndescription: Copied skill\nskill_uid: skl_SOURCE1\n---\n\nWork.\n";
970
+ const file = createSkill("copied", copied);
971
+ const landedCalls = [];
972
+ // Model the server: a landed call for the source-stamped copy 409s; a
973
+ // non-landed call forks a fresh identity for this path; and a landed call
974
+ // that now carries the FORKED identity reconciles successfully.
975
+ const registrar = vi.fn(async (input) => {
976
+ landedCalls.push(input.landed === true);
977
+ const uid = parseRegisteredCompanySkillUid(input.content);
978
+ if (input.landed) {
979
+ if (uid === "skl_FORKED1") {
980
+ return {
981
+ ok: true,
982
+ skillUid: "skl_FORKED1",
983
+ path: input.path,
984
+ vaultPath: input.path,
985
+ content: input.content,
986
+ action: "reused",
987
+ accessPolicy: "open",
988
+ skill: { name: "Copied", description: "Copied skill", tags: [] },
989
+ };
990
+ }
991
+ // The endpoint refuses to re-identify a copied/renamed pre-stamped
992
+ // skill on a landed call — the exact 409 behind HQ-DESKTOP-6T/64.
993
+ throw new VaultConflictError("The landed skill does not carry the registered identity for this path");
994
+ }
995
+ return forkedRegistration(input);
996
+ });
997
+ const events = [];
998
+ const result = await share({
999
+ paths: [file],
1000
+ hqRoot,
1001
+ entityContext: makeEntityContext(),
1002
+ registerCompanySkill: registrar,
1003
+ onEvent: (event) => events.push(event),
1004
+ });
1005
+ expect(result.filesUploaded).toBe(1);
1006
+ expect(result.aborted).toBe(false);
1007
+ // The landed reconcile 409'd, then the non-landed fallback ran (a fork).
1008
+ expect(landedCalls).toContain(true);
1009
+ expect(landedCalls).toContain(false);
1010
+ // The forked, re-stamped bytes were written back so the planner re-uploads.
1011
+ expect(parseRegisteredCompanySkillUid(fs.readFileSync(file, "utf8"))).toBe("skl_FORKED1");
1012
+ // No per-file error (the pass-1 HQ-DESKTOP-6T error) and no unresolved
1013
+ // conflict event, because the fallback healed it.
1014
+ expect(events.some((event) => event.type === "error")).toBe(false);
1015
+ expect(events.some((event) => event.type === "not-shipped" &&
1016
+ event.reason === "skill-registration-conflict")).toBe(false);
1017
+ // The pending marker is cleared, so a later pass can never loop on it.
1018
+ expect(readJournal("acme").files["skills/copied/SKILL.md"]?.skillMetadataPending).toBeUndefined();
1019
+ });
1020
+ it("HQ-DESKTOP-64: keeps the pending marker when a healed fallback's landed retry fails transiently, then reconciles next pass", async () => {
1021
+ const content = "---\nname: Moved\ndescription: Ready\nskill_uid: skl_EXISTING1\ntags: [sales]\n---\n";
1022
+ const file = createSkill("moved", content);
1023
+ // Pass 1: a transient registry failure leaves the pending marker set.
1024
+ await share({
1025
+ paths: [file],
1026
+ hqRoot,
1027
+ entityContext: makeEntityContext(),
1028
+ registerCompanySkill: vi.fn(async () => {
1029
+ throw new Error("registry temporarily unavailable");
1030
+ }),
1031
+ });
1032
+ expect(readJournal("acme").files["skills/moved/SKILL.md"]).toMatchObject({ skillMetadataPending: true });
1033
+ // Pass 2: the landed reconcile 409s; the non-landed fallback succeeds as a
1034
+ // `moved` (identity reserved, bytes unchanged); but the follow-up landed
1035
+ // retry hits a transient 5xx. The marker must be KEPT (not stranded) so the
1036
+ // metadata reconciles later — the fork's re-stamp did not change the bytes,
1037
+ // so nothing else would ever drive the reconcile.
1038
+ vi.mocked(headRemoteFile).mockResolvedValue({
1039
+ lastModified: new Date(),
1040
+ etag: '"upload-etag"',
1041
+ size: fs.statSync(file).size,
1042
+ });
1043
+ let landedRetryHappened = false;
1044
+ const flakyRegistrar = vi.fn(async (input) => {
1045
+ if (input.landed) {
1046
+ if (landedRetryHappened)
1047
+ throw new VaultClientError("registry unavailable", 503);
1048
+ landedRetryHappened = true;
1049
+ throw new VaultConflictError("landed identity mismatch");
1050
+ }
1051
+ // Non-landed fallback resolves as a move: identity reserved, bytes as-is.
1052
+ return {
1053
+ ok: true,
1054
+ skillUid: "skl_EXISTING1",
1055
+ path: input.path,
1056
+ vaultPath: input.path,
1057
+ content: input.content,
1058
+ action: "moved",
1059
+ accessPolicy: "open",
1060
+ skill: { name: "Moved", description: "Ready", tags: ["sales"] },
1061
+ };
1062
+ });
1063
+ const events = [];
1064
+ const second = await share({
1065
+ paths: [file],
1066
+ hqRoot,
1067
+ entityContext: makeEntityContext(),
1068
+ registerCompanySkill: flakyRegistrar,
1069
+ skipUnchanged: true,
1070
+ onEvent: (event) => events.push(event),
1071
+ });
1072
+ expect(second.aborted).toBe(false);
1073
+ // A transient retry is neither an error nor a deliberate skip.
1074
+ expect(events.some((event) => event.type === "error")).toBe(false);
1075
+ expect(events.some((event) => event.type === "not-shipped" &&
1076
+ event.reason === "skill-registration-conflict")).toBe(false);
1077
+ // The marker is RETAINED so the metadata reconciles on a later pass.
1078
+ expect(readJournal("acme").files["skills/moved/SKILL.md"]?.skillMetadataPending).toBe(true);
1079
+ // Pass 3: identity is reserved now, so the landed reconcile succeeds and the
1080
+ // marker finally clears — proving the retained marker does not loop.
1081
+ const healthyRegistrar = vi.fn(async (input) => ({
1082
+ ok: true,
1083
+ skillUid: "skl_EXISTING1",
1084
+ path: input.path,
1085
+ vaultPath: input.path,
1086
+ content: input.content,
1087
+ action: "reused",
1088
+ accessPolicy: "open",
1089
+ skill: { name: "Moved", description: "Ready", tags: ["sales"] },
1090
+ }));
1091
+ const third = await share({
1092
+ paths: [file],
1093
+ hqRoot,
1094
+ entityContext: makeEntityContext(),
1095
+ registerCompanySkill: healthyRegistrar,
1096
+ skipUnchanged: true,
1097
+ });
1098
+ expect(third.aborted).toBe(false);
1099
+ expect(readJournal("acme").files["skills/moved/SKILL.md"]?.skillMetadataPending).toBeUndefined();
1100
+ });
1101
+ it("HQ-DESKTOP-64: a pending landed reconcile that keeps hitting 409 no longer aborts the company push", async () => {
1102
+ const file = createSkill("copied", "---\nname: Copied\ndescription: Copied skill\nskill_uid: skl_SOURCE1\ntags: [sales]\n---\n");
1103
+ const other = path.join(hqRoot, "companies", "acme", "policies", "keep.md");
1104
+ fs.mkdirSync(path.dirname(other), { recursive: true });
1105
+ fs.writeFileSync(other, "keep syncing");
1106
+ // Pass 1: a transient registry failure leaves the pending marker set — the
1107
+ // unchanged base behaviour that produced the stuck journal in the field.
1108
+ await share({
1109
+ paths: [file, other],
1110
+ hqRoot,
1111
+ entityContext: makeEntityContext(),
1112
+ registerCompanySkill: vi.fn(async () => {
1113
+ throw new Error("registry temporarily unavailable");
1114
+ }),
1115
+ });
1116
+ expect(readJournal("acme").files["skills/copied/SKILL.md"]).toMatchObject({ skillMetadataPending: true });
1117
+ // Pass 2: the landed reconcile AND its non-landed fallback both 409 (a copy
1118
+ // the server will not re-identify from this machine). On the base runner
1119
+ // this rejected out of the pending loop and aborted the whole company leg.
1120
+ vi.mocked(uploadFile).mockClear();
1121
+ vi.mocked(headRemoteFile).mockResolvedValue({
1122
+ lastModified: new Date(),
1123
+ etag: '"upload-etag"',
1124
+ size: fs.statSync(file).size,
1125
+ });
1126
+ const conflictRegistrar = vi.fn(async () => {
1127
+ throw new VaultConflictError("landed identity mismatch");
1128
+ });
1129
+ const events = [];
1130
+ const second = await share({
1131
+ paths: [file, other],
1132
+ hqRoot,
1133
+ entityContext: makeEntityContext(),
1134
+ registerCompanySkill: conflictRegistrar,
1135
+ skipUnchanged: true,
1136
+ onEvent: (event) => events.push(event),
1137
+ });
1138
+ // The push completed instead of aborting the leg (HQ-DESKTOP-64).
1139
+ expect(second.aborted).toBe(false);
1140
+ expect(events.some((event) => event.type === "error")).toBe(false);
1141
+ // Exactly one deliberate-skip event names the skill and carries the reason.
1142
+ expect(events.filter((event) => event.type === "not-shipped" &&
1143
+ event.reason === "skill-registration-conflict")).toEqual([
1144
+ {
1145
+ type: "not-shipped",
1146
+ reason: "skill-registration-conflict",
1147
+ count: 1,
1148
+ samplePaths: ["skills/copied/SKILL.md"],
1149
+ message: "landed identity mismatch",
1150
+ },
1151
+ ]);
1152
+ // The marker is cleared, so the next pass cannot loop.
1153
+ expect(readJournal("acme").files["skills/copied/SKILL.md"]?.skillMetadataPending).toBeUndefined();
1154
+ });
1155
+ it.each([
1156
+ ["a permission denial (403)", new VaultPermissionDeniedError("this machine cannot fork skills"), "this machine cannot fork skills"],
1157
+ ["a validation rejection (400)", new VaultClientError("frontmatter.name is required", 400), "frontmatter.name is required"],
1158
+ ["a validation rejection (422)", new VaultClientError("frontmatter.tags is invalid", 422), "frontmatter.tags is invalid"],
1159
+ ["a second conflict (409)", new VaultConflictError("still ambiguous"), "still ambiguous"],
1160
+ ])("HQ-DESKTOP-64: a landed 409 whose non-landed fallback is refused by %s is a deliberate skip, not a company abort", async (_desc, fallbackError, message) => {
1161
+ const file = createSkill("copied", "---\nname: Copied\ndescription: Copied skill\nskill_uid: skl_SOURCE1\n---\n");
1162
+ const registrar = vi.fn(async (input) => {
1163
+ if (input.landed)
1164
+ throw new VaultConflictError("landed identity mismatch");
1165
+ throw fallbackError;
1166
+ });
1167
+ const events = [];
1168
+ const result = await share({
1169
+ paths: [file],
1170
+ hqRoot,
1171
+ entityContext: makeEntityContext(),
1172
+ registerCompanySkill: registrar,
1173
+ onEvent: (event) => events.push(event),
1174
+ });
1175
+ // The skill's content still synced; only its metadata was deferred.
1176
+ expect(result.filesUploaded).toBe(1);
1177
+ expect(result.aborted).toBe(false);
1178
+ expect(events.some((event) => event.type === "error")).toBe(false);
1179
+ expect(events).toContainEqual({
1180
+ type: "not-shipped",
1181
+ reason: "skill-registration-conflict",
1182
+ count: 1,
1183
+ samplePaths: ["skills/copied/SKILL.md"],
1184
+ message,
1185
+ });
1186
+ expect(readJournal("acme").files["skills/copied/SKILL.md"]?.skillMetadataPending).toBeUndefined();
1187
+ });
1188
+ it("still aborts the pass when the landed skill reconcile hits an auth refusal (unchanged)", async () => {
1189
+ const file = createSkill("existing", "---\nname: Existing\ndescription: Ready\nskill_uid: skl_EXISTING1\n---\n");
1190
+ const registrar = vi.fn(async (input) => {
1191
+ if (input.landed)
1192
+ throw new VaultAuthError("session expired");
1193
+ return registered(input, "skl_EXISTING1");
1194
+ });
1195
+ await expect(share({
1196
+ paths: [file],
1197
+ hqRoot,
1198
+ entityContext: makeEntityContext(),
1199
+ registerCompanySkill: registrar,
1200
+ })).rejects.toBeInstanceOf(VaultAuthError);
1201
+ });
694
1202
  it("propagates a mid-pass identity refusal from an upload instead of recording a per-file error (HQ-DESKTOP-5S)", async () => {
695
1203
  const file = createSkill("call-prep", "---\nname: Call Prep\ndescription: Prepare calls\nskill_uid: skl_PREFLIGHT1\n---\n\nDo the work.\n");
696
1204
  const registrar = vi.fn(async (input) => registered(input, "skl_PREFLIGHT1"));
@@ -1166,91 +1674,6 @@ describe("share", () => {
1166
1674
  // Remote key must be company-relative, not hqRoot-relative
1167
1675
  expect(uploadFile).toHaveBeenCalledWith(expect.anything(), testFile, "test.md", undefined, expect.anything());
1168
1676
  });
1169
- it("hands queued realtime work a settled full-push boundary without losing journal rows", async () => {
1170
- const companyRoot = path.join(tmpDir, "companies", "acme");
1171
- const fileCount = FULL_PUSH_COOPERATIVE_CHECKPOINT_BATCH_SIZE + 1;
1172
- for (let index = 0; index < fileCount; index++) {
1173
- const file = path.join(companyRoot, "docs", "full-push", `${index}.md`);
1174
- fs.mkdirSync(path.dirname(file), { recursive: true });
1175
- fs.writeFileSync(file, "full-push body");
1176
- }
1177
- const scheduler = new CooperativePassScheduler(() => 0);
1178
- let uploadsCompleted = 0;
1179
- let uploadsInFlight = 0;
1180
- let maxUploadsInFlight = 0;
1181
- let realtimeQueued = false;
1182
- let realtimeDispatchedAt = -1;
1183
- let checkpointCalls = 0;
1184
- let realtimePass;
1185
- const upload = vi.mocked(uploadFile);
1186
- const originalUpload = upload.getMockImplementation();
1187
- upload.mockImplementation(async () => {
1188
- uploadsInFlight++;
1189
- maxUploadsInFlight = Math.max(maxUploadsInFlight, uploadsInFlight);
1190
- await Promise.resolve();
1191
- uploadsCompleted++;
1192
- if (uploadsCompleted === 1) {
1193
- realtimeQueued = true;
1194
- realtimePass = scheduler.submit(async () => {
1195
- // `executeUploads` drains the full unit before the scheduler grants
1196
- // realtime the root lock: no two durable writers overlap.
1197
- expect(uploadsInFlight).toBe(0);
1198
- realtimeDispatchedAt = uploadsCompleted;
1199
- const realtimePath = path.join(companyRoot, "docs", "realtime.md");
1200
- fs.writeFileSync(realtimePath, "realtime body");
1201
- const journal = readJournal("acme");
1202
- journal.files["docs/realtime.md"] = {
1203
- hash: hashFile(realtimePath),
1204
- size: fs.statSync(realtimePath).size,
1205
- syncedAt: "2026-09-17T12:00:00.000Z",
1206
- direction: "up",
1207
- remoteEtag: "realtime",
1208
- mtimeMs: fs.statSync(realtimePath).mtimeMs,
1209
- ctimeMs: fs.statSync(realtimePath).ctimeMs,
1210
- };
1211
- writeJournal("acme", journal);
1212
- }, "realtime");
1213
- }
1214
- uploadsInFlight--;
1215
- return { etag: '"full-push-etag"' };
1216
- });
1217
- try {
1218
- await scheduler.submit(async ({ checkpoint }) => {
1219
- await share({
1220
- paths: [companyRoot],
1221
- company: "acme",
1222
- vaultConfig: mockConfig,
1223
- hqRoot: tmpDir,
1224
- skipUnchanged: true,
1225
- propagateDeletes: true,
1226
- cooperativeCheckpoint: async () => {
1227
- checkpointCalls++;
1228
- return checkpoint();
1229
- },
1230
- });
1231
- }, "chore");
1232
- await realtimePass;
1233
- }
1234
- finally {
1235
- if (originalUpload)
1236
- upload.mockImplementation(originalUpload);
1237
- else
1238
- upload.mockReset();
1239
- }
1240
- expect(maxUploadsInFlight).toBeGreaterThan(1);
1241
- expect(realtimeQueued).toBe(true);
1242
- expect(checkpointCalls).toBeGreaterThan(0);
1243
- expect(realtimeDispatchedAt).toBeGreaterThan(0);
1244
- expect(realtimeDispatchedAt).toBeLessThanOrEqual(FULL_PUSH_COOPERATIVE_CHECKPOINT_BATCH_SIZE);
1245
- // Reopen the durable journal, rather than inspecting the stale first-pass
1246
- // object: every pre-handoff key and the realtime key must survive.
1247
- const durable = readJournal("acme");
1248
- expect(Object.keys(durable.files)).toHaveLength(fileCount + 1);
1249
- expect(durable.files["docs/realtime.md"]).toBeDefined();
1250
- for (let index = 0; index < fileCount; index++) {
1251
- expect(durable.files[`docs/full-push/${index}.md`]).toBeDefined();
1252
- }
1253
- }, 120_000);
1254
1677
  it("replans an upload from the bytes present when its action starts", async () => {
1255
1678
  const companyRoot = path.join(tmpDir, "companies", "acme");
1256
1679
  fs.mkdirSync(companyRoot, { recursive: true });
@@ -2521,6 +2944,96 @@ describe("share", () => {
2521
2944
  remoteEtag: "288bfa91684ae21f9ae27c061254d412",
2522
2945
  });
2523
2946
  });
2947
+ it("does not PUT when the remote publishes the same SHA-256 under a new SSE-KMS ETag", async () => {
2948
+ const companyRoot = path.join(tmpDir, "companies", "acme");
2949
+ fs.mkdirSync(companyRoot, { recursive: true });
2950
+ const testFile = path.join(companyRoot, "lineage-noop.md");
2951
+ fs.writeFileSync(testFile, "same bytes, new encrypted version");
2952
+ const stat = fs.lstatSync(testFile);
2953
+ const localHash = hashFile(testFile);
2954
+ seedJournalAt(path.join(stateDir, "sync-journal.acme.json"), {
2955
+ version: "1",
2956
+ lastSync: new Date().toISOString(),
2957
+ files: {
2958
+ "lineage-noop.md": {
2959
+ hash: "b".repeat(64),
2960
+ size: stat.size,
2961
+ mtimeMs: stat.mtimeMs - 1,
2962
+ ctimeMs: stat.ctimeMs - 1,
2963
+ remoteEtag: "journal-kms-etag",
2964
+ syncedAt: new Date().toISOString(),
2965
+ direction: "up",
2966
+ },
2967
+ },
2968
+ });
2969
+ vi.mocked(headRemoteFile).mockResolvedValueOnce({
2970
+ lastModified: new Date(),
2971
+ etag: '"new-kms-etag"',
2972
+ size: stat.size,
2973
+ metadata: { "hq-content-sha256": localHash },
2974
+ });
2975
+ const result = await share({
2976
+ paths: [testFile],
2977
+ company: "acme",
2978
+ vaultConfig: mockConfig,
2979
+ hqRoot: tmpDir,
2980
+ onConflict: "overwrite",
2981
+ });
2982
+ expect(result.filesUploaded).toBe(0);
2983
+ expect(result.conflictPaths).toEqual([]);
2984
+ expect(uploadFile).not.toHaveBeenCalled();
2985
+ expect(readJournal("acme").files["lineage-noop.md"]).toMatchObject({
2986
+ hash: localHash,
2987
+ remoteEtag: "new-kms-etag",
2988
+ });
2989
+ });
2990
+ it("refuses an unchanged journal baseline after a published remote hash advances", async () => {
2991
+ const companyRoot = path.join(tmpDir, "companies", "acme");
2992
+ fs.mkdirSync(companyRoot, { recursive: true });
2993
+ const testFile = path.join(companyRoot, "lineage-stale-replay.md");
2994
+ fs.writeFileSync(testFile, "the old local generation");
2995
+ const stat = fs.lstatSync(testFile);
2996
+ const localHash = hashFile(testFile);
2997
+ seedJournalAt(path.join(stateDir, "sync-journal.acme.json"), {
2998
+ version: "1",
2999
+ lastSync: new Date().toISOString(),
3000
+ files: {
3001
+ "lineage-stale-replay.md": {
3002
+ hash: localHash,
3003
+ size: stat.size,
3004
+ mtimeMs: stat.mtimeMs,
3005
+ ctimeMs: stat.ctimeMs,
3006
+ remoteEtag: "old-kms-etag",
3007
+ syncedAt: new Date().toISOString(),
3008
+ direction: "up",
3009
+ },
3010
+ },
3011
+ });
3012
+ vi.mocked(headRemoteFile).mockResolvedValueOnce({
3013
+ lastModified: new Date(),
3014
+ etag: '"new-kms-etag"',
3015
+ size: stat.size,
3016
+ metadata: { "hq-content-sha256": "b".repeat(64) },
3017
+ });
3018
+ const events = [];
3019
+ const result = await share({
3020
+ paths: [testFile],
3021
+ company: "acme",
3022
+ vaultConfig: mockConfig,
3023
+ hqRoot: tmpDir,
3024
+ onConflict: "overwrite",
3025
+ onEvent: (event) => events.push(event),
3026
+ });
3027
+ expect(result.filesUploaded).toBe(0);
3028
+ expect(result.conflictPaths).toEqual(["lineage-stale-replay.md"]);
3029
+ expect(uploadFile).not.toHaveBeenCalled();
3030
+ expect(events).toContainEqual({
3031
+ type: "conflict",
3032
+ path: "lineage-stale-replay.md",
3033
+ direction: "push",
3034
+ resolution: "skip",
3035
+ });
3036
+ });
2524
3037
  it("fresh-install multipart collision: byte-identical remote is NOT a conflict (reconciled, no mirror)", async () => {
2525
3038
  // Root cause of "HQ installs with conflicts": on a first push the
2526
3039
  // journal is empty, so the fresh-collision branch decides conflict-vs-