@indigoai-us/hq-cloud 6.15.0 → 6.15.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (329) hide show
  1. package/dist/bin/sync-mutation.d.ts +16 -0
  2. package/dist/bin/sync-mutation.d.ts.map +1 -0
  3. package/dist/bin/sync-mutation.js +60 -0
  4. package/dist/bin/sync-mutation.js.map +1 -0
  5. package/dist/bin/sync-mutation.test.d.ts +2 -0
  6. package/dist/bin/sync-mutation.test.d.ts.map +1 -0
  7. package/dist/bin/sync-mutation.test.js +165 -0
  8. package/dist/bin/sync-mutation.test.js.map +1 -0
  9. package/dist/bin/sync-runner-company.d.ts +8 -0
  10. package/dist/bin/sync-runner-company.d.ts.map +1 -1
  11. package/dist/bin/sync-runner-company.js +16 -0
  12. package/dist/bin/sync-runner-company.js.map +1 -1
  13. package/dist/bin/sync-runner-company.test.d.ts +2 -0
  14. package/dist/bin/sync-runner-company.test.d.ts.map +1 -0
  15. package/dist/bin/sync-runner-company.test.js +36 -0
  16. package/dist/bin/sync-runner-company.test.js.map +1 -0
  17. package/dist/bin/sync-runner-watch-loop.d.ts.map +1 -1
  18. package/dist/bin/sync-runner-watch-loop.js +98 -8
  19. package/dist/bin/sync-runner-watch-loop.js.map +1 -1
  20. package/dist/bin/sync-runner.d.ts +17 -0
  21. package/dist/bin/sync-runner.d.ts.map +1 -1
  22. package/dist/bin/sync-runner.js.map +1 -1
  23. package/dist/bin/sync-runner.test.js +109 -0
  24. package/dist/bin/sync-runner.test.js.map +1 -1
  25. package/dist/cli/conflict-recovery.test.d.ts +2 -0
  26. package/dist/cli/conflict-recovery.test.d.ts.map +1 -0
  27. package/dist/cli/conflict-recovery.test.js +201 -0
  28. package/dist/cli/conflict-recovery.test.js.map +1 -0
  29. package/dist/cli/conflict.d.ts +60 -0
  30. package/dist/cli/conflict.d.ts.map +1 -1
  31. package/dist/cli/conflict.js +333 -0
  32. package/dist/cli/conflict.js.map +1 -1
  33. package/dist/cli/sync.d.ts +35 -0
  34. package/dist/cli/sync.d.ts.map +1 -1
  35. package/dist/cli/sync.js +100 -0
  36. package/dist/cli/sync.js.map +1 -1
  37. package/dist/cli/sync.test.js +85 -1
  38. package/dist/cli/sync.test.js.map +1 -1
  39. package/dist/index.d.ts +2 -0
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +1 -0
  42. package/dist/index.js.map +1 -1
  43. package/dist/skill-telemetry.d.ts +6 -0
  44. package/dist/skill-telemetry.d.ts.map +1 -1
  45. package/dist/skill-telemetry.js +14 -2
  46. package/dist/skill-telemetry.js.map +1 -1
  47. package/dist/skill-telemetry.test.js +79 -0
  48. package/dist/skill-telemetry.test.js.map +1 -1
  49. package/dist/sync/candidate-uploader.d.ts +88 -0
  50. package/dist/sync/candidate-uploader.d.ts.map +1 -0
  51. package/dist/sync/candidate-uploader.js +212 -0
  52. package/dist/sync/candidate-uploader.js.map +1 -0
  53. package/dist/sync/candidate-uploader.test.d.ts +2 -0
  54. package/dist/sync/candidate-uploader.test.d.ts.map +1 -0
  55. package/dist/sync/candidate-uploader.test.js +132 -0
  56. package/dist/sync/candidate-uploader.test.js.map +1 -0
  57. package/dist/sync/delta-client.d.ts +73 -0
  58. package/dist/sync/delta-client.d.ts.map +1 -0
  59. package/dist/sync/delta-client.js +201 -0
  60. package/dist/sync/delta-client.js.map +1 -0
  61. package/dist/sync/delta-client.test.d.ts +2 -0
  62. package/dist/sync/delta-client.test.d.ts.map +1 -0
  63. package/dist/sync/delta-client.test.js +97 -0
  64. package/dist/sync/delta-client.test.js.map +1 -0
  65. package/dist/sync/durable-apply.d.ts +76 -0
  66. package/dist/sync/durable-apply.d.ts.map +1 -0
  67. package/dist/sync/durable-apply.js +530 -0
  68. package/dist/sync/durable-apply.js.map +1 -0
  69. package/dist/sync/durable-apply.test.d.ts +2 -0
  70. package/dist/sync/durable-apply.test.d.ts.map +1 -0
  71. package/dist/sync/durable-apply.test.js +180 -0
  72. package/dist/sync/durable-apply.test.js.map +1 -0
  73. package/dist/sync/event-sync.d.ts +33 -1
  74. package/dist/sync/event-sync.d.ts.map +1 -1
  75. package/dist/sync/event-sync.js +149 -1
  76. package/dist/sync/event-sync.js.map +1 -1
  77. package/dist/sync/event-sync.test.js +142 -1
  78. package/dist/sync/event-sync.test.js.map +1 -1
  79. package/dist/sync/index.d.ts +2 -0
  80. package/dist/sync/index.d.ts.map +1 -1
  81. package/dist/sync/index.js +1 -0
  82. package/dist/sync/index.js.map +1 -1
  83. package/dist/sync/multipart-uploader.d.ts +99 -0
  84. package/dist/sync/multipart-uploader.d.ts.map +1 -0
  85. package/dist/sync/multipart-uploader.js +447 -0
  86. package/dist/sync/multipart-uploader.js.map +1 -0
  87. package/dist/sync/multipart-uploader.test.d.ts +2 -0
  88. package/dist/sync/multipart-uploader.test.d.ts.map +1 -0
  89. package/dist/sync/multipart-uploader.test.js +119 -0
  90. package/dist/sync/multipart-uploader.test.js.map +1 -0
  91. package/dist/sync/mutation-client.d.ts +85 -0
  92. package/dist/sync/mutation-client.d.ts.map +1 -0
  93. package/dist/sync/mutation-client.js +245 -0
  94. package/dist/sync/mutation-client.js.map +1 -0
  95. package/dist/sync/mutation-client.test.d.ts +2 -0
  96. package/dist/sync/mutation-client.test.d.ts.map +1 -0
  97. package/dist/sync/mutation-client.test.js +51 -0
  98. package/dist/sync/mutation-client.test.js.map +1 -0
  99. package/dist/sync/push-receiver.d.ts +45 -0
  100. package/dist/sync/push-receiver.d.ts.map +1 -1
  101. package/dist/sync/push-receiver.js +101 -0
  102. package/dist/sync/push-receiver.js.map +1 -1
  103. package/dist/sync/push-receiver.test.js +54 -2
  104. package/dist/sync/push-receiver.test.js.map +1 -1
  105. package/dist/sync/scope-inventory-client.d.ts +69 -0
  106. package/dist/sync/scope-inventory-client.d.ts.map +1 -0
  107. package/dist/sync/scope-inventory-client.js +210 -0
  108. package/dist/sync/scope-inventory-client.js.map +1 -0
  109. package/dist/sync/scope-inventory-client.test.d.ts +2 -0
  110. package/dist/sync/scope-inventory-client.test.d.ts.map +1 -0
  111. package/dist/sync/scope-inventory-client.test.js +94 -0
  112. package/dist/sync/scope-inventory-client.test.js.map +1 -0
  113. package/dist/sync/snapshot-client.d.ts +98 -0
  114. package/dist/sync/snapshot-client.d.ts.map +1 -0
  115. package/dist/sync/snapshot-client.js +402 -0
  116. package/dist/sync/snapshot-client.js.map +1 -0
  117. package/dist/sync/snapshot-client.test.d.ts +2 -0
  118. package/dist/sync/snapshot-client.test.d.ts.map +1 -0
  119. package/dist/sync/snapshot-client.test.js +169 -0
  120. package/dist/sync/snapshot-client.test.js.map +1 -0
  121. package/dist/sync/uploader-finalization.d.ts +97 -0
  122. package/dist/sync/uploader-finalization.d.ts.map +1 -0
  123. package/dist/sync/uploader-finalization.js +273 -0
  124. package/dist/sync/uploader-finalization.js.map +1 -0
  125. package/dist/sync/uploader-finalization.test.d.ts +2 -0
  126. package/dist/sync/uploader-finalization.test.d.ts.map +1 -0
  127. package/dist/sync/uploader-finalization.test.js +92 -0
  128. package/dist/sync/uploader-finalization.test.js.map +1 -0
  129. package/dist/telemetry.d.ts +11 -1
  130. package/dist/telemetry.d.ts.map +1 -1
  131. package/dist/telemetry.js +21 -2
  132. package/dist/telemetry.js.map +1 -1
  133. package/dist/telemetry.test.js +80 -0
  134. package/dist/telemetry.test.js.map +1 -1
  135. package/package.json +6 -1
  136. package/.claude/policies/hq-cloud-esm-cannot-spy-fs-builtins.md +0 -30
  137. package/.claude/policies/hq-cloud-strip-types-no-parameter-properties.md +0 -22
  138. package/.github/workflows/ci.yml +0 -84
  139. package/.github/workflows/publish.yml +0 -56
  140. package/.github/workflows/unreleased-commits-nag.yml +0 -256
  141. package/eslint.config.js +0 -67
  142. package/pnpm-workspace.yaml +0 -2
  143. package/scripts/presign-transport-e2e.mjs +0 -250
  144. package/scripts/vault-rebaseline.sh +0 -323
  145. package/scripts/vault-rescue.sh +0 -332
  146. package/src/active-company.test.ts +0 -188
  147. package/src/active-company.ts +0 -168
  148. package/src/agent-codex-instructions.test.ts +0 -332
  149. package/src/agent-codex-instructions.ts +0 -309
  150. package/src/auth.ts +0 -146
  151. package/src/backup-prune.test.ts +0 -98
  152. package/src/backup-prune.ts +0 -182
  153. package/src/bin/backup-prune-runner.ts +0 -33
  154. package/src/bin/rescue-runner.ts +0 -25
  155. package/src/bin/sync-runner-company.ts +0 -695
  156. package/src/bin/sync-runner-events.test.ts +0 -143
  157. package/src/bin/sync-runner-events.ts +0 -55
  158. package/src/bin/sync-runner-planning.test.ts +0 -311
  159. package/src/bin/sync-runner-planning.ts +0 -258
  160. package/src/bin/sync-runner-rollup.test.ts +0 -37
  161. package/src/bin/sync-runner-rollup.ts +0 -97
  162. package/src/bin/sync-runner-telemetry.ts +0 -15
  163. package/src/bin/sync-runner-watch-loop.ts +0 -1235
  164. package/src/bin/sync-runner-watch-routes.test.ts +0 -71
  165. package/src/bin/sync-runner-watch-routes.ts +0 -184
  166. package/src/bin/sync-runner.test.ts +0 -8767
  167. package/src/bin/sync-runner.ts +0 -2190
  168. package/src/cli/accept.ts +0 -124
  169. package/src/cli/conflict.ts +0 -119
  170. package/src/cli/doctor.test.ts +0 -581
  171. package/src/cli/doctor.ts +0 -642
  172. package/src/cli/index.ts +0 -49
  173. package/src/cli/invite.test.ts +0 -250
  174. package/src/cli/invite.ts +0 -214
  175. package/src/cli/promote.ts +0 -157
  176. package/src/cli/reindex-knowledge.test.ts +0 -307
  177. package/src/cli/reindex-knowledge.ts +0 -450
  178. package/src/cli/reindex.test.ts +0 -957
  179. package/src/cli/reindex.ts +0 -979
  180. package/src/cli/rescue-classify-ordering.test.ts +0 -548
  181. package/src/cli/rescue-clone-diagnostics.test.ts +0 -120
  182. package/src/cli/rescue-core.ts +0 -3011
  183. package/src/cli/rescue-drift-reconcile.test.ts +0 -179
  184. package/src/cli/rescue-drop-dir-symlink.test.ts +0 -224
  185. package/src/cli/rescue-exec-bit-preserve.test.ts +0 -187
  186. package/src/cli/rescue-hq-root-guard.test.ts +0 -232
  187. package/src/cli/rescue-journal-reconcile.test.ts +0 -215
  188. package/src/cli/rescue-mtime-preserve.test.ts +0 -203
  189. package/src/cli/rescue-settings-reconcile.test.ts +0 -637
  190. package/src/cli/rescue-snapshot.test.ts +0 -57
  191. package/src/cli/rescue-snapshot.ts +0 -51
  192. package/src/cli/rescue.reindex.test.ts +0 -63
  193. package/src/cli/rescue.test.ts +0 -131
  194. package/src/cli/rescue.ts +0 -182
  195. package/src/cli/share.test.ts +0 -7843
  196. package/src/cli/share.ts +0 -3663
  197. package/src/cli/sync-scope.test.ts +0 -652
  198. package/src/cli/sync.test.ts +0 -5207
  199. package/src/cli/sync.ts +0 -3470
  200. package/src/cli/tombstones.ts +0 -106
  201. package/src/cli/watch-event-push-conflict.test.ts +0 -234
  202. package/src/client-info.test.ts +0 -214
  203. package/src/client-info.ts +0 -121
  204. package/src/cognito-auth.test.ts +0 -712
  205. package/src/cognito-auth.ts +0 -1422
  206. package/src/company-resolver.test.ts +0 -618
  207. package/src/company-resolver.ts +0 -521
  208. package/src/context.test.ts +0 -583
  209. package/src/context.ts +0 -378
  210. package/src/daemon-worker.ts +0 -26
  211. package/src/daemon.ts +0 -99
  212. package/src/entity-resolver.test.ts +0 -315
  213. package/src/entity-resolver.ts +0 -180
  214. package/src/ignore.test.ts +0 -466
  215. package/src/ignore.ts +0 -469
  216. package/src/index.ts +0 -439
  217. package/src/journal.test.ts +0 -968
  218. package/src/journal.ts +0 -765
  219. package/src/lib/cloud-authoritative.test.ts +0 -45
  220. package/src/lib/cloud-authoritative.ts +0 -59
  221. package/src/lib/conflict-file.ts +0 -86
  222. package/src/lib/conflict-index.ts +0 -289
  223. package/src/lib/conflict.test.ts +0 -348
  224. package/src/lib/describe-error.test.ts +0 -100
  225. package/src/lib/describe-error.ts +0 -58
  226. package/src/lib/exit-codes.ts +0 -24
  227. package/src/lib/machine-id.test.ts +0 -231
  228. package/src/lib/machine-id.ts +0 -175
  229. package/src/lib/net-errors.test.ts +0 -65
  230. package/src/lib/net-errors.ts +0 -86
  231. package/src/lib/readlink-safe.test.ts +0 -43
  232. package/src/lib/readlink-safe.ts +0 -29
  233. package/src/local-path-codec.test.ts +0 -138
  234. package/src/local-path-codec.ts +0 -161
  235. package/src/machine-auth.test.ts +0 -1323
  236. package/src/manifest-reconcile.test.ts +0 -1123
  237. package/src/manifest-reconcile.ts +0 -518
  238. package/src/object-io.test.ts +0 -1221
  239. package/src/object-io.ts +0 -1306
  240. package/src/operation-lock.test.ts +0 -484
  241. package/src/operation-lock.ts +0 -680
  242. package/src/outcome-telemetry.test.ts +0 -498
  243. package/src/outcome-telemetry.ts +0 -639
  244. package/src/personal-vault-exclusions.test.ts +0 -308
  245. package/src/personal-vault-exclusions.ts +0 -354
  246. package/src/personal-vault.test.ts +0 -756
  247. package/src/personal-vault.ts +0 -496
  248. package/src/prefix-coalesce.test.ts +0 -240
  249. package/src/prefix-coalesce.ts +0 -273
  250. package/src/public-surface.test.ts +0 -117
  251. package/src/qmd-reindex.test.ts +0 -877
  252. package/src/qmd-reindex.ts +0 -842
  253. package/src/read-only-state-dir.test.ts +0 -188
  254. package/src/remote-pull.test.ts +0 -1130
  255. package/src/remote-pull.ts +0 -618
  256. package/src/s3.symlink-materialize.test.ts +0 -492
  257. package/src/s3.test.ts +0 -1789
  258. package/src/s3.ts +0 -1532
  259. package/src/schemas/signal-types.test.ts +0 -82
  260. package/src/schemas/signal-types.ts +0 -38
  261. package/src/schemas/source-channels.test.ts +0 -82
  262. package/src/schemas/source-channels.ts +0 -53
  263. package/src/scope-shrink.test.ts +0 -633
  264. package/src/scope-shrink.ts +0 -481
  265. package/src/signals/get.test.ts +0 -310
  266. package/src/signals/get.ts +0 -75
  267. package/src/signals/internals.ts +0 -195
  268. package/src/signals/list.test.ts +0 -420
  269. package/src/signals/list.ts +0 -79
  270. package/src/signals/parse.ts +0 -8
  271. package/src/signals/types.ts +0 -91
  272. package/src/skill-telemetry.test.ts +0 -1825
  273. package/src/skill-telemetry.ts +0 -1439
  274. package/src/sources/get.test.ts +0 -293
  275. package/src/sources/get.ts +0 -66
  276. package/src/sources/internals.ts +0 -198
  277. package/src/sources/list.test.ts +0 -402
  278. package/src/sources/list.ts +0 -84
  279. package/src/sources/parse.ts +0 -43
  280. package/src/sources/types.ts +0 -84
  281. package/src/sync/event-sync.test.ts +0 -594
  282. package/src/sync/event-sync.ts +0 -545
  283. package/src/sync/feature-flags.test.ts +0 -378
  284. package/src/sync/feature-flags.ts +0 -62
  285. package/src/sync/index.ts +0 -76
  286. package/src/sync/lease-client.test.ts +0 -128
  287. package/src/sync/lease-client.ts +0 -207
  288. package/src/sync/logger.test.ts +0 -242
  289. package/src/sync/logger.ts +0 -79
  290. package/src/sync/metrics.test.ts +0 -462
  291. package/src/sync/metrics.ts +0 -213
  292. package/src/sync/pull-scope.ts +0 -265
  293. package/src/sync/push-event.test.ts +0 -266
  294. package/src/sync/push-event.ts +0 -224
  295. package/src/sync/push-receiver.test.ts +0 -566
  296. package/src/sync/push-receiver.ts +0 -1048
  297. package/src/sync/push-transport.ts +0 -231
  298. package/src/sync/realtime-rollout.test.ts +0 -86
  299. package/src/sync/realtime-rollout.ts +0 -262
  300. package/src/sync/state-store.test.ts +0 -194
  301. package/src/sync/state-store.ts +0 -727
  302. package/src/sync-core.ts +0 -58
  303. package/src/sync-progress.test.ts +0 -94
  304. package/src/sync-progress.ts +0 -140
  305. package/src/telemetry-events.test.ts +0 -88
  306. package/src/telemetry-events.ts +0 -205
  307. package/src/telemetry.test.ts +0 -1280
  308. package/src/telemetry.ts +0 -1109
  309. package/src/types.ts +0 -314
  310. package/src/vault-client.test.ts +0 -1380
  311. package/src/vault-client.ts +0 -1694
  312. package/src/version.ts +0 -24
  313. package/src/watch-roots.test.ts +0 -278
  314. package/src/watch-roots.ts +0 -162
  315. package/src/watcher-event-gate.test.ts +0 -212
  316. package/src/watcher.test.ts +0 -1079
  317. package/src/watcher.ts +0 -1741
  318. package/test/e2e/sync/cross-tenant-isolation.test.ts +0 -630
  319. package/test/e2e/sync/skill-telemetry-oversized-transcript.test.ts +0 -124
  320. package/test/e2e/sync/transient-company-leg.test.ts +0 -384
  321. package/test/e2e/sync/windows-unreadable-link-leg.test.ts +0 -191
  322. package/test/e2e/watcher-real-chokidar.test.ts +0 -165
  323. package/test/e2e/watcher-recursive-backend.test.ts +0 -181
  324. package/test/e2e/watcher-scoped-coverage.test.ts +0 -381
  325. package/test/invite-flow.integration.test.ts +0 -244
  326. package/test/joiner-manifest-reconcile.integration.test.ts +0 -322
  327. package/test/share-sync.integration.test.ts +0 -213
  328. package/tsconfig.json +0 -19
  329. package/vitest.config.ts +0 -22
@@ -1,1079 +0,0 @@
1
- import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
2
- import * as fs from "fs";
3
- import * as os from "os";
4
- import * as path from "path";
5
- import { watch } from "chokidar";
6
- import {
7
- FakeClock,
8
- WatchPushDriver,
9
- TreeWatcher,
10
- ChokidarWatchBudget,
11
- createWatchPathFilter,
12
- toChokidarIgnored,
13
- PushEventEmitter,
14
- } from "./watcher.js";
15
- import { StaticFlagProvider } from "./sync/feature-flags.js";
16
- import type { PushEvent } from "./sync/push-event.js";
17
- import type { PushTransport } from "./sync/push-transport.js";
18
- import type { TelemetryEventsBatch } from "./vault-client.js";
19
-
20
- /**
21
- * US-001 — Phase 1 test harness: watch-triggered push seam + latency assertion.
22
- *
23
- * These tests drive the debounce/coalesce core ({@link WatchPushDriver}) with an
24
- * injected {@link FakeClock} and an injected spy push fn — no real chokidar
25
- * watcher, no real S3, no real 10-minute sleep. US-002/US-003 build the real
26
- * watcher + targeted-push fn on top of this same seam, so the tests here also
27
- * serve as regression guards for the contract those stories depend on.
28
- */
29
-
30
- const DEBOUNCE = 2000;
31
-
32
- /**
33
- * Build a driver wired to a FakeClock and a spy push fn. Returns everything a
34
- * test needs to drive and assert against the seam. This helper is the reusable
35
- * "test harness" the story asks for.
36
- */
37
- function makeHarness(opts?: { debounceMs?: number }) {
38
- const clock = new FakeClock();
39
- const push = vi.fn(() => {});
40
- const driver = new WatchPushDriver({
41
- debounceMs: opts?.debounceMs ?? DEBOUNCE,
42
- clock,
43
- push,
44
- });
45
- return {
46
- clock,
47
- push,
48
- driver,
49
- /** Emit a synthetic file-change event into the driver. */
50
- emitChange: () => driver.notifyChange(),
51
- /** Advance virtual time. */
52
- advance: (ms: number) => clock.advance(ms),
53
- };
54
- }
55
-
56
- async function flushImmediate(): Promise<void> {
57
- await new Promise<void>((resolve) => setImmediate(resolve));
58
- }
59
-
60
- describe("FakeClock", () => {
61
- it("fires a timer exactly when its deadline is reached", () => {
62
- const clock = new FakeClock();
63
- const fn = vi.fn();
64
- clock.setTimeout(fn, 100);
65
- clock.advance(99);
66
- expect(fn).not.toHaveBeenCalled();
67
- clock.advance(1);
68
- expect(fn).toHaveBeenCalledTimes(1);
69
- });
70
-
71
- it("does not fire a cleared timer", () => {
72
- const clock = new FakeClock();
73
- const fn = vi.fn();
74
- const handle = clock.setTimeout(fn, 100);
75
- clock.clearTimeout(handle);
76
- clock.advance(1000);
77
- expect(fn).not.toHaveBeenCalled();
78
- expect(clock.pendingTimerCount()).toBe(0);
79
- });
80
-
81
- it("reports pending timer count for leak checks", () => {
82
- const clock = new FakeClock();
83
- clock.setTimeout(() => {}, 100);
84
- clock.setTimeout(() => {}, 200);
85
- expect(clock.pendingTimerCount()).toBe(2);
86
- clock.advance(100);
87
- expect(clock.pendingTimerCount()).toBe(1);
88
- });
89
- });
90
-
91
- describe("US-001: WatchPushDriver — debounced push seam", () => {
92
- it("calls the injected push fn exactly once within debounce+grace after a synthetic change", async () => {
93
- const h = makeHarness();
94
-
95
- h.emitChange();
96
- // Before the window elapses, no push.
97
- h.advance(DEBOUNCE - 1);
98
- expect(h.push).not.toHaveBeenCalled();
99
-
100
- // Crossing the debounce boundary fires the push exactly once.
101
- h.advance(1);
102
- await Promise.resolve();
103
- expect(h.push).toHaveBeenCalledTimes(1);
104
- });
105
-
106
- it("coalesces N rapid changes within the window to exactly 1 push", async () => {
107
- const h = makeHarness();
108
-
109
- // 5 synthetic changes spread across less than one debounce window.
110
- for (let i = 0; i < 5; i++) {
111
- h.emitChange();
112
- h.advance(100); // total 500ms << 2000ms debounce
113
- }
114
- // Window has not fully elapsed since the LAST change yet.
115
- expect(h.push).not.toHaveBeenCalled();
116
-
117
- // Let the quiet window after the final change elapse.
118
- h.advance(DEBOUNCE);
119
- await Promise.resolve();
120
- expect(h.push).toHaveBeenCalledTimes(1);
121
- });
122
-
123
- it("treats two separate bursts as two pushes", async () => {
124
- const h = makeHarness();
125
-
126
- h.emitChange();
127
- h.advance(DEBOUNCE);
128
- await Promise.resolve();
129
- expect(h.push).toHaveBeenCalledTimes(1);
130
-
131
- h.emitChange();
132
- h.advance(DEBOUNCE);
133
- await Promise.resolve();
134
- expect(h.push).toHaveBeenCalledTimes(2);
135
- });
136
-
137
- it("never overlaps an in-flight push; a mid-push change re-triggers one follow-up pass", async () => {
138
- const clock = new FakeClock();
139
- let release!: () => void;
140
- const inFlight = new Promise<void>((r) => {
141
- release = r;
142
- });
143
- let calls = 0;
144
- const push = vi.fn(() => {
145
- calls += 1;
146
- // First push hangs until released; later pushes resolve immediately.
147
- return calls === 1 ? inFlight : Promise.resolve();
148
- });
149
- const driver = new WatchPushDriver({ debounceMs: DEBOUNCE, clock, push });
150
-
151
- // First burst -> first push starts and hangs.
152
- driver.notifyChange();
153
- clock.advance(DEBOUNCE);
154
- await Promise.resolve();
155
- expect(push).toHaveBeenCalledTimes(1);
156
- expect(driver.isPushing()).toBe(true);
157
-
158
- // A change arrives while the first push is in flight: must NOT start a
159
- // concurrent push.
160
- driver.notifyChange();
161
- clock.advance(DEBOUNCE);
162
- await Promise.resolve();
163
- expect(push).toHaveBeenCalledTimes(1);
164
-
165
- // Release the first push; the collapsed mid-push change re-arms.
166
- release();
167
- await inFlight;
168
- await Promise.resolve();
169
- // Re-armed window must elapse before the follow-up push fires.
170
- clock.advance(DEBOUNCE);
171
- await Promise.resolve();
172
- expect(push).toHaveBeenCalledTimes(2);
173
-
174
- driver.dispose();
175
- });
176
-
177
- it("F17: rejected watch push is caught instead of surfacing as an unhandled rejection", async () => {
178
- const clock = new FakeClock();
179
- const rejection = new Error("push failed");
180
- const push = vi.fn(async () => {
181
- throw rejection;
182
- });
183
- const driver = new WatchPushDriver({ debounceMs: DEBOUNCE, clock, push });
184
- const unhandled: unknown[] = [];
185
- const onUnhandled = (reason: unknown) => {
186
- unhandled.push(reason);
187
- };
188
-
189
- process.prependListener("unhandledRejection", onUnhandled);
190
- try {
191
- driver.notifyChange();
192
- clock.advance(DEBOUNCE);
193
- await Promise.resolve();
194
- await flushImmediate();
195
-
196
- expect(push).toHaveBeenCalledTimes(1);
197
- expect(driver.isPushing()).toBe(false);
198
- expect(unhandled).toEqual([]);
199
- } finally {
200
- process.removeListener("unhandledRejection", onUnhandled);
201
- driver.dispose();
202
- }
203
- });
204
-
205
- it("respects a custom debounce window", async () => {
206
- const h = makeHarness({ debounceMs: 500 });
207
- h.emitChange();
208
- h.advance(499);
209
- expect(h.push).not.toHaveBeenCalled();
210
- h.advance(1);
211
- await Promise.resolve();
212
- expect(h.push).toHaveBeenCalledTimes(1);
213
- });
214
- });
215
-
216
- describe("US-001: WatchPushDriver — teardown leaves no leaked timers", () => {
217
- it("dispose() cancels a pending debounce timer", () => {
218
- const h = makeHarness();
219
- h.emitChange();
220
- expect(h.clock.pendingTimerCount()).toBe(1);
221
-
222
- h.driver.dispose();
223
- expect(h.clock.pendingTimerCount()).toBe(0);
224
-
225
- // A push must not fire after dispose, even if time advances.
226
- h.advance(DEBOUNCE * 10);
227
- expect(h.push).not.toHaveBeenCalled();
228
- });
229
-
230
- it("notifyChange() after dispose is a no-op and schedules nothing", () => {
231
- const h = makeHarness();
232
- h.driver.dispose();
233
- h.emitChange();
234
- expect(h.clock.pendingTimerCount()).toBe(0);
235
- h.advance(DEBOUNCE * 10);
236
- expect(h.push).not.toHaveBeenCalled();
237
- });
238
-
239
- it("dispose() is idempotent", () => {
240
- const h = makeHarness();
241
- h.emitChange();
242
- h.driver.dispose();
243
- h.driver.dispose();
244
- expect(h.clock.pendingTimerCount()).toBe(0);
245
- });
246
-
247
- it("a fully drained burst leaves zero pending timers", async () => {
248
- const h = makeHarness();
249
- for (let i = 0; i < 5; i++) h.emitChange();
250
- h.advance(DEBOUNCE);
251
- await Promise.resolve();
252
- expect(h.push).toHaveBeenCalledTimes(1);
253
- expect(h.clock.pendingTimerCount()).toBe(0);
254
- });
255
- });
256
-
257
- /**
258
- * US-002 — file-watcher module (debounced, ignore-aware, exclusion-aware).
259
- *
260
- * `createWatchPathFilter` is pure (no chokidar) so the exclusion logic is
261
- * tested directly against absolute paths. `TreeWatcher` is then exercised via
262
- * its `handleEvent` seam + FakeClock so debounce/coalesce/lifecycle assert
263
- * deterministically without spinning a real chokidar instance.
264
- */
265
-
266
- const ROOT = "/tmp/hq-root";
267
-
268
- describe("US-002: createWatchPathFilter — ignore-list matching", () => {
269
- const filter = createWatchPathFilter(ROOT, false);
270
-
271
- it("emits for an ordinary tracked file", () => {
272
- expect(filter(path.join(ROOT, "personal/notes.md"))).toBe(true);
273
- });
274
-
275
- it("does NOT emit for a .env file (DEFAULT_IGNORES secret)", () => {
276
- expect(filter(path.join(ROOT, ".env"))).toBe(false);
277
- expect(filter(path.join(ROOT, "personal/.env.local"))).toBe(false);
278
- });
279
-
280
- it("does NOT emit for node_modules / dist build artifacts", () => {
281
- expect(filter(path.join(ROOT, "node_modules/foo/index.js"))).toBe(false);
282
- expect(filter(path.join(ROOT, "dist/bundle.js"))).toBe(false);
283
- });
284
-
285
- it("does NOT emit for the watched root itself or paths outside it", () => {
286
- expect(filter(ROOT)).toBe(false);
287
- expect(filter("/some/other/place/file.txt")).toBe(false);
288
- });
289
- });
290
-
291
- describe("US-002: createWatchPathFilter — personal-vault exclusions", () => {
292
- const personal = createWatchPathFilter(ROOT, true);
293
- const nonPersonal = createWatchPathFilter(ROOT, false);
294
-
295
- it("does NOT emit for PERSONAL_VAULT_DEFAULT_EXCLUSIONS in personalMode (output/, .beads/)", () => {
296
- expect(personal(path.join(ROOT, "personal/output/x.txt"))).toBe(false);
297
- expect(personal(path.join(ROOT, "personal/.beads/issues.db"))).toBe(false);
298
- });
299
-
300
- it("does NOT emit for PERSONAL_VAULT_EXCLUDED_TOP_LEVEL in personalMode (.git/companies/repos/workspace)", () => {
301
- expect(personal(path.join(ROOT, "companies/indigo/board.json"))).toBe(false);
302
- expect(personal(path.join(ROOT, "workspace/threads/x.json"))).toBe(false);
303
- expect(personal(path.join(ROOT, "repos/private/foo/file.ts"))).toBe(false);
304
- });
305
-
306
- // ── DEV-1778 continuity-pointer carve-out ───────────────────────────────
307
- it("DOES emit for workspace/threads/handoff.json (the continuity pointer)", () => {
308
- expect(personal(path.join(ROOT, "workspace/threads/handoff.json"))).toBe(
309
- true,
310
- );
311
- });
312
-
313
- it("still does NOT emit for other workspace/ files (carve-out is pointer-only)", () => {
314
- // The pointer is the ONLY re-include — sibling threads, the journal, and
315
- // unrelated workspace litter stay machine-local.
316
- expect(personal(path.join(ROOT, "workspace/threads/T-old.json"))).toBe(
317
- false,
318
- );
319
- expect(personal(path.join(ROOT, "workspace/threads/INDEX.md"))).toBe(false);
320
- expect(personal(path.join(ROOT, "workspace/locks/x.lock"))).toBe(false);
321
- // The pointer queried as a directory is not an emit target either.
322
- expect(
323
- personal(path.join(ROOT, "workspace/threads/handoff.json"), true),
324
- ).toBe(false);
325
- });
326
-
327
- it("allows chokidar to DESCEND through the pointer's ancestor dirs (dir probe)", () => {
328
- // Without this the Linux chokidar backend prunes `workspace/` before ever
329
- // reaching the leaf. Ancestor dirs return true ONLY when queried as dirs.
330
- expect(personal(path.join(ROOT, "workspace"), true)).toBe(true);
331
- expect(personal(path.join(ROOT, "workspace/threads"), true)).toBe(true);
332
- // A non-ancestor dir under workspace/ is still pruned.
333
- expect(personal(path.join(ROOT, "workspace/locks"), true)).toBe(false);
334
- // Ancestor dirs queried as FILES are not emit targets.
335
- expect(personal(path.join(ROOT, "workspace"), false)).toBe(false);
336
- });
337
-
338
- // ── workspace/agency subtree carve-out (personal mode) ──────────────────
339
- // The personal push uploads workspace/agency/** (computeAgencySyncPaths), so
340
- // the personal watcher must emit those changes event-driven, not leave them
341
- // for the 60s poll. Mirrors the continuity-pointer carve-out, for a subtree.
342
- it("DOES emit for workspace/agency files in personalMode (synced subtree)", () => {
343
- expect(
344
- personal(path.join(ROOT, "workspace/agency/indigo/nick/chat.jsonl")),
345
- ).toBe(true);
346
- expect(
347
- personal(path.join(ROOT, "workspace/agency/indigo/nick/status.json")),
348
- ).toBe(true);
349
- // The agency root itself, as a file event, also emits.
350
- expect(personal(path.join(ROOT, "workspace/agency"))).toBe(true);
351
- });
352
-
353
- it("allows chokidar to DESCEND to workspace/agency in personalMode (dir probes)", () => {
354
- // workspace/ and workspace/agency queried as dirs must return true so the
355
- // chokidar backend descends instead of pruning workspace/ at the top.
356
- expect(personal(path.join(ROOT, "workspace"), true)).toBe(true);
357
- expect(personal(path.join(ROOT, "workspace/agency"), true)).toBe(true);
358
- expect(
359
- personal(path.join(ROOT, "workspace/agency/indigo"), true),
360
- ).toBe(true);
361
- });
362
-
363
- it("agency carve-out is exact-segment (does NOT leak to workspace/agencyX)", () => {
364
- // Only workspace/agency (and its subtree) is re-included; a sibling whose
365
- // name merely starts with 'agency' stays excluded like other workspace litter.
366
- expect(personal(path.join(ROOT, "workspace/agencyX/foo.txt"))).toBe(false);
367
- expect(personal(path.join(ROOT, "workspace/agency-notes.md"))).toBe(false);
368
- });
369
-
370
- it("agency carve-out does not re-include other workspace/ litter", () => {
371
- // Regression: the new carve-out must not widen the workspace exclusion for
372
- // anything other than agency + the continuity pointer.
373
- expect(personal(path.join(ROOT, "workspace/locks/x.lock"))).toBe(false);
374
- expect(personal(path.join(ROOT, "workspace/threads/T-old.json"))).toBe(false);
375
- expect(personal(path.join(ROOT, "workspace/worktrees/x/a.ts"))).toBe(false);
376
- });
377
-
378
- // ── workspace/.session-logs subtree carve-out (personal mode) ────────────
379
- // The personal push uploads workspace/.session-logs/** (reindex-captured
380
- // Claude Code transcripts, computeSessionLogsSyncPaths), so the personal
381
- // watcher must emit those changes event-driven. Mirrors the agency carve-out.
382
- it("DOES emit for workspace/.session-logs files in personalMode (synced subtree)", () => {
383
- expect(
384
- personal(path.join(ROOT, "workspace/.session-logs/session.jsonl")),
385
- ).toBe(true);
386
- expect(
387
- personal(path.join(ROOT, "workspace/.session-logs/tool-results/r.txt")),
388
- ).toBe(true);
389
- // The subtree root itself, as a file event, also emits.
390
- expect(personal(path.join(ROOT, "workspace/.session-logs"))).toBe(true);
391
- });
392
-
393
- it("allows chokidar to DESCEND to workspace/.session-logs in personalMode (dir probes)", () => {
394
- expect(personal(path.join(ROOT, "workspace"), true)).toBe(true);
395
- expect(personal(path.join(ROOT, "workspace/.session-logs"), true)).toBe(true);
396
- expect(
397
- personal(path.join(ROOT, "workspace/.session-logs/tool-results"), true),
398
- ).toBe(true);
399
- });
400
-
401
- it("session-logs carve-out is exact-segment (does NOT leak to a similarly-named sibling)", () => {
402
- expect(
403
- personal(path.join(ROOT, "workspace/.session-logs-old/foo.txt")),
404
- ).toBe(false);
405
- expect(personal(path.join(ROOT, "workspace/.session-logsX.md"))).toBe(false);
406
- });
407
-
408
- it("does not apply the carve-out in non-personal mode", () => {
409
- // In non-personal mode the excluded-top-level layer never runs, so the
410
- // carve-out is irrelevant; handoff.json passes via the ordinary ignore
411
- // stack like any other tracked file (no special-casing needed).
412
- expect(
413
- nonPersonal(path.join(ROOT, "workspace/threads/handoff.json")),
414
- ).toBe(true);
415
- });
416
-
417
- it("DOES emit for an included top-level personal path in personalMode", () => {
418
- expect(personal(path.join(ROOT, "personal/notes.md"))).toBe(true);
419
- expect(personal(path.join(ROOT, "core/policies/x.md"))).toBe(true);
420
- });
421
-
422
- it("non-personal mode does NOT apply the excluded-top-level buckets", () => {
423
- // companies/ is only excluded by the personal-vault layer; in non-personal
424
- // mode the ignore stack alone governs and lets it through.
425
- expect(nonPersonal(path.join(ROOT, "companies/indigo/board.json"))).toBe(true);
426
- });
427
-
428
- // ── Never-synced heavy buckets pruned in BOTH modes ─────────────────────
429
- // In --companies mode personalMode=false, so the excluded-top-level layer
430
- // never ran and the watcher descended into the local git worktrees
431
- // (workspace/worktrees/, ~200k transient files from agent coding runs) and
432
- // the on-box repos checkout (repos/). Neither ever vault-syncs in any mode,
433
- // so watching them only burns inotify watches (near the OS limit) + CPU on
434
- // build churn it discards, and can trip the overflow→full-reconcile fallback.
435
- it("non-personal mode EXCLUDES never-synced heavy buckets (workspace/worktrees, repos)", () => {
436
- expect(
437
- nonPersonal(path.join(ROOT, "workspace/worktrees/hq-console/src/a.ts")),
438
- ).toBe(false);
439
- // The bucket dir itself is pruned so chokidar never descends into it.
440
- expect(nonPersonal(path.join(ROOT, "workspace/worktrees"), true)).toBe(false);
441
- expect(
442
- nonPersonal(path.join(ROOT, "repos/private/hq-cloud/src/x.ts")),
443
- ).toBe(false);
444
- expect(nonPersonal(path.join(ROOT, "repos"), true)).toBe(false);
445
- });
446
-
447
- it("non-personal mode STILL watches synced content (companies/, workspace/agency, continuity)", () => {
448
- expect(
449
- nonPersonal(path.join(ROOT, "companies/indigo/board.json")),
450
- ).toBe(true);
451
- expect(
452
- nonPersonal(path.join(ROOT, "workspace/agency/indigo/nick/status.json")),
453
- ).toBe(true);
454
- expect(
455
- nonPersonal(path.join(ROOT, "workspace/threads/handoff.json")),
456
- ).toBe(true);
457
- // chokidar must still descend into workspace/ to reach agency + continuity.
458
- expect(nonPersonal(path.join(ROOT, "workspace"), true)).toBe(true);
459
- // A worktrees SIBLING under workspace/ is unaffected (only worktrees pruned).
460
- expect(
461
- nonPersonal(path.join(ROOT, "workspace/agency"), true),
462
- ).toBe(true);
463
- });
464
-
465
- it("personal mode still excludes worktrees + repos (regression, unchanged)", () => {
466
- expect(personal(path.join(ROOT, "workspace/worktrees/x/a.ts"))).toBe(false);
467
- expect(personal(path.join(ROOT, "repos/private/x/a.ts"))).toBe(false);
468
- });
469
- });
470
-
471
- describe("US-002: chokidar descent scope", () => {
472
- let dir: string;
473
-
474
- beforeEach(() => {
475
- dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "watch-scope-")));
476
- // This is the real HQ allowlist shape. The synthetic heavy directories
477
- // deliberately sit both under an in-scope company and under the two
478
- // never-synced top-level buckets from #156.
479
- fs.writeFileSync(path.join(dir, ".hqinclude"), "companies/*/knowledge/\n");
480
- fs.mkdirSync(
481
- path.join(dir, "companies", "acme", "knowledge", "node_modules", "heavy"),
482
- { recursive: true },
483
- );
484
- fs.writeFileSync(
485
- path.join(dir, "companies", "acme", "knowledge", "node_modules", "heavy", "index.js"),
486
- "module.exports = 1;\n",
487
- );
488
- fs.mkdirSync(path.join(dir, "repos", "checkout", "heavy"), { recursive: true });
489
- fs.mkdirSync(
490
- path.join(dir, "workspace", "worktrees", "repo", "node_modules", "heavy"),
491
- { recursive: true },
492
- );
493
- });
494
-
495
- afterEach(() => {
496
- fs.rmSync(dir, { recursive: true, force: true });
497
- });
498
-
499
- it("uses the directory verdict, not a file-shaped false positive, for the pre-stat probe", () => {
500
- const filter = createWatchPathFilter(dir, false);
501
- const nodeModules = path.join(
502
- dir,
503
- "companies",
504
- "acme",
505
- "knowledge",
506
- "node_modules",
507
- );
508
- // `node_modules/` is directory-only. Asking the generic emit filter as
509
- // though it were a file returns true, which is exactly what the old
510
- // `file || directory` probe used to mistake for permission to descend.
511
- expect(filter(nodeModules, false)).toBe(true);
512
- expect(filter(nodeModules, true)).toBe(false);
513
- const ignored = toChokidarIgnored(filter, dir);
514
- expect(ignored(nodeModules)).toBe(true);
515
- // The allowlist's exact ancestor matcher remains the only carve-out: the
516
- // watcher can still reach companies/<slug>/knowledge without opening every
517
- // otherwise-file-shaped ignored directory below it.
518
- expect(ignored(path.join(dir, "companies"))).toBe(false);
519
- expect(ignored(path.join(dir, "companies", "acme"))).toBe(false);
520
- });
521
-
522
- it("prunes ignored directories during chokidar's pre-stat descent probe", async () => {
523
- const filter = createWatchPathFilter(dir, false);
524
- const chokidarWatcher = watch(dir, {
525
- ignored: toChokidarIgnored(filter, dir),
526
- ignoreInitial: true,
527
- persistent: false,
528
- });
529
- try {
530
- await new Promise<void>((resolve, reject) => {
531
- chokidarWatcher.once("ready", resolve);
532
- chokidarWatcher.once("error", reject);
533
- });
534
- const descended = Object.keys(chokidarWatcher.getWatched())
535
- .map((watchedPath) => path.resolve(watchedPath))
536
- .sort();
537
-
538
- expect(descended).toContain(
539
- path.join(dir, "companies", "acme", "knowledge"),
540
- );
541
- expect(descended).not.toContain(
542
- path.join(dir, "companies", "acme", "knowledge", "node_modules"),
543
- );
544
- expect(descended).not.toContain(path.join(dir, "repos"));
545
- expect(descended).not.toContain(path.join(dir, "workspace", "worktrees"));
546
- } finally {
547
- await chokidarWatcher.close();
548
- }
549
- });
550
- });
551
-
552
- describe("US-002: TreeWatcher — debounce coalesce (FakeClock seam)", () => {
553
- function makeWatcher(opts?: { debounceMs?: number; personalMode?: boolean }) {
554
- const clock = new FakeClock();
555
- const changed = vi.fn();
556
- const watcher = new TreeWatcher({
557
- hqRoot: ROOT,
558
- debounceMs: opts?.debounceMs ?? DEBOUNCE,
559
- personalMode: opts?.personalMode ?? false,
560
- clock,
561
- });
562
- watcher.onChange(changed);
563
- return { clock, changed, watcher };
564
- }
565
-
566
- it("coalesces 5 rapid changes within the window into exactly 1 changed signal", () => {
567
- const { clock, changed, watcher } = makeWatcher();
568
- for (let i = 0; i < 5; i++) {
569
- watcher.handleEvent(path.join(ROOT, `personal/file-${i}.md`));
570
- clock.advance(20); // 100ms total << 2000ms debounce
571
- }
572
- expect(changed).not.toHaveBeenCalled();
573
- clock.advance(DEBOUNCE);
574
- expect(changed).toHaveBeenCalledTimes(1);
575
- expect(watcher.pendingTimerCount()).toBe(0);
576
- });
577
-
578
- it("fires once after the quiet window for a single change", () => {
579
- const { clock, changed, watcher } = makeWatcher();
580
- watcher.handleEvent(path.join(ROOT, "personal/a.md"));
581
- clock.advance(DEBOUNCE - 1);
582
- expect(changed).not.toHaveBeenCalled();
583
- clock.advance(1);
584
- expect(changed).toHaveBeenCalledTimes(1);
585
- });
586
-
587
- it("does NOT emit for an ignored / excluded path", () => {
588
- const { clock, changed, watcher } = makeWatcher({ personalMode: true });
589
- watcher.handleEvent(path.join(ROOT, ".env"));
590
- watcher.handleEvent(path.join(ROOT, "personal/output/big.bin"));
591
- watcher.handleEvent(path.join(ROOT, "companies/indigo/board.json"));
592
- clock.advance(DEBOUNCE * 2);
593
- expect(changed).not.toHaveBeenCalled();
594
- expect(watcher.pendingTimerCount()).toBe(0);
595
- });
596
-
597
- it("treats two separate bursts as two changed signals", () => {
598
- const { clock, changed, watcher } = makeWatcher();
599
- watcher.handleEvent(path.join(ROOT, "personal/a.md"));
600
- clock.advance(DEBOUNCE);
601
- expect(changed).toHaveBeenCalledTimes(1);
602
- watcher.handleEvent(path.join(ROOT, "personal/b.md"));
603
- clock.advance(DEBOUNCE);
604
- expect(changed).toHaveBeenCalledTimes(2);
605
- });
606
-
607
- it("R-F13: caps watcher backlog and keeps EMFILE polling fallback removed", () => {
608
- const clock = new FakeClock();
609
- const changed = vi.fn();
610
- const overflow = vi.fn();
611
- const watcher = new TreeWatcher({
612
- hqRoot: ROOT,
613
- debounceMs: DEBOUNCE,
614
- clock,
615
- pathFilter: () => true,
616
- maxPendingPaths: 3,
617
- maxPendingBytes: 10_000,
618
- onBacklogOverflow: overflow,
619
- });
620
- watcher.onChange(changed);
621
-
622
- for (let i = 0; i < 10; i++) {
623
- watcher.handleEvent(path.join(ROOT, `bulk-${i}.md`));
624
- }
625
-
626
- expect(overflow).toHaveBeenCalledTimes(1);
627
- clock.advance(DEBOUNCE);
628
- expect(changed).toHaveBeenCalledTimes(1);
629
- const batch = changed.mock.calls[0][1] as {
630
- paths: Map<string, string>;
631
- overflowed?: boolean;
632
- droppedPaths?: number;
633
- };
634
- expect(batch.paths.size).toBe(3);
635
- expect(batch.overflowed).toBe(true);
636
- expect(batch.droppedPaths).toBe(7);
637
-
638
- const source = fs.readFileSync(path.join(process.cwd(), "src/watcher.ts"), "utf8");
639
- expect(source).not.toContain("startPollingTreeWatch");
640
- expect(source).not.toContain("snapshotWatchTree");
641
- });
642
-
643
- it("stops descending at the hard watch budget, reports, and degrades to polling", () => {
644
- const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "watch-cap-")));
645
- fs.mkdirSync(path.join(dir, "personal", "a", "deep"), { recursive: true });
646
- fs.mkdirSync(path.join(dir, "personal", "b", "deep"), { recursive: true });
647
- const clock = new FakeClock();
648
- const degraded = vi.fn();
649
- const changed = vi.fn();
650
- const descended: string[] = [];
651
- let backendClosed = false;
652
- try {
653
- const watcher = new TreeWatcher({
654
- hqRoot: dir,
655
- clock,
656
- debounceMs: DEBOUNCE,
657
- maxWatchedPaths: 3,
658
- onDegraded: degraded,
659
- // This faked backend drives chokidar's real ignored predicate through
660
- // its pre-stat and post-stat calls, without needing an inotify slot on
661
- // a host already exhausted by another process.
662
- backendFactory: ({
663
- hqRoot,
664
- shouldEmit,
665
- maxWatchedPaths,
666
- onWatchBudgetExceeded,
667
- }) => {
668
- const budget = new ChokidarWatchBudget(
669
- maxWatchedPaths,
670
- onWatchBudgetExceeded,
671
- );
672
- const ignored = toChokidarIgnored(shouldEmit, hqRoot, budget);
673
- const visit = (candidate: string): void => {
674
- if (ignored(candidate)) return;
675
- const stats = fs.lstatSync(candidate);
676
- if (ignored(candidate, stats)) return;
677
- if (!stats.isDirectory()) return;
678
- descended.push(path.resolve(candidate));
679
- for (const entry of fs.readdirSync(candidate)) {
680
- visit(path.join(candidate, entry));
681
- }
682
- };
683
- visit(hqRoot);
684
- return {
685
- close: () => {
686
- backendClosed = true;
687
- },
688
- needsKnownKinds: false,
689
- watchedPathCount: () => descended.length,
690
- };
691
- },
692
- });
693
- watcher.onChange(changed);
694
- watcher.start();
695
-
696
- expect(descended).toHaveLength(3);
697
- expect(descended).not.toContain(path.join(dir, "personal", "a", "deep"));
698
- expect(degraded).toHaveBeenCalledWith(
699
- expect.objectContaining({
700
- reason: "watch_budget_exhausted",
701
- maxWatchedPaths: 3,
702
- watchedPaths: 3,
703
- offendingPath: expect.stringContaining(path.join("personal", "a", "deep")),
704
- }),
705
- );
706
- expect(backendClosed).toBe(true);
707
- expect(watcher.isWatching()).toBe(false);
708
-
709
- clock.advance(DEBOUNCE);
710
- expect(changed).toHaveBeenCalledWith(
711
- undefined,
712
- expect.objectContaining({ overflowed: true }),
713
- );
714
- } finally {
715
- fs.rmSync(dir, { recursive: true, force: true });
716
- }
717
- });
718
-
719
- it("degrades instead of dying when chokidar emits runtime ENOSPC", () => {
720
- const clock = new FakeClock();
721
- const degraded = vi.fn();
722
- const changed = vi.fn();
723
- const telemetry: TelemetryEventsBatch[] = [];
724
- const telemetryClient = {
725
- postTelemetryEvents: vi.fn(async (batch: TelemetryEventsBatch) => {
726
- telemetry.push(batch);
727
- return { ok: true, written: batch.events.length, skipped: [] };
728
- }),
729
- };
730
- let closeCalls = 0;
731
- const watcher = new TreeWatcher({
732
- hqRoot: ROOT,
733
- clock,
734
- debounceMs: DEBOUNCE,
735
- onDegraded: degraded,
736
- telemetryClient,
737
- backendFactory: ({ onError }) => {
738
- const backend = {
739
- close: () => {
740
- closeCalls += 1;
741
- },
742
- needsKnownKinds: false,
743
- watchedPathCount: () => 0,
744
- };
745
- queueMicrotask(() =>
746
- onError(
747
- Object.assign(new Error("inotify limit"), {
748
- code: "ENOSPC",
749
- path: path.join(ROOT, "companies", "acme", "knowledge"),
750
- }),
751
- ),
752
- );
753
- return backend;
754
- },
755
- });
756
- watcher.onChange(changed);
757
- watcher.start();
758
-
759
- return new Promise<void>((resolve) => queueMicrotask(resolve)).then(() => {
760
- expect(closeCalls).toBe(1);
761
- expect(watcher.isWatching()).toBe(false);
762
- expect(degraded).toHaveBeenCalledWith(
763
- expect.objectContaining({
764
- reason: "inotify_enospc",
765
- errorCode: "ENOSPC",
766
- offendingPath: path.join(ROOT, "companies", "acme", "knowledge"),
767
- }),
768
- );
769
- expect(telemetry).toEqual([
770
- expect.objectContaining({
771
- events: [
772
- expect.objectContaining({
773
- eventName: "watcher_degraded",
774
- source: "watcher",
775
- properties: expect.objectContaining({
776
- reason: "inotify_enospc",
777
- offendingTopLevel: "companies",
778
- }),
779
- }),
780
- ],
781
- }),
782
- ]);
783
- clock.advance(DEBOUNCE);
784
- expect(changed).toHaveBeenCalledWith(
785
- undefined,
786
- expect.objectContaining({ overflowed: true }),
787
- );
788
- });
789
- });
790
-
791
- it("does not retain one rename-kind entry for every changed file", () => {
792
- const clock = new FakeClock();
793
- const watcher = new TreeWatcher({
794
- hqRoot: ROOT,
795
- clock,
796
- pathFilter: () => true,
797
- maxPendingPaths: 20_000,
798
- maxPendingBytes: 20_000_000,
799
- });
800
- for (let i = 0; i < 10_000; i++) {
801
- watcher.handleEvent(path.join(ROOT, "personal", `file-${i}.md`));
802
- }
803
- expect(watcher.knownDirectoryCount()).toBe(0);
804
- watcher.stop();
805
- });
806
- });
807
-
808
- describe("US-002: TreeWatcher — lifecycle (real chokidar over a temp dir)", () => {
809
- let dir: string;
810
-
811
- beforeEach(() => {
812
- // realpathSync resolves macOS's /var -> /private/var symlink so chokidar's
813
- // canonicalized event paths stay inside hqRoot (path.relative would
814
- // otherwise yield a `..`-prefixed path and the filter would reject them).
815
- dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "treewatcher-")));
816
- });
817
-
818
- afterEach(() => {
819
- fs.rmSync(dir, { recursive: true, force: true });
820
- });
821
-
822
- it("start() is idempotent — a second start does not open a second watcher", () => {
823
- const w = new TreeWatcher({ hqRoot: dir });
824
- w.start();
825
- expect(w.isWatching()).toBe(true);
826
- w.start(); // no throw, no second instance
827
- expect(w.isWatching()).toBe(true);
828
- w.stop();
829
- expect(w.isWatching()).toBe(false);
830
- });
831
-
832
- it("stop() closes the watcher and clears pending timers; dispose() is permanent", () => {
833
- const clock = new FakeClock();
834
- const w = new TreeWatcher({ hqRoot: dir, clock });
835
- w.start();
836
- w.handleEvent(path.join(dir, "x.md"));
837
- expect(w.pendingTimerCount()).toBe(1);
838
- w.stop();
839
- expect(w.pendingTimerCount()).toBe(0);
840
- expect(w.isWatching()).toBe(false);
841
-
842
- // After dispose, events are inert and start is a no-op.
843
- w.dispose();
844
- w.handleEvent(path.join(dir, "y.md"));
845
- expect(w.pendingTimerCount()).toBe(0);
846
- w.start();
847
- expect(w.isWatching()).toBe(false);
848
- });
849
-
850
- it("emits a debounced changed signal for a real file write", async () => {
851
- const w = new TreeWatcher({ hqRoot: dir, debounceMs: 50 });
852
- const changed = vi.fn();
853
- w.onChange(changed);
854
- w.start();
855
- // Give chokidar a beat to set up its watch before writing.
856
- await new Promise((r) => setTimeout(r, 200));
857
- fs.writeFileSync(path.join(dir, "hello.md"), "hi");
858
- await new Promise((r) => setTimeout(r, 1500));
859
- expect(changed).toHaveBeenCalled();
860
- w.dispose();
861
- }, 10_000);
862
- });
863
-
864
- describe("PushEventEmitter — directory and delete tombstone handling", () => {
865
- let dir: string;
866
-
867
- beforeEach(() => {
868
- dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "pushemit-")));
869
- });
870
-
871
- afterEach(() => {
872
- fs.rmSync(dir, { recursive: true, force: true });
873
- });
874
-
875
- function makeEmitter(opts?: {
876
- published?: PushEvent[];
877
- onError?: ReturnType<typeof vi.fn>;
878
- getSequenceNumber?: () => number;
879
- }): PushEventEmitter {
880
- const published = opts?.published ?? [];
881
- const transport: PushTransport = {
882
- start: async () => {},
883
- dispose: async () => {},
884
- connected: true,
885
- publish: async (event) => {
886
- published.push(event);
887
- },
888
- };
889
- return new PushEventEmitter({
890
- originTenantId: "tenant-indigo",
891
- originDeviceId: "device-a",
892
- transport,
893
- flagProvider: new StaticFlagProvider(["tenant-indigo"]),
894
- now: () => new Date("2026-06-18T12:00:00.000Z"),
895
- getSequenceNumber: opts?.getSequenceNumber,
896
- onError: opts?.onError,
897
- });
898
- }
899
-
900
- it("F13: watcher batch event publishing applies bounded backpressure", async () => {
901
- const paths = new Map<string, string>();
902
- for (let i = 0; i < 32; i++) {
903
- const rel = `bulk-${i}.md`;
904
- const abs = path.join(dir, rel);
905
- fs.writeFileSync(abs, `file ${i}`);
906
- paths.set(abs, rel);
907
- }
908
-
909
- let inFlight = 0;
910
- let maxInFlight = 0;
911
- let releaseGate!: () => void;
912
- const gate = new Promise<void>((resolve) => {
913
- releaseGate = resolve;
914
- });
915
- const transport: PushTransport = {
916
- start: async () => {},
917
- dispose: async () => {},
918
- connected: true,
919
- publish: async () => {
920
- inFlight += 1;
921
- maxInFlight = Math.max(maxInFlight, inFlight);
922
- await gate;
923
- inFlight -= 1;
924
- },
925
- };
926
- const emitter = new PushEventEmitter({
927
- originTenantId: "tenant-indigo",
928
- originDeviceId: "device-a",
929
- transport,
930
- flagProvider: new StaticFlagProvider(["tenant-indigo"]),
931
- now: () => new Date("2026-06-18T12:00:00.000Z"),
932
- });
933
-
934
- const run = emitter.emitForBatch({ paths });
935
- try {
936
- for (let i = 0; i < 200 && maxInFlight <= 16; i++) {
937
- await flushImmediate();
938
- }
939
- releaseGate();
940
- await run;
941
-
942
- expect(maxInFlight).toBeLessThanOrEqual(16);
943
- } finally {
944
- releaseGate();
945
- await run.catch(() => {});
946
- }
947
- });
948
-
949
- it("skips directory changes silently without publishing or reporting an error", async () => {
950
- const published: PushEvent[] = [];
951
- const onError = vi.fn();
952
- const subdir = path.join(dir, "folder");
953
- fs.mkdirSync(subdir);
954
- const emitter = makeEmitter({ published, onError });
955
-
956
- await emitter.emitForBatch({ paths: new Map([[subdir, "folder"]]) });
957
-
958
- expect(published).toEqual([]);
959
- expect(onError).not.toHaveBeenCalled();
960
- });
961
-
962
- it("emits and publishes a delete tombstone when the changed file is gone", async () => {
963
- const published: PushEvent[] = [];
964
- const onError = vi.fn();
965
- const emitter = makeEmitter({
966
- published,
967
- onError,
968
- getSequenceNumber: () => 99,
969
- });
970
- const missing = path.join(dir, "deleted.md");
971
-
972
- await emitter.emitForBatch({ paths: new Map([[missing, "deleted.md"]]) });
973
-
974
- expect(onError).not.toHaveBeenCalled();
975
- expect(published).toEqual([
976
- {
977
- kind: "delete",
978
- relativePath: "deleted.md",
979
- originDeviceId: "device-a",
980
- originTenantId: "tenant-indigo",
981
- sequenceNumber: 99,
982
- eventTimestamp: "2026-06-18T12:00:00.000Z",
983
- },
984
- ]);
985
- expect(published[0]).not.toHaveProperty("contentHash");
986
- expect(published[0]).not.toHaveProperty("mtime");
987
- });
988
-
989
- it("emits push telemetry only when publication fails", async () => {
990
- const posts: TelemetryEventsBatch[] = [];
991
- const telemetryClient = {
992
- postTelemetryEvents: vi.fn(async (batch: TelemetryEventsBatch) => {
993
- posts.push(batch);
994
- return { ok: true, written: batch.events.length, skipped: [] };
995
- }),
996
- };
997
- const changed = path.join(dir, "changed.md");
998
- fs.writeFileSync(changed, "changed");
999
- const success = new PushEventEmitter({
1000
- originTenantId: "tenant-indigo",
1001
- originDeviceId: "device-a",
1002
- transport: {
1003
- start: async () => {},
1004
- dispose: async () => {},
1005
- connected: true,
1006
- publish: async () => {},
1007
- },
1008
- flagProvider: new StaticFlagProvider(["tenant-indigo"]),
1009
- telemetryClient,
1010
- });
1011
-
1012
- await success.emitForBatch({ paths: new Map([[changed, "changed.md"]]) });
1013
- await flushImmediate();
1014
- expect(posts).toEqual([]);
1015
-
1016
- const failed = new PushEventEmitter({
1017
- originTenantId: "tenant-indigo",
1018
- originDeviceId: "device-a",
1019
- transport: {
1020
- start: async () => {},
1021
- dispose: async () => {},
1022
- connected: true,
1023
- publish: async () => {
1024
- throw new Error("network down");
1025
- },
1026
- },
1027
- flagProvider: new StaticFlagProvider(["tenant-indigo"]),
1028
- telemetryClient,
1029
- onError: vi.fn(),
1030
- });
1031
-
1032
- await failed.emitForBatch({ paths: new Map([[changed, "changed.md"]]) });
1033
- await flushImmediate();
1034
- expect(posts.flatMap((post) => post.events)).toEqual([
1035
- expect.objectContaining({
1036
- eventName: "push_event_failed",
1037
- properties: {
1038
- kind: "upsert",
1039
- count: 1,
1040
- status: "failure",
1041
- stage: "publish",
1042
- },
1043
- }),
1044
- ]);
1045
- });
1046
- });
1047
-
1048
- describe("TreeWatcher wire-key codec boundary (US-002)", () => {
1049
- it("emits the canonical vault key for an encoded win32 farm name (verbatim local name on POSIX)", () => {
1050
- const hqRoot = path.join(os.tmpdir(), "hq-watch-codec-test-root");
1051
- const clock = new FakeClock();
1052
- const watcher = new TreeWatcher({
1053
- hqRoot,
1054
- clock,
1055
- debounceMs: 100,
1056
- pathFilter: () => true,
1057
- });
1058
- const rels: string[] = [];
1059
- watcher.onChange((_first, batch) => {
1060
- if (batch) rels.push(...batch.paths.values());
1061
- });
1062
-
1063
- watcher.handleEvent(
1064
- path.join(hqRoot, ".claude", "skills", "indigo%3Acall-prep-brief"),
1065
- );
1066
- clock.advance(200);
1067
-
1068
- // The batch rel is a WIRE identifier (PushEvent.relativePath / targeted
1069
- // push route). On win32 the encoded local farm name must decode back to
1070
- // the canonical key or event-driven push re-mints the junk key family;
1071
- // on POSIX the local name IS the key verbatim (codec is identity there).
1072
- const expectedRel =
1073
- process.platform === "win32"
1074
- ? ".claude/skills/indigo:call-prep-brief"
1075
- : ".claude/skills/indigo%3Acall-prep-brief";
1076
- expect(rels).toEqual([expectedRel]);
1077
- watcher.dispose();
1078
- });
1079
- });