@indigoai-us/hq-cloud 6.11.10 → 6.11.12

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 (173) hide show
  1. package/dist/bin/sync-runner.d.ts +2 -0
  2. package/dist/bin/sync-runner.d.ts.map +1 -1
  3. package/dist/bin/sync-runner.js +231 -52
  4. package/dist/bin/sync-runner.js.map +1 -1
  5. package/dist/bin/sync-runner.test.js +330 -11
  6. package/dist/bin/sync-runner.test.js.map +1 -1
  7. package/dist/cli/reindex.d.ts.map +1 -1
  8. package/dist/cli/reindex.js +16 -1
  9. package/dist/cli/reindex.js.map +1 -1
  10. package/dist/cli/reindex.test.js +39 -1
  11. package/dist/cli/reindex.test.js.map +1 -1
  12. package/dist/cli/rescue-classify-ordering.test.js +58 -0
  13. package/dist/cli/rescue-classify-ordering.test.js.map +1 -1
  14. package/dist/cli/rescue-core.js +229 -15
  15. package/dist/cli/rescue-core.js.map +1 -1
  16. package/dist/cli/rescue-exec-bit-preserve.test.d.ts +2 -0
  17. package/dist/cli/rescue-exec-bit-preserve.test.d.ts.map +1 -0
  18. package/dist/cli/rescue-exec-bit-preserve.test.js +169 -0
  19. package/dist/cli/rescue-exec-bit-preserve.test.js.map +1 -0
  20. package/dist/cli/share.d.ts +2 -1
  21. package/dist/cli/share.d.ts.map +1 -1
  22. package/dist/cli/share.js +100 -32
  23. package/dist/cli/share.js.map +1 -1
  24. package/dist/cli/share.test.js +30 -0
  25. package/dist/cli/share.test.js.map +1 -1
  26. package/dist/cli/sync.d.ts +28 -1
  27. package/dist/cli/sync.d.ts.map +1 -1
  28. package/dist/cli/sync.js +188 -59
  29. package/dist/cli/sync.js.map +1 -1
  30. package/dist/cli/sync.test.js +487 -1
  31. package/dist/cli/sync.test.js.map +1 -1
  32. package/dist/cognito-auth.d.ts.map +1 -1
  33. package/dist/cognito-auth.js +55 -10
  34. package/dist/cognito-auth.js.map +1 -1
  35. package/dist/cognito-auth.test.js +61 -0
  36. package/dist/cognito-auth.test.js.map +1 -1
  37. package/dist/index.d.ts +2 -1
  38. package/dist/index.d.ts.map +1 -1
  39. package/dist/index.js +1 -1
  40. package/dist/index.js.map +1 -1
  41. package/dist/journal.d.ts.map +1 -1
  42. package/dist/journal.js +93 -6
  43. package/dist/journal.js.map +1 -1
  44. package/dist/journal.test.js +59 -0
  45. package/dist/journal.test.js.map +1 -1
  46. package/dist/machine-auth.test.js +60 -2
  47. package/dist/machine-auth.test.js.map +1 -1
  48. package/dist/object-io.d.ts +37 -1
  49. package/dist/object-io.d.ts.map +1 -1
  50. package/dist/object-io.js +148 -29
  51. package/dist/object-io.js.map +1 -1
  52. package/dist/object-io.test.js +121 -0
  53. package/dist/object-io.test.js.map +1 -1
  54. package/dist/operation-lock.d.ts +8 -8
  55. package/dist/operation-lock.d.ts.map +1 -1
  56. package/dist/operation-lock.js +99 -32
  57. package/dist/operation-lock.js.map +1 -1
  58. package/dist/operation-lock.test.js +51 -4
  59. package/dist/operation-lock.test.js.map +1 -1
  60. package/dist/personal-vault.d.ts +8 -0
  61. package/dist/personal-vault.d.ts.map +1 -1
  62. package/dist/personal-vault.js +17 -3
  63. package/dist/personal-vault.js.map +1 -1
  64. package/dist/personal-vault.test.js +34 -0
  65. package/dist/personal-vault.test.js.map +1 -1
  66. package/dist/prefix-coalesce.d.ts +20 -9
  67. package/dist/prefix-coalesce.d.ts.map +1 -1
  68. package/dist/prefix-coalesce.js +124 -28
  69. package/dist/prefix-coalesce.js.map +1 -1
  70. package/dist/prefix-coalesce.test.js +57 -2
  71. package/dist/prefix-coalesce.test.js.map +1 -1
  72. package/dist/remote-pull.d.ts +6 -1
  73. package/dist/remote-pull.d.ts.map +1 -1
  74. package/dist/remote-pull.js +62 -13
  75. package/dist/remote-pull.js.map +1 -1
  76. package/dist/remote-pull.test.js +189 -0
  77. package/dist/remote-pull.test.js.map +1 -1
  78. package/dist/s3.d.ts +2 -0
  79. package/dist/s3.d.ts.map +1 -1
  80. package/dist/s3.js +197 -116
  81. package/dist/s3.js.map +1 -1
  82. package/dist/s3.test.js +109 -0
  83. package/dist/s3.test.js.map +1 -1
  84. package/dist/scope-shrink.d.ts +3 -2
  85. package/dist/scope-shrink.d.ts.map +1 -1
  86. package/dist/scope-shrink.js +1 -1
  87. package/dist/scope-shrink.js.map +1 -1
  88. package/dist/skill-telemetry.d.ts +1 -1
  89. package/dist/skill-telemetry.d.ts.map +1 -1
  90. package/dist/skill-telemetry.js +69 -9
  91. package/dist/skill-telemetry.js.map +1 -1
  92. package/dist/skill-telemetry.test.js +86 -0
  93. package/dist/skill-telemetry.test.js.map +1 -1
  94. package/dist/sync/event-sync.d.ts +6 -0
  95. package/dist/sync/event-sync.d.ts.map +1 -1
  96. package/dist/sync/event-sync.js +34 -1
  97. package/dist/sync/event-sync.js.map +1 -1
  98. package/dist/sync/event-sync.test.js +73 -0
  99. package/dist/sync/event-sync.test.js.map +1 -1
  100. package/dist/sync/metrics.d.ts +17 -1
  101. package/dist/sync/metrics.d.ts.map +1 -1
  102. package/dist/sync/metrics.js +32 -1
  103. package/dist/sync/metrics.js.map +1 -1
  104. package/dist/sync/metrics.test.js +74 -1
  105. package/dist/sync/metrics.test.js.map +1 -1
  106. package/dist/sync/pull-scope.d.ts.map +1 -1
  107. package/dist/sync/pull-scope.js +15 -7
  108. package/dist/sync/pull-scope.js.map +1 -1
  109. package/dist/sync/push-receiver.d.ts +6 -5
  110. package/dist/sync/push-receiver.d.ts.map +1 -1
  111. package/dist/sync/push-receiver.js +13 -15
  112. package/dist/sync/push-receiver.js.map +1 -1
  113. package/dist/sync/push-receiver.test.js +36 -1
  114. package/dist/sync/push-receiver.test.js.map +1 -1
  115. package/dist/telemetry.d.ts +1 -1
  116. package/dist/telemetry.d.ts.map +1 -1
  117. package/dist/telemetry.js +59 -6
  118. package/dist/telemetry.js.map +1 -1
  119. package/dist/telemetry.test.js +74 -0
  120. package/dist/telemetry.test.js.map +1 -1
  121. package/dist/types.d.ts +8 -0
  122. package/dist/types.d.ts.map +1 -1
  123. package/dist/watcher.d.ts +36 -0
  124. package/dist/watcher.d.ts.map +1 -1
  125. package/dist/watcher.js +152 -30
  126. package/dist/watcher.js.map +1 -1
  127. package/dist/watcher.test.js +103 -0
  128. package/dist/watcher.test.js.map +1 -1
  129. package/package.json +1 -1
  130. package/src/bin/sync-runner.test.ts +396 -11
  131. package/src/bin/sync-runner.ts +254 -52
  132. package/src/cli/reindex.test.ts +47 -1
  133. package/src/cli/reindex.ts +17 -1
  134. package/src/cli/rescue-classify-ordering.test.ts +61 -0
  135. package/src/cli/rescue-core.ts +261 -15
  136. package/src/cli/rescue-exec-bit-preserve.test.ts +187 -0
  137. package/src/cli/share.test.ts +38 -0
  138. package/src/cli/share.ts +103 -34
  139. package/src/cli/sync.test.ts +594 -1
  140. package/src/cli/sync.ts +229 -65
  141. package/src/cognito-auth.test.ts +77 -0
  142. package/src/cognito-auth.ts +73 -11
  143. package/src/index.ts +8 -0
  144. package/src/journal.test.ts +72 -0
  145. package/src/journal.ts +95 -8
  146. package/src/machine-auth.test.ts +64 -2
  147. package/src/object-io.test.ts +142 -0
  148. package/src/object-io.ts +182 -30
  149. package/src/operation-lock.test.ts +63 -4
  150. package/src/operation-lock.ts +99 -31
  151. package/src/personal-vault.test.ts +42 -0
  152. package/src/personal-vault.ts +18 -3
  153. package/src/prefix-coalesce.test.ts +71 -1
  154. package/src/prefix-coalesce.ts +155 -30
  155. package/src/remote-pull.test.ts +205 -0
  156. package/src/remote-pull.ts +77 -14
  157. package/src/s3.test.ts +126 -0
  158. package/src/s3.ts +237 -122
  159. package/src/scope-shrink.ts +6 -3
  160. package/src/skill-telemetry.test.ts +109 -0
  161. package/src/skill-telemetry.ts +82 -14
  162. package/src/sync/event-sync.test.ts +75 -0
  163. package/src/sync/event-sync.ts +54 -1
  164. package/src/sync/metrics.test.ts +81 -0
  165. package/src/sync/metrics.ts +59 -4
  166. package/src/sync/pull-scope.ts +23 -7
  167. package/src/sync/push-receiver.test.ts +38 -1
  168. package/src/sync/push-receiver.ts +15 -18
  169. package/src/telemetry.test.ts +85 -0
  170. package/src/telemetry.ts +69 -6
  171. package/src/types.ts +8 -0
  172. package/src/watcher.test.ts +117 -0
  173. package/src/watcher.ts +209 -33
@@ -8,6 +8,7 @@ import * as path from "path";
8
8
  import * as os from "os";
9
9
  import { clearContextCache } from "../context.js";
10
10
  import type { VaultServiceConfig } from "../types.js";
11
+ import { lockPathFor } from "../operation-lock.js";
11
12
 
12
13
  // Mock s3 module at the top level
13
14
  vi.mock("../s3.js", async () => {
@@ -42,7 +43,7 @@ vi.mock("./reindex.js", () => ({
42
43
  reindex: vi.fn(() => ({ status: 0 })),
43
44
  }));
44
45
 
45
- import { sync } from "./sync.js";
46
+ import { sync, reportNewFilesToNotify } from "./sync.js";
46
47
  import * as s3Module from "../s3.js";
47
48
  import { reindex } from "./reindex.js";
48
49
 
@@ -143,6 +144,31 @@ describe("sync", () => {
143
144
  expect(reindex).toHaveBeenCalledWith({ repoRoot: tmpDir, skipLock: true });
144
145
  });
145
146
 
147
+ it("F15: public sync entrypoint refuses an already-held operation lock", async () => {
148
+ process.env.HQ_OP_LOCK_TIMEOUT = "0";
149
+ const lockPath = lockPathFor(tmpDir);
150
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
151
+ fs.writeFileSync(
152
+ lockPath,
153
+ JSON.stringify({
154
+ pid: 1,
155
+ command: "rescue",
156
+ startedAt: new Date().toISOString(),
157
+ hqRoot: path.resolve(tmpDir),
158
+ }),
159
+ );
160
+
161
+ try {
162
+ await expect(
163
+ sync({ company: "acme", vaultConfig: mockConfig, hqRoot: tmpDir }),
164
+ ).rejects.toThrow(/another HQ operation is already running/);
165
+ expect(s3Module.listRemoteFiles).not.toHaveBeenCalled();
166
+ expect(reindex).not.toHaveBeenCalled();
167
+ } finally {
168
+ delete process.env.HQ_OP_LOCK_TIMEOUT;
169
+ }
170
+ });
171
+
146
172
  it("skips reindex when skipReindex is set", async () => {
147
173
  const result = await sync({
148
174
  company: "acme",
@@ -522,6 +548,195 @@ describe("sync", () => {
522
548
  expect(fs.readFileSync(localPath, "utf-8")).toBe("mock file content");
523
549
  });
524
550
 
551
+ it("RF-F02EXEC: refuses a download whose parent symlink appears after planning", async () => {
552
+ const companyRoot = path.join(tmpDir, "companies", "acme");
553
+ const outsideRoot = fs.mkdtempSync(path.join(os.tmpdir(), "hq-sync-escape-"));
554
+ const previousConcurrency = process.env.HQ_SYNC_TRANSFER_CONCURRENCY;
555
+ const defaultDownload = vi.mocked(s3Module.downloadFile).getMockImplementation();
556
+ process.env.HQ_SYNC_TRANSFER_CONCURRENCY = "1";
557
+
558
+ vi.mocked(s3Module.listRemoteFiles).mockResolvedValueOnce([
559
+ { key: "docs/setup.md", size: 5, lastModified: new Date(), etag: '"setup"' },
560
+ { key: "trap/secret.md", size: 6, lastModified: new Date(), etag: '"secret"' },
561
+ ]);
562
+ vi.mocked(s3Module.downloadFile).mockImplementation(
563
+ async (_ctx: unknown, key: string, localPath: string) => {
564
+ fs.mkdirSync(path.dirname(localPath), { recursive: true });
565
+ if (key === "docs/setup.md") {
566
+ fs.writeFileSync(localPath, "setup");
567
+ fs.symlinkSync(outsideRoot, path.join(companyRoot, "trap"), "dir");
568
+ } else {
569
+ fs.writeFileSync(localPath, "escaped");
570
+ }
571
+ return { metadata: {} };
572
+ },
573
+ );
574
+
575
+ const events: Array<{ type: string; path?: string; message?: string }> = [];
576
+ try {
577
+ const result = await sync({
578
+ company: "acme",
579
+ vaultConfig: mockConfig,
580
+ hqRoot: tmpDir,
581
+ onEvent: (e) => events.push(e),
582
+ });
583
+
584
+ expect(result.filesDownloaded).toBe(1);
585
+ expect(fs.readFileSync(path.join(companyRoot, "docs", "setup.md"), "utf-8")).toBe(
586
+ "setup",
587
+ );
588
+ expect(fs.existsSync(path.join(outsideRoot, "secret.md"))).toBe(false);
589
+ expect(
590
+ events.some(
591
+ (e) =>
592
+ e.type === "error" &&
593
+ e.path === "trap/secret.md" &&
594
+ e.message?.includes("escaped the sync root"),
595
+ ),
596
+ ).toBe(true);
597
+ } finally {
598
+ if (defaultDownload) vi.mocked(s3Module.downloadFile).mockImplementation(defaultDownload);
599
+ if (previousConcurrency === undefined) {
600
+ delete process.env.HQ_SYNC_TRANSFER_CONCURRENCY;
601
+ } else {
602
+ process.env.HQ_SYNC_TRANSFER_CONCURRENCY = previousConcurrency;
603
+ }
604
+ fs.rmSync(outsideRoot, { recursive: true, force: true });
605
+ }
606
+ });
607
+
608
+ it("RF-F02EXEC-conflict", async () => {
609
+ const companyRoot = path.join(tmpDir, "companies", "acme");
610
+ const companyDocs = path.join(companyRoot, "docs");
611
+ const outsideRoot = fs.mkdtempSync(path.join(os.tmpdir(), "hq-sync-conflict-escape-"));
612
+ const localPath = path.join(companyDocs, "handoff.md");
613
+ fs.mkdirSync(companyDocs, { recursive: true });
614
+ fs.writeFileSync(localPath, "local version");
615
+
616
+ vi.mocked(s3Module.listRemoteFiles).mockResolvedValueOnce([
617
+ { key: "docs/handoff.md", size: 42, lastModified: new Date(), etag: '"new-etag"' },
618
+ ]);
619
+
620
+ fs.writeFileSync(
621
+ journalPath,
622
+ JSON.stringify({
623
+ version: "1",
624
+ lastSync: new Date().toISOString(),
625
+ files: {
626
+ "docs/handoff.md": {
627
+ hash: "stale-hash",
628
+ size: 20,
629
+ remoteEtag: "old-etag",
630
+ syncedAt: new Date(Date.now() - 3600000).toISOString(),
631
+ direction: "down",
632
+ },
633
+ },
634
+ }),
635
+ );
636
+
637
+ const events: Array<{ type: string; path?: string; message?: string }> = [];
638
+ let swappedParent = false;
639
+ try {
640
+ const result = await sync({
641
+ company: "acme",
642
+ onConflict: "keep",
643
+ vaultConfig: mockConfig,
644
+ hqRoot: tmpDir,
645
+ onEvent: (e) => {
646
+ events.push(e);
647
+ if (e.type === "plan" && !swappedParent) {
648
+ swappedParent = true;
649
+ fs.rmSync(companyDocs, { recursive: true, force: true });
650
+ fs.symlinkSync(outsideRoot, companyDocs, "dir");
651
+ }
652
+ },
653
+ });
654
+
655
+ expect(swappedParent).toBe(true);
656
+ expect(result.conflicts).toBe(0);
657
+ expect(result.filesSkipped).toBeGreaterThanOrEqual(1);
658
+ expect(s3Module.downloadFile).not.toHaveBeenCalled();
659
+ expect(fs.readdirSync(outsideRoot)).toEqual([]);
660
+ expect(
661
+ events.some(
662
+ (e) =>
663
+ e.type === "error" &&
664
+ e.path === "docs/handoff.md" &&
665
+ e.message?.includes("escaped the sync root"),
666
+ ),
667
+ ).toBe(true);
668
+ } finally {
669
+ fs.rmSync(outsideRoot, { recursive: true, force: true });
670
+ }
671
+ });
672
+
673
+ it("RF-F33: FILE_TOMBSTONE planned against absence does not delete a new untracked file", async () => {
674
+ const untrackedKey = "docs/untracked.md";
675
+ const trackedKey = "docs/tracked.md";
676
+ const companyRoot = path.join(tmpDir, "companies", "acme");
677
+ const untrackedPath = path.join(companyRoot, untrackedKey);
678
+ const trackedPath = path.join(companyRoot, trackedKey);
679
+ fs.mkdirSync(path.dirname(trackedPath), { recursive: true });
680
+ fs.writeFileSync(trackedPath, "tracked baseline");
681
+ const { hashFile } = await import("../journal.js");
682
+
683
+ setupFetchMock({
684
+ tombstones: [
685
+ { key: untrackedKey, deletedAt: "2026-06-20T00:00:00.000Z" },
686
+ { key: trackedKey, deletedAt: "2026-06-20T00:00:00.000Z" },
687
+ ],
688
+ });
689
+ vi.mocked(s3Module.listRemoteFiles).mockResolvedValueOnce([
690
+ {
691
+ key: untrackedKey,
692
+ size: 10,
693
+ lastModified: new Date("2026-06-19T00:00:00.000Z"),
694
+ etag: '"untracked"',
695
+ },
696
+ {
697
+ key: trackedKey,
698
+ size: 16,
699
+ lastModified: new Date("2026-06-19T00:00:00.000Z"),
700
+ etag: '"tracked"',
701
+ },
702
+ ]);
703
+ fs.writeFileSync(
704
+ journalPath,
705
+ JSON.stringify({
706
+ version: "2",
707
+ lastSync: "2026-06-19T00:00:00.000Z",
708
+ files: {
709
+ [trackedKey]: {
710
+ hash: hashFile(trackedPath),
711
+ size: Buffer.byteLength("tracked baseline"),
712
+ syncedAt: "2026-06-19T00:00:00.000Z",
713
+ direction: "down",
714
+ remoteEtag: "tracked",
715
+ },
716
+ },
717
+ pulls: [],
718
+ }),
719
+ );
720
+
721
+ await sync({
722
+ company: "acme",
723
+ vaultConfig: mockConfig,
724
+ hqRoot: tmpDir,
725
+ onEvent: (e) => {
726
+ if (e.type === "plan") {
727
+ fs.mkdirSync(path.dirname(untrackedPath), { recursive: true });
728
+ fs.writeFileSync(untrackedPath, "brand new local work");
729
+ }
730
+ },
731
+ });
732
+
733
+ expect(fs.readFileSync(untrackedPath, "utf-8")).toBe("brand new local work");
734
+ expect(fs.existsSync(trackedPath)).toBe(false);
735
+ const journal = JSON.parse(fs.readFileSync(journalPath, "utf-8"));
736
+ expect(journal.files[untrackedKey]).toBeUndefined();
737
+ expect(journal.files[trackedKey]).toBeUndefined();
738
+ });
739
+
525
740
  it("aborts on --on-conflict abort", async () => {
526
741
  const companyDocs = path.join(tmpDir, "companies", "acme", "docs");
527
742
  fs.mkdirSync(companyDocs, { recursive: true });
@@ -611,6 +826,165 @@ describe("sync", () => {
611
826
  expect(fs.existsSync(path.join(tmpDir, "companies", "acme", "docs", "readme.md"))).toBe(false);
612
827
  });
613
828
 
829
+ it("personalMode: downloads + journals companies/manifest.yaml (carve-out round-trips) while still skipping other companies/* keys", async () => {
830
+ vi.mocked(s3Module.listRemoteFiles).mockResolvedValueOnce([
831
+ { key: "companies/foo/bar.md", size: 50, lastModified: new Date(), etag: '"xyz789"' },
832
+ { key: "companies/manifest.yaml", size: 40, lastModified: new Date(), etag: '"man111"' },
833
+ ]);
834
+
835
+ const result = await sync({
836
+ company: "acme",
837
+ vaultConfig: mockConfig,
838
+ hqRoot: tmpDir,
839
+ personalMode: true,
840
+ });
841
+
842
+ // The manifest is the lone companies/* exemption: it downloads; other
843
+ // companies/* keys are still dropped.
844
+ expect(result.filesSkipped).toBe(1);
845
+ expect(result.filesDownloaded).toBe(1);
846
+ expect(fs.existsSync(path.join(tmpDir, "companies", "manifest.yaml"))).toBe(true);
847
+ expect(fs.existsSync(path.join(tmpDir, "companies", "foo", "bar.md"))).toBe(false);
848
+
849
+ // The whole point: it now gets a journal baseline, so the push side stops
850
+ // re-firing a transient conflict every sync (the bug this fix closes).
851
+ const journaledManifest = fs
852
+ .readdirSync(stateDir)
853
+ .filter((f) => f.startsWith("sync-journal."))
854
+ .some((f) => {
855
+ const j = JSON.parse(fs.readFileSync(path.join(stateDir, f), "utf8"));
856
+ return j.files?.["companies/manifest.yaml"] != null;
857
+ });
858
+ expect(journaledManifest).toBe(true);
859
+ });
860
+
861
+ it("personalMode pull lands the session-continuity pointer + active thread file under <hqRoot>/workspace/threads/ so a handoff resumes on machine B (DEV-1778)", async () => {
862
+ // End-to-end download leg of the cross-machine handoff. Machine A pushed
863
+ // workspace/threads/handoff.json + the thread file it points to into the
864
+ // personal bucket; machine B pulls and both must land hq-root-relative
865
+ // (NOT under companies/<slug>/) with the pointer still resolving to the
866
+ // thread file that also landed — that is what lets /startwork resume.
867
+ const handoffKey = "workspace/threads/handoff.json";
868
+ const threadKey = "workspace/threads/T-20260619-1200-resume-me.json";
869
+
870
+ vi.mocked(s3Module.listRemoteFiles).mockResolvedValueOnce([
871
+ { key: handoffKey, size: 80, lastModified: new Date(), etag: '"h1"' },
872
+ { key: threadKey, size: 40, lastModified: new Date(), etag: '"t1"' },
873
+ ]);
874
+
875
+ // Materialize realistic bytes per key (the default mock writes a fixed
876
+ // string, but the pointer must be valid JSON referencing the thread).
877
+ const origDownload = vi.mocked(s3Module.downloadFile).getMockImplementation();
878
+ vi.mocked(s3Module.downloadFile).mockImplementation(
879
+ async (_ctx: unknown, key: string, localPath: string) => {
880
+ fs.mkdirSync(path.dirname(localPath), { recursive: true });
881
+ const body = key.endsWith("handoff.json")
882
+ ? JSON.stringify({ thread_path: threadKey, message: "from machine A" })
883
+ : JSON.stringify({ conversation_summary: "pick up here" });
884
+ fs.writeFileSync(localPath, body);
885
+ return { metadata: {} };
886
+ },
887
+ );
888
+
889
+ try {
890
+ const result = await sync({
891
+ company: "acme",
892
+ vaultConfig: mockConfig,
893
+ hqRoot: tmpDir,
894
+ personalMode: true,
895
+ });
896
+
897
+ expect(result.filesDownloaded).toBe(2);
898
+
899
+ const handoffLocal = path.join(tmpDir, "workspace", "threads", "handoff.json");
900
+ const threadLocal = path.join(
901
+ tmpDir,
902
+ "workspace",
903
+ "threads",
904
+ "T-20260619-1200-resume-me.json",
905
+ );
906
+ expect(fs.existsSync(handoffLocal)).toBe(true);
907
+ expect(fs.existsSync(threadLocal)).toBe(true);
908
+
909
+ // Pointer round-trips and resolves to the thread file that also landed.
910
+ const pointer = JSON.parse(fs.readFileSync(handoffLocal, "utf-8"));
911
+ expect(pointer.thread_path).toBe(threadKey);
912
+ expect(fs.existsSync(path.join(tmpDir, pointer.thread_path))).toBe(true);
913
+
914
+ // Must NOT be misfiled under companies/<slug>/.
915
+ expect(
916
+ fs.existsSync(path.join(tmpDir, "companies", "acme", handoffKey)),
917
+ ).toBe(false);
918
+ } finally {
919
+ if (origDownload) {
920
+ vi.mocked(s3Module.downloadFile).mockImplementation(origDownload);
921
+ }
922
+ }
923
+ });
924
+
925
+ it("personalMode pull does NOT clobber a newer local session-continuity pointer (conflict → keep local) (DEV-1778)", async () => {
926
+ // Machine B did its OWN /handoff after machine A's push, so B's local
927
+ // handoff.json is newer than the remote. The pull must preserve B's
928
+ // pointer rather than overwrite it with A's stale one — the brief's
929
+ // "download cleanly without clobbering a newer local pointer".
930
+ const threadsLocal = path.join(tmpDir, "workspace", "threads");
931
+ fs.mkdirSync(threadsLocal, { recursive: true });
932
+ fs.writeFileSync(
933
+ path.join(threadsLocal, "handoff.json"),
934
+ JSON.stringify({
935
+ thread_path: "workspace/threads/T-machineB.json",
936
+ message: "newer local from B",
937
+ }),
938
+ );
939
+
940
+ // Journal records a prior synced baseline (stale hash, no remoteEtag) so
941
+ // the planner sees local-changed AND remote-changed → conflict. Keys are
942
+ // hq-root-relative in personalMode.
943
+ fs.writeFileSync(
944
+ journalPath,
945
+ JSON.stringify({
946
+ version: "1",
947
+ lastSync: new Date().toISOString(),
948
+ files: {
949
+ "workspace/threads/handoff.json": {
950
+ hash: "old-hash-from-last-sync",
951
+ size: 10,
952
+ syncedAt: new Date(Date.now() - 3600000).toISOString(),
953
+ direction: "down",
954
+ },
955
+ },
956
+ }),
957
+ );
958
+
959
+ vi.mocked(s3Module.listRemoteFiles).mockResolvedValueOnce([
960
+ {
961
+ key: "workspace/threads/handoff.json",
962
+ size: 50,
963
+ lastModified: new Date(),
964
+ etag: '"remote-from-A"',
965
+ },
966
+ ]);
967
+
968
+ const result = await sync({
969
+ company: "acme",
970
+ onConflict: "keep",
971
+ vaultConfig: mockConfig,
972
+ hqRoot: tmpDir,
973
+ personalMode: true,
974
+ });
975
+
976
+ expect(result.conflicts).toBe(1);
977
+ expect(result.conflictPaths).toEqual(["workspace/threads/handoff.json"]);
978
+ expect(result.filesSkipped).toBeGreaterThanOrEqual(1);
979
+
980
+ // B's newer local pointer is preserved verbatim — not clobbered by A's.
981
+ const kept = JSON.parse(
982
+ fs.readFileSync(path.join(threadsLocal, "handoff.json"), "utf-8"),
983
+ );
984
+ expect(kept.message).toBe("newer local from B");
985
+ expect(kept.thread_path).toBe("workspace/threads/T-machineB.json");
986
+ });
987
+
614
988
  it("personalMode + includeLocalCompanies: downloads companies/{cloud-false-slug}/... keys when slug NOT in teamSyncedSlugs", async () => {
615
989
  // The symmetric flip for the cloud:false → personal-bucket fallback.
616
990
  // Machine A pushed `companies/free-co/notes.md` to the personal bucket
@@ -936,6 +1310,60 @@ describe("sync", () => {
936
1310
  expect(journal.files["docs/edited-locally.md"].hash).toBe(baselineHash);
937
1311
  });
938
1312
 
1313
+ it("F33: rechecks a tombstone candidate after HEAD verification and preserves a stale local edit", async () => {
1314
+ const companyRoot = path.join(tmpDir, "companies", "acme");
1315
+ fs.mkdirSync(path.join(companyRoot, "docs"), { recursive: true });
1316
+ const racedPath = path.join(companyRoot, "docs", "racy-delete.md");
1317
+ fs.writeFileSync(racedPath, "synced baseline");
1318
+
1319
+ const crypto = await import("node:crypto");
1320
+ const baselineHash = crypto
1321
+ .createHash("sha256")
1322
+ .update("synced baseline")
1323
+ .digest("hex");
1324
+
1325
+ fs.writeFileSync(
1326
+ journalPath,
1327
+ JSON.stringify({
1328
+ version: "1",
1329
+ lastSync: new Date(Date.now() - 60_000).toISOString(),
1330
+ files: {
1331
+ "docs/racy-delete.md": {
1332
+ hash: baselineHash,
1333
+ size: 15,
1334
+ syncedAt: new Date(Date.now() - 60_000).toISOString(),
1335
+ direction: "down",
1336
+ remoteEtag: "remote-before-delete",
1337
+ },
1338
+ },
1339
+ }),
1340
+ );
1341
+
1342
+ vi.mocked(s3Module.listRemoteFiles).mockResolvedValueOnce([]);
1343
+ let editInjected = false;
1344
+ vi.mocked(s3Module.headRemoteFile).mockImplementationOnce(async (_ctx, key) => {
1345
+ expect(key).toBe("docs/racy-delete.md");
1346
+ fs.writeFileSync(racedPath, "concurrent local edit");
1347
+ editInjected = true;
1348
+ return null;
1349
+ });
1350
+
1351
+ const result = await sync({
1352
+ company: "acme",
1353
+ vaultConfig: mockConfig,
1354
+ hqRoot: tmpDir,
1355
+ });
1356
+
1357
+ expect(editInjected).toBe(true);
1358
+ expect(result.filesTombstoned).toBe(0);
1359
+ expect(fs.existsSync(racedPath)).toBe(true);
1360
+ expect(fs.readFileSync(racedPath, "utf-8")).toBe("concurrent local edit");
1361
+
1362
+ const journal = JSON.parse(fs.readFileSync(journalPath, "utf-8"));
1363
+ expect(journal.files["docs/racy-delete.md"]).toBeDefined();
1364
+ expect(journal.files["docs/racy-delete.md"].hash).toBe(baselineHash);
1365
+ });
1366
+
939
1367
  it("does NOT tombstone symlinks whose readlink target has diverged from the journal (Codex P1 round 4)", async () => {
940
1368
  // Codex review on PR #24 round 4 caught: the round-3 local-edit
941
1369
  // divergence guard only covered regular files (`isFile()` is false
@@ -1576,6 +2004,79 @@ describe("sync", () => {
1576
2004
  expect(result.filesExcludedByPolicy).toBeGreaterThanOrEqual(1);
1577
2005
  });
1578
2006
 
2007
+ it("F02: rejects traversal remote keys before they can escape the company root", async () => {
2008
+ const escapeName = `${path.basename(tmpDir)}-escaped.md`;
2009
+ const traversalKey = `../../../${escapeName}`;
2010
+ const escapedPath = path.join(path.dirname(tmpDir), escapeName);
2011
+ const companyRoot = path.join(tmpDir, "companies", "acme");
2012
+
2013
+ vi.mocked(s3Module.listRemoteFiles).mockResolvedValueOnce([
2014
+ {
2015
+ key: traversalKey,
2016
+ size: 13,
2017
+ lastModified: new Date(),
2018
+ etag: '"traversal"',
2019
+ },
2020
+ ]);
2021
+
2022
+ try {
2023
+ const result = await sync({
2024
+ company: "acme",
2025
+ vaultConfig: mockConfig,
2026
+ hqRoot: tmpDir,
2027
+ });
2028
+
2029
+ expect(result.filesDownloaded).toBe(0);
2030
+ expect(result.filesExcludedByPolicy).toBeGreaterThanOrEqual(1);
2031
+ expect(s3Module.downloadFile).not.toHaveBeenCalled();
2032
+ expect(fs.existsSync(escapedPath)).toBe(false);
2033
+ expect(fs.existsSync(path.join(companyRoot, traversalKey))).toBe(false);
2034
+
2035
+ const journal = JSON.parse(fs.readFileSync(journalPath, "utf-8"));
2036
+ expect(journal.files[traversalKey]).toBeUndefined();
2037
+ } finally {
2038
+ fs.rmSync(escapedPath, { force: true });
2039
+ }
2040
+ });
2041
+
2042
+ it("R-F02: rejects remote children under an in-root symlink directory", async () => {
2043
+ const companyRoot = path.join(tmpDir, "companies", "acme");
2044
+ const outsideDir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-sync-escape-"));
2045
+ const linkDir = path.join(companyRoot, "linked-out");
2046
+ const remoteKey = "linked-out/owned-by-remote.md";
2047
+ const escapedPath = path.join(outsideDir, "owned-by-remote.md");
2048
+
2049
+ fs.mkdirSync(companyRoot, { recursive: true });
2050
+ fs.symlinkSync(outsideDir, linkDir, "dir");
2051
+ vi.mocked(s3Module.listRemoteFiles).mockResolvedValueOnce([
2052
+ {
2053
+ key: remoteKey,
2054
+ size: 13,
2055
+ lastModified: new Date(),
2056
+ etag: '"symlink-dir-escape"',
2057
+ },
2058
+ ]);
2059
+
2060
+ try {
2061
+ const result = await sync({
2062
+ company: "acme",
2063
+ vaultConfig: mockConfig,
2064
+ hqRoot: tmpDir,
2065
+ });
2066
+
2067
+ expect(result.filesDownloaded).toBe(0);
2068
+ expect(result.filesExcludedByPolicy).toBeGreaterThanOrEqual(1);
2069
+ expect(s3Module.downloadFile).not.toHaveBeenCalled();
2070
+ expect(fs.existsSync(escapedPath)).toBe(false);
2071
+ expect(fs.existsSync(path.join(companyRoot, remoteKey))).toBe(false);
2072
+
2073
+ const journal = JSON.parse(fs.readFileSync(journalPath, "utf-8"));
2074
+ expect(journal.files[remoteKey]).toBeUndefined();
2075
+ } finally {
2076
+ fs.rmSync(outsideDir, { recursive: true, force: true });
2077
+ }
2078
+ });
2079
+
1579
2080
  it("overwrites local on --on-conflict overwrite", async () => {
1580
2081
  const companyDocs = path.join(tmpDir, "companies", "acme", "docs");
1581
2082
  fs.mkdirSync(companyDocs, { recursive: true });
@@ -2490,3 +2991,95 @@ describe("sync", () => {
2490
2991
  expect(entry.remoteEtag).toBe(newRemoteEtagNormalized);
2491
2992
  });
2492
2993
  });
2994
+
2995
+ describe("reportNewFilesToNotify chunking (server cap = 1000 files/report)", () => {
2996
+ // The /v1/notify/file-added endpoint rejects an oversized batch wholesale.
2997
+ // Without chunking, a first sync with >1000 new files reports NONE of them and
2998
+ // the same oversized batch re-triggers every cycle. These lock that the client
2999
+ // splits into chunks at or under the cap.
3000
+ const cfg: VaultServiceConfig = {
3001
+ apiUrl: "https://vault-api.test",
3002
+ authToken: "test-jwt-token",
3003
+ region: "us-east-1",
3004
+ };
3005
+ const mkFiles = (n: number) =>
3006
+ Array.from({ length: n }, (_v, i) => ({
3007
+ path: `docs/file-${i}.md`,
3008
+ bytes: i,
3009
+ addedBy: null as string | null,
3010
+ }));
3011
+ const notifyBatchSizes = (fetchMock: ReturnType<typeof vi.fn>): number[] =>
3012
+ (fetchMock.mock.calls as Array<[string, RequestInit?]>)
3013
+ .filter(([u]) => String(u).includes("/v1/notify/file-added"))
3014
+ .map(([, init]) => JSON.parse(String(init!.body)).files.length);
3015
+
3016
+ afterEach(() => {
3017
+ vi.unstubAllGlobals();
3018
+ vi.clearAllMocks();
3019
+ });
3020
+
3021
+ it("sends a single request when exactly at the cap (1000 files)", async () => {
3022
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200, text: async () => "" });
3023
+ vi.stubGlobal("fetch", fetchMock);
3024
+
3025
+ await reportNewFilesToNotify(cfg, "cmp_X", "acme", mkFiles(1000));
3026
+
3027
+ const sizes = notifyBatchSizes(fetchMock);
3028
+ expect(sizes).toEqual([1000]); // one POST, exactly at the cap
3029
+ });
3030
+
3031
+ it("splits an over-cap report into batches all at or under the cap", async () => {
3032
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200, text: async () => "" });
3033
+ vi.stubGlobal("fetch", fetchMock);
3034
+
3035
+ await reportNewFilesToNotify(cfg, "cmp_X", "acme", mkFiles(1001));
3036
+
3037
+ const sizes = notifyBatchSizes(fetchMock);
3038
+ expect(sizes).toEqual([1000, 1]); // 1001 → 1000 + 1, never one oversized POST
3039
+ expect(Math.max(...sizes)).toBeLessThanOrEqual(1000);
3040
+ expect(sizes.reduce((a, b) => a + b, 0)).toBe(1001); // every file reported
3041
+ });
3042
+
3043
+ it("chunks a large report into ceil(n/1000) batches with no file dropped", async () => {
3044
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200, text: async () => "" });
3045
+ vi.stubGlobal("fetch", fetchMock);
3046
+
3047
+ const all = mkFiles(2500);
3048
+ await reportNewFilesToNotify(cfg, "cmp_X", "acme", all);
3049
+
3050
+ const calls = (fetchMock.mock.calls as Array<[string, RequestInit?]>).filter(([u]) =>
3051
+ String(u).includes("/v1/notify/file-added"),
3052
+ );
3053
+ const sizes = calls.map(([, init]) => JSON.parse(String(init!.body)).files.length);
3054
+ expect(sizes).toEqual([1000, 1000, 500]); // 2500 → three batches
3055
+ // Union of all reported paths equals the input, in order, nothing lost.
3056
+ const reported = calls.flatMap(([, init]) =>
3057
+ (JSON.parse(String(init!.body)).files as Array<{ path: string }>).map((f) => f.path),
3058
+ );
3059
+ expect(reported).toEqual(all.map((f) => f.path));
3060
+ });
3061
+
3062
+ it("a failing chunk does not abort the remaining chunks (best-effort per batch)", async () => {
3063
+ let call = 0;
3064
+ const fetchMock = vi.fn().mockImplementation(async () => {
3065
+ call += 1;
3066
+ if (call === 1) throw new Error("notify endpoint down");
3067
+ return { ok: true, status: 200, text: async () => "" };
3068
+ });
3069
+ vi.stubGlobal("fetch", fetchMock);
3070
+
3071
+ // Must not reject even though the first chunk throws.
3072
+ await expect(reportNewFilesToNotify(cfg, "cmp_X", "acme", mkFiles(2001))).resolves.toBeUndefined();
3073
+ // All three chunks were still attempted (1000 + 1000 + 1).
3074
+ expect(notifyBatchSizes(fetchMock)).toEqual([1000, 1000, 1]);
3075
+ });
3076
+
3077
+ it("no request at all when there are no new files", async () => {
3078
+ const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200, text: async () => "" });
3079
+ vi.stubGlobal("fetch", fetchMock);
3080
+
3081
+ await reportNewFilesToNotify(cfg, "cmp_X", "acme", []);
3082
+
3083
+ expect(fetchMock).not.toHaveBeenCalled();
3084
+ });
3085
+ });