@indigoai-us/hq-cloud 6.14.50 → 6.15.1

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 (340) hide show
  1. package/dist/bin/sync-mutation.d.ts +14 -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 +64 -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/reindex-knowledge.d.ts +7 -0
  34. package/dist/cli/reindex-knowledge.d.ts.map +1 -0
  35. package/dist/cli/reindex-knowledge.js +389 -0
  36. package/dist/cli/reindex-knowledge.js.map +1 -0
  37. package/dist/cli/reindex-knowledge.test.d.ts +12 -0
  38. package/dist/cli/reindex-knowledge.test.d.ts.map +1 -0
  39. package/dist/cli/reindex-knowledge.test.js +260 -0
  40. package/dist/cli/reindex-knowledge.test.js.map +1 -0
  41. package/dist/cli/reindex.d.ts.map +1 -1
  42. package/dist/cli/reindex.js +8 -0
  43. package/dist/cli/reindex.js.map +1 -1
  44. package/dist/cli/rescue-settings-reconcile.test.js +47 -0
  45. package/dist/cli/rescue-settings-reconcile.test.js.map +1 -1
  46. package/dist/cli/sync.d.ts +27 -0
  47. package/dist/cli/sync.d.ts.map +1 -1
  48. package/dist/cli/sync.js +52 -0
  49. package/dist/cli/sync.js.map +1 -1
  50. package/dist/cli/sync.test.js +31 -1
  51. package/dist/cli/sync.test.js.map +1 -1
  52. package/dist/index.d.ts +2 -0
  53. package/dist/index.d.ts.map +1 -1
  54. package/dist/index.js +1 -0
  55. package/dist/index.js.map +1 -1
  56. package/dist/skill-telemetry.d.ts +6 -0
  57. package/dist/skill-telemetry.d.ts.map +1 -1
  58. package/dist/skill-telemetry.js +14 -2
  59. package/dist/skill-telemetry.js.map +1 -1
  60. package/dist/skill-telemetry.test.js +79 -0
  61. package/dist/skill-telemetry.test.js.map +1 -1
  62. package/dist/sync/candidate-uploader.d.ts +88 -0
  63. package/dist/sync/candidate-uploader.d.ts.map +1 -0
  64. package/dist/sync/candidate-uploader.js +212 -0
  65. package/dist/sync/candidate-uploader.js.map +1 -0
  66. package/dist/sync/candidate-uploader.test.d.ts +2 -0
  67. package/dist/sync/candidate-uploader.test.d.ts.map +1 -0
  68. package/dist/sync/candidate-uploader.test.js +132 -0
  69. package/dist/sync/candidate-uploader.test.js.map +1 -0
  70. package/dist/sync/delta-client.d.ts +73 -0
  71. package/dist/sync/delta-client.d.ts.map +1 -0
  72. package/dist/sync/delta-client.js +201 -0
  73. package/dist/sync/delta-client.js.map +1 -0
  74. package/dist/sync/delta-client.test.d.ts +2 -0
  75. package/dist/sync/delta-client.test.d.ts.map +1 -0
  76. package/dist/sync/delta-client.test.js +97 -0
  77. package/dist/sync/delta-client.test.js.map +1 -0
  78. package/dist/sync/durable-apply.d.ts +76 -0
  79. package/dist/sync/durable-apply.d.ts.map +1 -0
  80. package/dist/sync/durable-apply.js +530 -0
  81. package/dist/sync/durable-apply.js.map +1 -0
  82. package/dist/sync/durable-apply.test.d.ts +2 -0
  83. package/dist/sync/durable-apply.test.d.ts.map +1 -0
  84. package/dist/sync/durable-apply.test.js +180 -0
  85. package/dist/sync/durable-apply.test.js.map +1 -0
  86. package/dist/sync/event-sync.d.ts +33 -1
  87. package/dist/sync/event-sync.d.ts.map +1 -1
  88. package/dist/sync/event-sync.js +149 -1
  89. package/dist/sync/event-sync.js.map +1 -1
  90. package/dist/sync/event-sync.test.js +142 -1
  91. package/dist/sync/event-sync.test.js.map +1 -1
  92. package/dist/sync/index.d.ts +2 -0
  93. package/dist/sync/index.d.ts.map +1 -1
  94. package/dist/sync/index.js +1 -0
  95. package/dist/sync/index.js.map +1 -1
  96. package/dist/sync/multipart-uploader.d.ts +99 -0
  97. package/dist/sync/multipart-uploader.d.ts.map +1 -0
  98. package/dist/sync/multipart-uploader.js +447 -0
  99. package/dist/sync/multipart-uploader.js.map +1 -0
  100. package/dist/sync/multipart-uploader.test.d.ts +2 -0
  101. package/dist/sync/multipart-uploader.test.d.ts.map +1 -0
  102. package/dist/sync/multipart-uploader.test.js +119 -0
  103. package/dist/sync/multipart-uploader.test.js.map +1 -0
  104. package/dist/sync/mutation-client.d.ts +82 -0
  105. package/dist/sync/mutation-client.d.ts.map +1 -0
  106. package/dist/sync/mutation-client.js +221 -0
  107. package/dist/sync/mutation-client.js.map +1 -0
  108. package/dist/sync/mutation-client.test.d.ts +2 -0
  109. package/dist/sync/mutation-client.test.d.ts.map +1 -0
  110. package/dist/sync/mutation-client.test.js +51 -0
  111. package/dist/sync/mutation-client.test.js.map +1 -0
  112. package/dist/sync/push-receiver.d.ts +45 -0
  113. package/dist/sync/push-receiver.d.ts.map +1 -1
  114. package/dist/sync/push-receiver.js +101 -0
  115. package/dist/sync/push-receiver.js.map +1 -1
  116. package/dist/sync/push-receiver.test.js +54 -2
  117. package/dist/sync/push-receiver.test.js.map +1 -1
  118. package/dist/sync/scope-inventory-client.d.ts +69 -0
  119. package/dist/sync/scope-inventory-client.d.ts.map +1 -0
  120. package/dist/sync/scope-inventory-client.js +210 -0
  121. package/dist/sync/scope-inventory-client.js.map +1 -0
  122. package/dist/sync/scope-inventory-client.test.d.ts +2 -0
  123. package/dist/sync/scope-inventory-client.test.d.ts.map +1 -0
  124. package/dist/sync/scope-inventory-client.test.js +94 -0
  125. package/dist/sync/scope-inventory-client.test.js.map +1 -0
  126. package/dist/sync/snapshot-client.d.ts +98 -0
  127. package/dist/sync/snapshot-client.d.ts.map +1 -0
  128. package/dist/sync/snapshot-client.js +402 -0
  129. package/dist/sync/snapshot-client.js.map +1 -0
  130. package/dist/sync/snapshot-client.test.d.ts +2 -0
  131. package/dist/sync/snapshot-client.test.d.ts.map +1 -0
  132. package/dist/sync/snapshot-client.test.js +169 -0
  133. package/dist/sync/snapshot-client.test.js.map +1 -0
  134. package/dist/sync/uploader-finalization.d.ts +97 -0
  135. package/dist/sync/uploader-finalization.d.ts.map +1 -0
  136. package/dist/sync/uploader-finalization.js +273 -0
  137. package/dist/sync/uploader-finalization.js.map +1 -0
  138. package/dist/sync/uploader-finalization.test.d.ts +2 -0
  139. package/dist/sync/uploader-finalization.test.d.ts.map +1 -0
  140. package/dist/sync/uploader-finalization.test.js +92 -0
  141. package/dist/sync/uploader-finalization.test.js.map +1 -0
  142. package/dist/telemetry.d.ts +11 -1
  143. package/dist/telemetry.d.ts.map +1 -1
  144. package/dist/telemetry.js +21 -2
  145. package/dist/telemetry.js.map +1 -1
  146. package/dist/telemetry.test.js +80 -0
  147. package/dist/telemetry.test.js.map +1 -1
  148. package/package.json +6 -1
  149. package/.claude/policies/hq-cloud-esm-cannot-spy-fs-builtins.md +0 -30
  150. package/.claude/policies/hq-cloud-strip-types-no-parameter-properties.md +0 -22
  151. package/.github/workflows/ci.yml +0 -84
  152. package/.github/workflows/publish.yml +0 -56
  153. package/.github/workflows/unreleased-commits-nag.yml +0 -256
  154. package/eslint.config.js +0 -67
  155. package/pnpm-workspace.yaml +0 -2
  156. package/scripts/presign-transport-e2e.mjs +0 -250
  157. package/scripts/vault-rebaseline.sh +0 -323
  158. package/scripts/vault-rescue.sh +0 -332
  159. package/src/active-company.test.ts +0 -188
  160. package/src/active-company.ts +0 -168
  161. package/src/agent-codex-instructions.test.ts +0 -332
  162. package/src/agent-codex-instructions.ts +0 -309
  163. package/src/auth.ts +0 -146
  164. package/src/backup-prune.test.ts +0 -98
  165. package/src/backup-prune.ts +0 -182
  166. package/src/bin/backup-prune-runner.ts +0 -33
  167. package/src/bin/rescue-runner.ts +0 -25
  168. package/src/bin/sync-runner-company.ts +0 -695
  169. package/src/bin/sync-runner-events.test.ts +0 -143
  170. package/src/bin/sync-runner-events.ts +0 -55
  171. package/src/bin/sync-runner-planning.test.ts +0 -311
  172. package/src/bin/sync-runner-planning.ts +0 -258
  173. package/src/bin/sync-runner-rollup.test.ts +0 -37
  174. package/src/bin/sync-runner-rollup.ts +0 -97
  175. package/src/bin/sync-runner-telemetry.ts +0 -15
  176. package/src/bin/sync-runner-watch-loop.ts +0 -1235
  177. package/src/bin/sync-runner-watch-routes.test.ts +0 -71
  178. package/src/bin/sync-runner-watch-routes.ts +0 -184
  179. package/src/bin/sync-runner.test.ts +0 -8767
  180. package/src/bin/sync-runner.ts +0 -2190
  181. package/src/cli/accept.ts +0 -124
  182. package/src/cli/conflict.ts +0 -119
  183. package/src/cli/doctor.test.ts +0 -581
  184. package/src/cli/doctor.ts +0 -642
  185. package/src/cli/index.ts +0 -49
  186. package/src/cli/invite.test.ts +0 -250
  187. package/src/cli/invite.ts +0 -214
  188. package/src/cli/promote.ts +0 -157
  189. package/src/cli/reindex.test.ts +0 -957
  190. package/src/cli/reindex.ts +0 -970
  191. package/src/cli/rescue-classify-ordering.test.ts +0 -548
  192. package/src/cli/rescue-clone-diagnostics.test.ts +0 -120
  193. package/src/cli/rescue-core.ts +0 -3011
  194. package/src/cli/rescue-drift-reconcile.test.ts +0 -179
  195. package/src/cli/rescue-drop-dir-symlink.test.ts +0 -224
  196. package/src/cli/rescue-exec-bit-preserve.test.ts +0 -187
  197. package/src/cli/rescue-hq-root-guard.test.ts +0 -232
  198. package/src/cli/rescue-journal-reconcile.test.ts +0 -215
  199. package/src/cli/rescue-mtime-preserve.test.ts +0 -203
  200. package/src/cli/rescue-settings-reconcile.test.ts +0 -583
  201. package/src/cli/rescue-snapshot.test.ts +0 -57
  202. package/src/cli/rescue-snapshot.ts +0 -51
  203. package/src/cli/rescue.reindex.test.ts +0 -63
  204. package/src/cli/rescue.test.ts +0 -131
  205. package/src/cli/rescue.ts +0 -182
  206. package/src/cli/share.test.ts +0 -7843
  207. package/src/cli/share.ts +0 -3663
  208. package/src/cli/sync-scope.test.ts +0 -652
  209. package/src/cli/sync.test.ts +0 -5207
  210. package/src/cli/sync.ts +0 -3470
  211. package/src/cli/tombstones.ts +0 -106
  212. package/src/cli/watch-event-push-conflict.test.ts +0 -234
  213. package/src/client-info.test.ts +0 -214
  214. package/src/client-info.ts +0 -121
  215. package/src/cognito-auth.test.ts +0 -712
  216. package/src/cognito-auth.ts +0 -1422
  217. package/src/company-resolver.test.ts +0 -618
  218. package/src/company-resolver.ts +0 -521
  219. package/src/context.test.ts +0 -583
  220. package/src/context.ts +0 -378
  221. package/src/daemon-worker.ts +0 -26
  222. package/src/daemon.ts +0 -99
  223. package/src/entity-resolver.test.ts +0 -315
  224. package/src/entity-resolver.ts +0 -180
  225. package/src/ignore.test.ts +0 -466
  226. package/src/ignore.ts +0 -469
  227. package/src/index.ts +0 -439
  228. package/src/journal.test.ts +0 -968
  229. package/src/journal.ts +0 -765
  230. package/src/lib/cloud-authoritative.test.ts +0 -45
  231. package/src/lib/cloud-authoritative.ts +0 -59
  232. package/src/lib/conflict-file.ts +0 -86
  233. package/src/lib/conflict-index.ts +0 -289
  234. package/src/lib/conflict.test.ts +0 -348
  235. package/src/lib/describe-error.test.ts +0 -100
  236. package/src/lib/describe-error.ts +0 -58
  237. package/src/lib/exit-codes.ts +0 -24
  238. package/src/lib/machine-id.test.ts +0 -231
  239. package/src/lib/machine-id.ts +0 -175
  240. package/src/lib/net-errors.test.ts +0 -65
  241. package/src/lib/net-errors.ts +0 -86
  242. package/src/lib/readlink-safe.test.ts +0 -43
  243. package/src/lib/readlink-safe.ts +0 -29
  244. package/src/local-path-codec.test.ts +0 -138
  245. package/src/local-path-codec.ts +0 -161
  246. package/src/machine-auth.test.ts +0 -1323
  247. package/src/manifest-reconcile.test.ts +0 -1123
  248. package/src/manifest-reconcile.ts +0 -518
  249. package/src/object-io.test.ts +0 -1221
  250. package/src/object-io.ts +0 -1306
  251. package/src/operation-lock.test.ts +0 -484
  252. package/src/operation-lock.ts +0 -680
  253. package/src/outcome-telemetry.test.ts +0 -498
  254. package/src/outcome-telemetry.ts +0 -639
  255. package/src/personal-vault-exclusions.test.ts +0 -308
  256. package/src/personal-vault-exclusions.ts +0 -354
  257. package/src/personal-vault.test.ts +0 -756
  258. package/src/personal-vault.ts +0 -496
  259. package/src/prefix-coalesce.test.ts +0 -240
  260. package/src/prefix-coalesce.ts +0 -273
  261. package/src/public-surface.test.ts +0 -117
  262. package/src/qmd-reindex.test.ts +0 -877
  263. package/src/qmd-reindex.ts +0 -842
  264. package/src/read-only-state-dir.test.ts +0 -188
  265. package/src/remote-pull.test.ts +0 -1130
  266. package/src/remote-pull.ts +0 -618
  267. package/src/s3.symlink-materialize.test.ts +0 -492
  268. package/src/s3.test.ts +0 -1789
  269. package/src/s3.ts +0 -1532
  270. package/src/schemas/signal-types.test.ts +0 -82
  271. package/src/schemas/signal-types.ts +0 -38
  272. package/src/schemas/source-channels.test.ts +0 -82
  273. package/src/schemas/source-channels.ts +0 -53
  274. package/src/scope-shrink.test.ts +0 -633
  275. package/src/scope-shrink.ts +0 -481
  276. package/src/signals/get.test.ts +0 -310
  277. package/src/signals/get.ts +0 -75
  278. package/src/signals/internals.ts +0 -195
  279. package/src/signals/list.test.ts +0 -420
  280. package/src/signals/list.ts +0 -79
  281. package/src/signals/parse.ts +0 -8
  282. package/src/signals/types.ts +0 -91
  283. package/src/skill-telemetry.test.ts +0 -1825
  284. package/src/skill-telemetry.ts +0 -1439
  285. package/src/sources/get.test.ts +0 -293
  286. package/src/sources/get.ts +0 -66
  287. package/src/sources/internals.ts +0 -198
  288. package/src/sources/list.test.ts +0 -402
  289. package/src/sources/list.ts +0 -84
  290. package/src/sources/parse.ts +0 -43
  291. package/src/sources/types.ts +0 -84
  292. package/src/sync/event-sync.test.ts +0 -594
  293. package/src/sync/event-sync.ts +0 -545
  294. package/src/sync/feature-flags.test.ts +0 -378
  295. package/src/sync/feature-flags.ts +0 -62
  296. package/src/sync/index.ts +0 -76
  297. package/src/sync/lease-client.test.ts +0 -128
  298. package/src/sync/lease-client.ts +0 -207
  299. package/src/sync/logger.test.ts +0 -242
  300. package/src/sync/logger.ts +0 -79
  301. package/src/sync/metrics.test.ts +0 -462
  302. package/src/sync/metrics.ts +0 -213
  303. package/src/sync/pull-scope.ts +0 -265
  304. package/src/sync/push-event.test.ts +0 -266
  305. package/src/sync/push-event.ts +0 -224
  306. package/src/sync/push-receiver.test.ts +0 -566
  307. package/src/sync/push-receiver.ts +0 -1048
  308. package/src/sync/push-transport.ts +0 -231
  309. package/src/sync/realtime-rollout.test.ts +0 -86
  310. package/src/sync/realtime-rollout.ts +0 -262
  311. package/src/sync/state-store.test.ts +0 -194
  312. package/src/sync/state-store.ts +0 -727
  313. package/src/sync-core.ts +0 -58
  314. package/src/sync-progress.test.ts +0 -94
  315. package/src/sync-progress.ts +0 -140
  316. package/src/telemetry-events.test.ts +0 -88
  317. package/src/telemetry-events.ts +0 -205
  318. package/src/telemetry.test.ts +0 -1280
  319. package/src/telemetry.ts +0 -1109
  320. package/src/types.ts +0 -314
  321. package/src/vault-client.test.ts +0 -1380
  322. package/src/vault-client.ts +0 -1694
  323. package/src/version.ts +0 -24
  324. package/src/watch-roots.test.ts +0 -278
  325. package/src/watch-roots.ts +0 -162
  326. package/src/watcher-event-gate.test.ts +0 -212
  327. package/src/watcher.test.ts +0 -1079
  328. package/src/watcher.ts +0 -1741
  329. package/test/e2e/sync/cross-tenant-isolation.test.ts +0 -630
  330. package/test/e2e/sync/skill-telemetry-oversized-transcript.test.ts +0 -124
  331. package/test/e2e/sync/transient-company-leg.test.ts +0 -384
  332. package/test/e2e/sync/windows-unreadable-link-leg.test.ts +0 -191
  333. package/test/e2e/watcher-real-chokidar.test.ts +0 -165
  334. package/test/e2e/watcher-recursive-backend.test.ts +0 -181
  335. package/test/e2e/watcher-scoped-coverage.test.ts +0 -381
  336. package/test/invite-flow.integration.test.ts +0 -244
  337. package/test/joiner-manifest-reconcile.integration.test.ts +0 -322
  338. package/test/share-sync.integration.test.ts +0 -213
  339. package/tsconfig.json +0 -19
  340. package/vitest.config.ts +0 -22
@@ -1,1280 +0,0 @@
1
- /**
2
- * Tests for the usage telemetry collector. Mirrors the Rust test matrix at
3
- * `hq-workspace/apps/hq-sync/src-tauri/src/commands/telemetry.rs::tests` so a
4
- * behavioral regression in either implementation surfaces in both suites.
5
- *
6
- * The vault client is stubbed structurally rather than via fetch-mock so the
7
- * tests stay deterministic without spinning up wiremock — the production
8
- * boundary is `TelemetryClientSurface`, not the HTTP layer.
9
- */
10
-
11
- import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
12
- import * as fs from "fs";
13
- import { promises as fsp } from "fs";
14
- import * as os from "os";
15
- import * as path from "path";
16
- import {
17
- collectAndSendTelemetry,
18
- sanitizeRow,
19
- extractServices,
20
- type CollectTelemetryOptions,
21
- type TelemetryClientSurface,
22
- } from "./telemetry.js";
23
- import type {
24
- TelemetryOptInResponse,
25
- UsageBatch,
26
- UsageIngestResult,
27
- } from "./vault-client.js";
28
-
29
- // ── Test stubs ────────────────────────────────────────────────────────────────
30
-
31
- interface StubClient extends TelemetryClientSurface {
32
- /** Every UsageBatch handed to `postUsage`, in arrival order. */
33
- posts: UsageBatch[];
34
- /** Number of times `getTelemetryOptIn` was called. */
35
- optInCalls: number;
36
- /** Every value handed to `setTelemetryOptIn`, in arrival order. */
37
- optInSets: boolean[];
38
- /** The options object passed alongside each `setTelemetryOptIn` call. */
39
- optInSetOpts: Array<{ onlyIfUnset?: boolean } | undefined>;
40
- }
41
-
42
- function makeClient(opts: {
43
- optInResponse?: TelemetryOptInResponse | Error;
44
- postResponse?: UsageIngestResult | Error;
45
- /** When set, `setTelemetryOptIn` rejects with this error. */
46
- setOptInError?: Error;
47
- /** `applied` value the conditional write reports back (default true). */
48
- setOptInApplied?: boolean;
49
- } = {}): StubClient {
50
- const optInResponse = opts.optInResponse ?? { enabled: true, updatedAt: null };
51
- const postResponse = opts.postResponse ?? { ok: true, written: 0, skipped: [] };
52
-
53
- const posts: UsageBatch[] = [];
54
- const optInSets: boolean[] = [];
55
- const optInSetOpts: Array<{ onlyIfUnset?: boolean } | undefined> = [];
56
- const stub: StubClient = {
57
- posts,
58
- optInCalls: 0,
59
- optInSets,
60
- optInSetOpts,
61
- async getTelemetryOptIn() {
62
- this.optInCalls++;
63
- if (optInResponse instanceof Error) throw optInResponse;
64
- return optInResponse;
65
- },
66
- async setTelemetryOptIn(enabled: boolean, setOpts?: { onlyIfUnset?: boolean }) {
67
- optInSets.push(enabled);
68
- optInSetOpts.push(setOpts);
69
- if (opts.setOptInError) throw opts.setOptInError;
70
- return { applied: opts.setOptInApplied ?? true };
71
- },
72
- async postUsage(batch: UsageBatch) {
73
- posts.push(batch);
74
- if (postResponse instanceof Error) throw postResponse;
75
- return postResponse;
76
- },
77
- };
78
- return stub;
79
- }
80
-
81
- interface TestEnv {
82
- root: string;
83
- claudeProjects: string;
84
- codexRoot: string;
85
- cursorPath: string;
86
- menubarPath: string;
87
- }
88
-
89
- function setupEnv(): TestEnv {
90
- const root = fs.mkdtempSync(path.join(os.tmpdir(), "hq-telemetry-test-"));
91
- const claudeProjects = path.join(root, ".claude", "projects");
92
- const codexRoot = path.join(root, ".codex");
93
- fs.mkdirSync(claudeProjects, { recursive: true });
94
- fs.mkdirSync(path.join(codexRoot, "sessions"), { recursive: true });
95
- fs.mkdirSync(path.join(codexRoot, "archived_sessions"), { recursive: true });
96
- fs.mkdirSync(path.join(root, ".hq"), { recursive: true });
97
- return {
98
- root,
99
- claudeProjects,
100
- codexRoot,
101
- cursorPath: path.join(root, ".hq", "telemetry-cursor.json"),
102
- menubarPath: path.join(root, ".hq", "menubar.json"),
103
- };
104
- }
105
-
106
- function teardownEnv(env: TestEnv): void {
107
- fs.rmSync(env.root, { recursive: true, force: true });
108
- }
109
-
110
- function writeJsonl(env: TestEnv, sub: string, name: string, lines: string[]): string {
111
- const dir = path.join(env.claudeProjects, sub);
112
- fs.mkdirSync(dir, { recursive: true });
113
- const p = path.join(dir, name);
114
- fs.writeFileSync(p, lines.map((l) => `${l}\n`).join(""));
115
- return p;
116
- }
117
-
118
- function readCursor(env: TestEnv): { version: string; files: Record<string, { offset: number; mtime: number }> } {
119
- return JSON.parse(fs.readFileSync(env.cursorPath, "utf-8"));
120
- }
121
-
122
- function makeOpts(env: TestEnv, client: TelemetryClientSurface): CollectTelemetryOptions {
123
- return {
124
- client,
125
- machineId: "test-machine",
126
- installerVersion: "test-version",
127
- claudeProjectsRoot: env.claudeProjects,
128
- codexRoot: env.codexRoot,
129
- maxScanBytesPerSource: Number.MAX_SAFE_INTEGER,
130
- maxBatchesPerRun: Number.MAX_SAFE_INTEGER,
131
- cursorPath: env.cursorPath,
132
- menubarPath: env.menubarPath,
133
- };
134
- }
135
-
136
- // Representative Claude Code session rows. Mirror the Rust fixtures exactly so
137
- // drift between implementations is detectable.
138
- const USER_ROW = JSON.stringify({
139
- type: "user",
140
- timestamp: "2026-04-25T10:00:00Z",
141
- sessionId: "s1",
142
- uuid: "u1",
143
- parentUuid: null,
144
- userType: "human",
145
- entrypoint: "cli",
146
- cwd: "/Users/x/proj",
147
- gitBranch: "main",
148
- version: "1.0",
149
- message: { role: "user", content: [{ type: "text", text: "hello world" }], id: "msg_1" },
150
- });
151
-
152
- const ASST_ROW = JSON.stringify({
153
- type: "assistant",
154
- timestamp: "2026-04-25T10:00:01Z",
155
- sessionId: "s1",
156
- uuid: "u2",
157
- parentUuid: "u1",
158
- message: {
159
- role: "assistant",
160
- model: "claude-opus",
161
- content: [{ type: "text", text: "hi" }, { type: "thinking", thinking: "hmm" }],
162
- stop_sequence: "</end>",
163
- usage: { input_tokens: 42, output_tokens: 7, cache_read_input_tokens: 100 },
164
- id: "msg_2",
165
- },
166
- toolUseIds: ["t1"],
167
- toolResults: [{ id: "t1", output: "x" }],
168
- requestId: "req_1",
169
- });
170
-
171
- // ── sanitizeRow ───────────────────────────────────────────────────────────────
172
-
173
- describe("sanitizeRow", () => {
174
- it("returns null for non-objects", () => {
175
- expect(sanitizeRow(null)).toBeNull();
176
- expect(sanitizeRow("string")).toBeNull();
177
- expect(sanitizeRow(42)).toBeNull();
178
- expect(sanitizeRow([])).toBeNull();
179
- });
180
-
181
- it("keeps only top-level allowlist fields", () => {
182
- const row = JSON.parse(USER_ROW);
183
- const out = sanitizeRow(row);
184
- expect(out).not.toBeNull();
185
- const keys = new Set(Object.keys(out!));
186
- // KEEP: sessionId, timestamp, uuid, cwd, gitBranch, userType
187
- for (const expected of ["sessionId", "timestamp", "uuid", "cwd", "gitBranch", "userType"]) {
188
- expect(keys.has(expected)).toBe(true);
189
- }
190
- // Sensitive / unknown fields must be absent:
191
- for (const removed of ["type", "parentUuid", "entrypoint", "version", "message", "content", "thinking", "text", "toolUseIds", "toolResults"]) {
192
- expect(keys.has(removed)).toBe(false);
193
- }
194
- });
195
-
196
- it("promotes message.model and flattens message.usage to camelCase", () => {
197
- const row = JSON.parse(ASST_ROW);
198
- const out = sanitizeRow(row);
199
- expect(out).not.toBeNull();
200
- expect(out!.model).toBe("claude-opus");
201
- expect(out!.inputTokens).toBe(42);
202
- expect(out!.outputTokens).toBe(7);
203
- expect(out!.cacheReadInputTokens).toBe(100);
204
- // cacheCreationInputTokens not present in fixture; must be absent (not 0/null).
205
- expect("cacheCreationInputTokens" in out!).toBe(false);
206
- // `message` must not survive — its prompt/thinking/tools are exactly what
207
- // we're trying to keep off the wire.
208
- expect("message" in out!).toBe(false);
209
- });
210
-
211
- it("rejects every field outside the server KEEP allowlist", () => {
212
- const out = sanitizeRow(JSON.parse(ASST_ROW))!;
213
- const allowed = new Set([
214
- "sessionId", "timestamp", "uuid", "cwd", "gitBranch", "userType",
215
- "model", "inputTokens", "outputTokens",
216
- "cacheCreationInputTokens", "cacheReadInputTokens",
217
- "companyUid",
218
- ]);
219
- for (const key of Object.keys(out)) {
220
- expect(allowed.has(key), `field "${key}" must be in server allowlist`).toBe(true);
221
- }
222
- });
223
-
224
- it("(US-002) stamps companyUid when provided, omits it when not", () => {
225
- const withUid = sanitizeRow(JSON.parse(USER_ROW), "cmp_01INDIGO")!;
226
- expect(withUid.companyUid).toBe("cmp_01INDIGO");
227
-
228
- const withoutUid = sanitizeRow(JSON.parse(USER_ROW))!;
229
- expect("companyUid" in withoutUid).toBe(false);
230
- });
231
- });
232
-
233
- // ── extractServices + sanitizeRow services emission (US-007) ─────────────────
234
-
235
- // An assistant row that invoked the Slack + Figma MCP servers. The tool_use
236
- // block `input` deliberately carries a URL + secret so the redaction assertions
237
- // have something dangerous to prove is dropped.
238
- const MCP_ROW = JSON.stringify({
239
- type: "assistant",
240
- timestamp: "2026-04-25T10:00:02Z",
241
- sessionId: "s1",
242
- uuid: "u3",
243
- message: {
244
- role: "assistant",
245
- model: "claude-opus",
246
- usage: { input_tokens: 10, output_tokens: 5 },
247
- content: [
248
- { type: "text", text: "calling tools" },
249
- {
250
- type: "tool_use",
251
- id: "t1",
252
- name: "mcp__slack__slack_send_message",
253
- input: { channel: "#secret-ops", token: "xoxb-SECRET-TOKEN", text: "hi" },
254
- },
255
- {
256
- type: "tool_use",
257
- id: "t2",
258
- name: "mcp__slack__slack_read_channel",
259
- input: { url: "https://hooks.slack.com/leak", channel: "C123" },
260
- },
261
- {
262
- type: "tool_use",
263
- id: "t3",
264
- name: "mcp__figma__get_screenshot",
265
- input: { fileKey: "https://figma.com/file/PRIVATE" },
266
- },
267
- // A non-MCP builtin tool must NOT count as a service.
268
- { type: "tool_use", id: "t4", name: "Bash", input: { command: "rm -rf /" } },
269
- ],
270
- id: "msg_3",
271
- },
272
- });
273
-
274
- describe("extractServices (US-007)", () => {
275
- it("counts MCP servers by name from tool_use block names", () => {
276
- const services = extractServices(JSON.parse(MCP_ROW).message);
277
- // Slack invoked twice, Figma once; Bash (builtin) excluded.
278
- expect(services).toEqual({ slack: 2, figma: 1 });
279
- });
280
-
281
- it("returns undefined when the row touched no MCP server", () => {
282
- expect(extractServices(JSON.parse(ASST_ROW).message)).toBeUndefined();
283
- expect(extractServices(JSON.parse(USER_ROW).message)).toBeUndefined();
284
- expect(extractServices(undefined)).toBeUndefined();
285
- expect(extractServices({ content: "not an array" })).toBeUndefined();
286
- });
287
-
288
- it("preserves multi-underscore server names (mcp__claude_ai_Slack__…)", () => {
289
- const msg = {
290
- content: [
291
- { type: "tool_use", id: "a", name: "mcp__claude_ai_Slack__slack_send_message", input: {} },
292
- { type: "tool_use", id: "b", name: "mcp__claude_ai_Figma__get_screenshot", input: {} },
293
- ],
294
- };
295
- // The server segment is everything between the first and the LAST `__`.
296
- expect(extractServices(msg)).toEqual({
297
- claude_ai_Slack: 1,
298
- claude_ai_Figma: 1,
299
- });
300
- });
301
-
302
- it("preserves a double-underscore in the server name (mcp__foo__bar__run)", () => {
303
- const msg = {
304
- content: [
305
- { type: "tool_use", id: "a", name: "mcp__foo__bar__run", input: {} },
306
- ],
307
- };
308
- // Delimiter is the LAST `__`, so server = `foo__bar`, tool = `run`.
309
- expect(extractServices(msg)).toEqual({ "foo__bar": 1 });
310
- });
311
-
312
- it("counts servers whose names collide with Object.prototype members", () => {
313
- const msg = {
314
- content: [
315
- { type: "tool_use", id: "a", name: "mcp__constructor__x", input: {} },
316
- { type: "tool_use", id: "b", name: "mcp__constructor__y", input: {} },
317
- { type: "tool_use", id: "c", name: "mcp__toString__z", input: {} },
318
- ],
319
- };
320
- // A plain-object counter would read these off the prototype and produce a
321
- // non-numeric count; the null-prototype map keeps them honest integers.
322
- const out = extractServices(msg)!;
323
- expect(out).toEqual({ constructor: 2, toString: 1 });
324
- expect(typeof out.constructor).toBe("number");
325
- });
326
-
327
- // SECURITY-CRITICAL: names + counts ONLY. No args / URLs / payloads / secrets.
328
- it("emits NAMES + COUNTS only — no args, URLs, payloads, or secrets", () => {
329
- const out = sanitizeRow(JSON.parse(MCP_ROW))!;
330
- expect(out.services).toEqual({ slack: 2, figma: 1 });
331
-
332
- // The full serialized wire row must contain NONE of the dangerous input data.
333
- const serialized = JSON.stringify(out);
334
- expect(serialized).not.toContain("xoxb-SECRET-TOKEN");
335
- expect(serialized).not.toContain("hooks.slack.com");
336
- expect(serialized).not.toContain("figma.com/file/PRIVATE");
337
- expect(serialized).not.toContain("#secret-ops");
338
- expect(serialized).not.toContain("rm -rf");
339
- // No tool names or input keys leaked — only the server names + counts.
340
- expect(serialized).not.toContain("slack_send_message");
341
- expect(serialized).not.toContain("get_screenshot");
342
- expect(serialized).not.toContain("channel");
343
- expect(serialized).not.toContain("token");
344
- expect(serialized).not.toContain("url");
345
-
346
- // The services VALUE is a map of string → number (counts) — never objects
347
- // or strings that could smuggle structured data.
348
- for (const [name, count] of Object.entries(out.services as Record<string, unknown>)) {
349
- expect(typeof name).toBe("string");
350
- expect(typeof count).toBe("number");
351
- }
352
- });
353
-
354
- it("omits services entirely for a row with no MCP calls (backward-compatible)", () => {
355
- const out = sanitizeRow(JSON.parse(ASST_ROW))!;
356
- expect("services" in out).toBe(false);
357
- });
358
- });
359
-
360
- // ── collectAndSendTelemetry ───────────────────────────────────────────────────
361
-
362
- describe("collectAndSendTelemetry", () => {
363
- let env: TestEnv;
364
- beforeEach(() => { env = setupEnv(); });
365
- afterEach(() => { teardownEnv(env); });
366
-
367
- it("(a) opt-in=false → sends nothing and does not write cursor", async () => {
368
- const client = makeClient({ optInResponse: { enabled: false, updatedAt: null } });
369
- writeJsonl(env, "proj", "s.jsonl", [USER_ROW, ASST_ROW]);
370
-
371
- const result = await collectAndSendTelemetry(makeOpts(env, client));
372
-
373
- expect(result.enabled).toBe(false);
374
- expect(result.optInSource).toBe("server");
375
- expect(client.posts).toHaveLength(0);
376
- expect(fs.existsSync(env.cursorPath)).toBe(false);
377
- });
378
-
379
- it("(b) missing cursor → reads all rows from offset 0, advances to EOF", async () => {
380
- const client = makeClient();
381
- const jsonlPath = writeJsonl(env, "proj", "s.jsonl", [USER_ROW, ASST_ROW]);
382
- const fileSize = fs.statSync(jsonlPath).size;
383
-
384
- const result = await collectAndSendTelemetry(makeOpts(env, client));
385
-
386
- expect(result.enabled).toBe(true);
387
- expect(result.eventsSent).toBe(2);
388
- expect(client.posts).toHaveLength(1);
389
- expect(client.posts[0].events).toHaveLength(2);
390
- expect(client.posts[0].machineId).toBe("test-machine");
391
- expect(client.posts[0].installerVersion).toBe("test-version");
392
-
393
- const cursor = readCursor(env);
394
- expect(cursor.files[jsonlPath].offset).toBe(fileSize);
395
- });
396
-
397
- it("(c) sanitizer strips REMOVE fields — only allowlisted fields reach wire", async () => {
398
- const client = makeClient();
399
- writeJsonl(env, "proj", "full.jsonl", [USER_ROW, ASST_ROW]);
400
-
401
- await collectAndSendTelemetry(makeOpts(env, client));
402
- expect(client.posts).toHaveLength(1);
403
-
404
- const allowed = new Set([
405
- "sessionId", "timestamp", "uuid", "cwd", "gitBranch", "userType",
406
- "model", "inputTokens", "outputTokens",
407
- "cacheCreationInputTokens", "cacheReadInputTokens",
408
- ]);
409
- for (const ev of client.posts[0].events) {
410
- for (const key of Object.keys(ev)) {
411
- expect(allowed.has(key), `field "${key}" must be in allowlist`).toBe(true);
412
- }
413
- expect("message" in ev).toBe(false);
414
- for (const banned of ["content", "thinking", "text", "toolUseIds", "toolResults"]) {
415
- expect(banned in ev).toBe(false);
416
- }
417
- }
418
- });
419
-
420
- it("(d) 1 MiB cap forces ≥2 batches when rows are large", async () => {
421
- const client = makeClient();
422
- // ~25 KiB per row × 50 rows ≈ 1.25 MiB → ≥2 batches.
423
- const longBranch = "x".repeat(25_000);
424
- const lines: string[] = [];
425
- for (let i = 0; i < 50; i++) {
426
- lines.push(JSON.stringify({
427
- type: "user",
428
- timestamp: `2026-04-25T10:00:${String(i % 60).padStart(2, "0")}Z`,
429
- sessionId: "s1",
430
- uuid: `u${i}`,
431
- cwd: "/Users/x",
432
- gitBranch: longBranch,
433
- userType: "human",
434
- message: { role: "user", content: [{ type: "text", text: "hi" }], id: "m" },
435
- }));
436
- }
437
- writeJsonl(env, "proj", "large.jsonl", lines);
438
-
439
- const result = await collectAndSendTelemetry(makeOpts(env, client));
440
-
441
- expect(result.batchesSent).toBeGreaterThanOrEqual(2);
442
- expect(result.eventsSent).toBe(50);
443
-
444
- // Final batch must be < 1 MiB on the wire.
445
- const lastWire = Buffer.byteLength(JSON.stringify(client.posts.at(-1)), "utf-8");
446
- expect(lastWire).toBeLessThan(1_000_000);
447
- });
448
-
449
- it("F19: caps usage telemetry batches at 100 events", async () => {
450
- const client = makeClient();
451
- const lines = Array.from({ length: 101 }, (_, i) => JSON.stringify({
452
- type: "user",
453
- timestamp: `2026-04-25T10:${String(Math.floor(i / 60)).padStart(2, "0")}:${String(i % 60).padStart(2, "0")}Z`,
454
- sessionId: "s-f19-row-cap",
455
- uuid: `u-f19-row-${i}`,
456
- cwd: "/Users/x",
457
- gitBranch: "main",
458
- userType: "human",
459
- message: { role: "user", content: [{ type: "text", text: "hi" }], id: `m${i}` },
460
- }));
461
- writeJsonl(env, "proj", "f19-row-cap.jsonl", lines);
462
-
463
- const result = await collectAndSendTelemetry(makeOpts(env, client));
464
-
465
- expect(result.eventsSent).toBe(101);
466
- expect(result.batchesSent).toBe(2);
467
- expect(client.posts.map((post) => post.events.length)).toEqual([100, 1]);
468
- for (const post of client.posts) {
469
- expect(post.events.length).toBeLessThanOrEqual(100);
470
- }
471
- });
472
-
473
- it("F19: caps usage telemetry POST bodies at 240 KiB", async () => {
474
- const client = makeClient();
475
- const branch = "x".repeat(9_000);
476
- const lines = Array.from({ length: 30 }, (_, i) => JSON.stringify({
477
- type: "user",
478
- timestamp: `2026-04-25T11:${String(Math.floor(i / 60)).padStart(2, "0")}:${String(i % 60).padStart(2, "0")}Z`,
479
- sessionId: "s-f19-byte-cap",
480
- uuid: `u-f19-byte-${i}`,
481
- cwd: "/Users/x",
482
- gitBranch: branch,
483
- userType: "human",
484
- message: { role: "user", content: [{ type: "text", text: "hi" }], id: `m${i}` },
485
- }));
486
- writeJsonl(env, "proj", "f19-byte-cap.jsonl", lines);
487
-
488
- const result = await collectAndSendTelemetry(makeOpts(env, client));
489
- const wireSizes = client.posts.map((post) => Buffer.byteLength(JSON.stringify(post), "utf-8"));
490
-
491
- expect(result.eventsSent).toBe(30);
492
- expect(result.batchesSent).toBeGreaterThan(1);
493
- for (const wireSize of wireSizes) {
494
- expect(wireSize).toBeLessThanOrEqual(240 * 1024);
495
- }
496
- });
497
-
498
- it("R-F19: bounds a single oversized sanitized usage row before POST", async () => {
499
- const client = makeClient();
500
- const logs: string[] = [];
501
- const hugeBranch = "x".repeat(400_000);
502
- writeJsonl(env, "proj", "r-f19-singleton.jsonl", [
503
- JSON.stringify({
504
- type: "user",
505
- timestamp: "2026-06-19T10:00:00.000Z",
506
- sessionId: "s-r-f19-singleton",
507
- uuid: "u-r-f19-singleton",
508
- cwd: "/Users/x",
509
- gitBranch: hugeBranch,
510
- userType: "human",
511
- message: {
512
- role: "user",
513
- content: [{ type: "text", text: "hi" }],
514
- id: "m-r-f19-singleton",
515
- },
516
- }),
517
- ]);
518
-
519
- const result = await collectAndSendTelemetry({
520
- ...makeOpts(env, client),
521
- log: (msg) => logs.push(msg),
522
- });
523
-
524
- expect(result.eventsSent).toBe(1);
525
- expect(client.posts).toHaveLength(1);
526
- const wireSize = Buffer.byteLength(JSON.stringify(client.posts[0]), "utf-8");
527
- expect(wireSize).toBeLessThanOrEqual(240 * 1024);
528
- expect(client.posts[0].events[0].gitBranch).not.toBe(hugeBranch);
529
- expect(logs.some((line) => line.includes("oversized row truncated"))).toBe(
530
- true,
531
- );
532
- });
533
-
534
- it("(e) POST 500 → cursor NOT advanced", async () => {
535
- const client = makeClient({ postResponse: new Error("server 500") });
536
- writeJsonl(env, "proj", "s.jsonl", [USER_ROW, ASST_ROW, USER_ROW]);
537
-
538
- const result = await collectAndSendTelemetry(makeOpts(env, client));
539
-
540
- expect(result.eventsSent).toBe(0);
541
- expect(result.batchesSent).toBe(0);
542
- expect(client.posts).toHaveLength(1); // we still tried
543
-
544
- // Cursor file is written (with rotation/empty resets), but the file's
545
- // entry must NOT carry a non-zero offset.
546
- if (fs.existsSync(env.cursorPath)) {
547
- const cursor = readCursor(env);
548
- const allOffsets = Object.values(cursor.files).map((e) => e.offset);
549
- expect(allOffsets.every((off) => off === 0)).toBe(true);
550
- }
551
- });
552
-
553
- it("(f) atomic cursor write — no .tmp leftover", async () => {
554
- const client = makeClient();
555
- writeJsonl(env, "proj", "s.jsonl", [USER_ROW]);
556
-
557
- await collectAndSendTelemetry(makeOpts(env, client));
558
-
559
- expect(fs.existsSync(env.cursorPath)).toBe(true);
560
- expect(fs.existsSync(`${env.cursorPath}.tmp`)).toBe(false);
561
- });
562
-
563
- it("(g) new file between runs starts at offset 0", async () => {
564
- const client = makeClient();
565
- writeJsonl(env, "proj-a", "a.jsonl", [USER_ROW]);
566
-
567
- await collectAndSendTelemetry(makeOpts(env, client));
568
- const postsAfterRun1 = client.posts.length;
569
- expect(postsAfterRun1).toBeGreaterThanOrEqual(1);
570
-
571
- // Add a new fixture between runs.
572
- const pathB = writeJsonl(env, "proj-b", "b.jsonl", [ASST_ROW]);
573
- await collectAndSendTelemetry(makeOpts(env, client));
574
-
575
- const cursor = readCursor(env);
576
- const sizeB = fs.statSync(pathB).size;
577
- expect(cursor.files[pathB].offset).toBe(sizeB);
578
- });
579
-
580
- it("(h) truncated/rotated file resets cursor to 0", async () => {
581
- const client = makeClient();
582
- const pathA = writeJsonl(env, "proj", "a.jsonl", [USER_ROW, ASST_ROW, USER_ROW]);
583
- const originalSize = fs.statSync(pathA).size;
584
-
585
- await collectAndSendTelemetry(makeOpts(env, client));
586
- let cursor = readCursor(env);
587
- expect(cursor.files[pathA].offset).toBe(originalSize);
588
-
589
- // Truncate to 0 → next run must detect rotation and reset.
590
- fs.truncateSync(pathA, 0);
591
-
592
- await collectAndSendTelemetry(makeOpts(env, client));
593
-
594
- cursor = readCursor(env);
595
- expect(cursor.files[pathA].offset).toBe(0);
596
- });
597
-
598
- it("(i) opt-in GET fails → falls back to menubar.json (telemetryEnabled=true → runs)", async () => {
599
- const client = makeClient({ optInResponse: new Error("server 500") });
600
- fs.writeFileSync(env.menubarPath, JSON.stringify({ telemetryEnabled: true }));
601
- writeJsonl(env, "proj", "s.jsonl", [USER_ROW]);
602
-
603
- const result = await collectAndSendTelemetry(makeOpts(env, client));
604
-
605
- expect(result.enabled).toBe(true);
606
- expect(result.optInSource).toBe("menubar-fallback");
607
- expect(client.posts).toHaveLength(1);
608
- });
609
-
610
- it("(i') opt-in GET fails AND menubar.json says false → skips", async () => {
611
- const client = makeClient({ optInResponse: new Error("server 500") });
612
- fs.writeFileSync(env.menubarPath, JSON.stringify({ telemetryEnabled: false }));
613
- writeJsonl(env, "proj", "s.jsonl", [USER_ROW]);
614
-
615
- const result = await collectAndSendTelemetry(makeOpts(env, client));
616
-
617
- expect(result.enabled).toBe(false);
618
- expect(result.optInSource).toBe("menubar-fallback");
619
- expect(client.posts).toHaveLength(0);
620
- });
621
-
622
- it("(j) missing claude/projects directory → no crash, no posts", async () => {
623
- fs.rmSync(env.claudeProjects, { recursive: true });
624
- const client = makeClient();
625
-
626
- const result = await collectAndSendTelemetry(makeOpts(env, client));
627
-
628
- expect(result.enabled).toBe(true);
629
- expect(result.filesScanned).toBe(0);
630
- expect(client.posts).toHaveLength(0);
631
- });
632
-
633
- it("(k) second run with no new content sends nothing", async () => {
634
- const client = makeClient();
635
- writeJsonl(env, "proj", "s.jsonl", [USER_ROW, ASST_ROW]);
636
-
637
- await collectAndSendTelemetry(makeOpts(env, client));
638
- expect(client.posts).toHaveLength(1);
639
-
640
- await collectAndSendTelemetry(makeOpts(env, client));
641
- expect(client.posts).toHaveLength(1); // no second POST
642
- });
643
- });
644
-
645
- // ── Codex rollout collection ────────────────────────────────────────────────
646
-
647
- function codexLine(value: Record<string, unknown>): string {
648
- return JSON.stringify(value);
649
- }
650
-
651
- function writeCodexRollout(
652
- env: TestEnv,
653
- location: "sessions" | "archived_sessions",
654
- name: string,
655
- lines: Array<Record<string, unknown>>,
656
- ): string {
657
- const dir =
658
- location === "sessions"
659
- ? path.join(env.codexRoot, location, "2026", "07", "30")
660
- : path.join(env.codexRoot, location);
661
- fs.mkdirSync(dir, { recursive: true });
662
- const file = path.join(dir, name);
663
- fs.writeFileSync(file, lines.map(codexLine).join("\n") + "\n", "utf-8");
664
- return file;
665
- }
666
-
667
- function codexToken(
668
- timestamp: string,
669
- uuid: string,
670
- input: number,
671
- output: number,
672
- reasoning = 0,
673
- cached = 0,
674
- ): Record<string, unknown> {
675
- return {
676
- timestamp,
677
- uuid,
678
- type: "event_msg",
679
- payload: {
680
- type: "token_count",
681
- info: {
682
- last_token_usage: {
683
- input_tokens: input,
684
- output_tokens: output,
685
- reasoning_output_tokens: reasoning,
686
- cached_input_tokens: cached,
687
- },
688
- total_token_usage: {
689
- input_tokens: 999_999,
690
- output_tokens: 999_999,
691
- },
692
- },
693
- raw_content: "must never leave the machine",
694
- },
695
- };
696
- }
697
-
698
- describe("collectAndSendTelemetry — Codex rollouts", () => {
699
- let env: TestEnv;
700
- beforeEach(() => {
701
- env = setupEnv();
702
- });
703
- afterEach(() => teardownEnv(env));
704
-
705
- it("collects token deltas from live and archived Linux rollouts", async () => {
706
- writeCodexRollout(env, "sessions", "rollout-live.jsonl", [
707
- {
708
- timestamp: "2026-07-30T10:00:00Z",
709
- type: "session_meta",
710
- payload: {
711
- id: "codex-live",
712
- cwd: "/home/yousuf/hq/repos/private/hq-cloud",
713
- git: { branch: "feature/live" },
714
- model: "session-model",
715
- instructions: "private prompt",
716
- },
717
- },
718
- {
719
- timestamp: "2026-07-30T10:00:01Z",
720
- type: "turn_context",
721
- payload: { model: "codex-auto-review" },
722
- },
723
- codexToken("2026-07-30T10:00:02Z", "codex-event-live", 11, 7, 5, 3),
724
- ]);
725
- writeCodexRollout(env, "archived_sessions", "rollout-archived.jsonl", [
726
- {
727
- timestamp: "2026-07-29T10:00:00Z",
728
- type: "session_meta",
729
- payload: { id: "codex-archived", cwd: "/repo", model: "gpt-5-codex" },
730
- },
731
- codexToken("2026-07-29T10:00:01Z", "codex-event-archived", 2, 3, 1, 1),
732
- ]);
733
-
734
- const client = makeClient();
735
- const result = await collectAndSendTelemetry(makeOpts(env, client));
736
- const events = client.posts.flatMap((post) => post.events);
737
-
738
- expect(result.filesScanned).toBe(2);
739
- expect(result.eventsSent).toBe(2);
740
- expect(events).toEqual(
741
- expect.arrayContaining([
742
- {
743
- sessionId: "codex-live",
744
- timestamp: "2026-07-30T10:00:02Z",
745
- uuid: "codex-event-live",
746
- cwd: "/home/yousuf/hq/repos/private/hq-cloud",
747
- gitBranch: "feature/live",
748
- model: "codex-auto-review",
749
- inputTokens: 11,
750
- outputTokens: 12,
751
- cacheReadInputTokens: 3,
752
- },
753
- expect.objectContaining({
754
- sessionId: "codex-archived",
755
- model: "gpt-5-codex",
756
- inputTokens: 2,
757
- outputTokens: 4,
758
- cacheReadInputTokens: 1,
759
- }),
760
- ]),
761
- );
762
- expect(JSON.stringify(events)).not.toContain("private prompt");
763
- expect(JSON.stringify(events)).not.toContain("raw_content");
764
- expect(JSON.stringify(events)).not.toContain("999999");
765
-
766
- await collectAndSendTelemetry(makeOpts(env, client));
767
- expect(client.posts.flatMap((post) => post.events)).toHaveLength(2);
768
- });
769
-
770
- it("persists model context for incremental rollouts and generates stable IDs", async () => {
771
- const file = writeCodexRollout(env, "sessions", "rollout-incremental.jsonl", [
772
- {
773
- type: "session_meta",
774
- payload: { id: "incremental", cwd: "/repo", model: "session-model" },
775
- },
776
- { type: "turn_context", payload: { model: "model-a" } },
777
- codexToken("2026-07-30T13:00:00Z", "first-event", 1, 2),
778
- ]);
779
- fs.writeFileSync(
780
- env.cursorPath,
781
- JSON.stringify({ version: "1", files: {}, codex_next_rollout: file }),
782
- );
783
- const client = makeClient();
784
-
785
- await collectAndSendTelemetry(makeOpts(env, client));
786
- fs.appendFileSync(
787
- file,
788
- [
789
- codexLine({ type: "turn_context", payload: { model: "model-b" } }),
790
- codexLine({
791
- ...codexToken("2026-07-30T13:01:00Z", "temporary", 3, 4),
792
- uuid: undefined,
793
- }),
794
- ].join("\n") + "\n",
795
- );
796
- await collectAndSendTelemetry(makeOpts(env, client));
797
-
798
- const events = client.posts.flatMap((post) => post.events);
799
- expect(events).toHaveLength(2);
800
- expect(events[1]).toMatchObject({
801
- sessionId: "incremental",
802
- cwd: "/repo",
803
- model: "model-b",
804
- inputTokens: 3,
805
- outputTokens: 4,
806
- });
807
- expect(events[1].uuid).toMatch(/^codex-[a-f0-9]{64}$/);
808
- const cursor = JSON.parse(fs.readFileSync(env.cursorPath, "utf-8"));
809
- expect(cursor.files[file].context).toMatchObject({
810
- session_id: "incremental",
811
- cwd: "/repo",
812
- session_model: "session-model",
813
- turn_model: "model-b",
814
- });
815
- expect(cursor.codex_next_rollout).toBe(file);
816
- });
817
-
818
- it("bounds a quiet first backfill and resumes until the token event", async () => {
819
- const file = writeCodexRollout(env, "sessions", "rollout-bounded.jsonl", [
820
- { type: "session_meta", payload: { id: "bounded", model: "gpt-5-codex" } },
821
- ...Array.from({ length: 8 }, (_, index) => ({
822
- type: "response_item",
823
- payload: { type: "message", content: "x".repeat(140), index },
824
- })),
825
- codexToken("2026-07-30T14:00:00Z", "bounded-event", 5, 7),
826
- ]);
827
- const client = makeClient();
828
- const opts = {
829
- ...makeOpts(env, client),
830
- maxScanBytesPerSource: 350,
831
- };
832
-
833
- const first = await collectAndSendTelemetry(opts);
834
-
835
- expect(first.eventsSent).toBe(0);
836
- const firstOffset = readCursor(env).files[file]?.offset ?? 0;
837
- expect(firstOffset).toBeGreaterThan(0);
838
- expect(firstOffset).toBeLessThan(fs.statSync(file).size);
839
-
840
- for (let run = 0; run < 10 && client.posts.length === 0; run++) {
841
- await collectAndSendTelemetry(opts);
842
- }
843
- expect(client.posts.flatMap((post) => post.events)).toEqual([
844
- expect.objectContaining({
845
- sessionId: "bounded",
846
- uuid: "bounded-event",
847
- model: "gpt-5-codex",
848
- }),
849
- ]);
850
- });
851
-
852
- it("discards an oversized UTF-8 row without corrupting resume offsets", async () => {
853
- const file = writeCodexRollout(env, "sessions", "rollout-utf8.jsonl", [
854
- { type: "session_meta", payload: { id: "utf8", model: "gpt-5-codex" } },
855
- {
856
- type: "response_item",
857
- payload: { type: "message", content: "😀".repeat(20_000) },
858
- },
859
- codexToken("2026-07-30T14:00:01Z", "utf8-event", 2, 3),
860
- ]);
861
- const client = makeClient();
862
- const opts = {
863
- ...makeOpts(env, client),
864
- maxScanBytesPerSource: 64 * 1024,
865
- };
866
-
867
- for (let run = 0; run < 5 && client.posts.length === 0; run++) {
868
- await collectAndSendTelemetry(opts);
869
- }
870
-
871
- const events = client.posts.flatMap((post) => post.events);
872
- expect(events).toEqual([
873
- expect.objectContaining({ uuid: "utf8-event", sessionId: "utf8" }),
874
- ]);
875
- expect(readCursor(env).files[file].offset).toBeLessThanOrEqual(
876
- fs.statSync(file).size,
877
- );
878
- });
879
-
880
- it("caps upload batches and resumes remaining token events", async () => {
881
- writeCodexRollout(env, "sessions", "rollout-batch-cap.jsonl", [
882
- { type: "session_meta", payload: { id: "batch-cap", model: "gpt-5-codex" } },
883
- ...Array.from({ length: 201 }, (_, index) =>
884
- codexToken(
885
- "2026-07-30T14:01:" + String(index % 60).padStart(2, "0") + "Z",
886
- "batch-cap-" + index,
887
- 1,
888
- 1,
889
- ),
890
- ),
891
- ]);
892
- const client = makeClient();
893
- const opts = {
894
- ...makeOpts(env, client),
895
- maxScanBytesPerSource: 1_000_000,
896
- maxBatchesPerRun: 2,
897
- };
898
-
899
- const first = await collectAndSendTelemetry(opts);
900
- expect(first.batchesSent).toBe(2);
901
- expect(first.eventsSent).toBe(200);
902
-
903
- const second = await collectAndSendTelemetry(opts);
904
- expect(second.eventsSent).toBe(1);
905
- expect(client.posts.flatMap((post) => post.events)).toHaveLength(201);
906
- });
907
-
908
- it("does not advance a Codex rollout cursor when upload fails", async () => {
909
- const file = writeCodexRollout(env, "sessions", "rollout-retry.jsonl", [
910
- { type: "session_meta", payload: { id: "retry", model: "gpt-5-codex" } },
911
- codexToken("2026-07-30T12:00:00Z", "retry-event", 1, 2),
912
- ]);
913
- const client = makeClient({ postResponse: new Error("server 500") });
914
-
915
- const result = await collectAndSendTelemetry(makeOpts(env, client));
916
-
917
- expect(result.eventsSent).toBe(0);
918
- const cursor = readCursor(env);
919
- expect(cursor.files[file]?.offset ?? 0).toBe(0);
920
- });
921
- });
922
-
923
- // ── companyUid edge attribution (US-002) ────────────────────────────────────────
924
-
925
- describe("collectAndSendTelemetry — companyUid attribution", () => {
926
- const COMPANY_UID = "cmp_01INDIGOTEST";
927
- let env: TestEnv;
928
- let hqRoot: string;
929
-
930
- // The manifest lives at <hqRoot>/companies/manifest.yaml; the repo it maps is
931
- // a real subdir of hqRoot so the resolver's absolute-path math lines up.
932
- function writeManifest(): void {
933
- fs.mkdirSync(path.join(hqRoot, "companies"), { recursive: true });
934
- fs.writeFileSync(
935
- path.join(hqRoot, "companies", "manifest.yaml"),
936
- `companies:\n indigo:\n repos:\n - repos/private/hq-cloud\n cloud_uid: ${COMPANY_UID}\n`,
937
- );
938
- }
939
-
940
- function rowWithCwd(uuid: string, cwd: string): string {
941
- return JSON.stringify({
942
- type: "user",
943
- timestamp: "2026-06-10T10:00:00Z",
944
- sessionId: "s1",
945
- uuid,
946
- userType: "human",
947
- cwd,
948
- message: { role: "user", content: [{ type: "text", text: "hi" }] },
949
- });
950
- }
951
-
952
- beforeEach(() => {
953
- env = setupEnv();
954
- // Use the same tmp root as hqRoot so the repo path resolves under it.
955
- hqRoot = env.root;
956
- writeManifest();
957
- });
958
- afterEach(() => { teardownEnv(env); });
959
-
960
- it("stamps companyUid on events whose cwd is inside a company repo", async () => {
961
- const client = makeClient();
962
- const inRepo = path.join(hqRoot, "repos/private/hq-cloud/src");
963
- writeJsonl(env, "proj", "s.jsonl", [rowWithCwd("u1", inRepo)]);
964
-
965
- await collectAndSendTelemetry({ ...makeOpts(env, client), hqRoot });
966
-
967
- expect(client.posts).toHaveLength(1);
968
- expect(client.posts[0].events[0].companyUid).toBe(COMPANY_UID);
969
- });
970
-
971
- it("omits companyUid when the cwd maps to no company repo", async () => {
972
- const client = makeClient();
973
- writeJsonl(env, "proj", "s.jsonl", [rowWithCwd("u1", "/Users/x/some-other-repo")]);
974
-
975
- await collectAndSendTelemetry({ ...makeOpts(env, client), hqRoot });
976
-
977
- expect(client.posts).toHaveLength(1);
978
- expect("companyUid" in client.posts[0].events[0]).toBe(false);
979
- });
980
-
981
- it("uses the explicit single-company fallback when cwd is the shared HQ root", async () => {
982
- const client = makeClient();
983
- writeJsonl(env, "proj", "s.jsonl", [rowWithCwd("u1", hqRoot)]);
984
-
985
- await collectAndSendTelemetry({
986
- ...makeOpts(env, client),
987
- hqRoot,
988
- fallbackCompany: "indigo",
989
- });
990
-
991
- expect(client.posts).toHaveLength(1);
992
- expect(client.posts[0].events[0].companyUid).toBe(COMPANY_UID);
993
- });
994
-
995
- it("prefers the cwd-resolved company over the single-company fallback", async () => {
996
- const client = makeClient();
997
- const inRepo = path.join(hqRoot, "repos/private/hq-cloud");
998
- writeJsonl(env, "proj", "s.jsonl", [rowWithCwd("u1", inRepo)]);
999
-
1000
- await collectAndSendTelemetry({
1001
- ...makeOpts(env, client),
1002
- hqRoot,
1003
- fallbackCompany: "cmp_01OTHER",
1004
- });
1005
-
1006
- expect(client.posts).toHaveLength(1);
1007
- expect(client.posts[0].events[0].companyUid).toBe(COMPANY_UID);
1008
- });
1009
-
1010
- it("never sends the reserved 'unattributed' value", async () => {
1011
- const client = makeClient();
1012
- writeJsonl(env, "proj", "s.jsonl", [
1013
- rowWithCwd("u1", path.join(hqRoot, "repos/private/hq-cloud")),
1014
- rowWithCwd("u2", "/elsewhere"),
1015
- ]);
1016
-
1017
- await collectAndSendTelemetry({ ...makeOpts(env, client), hqRoot });
1018
-
1019
- for (const ev of client.posts.flatMap((p) => p.events)) {
1020
- expect(ev.companyUid).not.toBe("unattributed");
1021
- }
1022
- });
1023
-
1024
- it("parses the manifest once per run (cache), not per event", async () => {
1025
- const client = makeClient();
1026
- const inRepo = path.join(hqRoot, "repos/private/hq-cloud");
1027
- // 5 events in one run; assert the manifest file is read exactly once.
1028
- writeJsonl(
1029
- env,
1030
- "proj",
1031
- "s.jsonl",
1032
- Array.from({ length: 5 }, (_, i) => rowWithCwd(`u${i}`, inRepo)),
1033
- );
1034
-
1035
- const manifestPath = path.join(hqRoot, "companies", "manifest.yaml");
1036
- const realReadFile = fsp.readFile;
1037
- let manifestReads = 0;
1038
- const spy = vi
1039
- .spyOn(fsp, "readFile")
1040
- .mockImplementation((async (p: Parameters<typeof realReadFile>[0], ...rest: unknown[]) => {
1041
- if (typeof p === "string" && p === manifestPath) manifestReads++;
1042
- // @ts-expect-error pass-through to the real implementation
1043
- return realReadFile(p, ...rest);
1044
- }) as typeof realReadFile);
1045
-
1046
- try {
1047
- await collectAndSendTelemetry({ ...makeOpts(env, client), hqRoot });
1048
- } finally {
1049
- spy.mockRestore();
1050
- }
1051
-
1052
- expect(manifestReads).toBe(1); // one parse for all 5 events
1053
- const events = client.posts.flatMap((p) => p.events);
1054
- expect(events).toHaveLength(5);
1055
- for (const ev of events) expect(ev.companyUid).toBe(COMPANY_UID);
1056
- });
1057
- });
1058
-
1059
- const CALLER = "prs_01CALLER";
1060
-
1061
- // ── Consent self-heal ────────────────────────────────────────────────────────
1062
- //
1063
- // Regression for the opt-in race: the installer writes the user's answer to
1064
- // `~/.hq/menubar.json` (always succeeds) AND posts it to `/v1/usage/opt-in` —
1065
- // but that post fires before the person entity exists, so it 404s and the
1066
- // server attribute is never written. Absence read as `false`, the emitter went
1067
- // silent, and the person showed as "not opted in" forever. Measured in prod:
1068
- // 22 of 33 active Indigo members had NO attribute at all, against 2 genuine
1069
- // opt-outs.
1070
- //
1071
- // The heal replays the answer the user already gave. It must fire ONLY on the
1072
- // server's `unset` state, and must never invent or overwrite consent.
1073
-
1074
- describe("collectAndSendTelemetry — consent self-heal", () => {
1075
- let env: TestEnv;
1076
- beforeEach(() => {
1077
- env = setupEnv();
1078
- });
1079
- afterEach(() => teardownEnv(env));
1080
-
1081
- // The cached answer must name the account it belongs to; an unbound record is
1082
- // deliberately not replayable (see the cross-account test below).
1083
- function writeMenubar(value: unknown, personUid: string | undefined = CALLER): void {
1084
- fs.writeFileSync(
1085
- env.menubarPath,
1086
- JSON.stringify({
1087
- telemetryEnabled: value,
1088
- ...(personUid ? { telemetryOptInPersonUid: personUid } : {}),
1089
- }),
1090
- );
1091
- }
1092
-
1093
- it("re-asserts a local opt-IN when the server has no recorded consent", async () => {
1094
- writeMenubar(true);
1095
- const client = makeClient({
1096
- optInResponse: { enabled: false, updatedAt: null, unset: true, personUid: CALLER },
1097
- });
1098
-
1099
- const result = await collectAndSendTelemetry(makeOpts(env, client));
1100
-
1101
- expect(client.optInSets).toEqual([true]);
1102
- expect(result.enabled).toBe(true);
1103
- expect(result.optInSource).toBe("menubar-reasserted");
1104
- });
1105
-
1106
- it("re-asserts a local opt-OUT so the server records the real answer", async () => {
1107
- writeMenubar(false);
1108
- const client = makeClient({
1109
- optInResponse: { enabled: false, updatedAt: null, unset: true, personUid: CALLER },
1110
- });
1111
-
1112
- const result = await collectAndSendTelemetry(makeOpts(env, client));
1113
-
1114
- expect(client.optInSets).toEqual([false]);
1115
- expect(result.enabled).toBe(false);
1116
- });
1117
-
1118
- it("NEVER overwrites an explicit server opt-out", async () => {
1119
- // The user opted in on this machine at some point, then explicitly opted
1120
- // out account-wide. The account-wide answer must win.
1121
- writeMenubar(true);
1122
- const client = makeClient({
1123
- optInResponse: { enabled: false, updatedAt: "2026-06-19T16:11:09.939Z", unset: false },
1124
- });
1125
-
1126
- const result = await collectAndSendTelemetry(makeOpts(env, client));
1127
-
1128
- expect(client.optInSets).toEqual([]);
1129
- expect(result.enabled).toBe(false);
1130
- expect(result.optInSource).toBe("server");
1131
- });
1132
-
1133
- it("does not invent consent when no local answer exists", async () => {
1134
- // No menubar.json at all — we hold no answer, so we assert nothing.
1135
- const client = makeClient({
1136
- optInResponse: { enabled: false, updatedAt: null, unset: true, personUid: CALLER },
1137
- });
1138
-
1139
- const result = await collectAndSendTelemetry(makeOpts(env, client));
1140
-
1141
- expect(client.optInSets).toEqual([]);
1142
- expect(result.enabled).toBe(false);
1143
- });
1144
-
1145
- it("does not invent consent when the local value is not a boolean", async () => {
1146
- writeMenubar("yes");
1147
- const client = makeClient({
1148
- optInResponse: { enabled: false, updatedAt: null, unset: true, personUid: CALLER },
1149
- });
1150
-
1151
- const result = await collectAndSendTelemetry(makeOpts(env, client));
1152
-
1153
- expect(client.optInSets).toEqual([]);
1154
- expect(result.enabled).toBe(false);
1155
- });
1156
-
1157
- it("falls back to the server answer when the re-assert POST fails", async () => {
1158
- writeMenubar(true);
1159
- const client = makeClient({
1160
- optInResponse: { enabled: false, updatedAt: null, unset: true, personUid: CALLER },
1161
- setOptInError: new Error("network down"),
1162
- });
1163
-
1164
- const result = await collectAndSendTelemetry(makeOpts(env, client));
1165
-
1166
- expect(client.optInSets).toEqual([true]);
1167
- // Non-fatal: the run completes on the server's answer and retries next time.
1168
- expect(result.enabled).toBe(false);
1169
- expect(result.optInSource).toBe("server");
1170
- });
1171
-
1172
- it("skips the heal entirely against an older server that omits `unset`", async () => {
1173
- writeMenubar(true);
1174
- const client = makeClient({ optInResponse: { enabled: false, updatedAt: null } });
1175
-
1176
- const result = await collectAndSendTelemetry(makeOpts(env, client));
1177
-
1178
- expect(client.optInSets).toEqual([]);
1179
- expect(result.optInSource).toBe("server");
1180
- });
1181
- });
1182
-
1183
- // The self-heal must be ATOMIC. Reading `unset` and replaying the local answer
1184
- // are two requests; without a server-side condition another device could record
1185
- // a real opt-out in between and the replay would clobber it.
1186
- describe("collectAndSendTelemetry — self-heal is conditional", () => {
1187
- let env: TestEnv;
1188
- beforeEach(() => {
1189
- env = setupEnv();
1190
- });
1191
- afterEach(() => teardownEnv(env));
1192
-
1193
- it("asks the server to write ONLY if the consent is still unset", async () => {
1194
- fs.writeFileSync(
1195
- env.menubarPath,
1196
- JSON.stringify({ telemetryEnabled: true, telemetryOptInPersonUid: CALLER }),
1197
- );
1198
- const client = makeClient({
1199
- optInResponse: { enabled: false, updatedAt: null, unset: true, personUid: CALLER },
1200
- });
1201
-
1202
- await collectAndSendTelemetry(makeOpts(env, client));
1203
-
1204
- expect(client.optInSetOpts[0]).toMatchObject({ onlyIfUnset: true });
1205
- });
1206
-
1207
- it("defers to the server when the conditional write loses the race", async () => {
1208
- // A real answer was recorded elsewhere between our GET and our POST.
1209
- fs.writeFileSync(
1210
- env.menubarPath,
1211
- JSON.stringify({ telemetryEnabled: true, telemetryOptInPersonUid: CALLER }),
1212
- );
1213
- const client = makeClient({
1214
- optInResponse: { enabled: false, updatedAt: null, unset: true, personUid: CALLER },
1215
- setOptInApplied: false,
1216
- });
1217
-
1218
- const result = await collectAndSendTelemetry(makeOpts(env, client));
1219
-
1220
- // The stale local `true` must NOT win over the answer that landed first.
1221
- expect(result.enabled).toBe(false);
1222
- expect(result.optInSource).toBe("server");
1223
- });
1224
- });
1225
-
1226
- // The cached consent lives in a per-MACHINE file. If two people sign in under
1227
- // the same OS user it holds whoever answered LAST, so replaying it for a
1228
- // different account would opt in someone who never consented.
1229
- describe("collectAndSendTelemetry — consent replay is account-scoped", () => {
1230
- let env: TestEnv;
1231
- beforeEach(() => {
1232
- env = setupEnv();
1233
- });
1234
- afterEach(() => teardownEnv(env));
1235
-
1236
- it("does NOT replay a cached answer belonging to a different account", async () => {
1237
- fs.writeFileSync(
1238
- env.menubarPath,
1239
- JSON.stringify({ telemetryEnabled: true, telemetryOptInPersonUid: "prs_01SOMEONE_ELSE" }),
1240
- );
1241
- const client = makeClient({
1242
- optInResponse: { enabled: false, updatedAt: null, unset: true, personUid: CALLER },
1243
- });
1244
-
1245
- const result = await collectAndSendTelemetry(makeOpts(env, client));
1246
-
1247
- expect(client.optInSets).toEqual([]);
1248
- expect(result.enabled).toBe(false);
1249
- });
1250
-
1251
- it("does NOT replay a legacy record with no account binding", async () => {
1252
- // Written before consent was bound to an account — we cannot prove whose
1253
- // answer it is, so the installer's post-sign-in upload is the recovery path.
1254
- fs.writeFileSync(env.menubarPath, JSON.stringify({ telemetryEnabled: true }));
1255
- const client = makeClient({
1256
- optInResponse: { enabled: false, updatedAt: null, unset: true, personUid: CALLER },
1257
- });
1258
-
1259
- const result = await collectAndSendTelemetry(makeOpts(env, client));
1260
-
1261
- expect(client.optInSets).toEqual([]);
1262
- expect(result.enabled).toBe(false);
1263
- });
1264
-
1265
- it("does NOT replay when the server cannot say who the caller is", async () => {
1266
- fs.writeFileSync(
1267
- env.menubarPath,
1268
- JSON.stringify({ telemetryEnabled: true, telemetryOptInPersonUid: CALLER }),
1269
- );
1270
- // Older server: no `personUid`, so the match cannot be proven.
1271
- const client = makeClient({
1272
- optInResponse: { enabled: false, updatedAt: null, unset: true },
1273
- });
1274
-
1275
- const result = await collectAndSendTelemetry(makeOpts(env, client));
1276
-
1277
- expect(client.optInSets).toEqual([]);
1278
- expect(result.enabled).toBe(false);
1279
- });
1280
- });