@indigoai-us/hq-cloud 6.16.52 → 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.
@@ -66,7 +66,7 @@ vi.mock("readline", () => ({
66
66
  import * as readline from "readline";
67
67
  import { share, ServerOwnedPushPathsError, UnreachablePushPathsError, UnregisteredCompanySkillError, currentUploadBytes, parseRegisteredCompanySkillUid, _testing as shareTesting, } from "./share.js";
68
68
  import { deleteRemoteFile, downloadFile, headRemoteFile, primeObjectTransport, primeUploads, uploadFile, uploadSymlink, WindowsSymlinkPrivilegeError, } from "../s3.js";
69
- import { VaultAuthError, VaultClientError, VaultPermissionDeniedError, } from "../vault-client.js";
69
+ import { VaultAuthError, VaultClientError, VaultConflictError, VaultPermissionDeniedError, } from "../vault-client.js";
70
70
  import { CognitoRefreshError } from "../cognito-auth.js";
71
71
  import { AreaLedgerMigration, closeCachedAreaJournalMigration, hashFile, openJournalStateStoreForMigration, readJournal, readJournalScoped, setAreaLedgerMigrationTestHooksForTest, writeJournal, } from "../journal.js";
72
72
  import { ReconcileCursorStore } from "../sync/reconcile-cursor.js";
@@ -201,6 +201,20 @@ describe("company skill identity preflight", () => {
201
201
  skill: { name: "Call Prep", description: "Prepare calls", tags: [] },
202
202
  };
203
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
+ }
204
218
  it("registers and atomically stamps an unstamped canonical skill before upload", async () => {
205
219
  const file = createSkill("call-prep", "---\nname: Call Prep\ndescription: Prepare calls\n---\n\nDo the work.\n");
206
220
  const registrar = vi.fn(async (input) => registered(input));
@@ -383,15 +397,254 @@ describe("company skill identity preflight", () => {
383
397
  registerCompanySkill: registrar,
384
398
  onEvent: (event) => events.push(event),
385
399
  });
386
- expect(registrar).toHaveBeenCalledOnce();
387
- 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, {
388
405
  companySlug: "acme",
389
406
  path: "skills/existing/SKILL.md",
390
407
  content: expect.stringContaining("skill_uid: skl_EXISTING1"),
408
+ });
409
+ expect(registrar).toHaveBeenLastCalledWith({
410
+ companySlug: "acme",
411
+ path: "skills/existing/SKILL.md",
412
+ content: expect.stringContaining("skill_uid: skl_EXISTING1"),
413
+ landed: true,
414
+ });
415
+ expect(result.filesUploaded).toBe(1);
416
+ expect(events.some((event) => event.type === "not-shipped")).toBe(false);
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"),
391
472
  landed: true,
392
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.
393
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
+ }));
394
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);
395
648
  });
396
649
  it("does not reconcile bytes edited while the upload is in flight", async () => {
397
650
  const original = "---\nname: Existing\ndescription: Ready\nskill_uid: skl_EXISTING1\ntags: [sales]\n---\n";
@@ -408,7 +661,10 @@ describe("company skill identity preflight", () => {
408
661
  registerCompanySkill: registrar,
409
662
  });
410
663
  expect(result.filesUploaded).toBe(1);
411
- 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 }));
412
668
  });
413
669
  it("retries a failed post-upload metadata reconciliation without re-uploading", async () => {
414
670
  const file = createSkill("existing", "---\nname: Existing\ndescription: Ready\nskill_uid: skl_EXISTING1\ntags: [sales]\n---\n");
@@ -484,7 +740,10 @@ describe("company skill identity preflight", () => {
484
740
  entityContext: makeEntityContext(),
485
741
  registerCompanySkill: registrar,
486
742
  });
487
- 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 }));
488
747
  expect(pendingAtReconcile)
489
748
  .toMatchObject({ skillMetadataPending: true, remoteEtag: "upload-etag" });
490
749
  });
@@ -556,8 +815,10 @@ describe("company skill identity preflight", () => {
556
815
  }
557
816
  expect(result.filesUploaded).toBe(1);
558
817
  expect(uploadFile).toHaveBeenCalledOnce();
559
- expect(registrar).toHaveBeenCalledOnce();
560
- 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({
561
822
  content: changed,
562
823
  landed: true,
563
824
  }));
@@ -628,13 +889,24 @@ describe("company skill identity preflight", () => {
628
889
  size: fs.statSync(file).size,
629
890
  });
630
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 = [];
631
896
  await expect(share({
632
897
  paths: [file],
633
898
  hqRoot,
634
899
  entityContext: makeEntityContext(),
635
900
  registerCompanySkill: vi.fn(async (input) => registered(input, "skl_EXISTING1")),
636
901
  skipUnchanged: true,
637
- })).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
+ }));
638
910
  expect(readJournal("acme").files["skills/existing/SKILL.md"])
639
911
  .toBeUndefined();
640
912
  });
@@ -692,6 +964,241 @@ describe("company skill identity preflight", () => {
692
964
  expect(fs.readFileSync(file, "utf8")).toBe(original);
693
965
  expect(uploadFile).not.toHaveBeenCalled();
694
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
+ });
695
1202
  it("propagates a mid-pass identity refusal from an upload instead of recording a per-file error (HQ-DESKTOP-5S)", async () => {
696
1203
  const file = createSkill("call-prep", "---\nname: Call Prep\ndescription: Prepare calls\nskill_uid: skl_PREFLIGHT1\n---\n\nDo the work.\n");
697
1204
  const registrar = vi.fn(async (input) => registered(input, "skl_PREFLIGHT1"));