@indigoai-us/hq-cloud 6.11.11 → 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 (160) 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 +265 -11
  6. package/dist/bin/sync-runner.test.js.map +1 -1
  7. package/dist/cli/rescue-classify-ordering.test.js +58 -0
  8. package/dist/cli/rescue-classify-ordering.test.js.map +1 -1
  9. package/dist/cli/rescue-core.js +138 -15
  10. package/dist/cli/rescue-core.js.map +1 -1
  11. package/dist/cli/share.d.ts +2 -1
  12. package/dist/cli/share.d.ts.map +1 -1
  13. package/dist/cli/share.js +100 -32
  14. package/dist/cli/share.js.map +1 -1
  15. package/dist/cli/share.test.js +30 -0
  16. package/dist/cli/share.test.js.map +1 -1
  17. package/dist/cli/sync.d.ts +28 -1
  18. package/dist/cli/sync.d.ts.map +1 -1
  19. package/dist/cli/sync.js +178 -58
  20. package/dist/cli/sync.js.map +1 -1
  21. package/dist/cli/sync.test.js +362 -1
  22. package/dist/cli/sync.test.js.map +1 -1
  23. package/dist/cognito-auth.d.ts.map +1 -1
  24. package/dist/cognito-auth.js +55 -10
  25. package/dist/cognito-auth.js.map +1 -1
  26. package/dist/cognito-auth.test.js +61 -0
  27. package/dist/cognito-auth.test.js.map +1 -1
  28. package/dist/index.d.ts +2 -1
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +1 -1
  31. package/dist/index.js.map +1 -1
  32. package/dist/journal.d.ts.map +1 -1
  33. package/dist/journal.js +93 -6
  34. package/dist/journal.js.map +1 -1
  35. package/dist/journal.test.js +59 -0
  36. package/dist/journal.test.js.map +1 -1
  37. package/dist/machine-auth.test.js +60 -2
  38. package/dist/machine-auth.test.js.map +1 -1
  39. package/dist/object-io.d.ts +37 -1
  40. package/dist/object-io.d.ts.map +1 -1
  41. package/dist/object-io.js +148 -29
  42. package/dist/object-io.js.map +1 -1
  43. package/dist/object-io.test.js +121 -0
  44. package/dist/object-io.test.js.map +1 -1
  45. package/dist/operation-lock.d.ts +8 -8
  46. package/dist/operation-lock.d.ts.map +1 -1
  47. package/dist/operation-lock.js +99 -32
  48. package/dist/operation-lock.js.map +1 -1
  49. package/dist/operation-lock.test.js +51 -4
  50. package/dist/operation-lock.test.js.map +1 -1
  51. package/dist/personal-vault.d.ts.map +1 -1
  52. package/dist/personal-vault.js +8 -2
  53. package/dist/personal-vault.js.map +1 -1
  54. package/dist/personal-vault.test.js +34 -0
  55. package/dist/personal-vault.test.js.map +1 -1
  56. package/dist/prefix-coalesce.d.ts +20 -9
  57. package/dist/prefix-coalesce.d.ts.map +1 -1
  58. package/dist/prefix-coalesce.js +124 -28
  59. package/dist/prefix-coalesce.js.map +1 -1
  60. package/dist/prefix-coalesce.test.js +57 -2
  61. package/dist/prefix-coalesce.test.js.map +1 -1
  62. package/dist/remote-pull.d.ts +6 -1
  63. package/dist/remote-pull.d.ts.map +1 -1
  64. package/dist/remote-pull.js +62 -13
  65. package/dist/remote-pull.js.map +1 -1
  66. package/dist/remote-pull.test.js +189 -0
  67. package/dist/remote-pull.test.js.map +1 -1
  68. package/dist/s3.d.ts +2 -0
  69. package/dist/s3.d.ts.map +1 -1
  70. package/dist/s3.js +197 -116
  71. package/dist/s3.js.map +1 -1
  72. package/dist/s3.test.js +109 -0
  73. package/dist/s3.test.js.map +1 -1
  74. package/dist/scope-shrink.d.ts +3 -2
  75. package/dist/scope-shrink.d.ts.map +1 -1
  76. package/dist/scope-shrink.js +1 -1
  77. package/dist/scope-shrink.js.map +1 -1
  78. package/dist/skill-telemetry.d.ts +1 -1
  79. package/dist/skill-telemetry.d.ts.map +1 -1
  80. package/dist/skill-telemetry.js +69 -9
  81. package/dist/skill-telemetry.js.map +1 -1
  82. package/dist/skill-telemetry.test.js +86 -0
  83. package/dist/skill-telemetry.test.js.map +1 -1
  84. package/dist/sync/event-sync.d.ts +6 -0
  85. package/dist/sync/event-sync.d.ts.map +1 -1
  86. package/dist/sync/event-sync.js +34 -1
  87. package/dist/sync/event-sync.js.map +1 -1
  88. package/dist/sync/event-sync.test.js +73 -0
  89. package/dist/sync/event-sync.test.js.map +1 -1
  90. package/dist/sync/metrics.d.ts +17 -1
  91. package/dist/sync/metrics.d.ts.map +1 -1
  92. package/dist/sync/metrics.js +32 -1
  93. package/dist/sync/metrics.js.map +1 -1
  94. package/dist/sync/metrics.test.js +74 -1
  95. package/dist/sync/metrics.test.js.map +1 -1
  96. package/dist/sync/pull-scope.d.ts.map +1 -1
  97. package/dist/sync/pull-scope.js +15 -7
  98. package/dist/sync/pull-scope.js.map +1 -1
  99. package/dist/sync/push-receiver.d.ts +6 -5
  100. package/dist/sync/push-receiver.d.ts.map +1 -1
  101. package/dist/sync/push-receiver.js +13 -15
  102. package/dist/sync/push-receiver.js.map +1 -1
  103. package/dist/sync/push-receiver.test.js +36 -1
  104. package/dist/sync/push-receiver.test.js.map +1 -1
  105. package/dist/telemetry.d.ts +1 -1
  106. package/dist/telemetry.d.ts.map +1 -1
  107. package/dist/telemetry.js +59 -6
  108. package/dist/telemetry.js.map +1 -1
  109. package/dist/telemetry.test.js +74 -0
  110. package/dist/telemetry.test.js.map +1 -1
  111. package/dist/types.d.ts +8 -0
  112. package/dist/types.d.ts.map +1 -1
  113. package/dist/watcher.d.ts +36 -0
  114. package/dist/watcher.d.ts.map +1 -1
  115. package/dist/watcher.js +152 -30
  116. package/dist/watcher.js.map +1 -1
  117. package/dist/watcher.test.js +103 -0
  118. package/dist/watcher.test.js.map +1 -1
  119. package/package.json +1 -1
  120. package/src/bin/sync-runner.test.ts +298 -11
  121. package/src/bin/sync-runner.ts +254 -52
  122. package/src/cli/rescue-classify-ordering.test.ts +61 -0
  123. package/src/cli/rescue-core.ts +174 -15
  124. package/src/cli/share.test.ts +38 -0
  125. package/src/cli/share.ts +103 -34
  126. package/src/cli/sync.test.ts +435 -1
  127. package/src/cli/sync.ts +217 -64
  128. package/src/cognito-auth.test.ts +77 -0
  129. package/src/cognito-auth.ts +73 -11
  130. package/src/index.ts +8 -0
  131. package/src/journal.test.ts +72 -0
  132. package/src/journal.ts +95 -8
  133. package/src/machine-auth.test.ts +64 -2
  134. package/src/object-io.test.ts +142 -0
  135. package/src/object-io.ts +182 -30
  136. package/src/operation-lock.test.ts +63 -4
  137. package/src/operation-lock.ts +99 -31
  138. package/src/personal-vault.test.ts +42 -0
  139. package/src/personal-vault.ts +8 -2
  140. package/src/prefix-coalesce.test.ts +71 -1
  141. package/src/prefix-coalesce.ts +155 -30
  142. package/src/remote-pull.test.ts +205 -0
  143. package/src/remote-pull.ts +77 -14
  144. package/src/s3.test.ts +126 -0
  145. package/src/s3.ts +237 -122
  146. package/src/scope-shrink.ts +6 -3
  147. package/src/skill-telemetry.test.ts +109 -0
  148. package/src/skill-telemetry.ts +82 -14
  149. package/src/sync/event-sync.test.ts +75 -0
  150. package/src/sync/event-sync.ts +54 -1
  151. package/src/sync/metrics.test.ts +81 -0
  152. package/src/sync/metrics.ts +59 -4
  153. package/src/sync/pull-scope.ts +23 -7
  154. package/src/sync/push-receiver.test.ts +38 -1
  155. package/src/sync/push-receiver.ts +15 -18
  156. package/src/telemetry.test.ts +85 -0
  157. package/src/telemetry.ts +69 -6
  158. package/src/types.ts +8 -0
  159. package/src/watcher.test.ts +117 -0
  160. 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 });
@@ -1095,6 +1310,60 @@ describe("sync", () => {
1095
1310
  expect(journal.files["docs/edited-locally.md"].hash).toBe(baselineHash);
1096
1311
  });
1097
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
+
1098
1367
  it("does NOT tombstone symlinks whose readlink target has diverged from the journal (Codex P1 round 4)", async () => {
1099
1368
  // Codex review on PR #24 round 4 caught: the round-3 local-edit
1100
1369
  // divergence guard only covered regular files (`isFile()` is false
@@ -1735,6 +2004,79 @@ describe("sync", () => {
1735
2004
  expect(result.filesExcludedByPolicy).toBeGreaterThanOrEqual(1);
1736
2005
  });
1737
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
+
1738
2080
  it("overwrites local on --on-conflict overwrite", async () => {
1739
2081
  const companyDocs = path.join(tmpDir, "companies", "acme", "docs");
1740
2082
  fs.mkdirSync(companyDocs, { recursive: true });
@@ -2649,3 +2991,95 @@ describe("sync", () => {
2649
2991
  expect(entry.remoteEtag).toBe(newRemoteEtagNormalized);
2650
2992
  });
2651
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
+ });