@indigoai-us/hq-cloud 6.18.44-alpha.48 → 6.18.44-alpha.49

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 (1021) hide show
  1. package/dist/active-company.test.d.ts +2 -0
  2. package/dist/active-company.test.d.ts.map +1 -0
  3. package/dist/active-company.test.js +149 -0
  4. package/dist/active-company.test.js.map +1 -0
  5. package/dist/agent-codex-instructions.test.d.ts +2 -0
  6. package/dist/agent-codex-instructions.test.d.ts.map +1 -0
  7. package/dist/agent-codex-instructions.test.js +276 -0
  8. package/dist/agent-codex-instructions.test.js.map +1 -0
  9. package/dist/backup-prune.test.d.ts +2 -0
  10. package/dist/backup-prune.test.d.ts.map +1 -0
  11. package/dist/backup-prune.test.js +154 -0
  12. package/dist/backup-prune.test.js.map +1 -0
  13. package/dist/bandwidth.test.d.ts +2 -0
  14. package/dist/bandwidth.test.d.ts.map +1 -0
  15. package/dist/bandwidth.test.js +342 -0
  16. package/dist/bandwidth.test.js.map +1 -0
  17. package/dist/best-effort-error.test.d.ts +2 -0
  18. package/dist/best-effort-error.test.d.ts.map +1 -0
  19. package/dist/best-effort-error.test.js +54 -0
  20. package/dist/best-effort-error.test.js.map +1 -0
  21. package/dist/bin/area-ledger-migration.test.d.ts +2 -0
  22. package/dist/bin/area-ledger-migration.test.d.ts.map +1 -0
  23. package/dist/bin/area-ledger-migration.test.js +410 -0
  24. package/dist/bin/area-ledger-migration.test.js.map +1 -0
  25. package/dist/bin/backup-prune-runner.test.d.ts +2 -0
  26. package/dist/bin/backup-prune-runner.test.d.ts.map +1 -0
  27. package/dist/bin/backup-prune-runner.test.js +22 -0
  28. package/dist/bin/backup-prune-runner.test.js.map +1 -0
  29. package/dist/bin/journal-repair.test.d.ts +2 -0
  30. package/dist/bin/journal-repair.test.d.ts.map +1 -0
  31. package/dist/bin/journal-repair.test.js +53 -0
  32. package/dist/bin/journal-repair.test.js.map +1 -0
  33. package/dist/bin/layout-compatibility.test.d.ts +2 -0
  34. package/dist/bin/layout-compatibility.test.d.ts.map +1 -0
  35. package/dist/bin/layout-compatibility.test.js +87 -0
  36. package/dist/bin/layout-compatibility.test.js.map +1 -0
  37. package/dist/bin/outpost-heartbeat.test.d.ts +7 -0
  38. package/dist/bin/outpost-heartbeat.test.d.ts.map +1 -0
  39. package/dist/bin/outpost-heartbeat.test.js +84 -0
  40. package/dist/bin/outpost-heartbeat.test.js.map +1 -0
  41. package/dist/bin/outpost-session-host.test.d.ts +7 -0
  42. package/dist/bin/outpost-session-host.test.d.ts.map +1 -0
  43. package/dist/bin/outpost-session-host.test.js +52 -0
  44. package/dist/bin/outpost-session-host.test.js.map +1 -0
  45. package/dist/bin/sync-mutation.test.d.ts +2 -0
  46. package/dist/bin/sync-mutation.test.d.ts.map +1 -0
  47. package/dist/bin/sync-mutation.test.js +64 -0
  48. package/dist/bin/sync-mutation.test.js.map +1 -0
  49. package/dist/bin/sync-runner-args.test.d.ts +2 -0
  50. package/dist/bin/sync-runner-args.test.d.ts.map +1 -0
  51. package/dist/bin/sync-runner-args.test.js +82 -0
  52. package/dist/bin/sync-runner-args.test.js.map +1 -0
  53. package/dist/bin/sync-runner-auth-wait.test.d.ts +2 -0
  54. package/dist/bin/sync-runner-auth-wait.test.d.ts.map +1 -0
  55. package/dist/bin/sync-runner-auth-wait.test.js +406 -0
  56. package/dist/bin/sync-runner-auth-wait.test.js.map +1 -0
  57. package/dist/bin/sync-runner-backoff.regression.test.d.ts +29 -0
  58. package/dist/bin/sync-runner-backoff.regression.test.d.ts.map +1 -0
  59. package/dist/bin/sync-runner-backoff.regression.test.js +224 -0
  60. package/dist/bin/sync-runner-backoff.regression.test.js.map +1 -0
  61. package/dist/bin/sync-runner-company.test.d.ts +2 -0
  62. package/dist/bin/sync-runner-company.test.d.ts.map +1 -0
  63. package/dist/bin/sync-runner-company.test.js +2439 -0
  64. package/dist/bin/sync-runner-company.test.js.map +1 -0
  65. package/dist/bin/sync-runner-delete-snapshot-mixed.bench.test.d.ts +2 -0
  66. package/dist/bin/sync-runner-delete-snapshot-mixed.bench.test.d.ts.map +1 -0
  67. package/dist/bin/sync-runner-delete-snapshot-mixed.bench.test.js +648 -0
  68. package/dist/bin/sync-runner-delete-snapshot-mixed.bench.test.js.map +1 -0
  69. package/dist/bin/sync-runner-delete-snapshot.bench.test.d.ts +2 -0
  70. package/dist/bin/sync-runner-delete-snapshot.bench.test.d.ts.map +1 -0
  71. package/dist/bin/sync-runner-delete-snapshot.bench.test.js +329 -0
  72. package/dist/bin/sync-runner-delete-snapshot.bench.test.js.map +1 -0
  73. package/dist/bin/sync-runner-events.test.d.ts +2 -0
  74. package/dist/bin/sync-runner-events.test.d.ts.map +1 -0
  75. package/dist/bin/sync-runner-events.test.js +364 -0
  76. package/dist/bin/sync-runner-events.test.js.map +1 -0
  77. package/dist/bin/sync-runner-heap-telemetry.test.d.ts +2 -0
  78. package/dist/bin/sync-runner-heap-telemetry.test.d.ts.map +1 -0
  79. package/dist/bin/sync-runner-heap-telemetry.test.js +1966 -0
  80. package/dist/bin/sync-runner-heap-telemetry.test.js.map +1 -0
  81. package/dist/bin/sync-runner-manifest.test.d.ts +12 -0
  82. package/dist/bin/sync-runner-manifest.test.d.ts.map +1 -0
  83. package/dist/bin/sync-runner-manifest.test.js +921 -0
  84. package/dist/bin/sync-runner-manifest.test.js.map +1 -0
  85. package/dist/bin/sync-runner-planning.test.d.ts +2 -0
  86. package/dist/bin/sync-runner-planning.test.d.ts.map +1 -0
  87. package/dist/bin/sync-runner-planning.test.js +448 -0
  88. package/dist/bin/sync-runner-planning.test.js.map +1 -0
  89. package/dist/bin/sync-runner-post-sync-flags.test.d.ts +2 -0
  90. package/dist/bin/sync-runner-post-sync-flags.test.d.ts.map +1 -0
  91. package/dist/bin/sync-runner-post-sync-flags.test.js +64 -0
  92. package/dist/bin/sync-runner-post-sync-flags.test.js.map +1 -0
  93. package/dist/bin/sync-runner-publish-expansion.test.d.ts +2 -0
  94. package/dist/bin/sync-runner-publish-expansion.test.d.ts.map +1 -0
  95. package/dist/bin/sync-runner-publish-expansion.test.js +54 -0
  96. package/dist/bin/sync-runner-publish-expansion.test.js.map +1 -0
  97. package/dist/bin/sync-runner-receiver-unresolved-company.test.d.ts +2 -0
  98. package/dist/bin/sync-runner-receiver-unresolved-company.test.d.ts.map +1 -0
  99. package/dist/bin/sync-runner-receiver-unresolved-company.test.js +379 -0
  100. package/dist/bin/sync-runner-receiver-unresolved-company.test.js.map +1 -0
  101. package/dist/bin/sync-runner-rollup.test.d.ts +2 -0
  102. package/dist/bin/sync-runner-rollup.test.d.ts.map +1 -0
  103. package/dist/bin/sync-runner-rollup.test.js +24 -0
  104. package/dist/bin/sync-runner-rollup.test.js.map +1 -0
  105. package/dist/bin/sync-runner-watch-loop.test.d.ts +2 -0
  106. package/dist/bin/sync-runner-watch-loop.test.d.ts.map +1 -0
  107. package/dist/bin/sync-runner-watch-loop.test.js +735 -0
  108. package/dist/bin/sync-runner-watch-loop.test.js.map +1 -0
  109. package/dist/bin/sync-runner-watch-routes.test.d.ts +2 -0
  110. package/dist/bin/sync-runner-watch-routes.test.d.ts.map +1 -0
  111. package/dist/bin/sync-runner-watch-routes.test.js +181 -0
  112. package/dist/bin/sync-runner-watch-routes.test.js.map +1 -0
  113. package/dist/bin/sync-runner.test.d.ts +10 -0
  114. package/dist/bin/sync-runner.test.d.ts.map +1 -0
  115. package/dist/bin/sync-runner.test.js +19084 -0
  116. package/dist/bin/sync-runner.test.js.map +1 -0
  117. package/dist/cli/case-alias.test.d.ts +2 -0
  118. package/dist/cli/case-alias.test.d.ts.map +1 -0
  119. package/dist/cli/case-alias.test.js +96 -0
  120. package/dist/cli/case-alias.test.js.map +1 -0
  121. package/dist/cli/conflict-recovery.test.d.ts +2 -0
  122. package/dist/cli/conflict-recovery.test.d.ts.map +1 -0
  123. package/dist/cli/conflict-recovery.test.js +207 -0
  124. package/dist/cli/conflict-recovery.test.js.map +1 -0
  125. package/dist/cli/conflict-winner.test.d.ts +7 -0
  126. package/dist/cli/conflict-winner.test.d.ts.map +1 -0
  127. package/dist/cli/conflict-winner.test.js +98 -0
  128. package/dist/cli/conflict-winner.test.js.map +1 -0
  129. package/dist/cli/doctor.test.d.ts +13 -0
  130. package/dist/cli/doctor.test.d.ts.map +1 -0
  131. package/dist/cli/doctor.test.js +607 -0
  132. package/dist/cli/doctor.test.js.map +1 -0
  133. package/dist/cli/invite.test.d.ts +5 -0
  134. package/dist/cli/invite.test.d.ts.map +1 -0
  135. package/dist/cli/invite.test.js +178 -0
  136. package/dist/cli/invite.test.js.map +1 -0
  137. package/dist/cli/onepass-pull-planner-regressions.test.d.ts +2 -0
  138. package/dist/cli/onepass-pull-planner-regressions.test.d.ts.map +1 -0
  139. package/dist/cli/onepass-pull-planner-regressions.test.js +300 -0
  140. package/dist/cli/onepass-pull-planner-regressions.test.js.map +1 -0
  141. package/dist/cli/onepass-pull-planner.test.d.ts +2 -0
  142. package/dist/cli/onepass-pull-planner.test.d.ts.map +1 -0
  143. package/dist/cli/onepass-pull-planner.test.js +266 -0
  144. package/dist/cli/onepass-pull-planner.test.js.map +1 -0
  145. package/dist/cli/push-scan-exclusions.test.d.ts +2 -0
  146. package/dist/cli/push-scan-exclusions.test.d.ts.map +1 -0
  147. package/dist/cli/push-scan-exclusions.test.js +99 -0
  148. package/dist/cli/push-scan-exclusions.test.js.map +1 -0
  149. package/dist/cli/reindex-knowledge.test.d.ts +12 -0
  150. package/dist/cli/reindex-knowledge.test.d.ts.map +1 -0
  151. package/dist/cli/reindex-knowledge.test.js +318 -0
  152. package/dist/cli/reindex-knowledge.test.js.map +1 -0
  153. package/dist/cli/reindex.test.d.ts +11 -0
  154. package/dist/cli/reindex.test.d.ts.map +1 -0
  155. package/dist/cli/reindex.test.js +860 -0
  156. package/dist/cli/reindex.test.js.map +1 -0
  157. package/dist/cli/rescue-breaker.test.d.ts +2 -0
  158. package/dist/cli/rescue-breaker.test.d.ts.map +1 -0
  159. package/dist/cli/rescue-breaker.test.js +812 -0
  160. package/dist/cli/rescue-breaker.test.js.map +1 -0
  161. package/dist/cli/rescue-classify-ordering.test.d.ts +2 -0
  162. package/dist/cli/rescue-classify-ordering.test.d.ts.map +1 -0
  163. package/dist/cli/rescue-classify-ordering.test.js +500 -0
  164. package/dist/cli/rescue-classify-ordering.test.js.map +1 -0
  165. package/dist/cli/rescue-clone-diagnostics.test.d.ts +2 -0
  166. package/dist/cli/rescue-clone-diagnostics.test.d.ts.map +1 -0
  167. package/dist/cli/rescue-clone-diagnostics.test.js +101 -0
  168. package/dist/cli/rescue-clone-diagnostics.test.js.map +1 -0
  169. package/dist/cli/rescue-clone-network-retry.test.d.ts +2 -0
  170. package/dist/cli/rescue-clone-network-retry.test.d.ts.map +1 -0
  171. package/dist/cli/rescue-clone-network-retry.test.js +415 -0
  172. package/dist/cli/rescue-clone-network-retry.test.js.map +1 -0
  173. package/dist/cli/rescue-core-stamp.test.d.ts +2 -0
  174. package/dist/cli/rescue-core-stamp.test.d.ts.map +1 -0
  175. package/dist/cli/rescue-core-stamp.test.js +364 -0
  176. package/dist/cli/rescue-core-stamp.test.js.map +1 -0
  177. package/dist/cli/rescue-drift-reconcile.test.d.ts +2 -0
  178. package/dist/cli/rescue-drift-reconcile.test.d.ts.map +1 -0
  179. package/dist/cli/rescue-drift-reconcile.test.js +162 -0
  180. package/dist/cli/rescue-drift-reconcile.test.js.map +1 -0
  181. package/dist/cli/rescue-drop-dir-symlink.test.d.ts +2 -0
  182. package/dist/cli/rescue-drop-dir-symlink.test.d.ts.map +1 -0
  183. package/dist/cli/rescue-drop-dir-symlink.test.js +255 -0
  184. package/dist/cli/rescue-drop-dir-symlink.test.js.map +1 -0
  185. package/dist/cli/rescue-exec-bit-preserve.test.d.ts +2 -0
  186. package/dist/cli/rescue-exec-bit-preserve.test.d.ts.map +1 -0
  187. package/dist/cli/rescue-exec-bit-preserve.test.js +177 -0
  188. package/dist/cli/rescue-exec-bit-preserve.test.js.map +1 -0
  189. package/dist/cli/rescue-hq-root-guard.test.d.ts +2 -0
  190. package/dist/cli/rescue-hq-root-guard.test.d.ts.map +1 -0
  191. package/dist/cli/rescue-hq-root-guard.test.js +210 -0
  192. package/dist/cli/rescue-hq-root-guard.test.js.map +1 -0
  193. package/dist/cli/rescue-journal-reconcile.test.d.ts +2 -0
  194. package/dist/cli/rescue-journal-reconcile.test.d.ts.map +1 -0
  195. package/dist/cli/rescue-journal-reconcile.test.js +186 -0
  196. package/dist/cli/rescue-journal-reconcile.test.js.map +1 -0
  197. package/dist/cli/rescue-keep-local-ignore.test.d.ts +2 -0
  198. package/dist/cli/rescue-keep-local-ignore.test.d.ts.map +1 -0
  199. package/dist/cli/rescue-keep-local-ignore.test.js +315 -0
  200. package/dist/cli/rescue-keep-local-ignore.test.js.map +1 -0
  201. package/dist/cli/rescue-move.test.d.ts +2 -0
  202. package/dist/cli/rescue-move.test.d.ts.map +1 -0
  203. package/dist/cli/rescue-move.test.js +166 -0
  204. package/dist/cli/rescue-move.test.js.map +1 -0
  205. package/dist/cli/rescue-mtime-preserve.test.d.ts +2 -0
  206. package/dist/cli/rescue-mtime-preserve.test.d.ts.map +1 -0
  207. package/dist/cli/rescue-mtime-preserve.test.js +186 -0
  208. package/dist/cli/rescue-mtime-preserve.test.js.map +1 -0
  209. package/dist/cli/rescue-preserve-copy-symlink.test.d.ts +2 -0
  210. package/dist/cli/rescue-preserve-copy-symlink.test.d.ts.map +1 -0
  211. package/dist/cli/rescue-preserve-copy-symlink.test.js +483 -0
  212. package/dist/cli/rescue-preserve-copy-symlink.test.js.map +1 -0
  213. package/dist/cli/rescue-realpath.test.d.ts +2 -0
  214. package/dist/cli/rescue-realpath.test.d.ts.map +1 -0
  215. package/dist/cli/rescue-realpath.test.js +109 -0
  216. package/dist/cli/rescue-realpath.test.js.map +1 -0
  217. package/dist/cli/rescue-restore-flag.test.d.ts +2 -0
  218. package/dist/cli/rescue-restore-flag.test.d.ts.map +1 -0
  219. package/dist/cli/rescue-restore-flag.test.js +82 -0
  220. package/dist/cli/rescue-restore-flag.test.js.map +1 -0
  221. package/dist/cli/rescue-rsync-preflight.test.d.ts +2 -0
  222. package/dist/cli/rescue-rsync-preflight.test.d.ts.map +1 -0
  223. package/dist/cli/rescue-rsync-preflight.test.js +579 -0
  224. package/dist/cli/rescue-rsync-preflight.test.js.map +1 -0
  225. package/dist/cli/rescue-rsync-status.test.d.ts +2 -0
  226. package/dist/cli/rescue-rsync-status.test.d.ts.map +1 -0
  227. package/dist/cli/rescue-rsync-status.test.js +406 -0
  228. package/dist/cli/rescue-rsync-status.test.js.map +1 -0
  229. package/dist/cli/rescue-settings-reconcile.test.d.ts +2 -0
  230. package/dist/cli/rescue-settings-reconcile.test.d.ts.map +1 -0
  231. package/dist/cli/rescue-settings-reconcile.test.js +610 -0
  232. package/dist/cli/rescue-settings-reconcile.test.js.map +1 -0
  233. package/dist/cli/rescue-snapshot-copy.test.d.ts +2 -0
  234. package/dist/cli/rescue-snapshot-copy.test.d.ts.map +1 -0
  235. package/dist/cli/rescue-snapshot-copy.test.js +790 -0
  236. package/dist/cli/rescue-snapshot-copy.test.js.map +1 -0
  237. package/dist/cli/rescue-snapshot-recovery.test.d.ts +2 -0
  238. package/dist/cli/rescue-snapshot-recovery.test.d.ts.map +1 -0
  239. package/dist/cli/rescue-snapshot-recovery.test.js +265 -0
  240. package/dist/cli/rescue-snapshot-recovery.test.js.map +1 -0
  241. package/dist/cli/rescue-snapshot.test.d.ts +2 -0
  242. package/dist/cli/rescue-snapshot.test.d.ts.map +1 -0
  243. package/dist/cli/rescue-snapshot.test.js +46 -0
  244. package/dist/cli/rescue-snapshot.test.js.map +1 -0
  245. package/dist/cli/rescue-source-switch-floor.test.d.ts +2 -0
  246. package/dist/cli/rescue-source-switch-floor.test.d.ts.map +1 -0
  247. package/dist/cli/rescue-source-switch-floor.test.js +247 -0
  248. package/dist/cli/rescue-source-switch-floor.test.js.map +1 -0
  249. package/dist/cli/rescue-unchanged-delete.test.d.ts +2 -0
  250. package/dist/cli/rescue-unchanged-delete.test.d.ts.map +1 -0
  251. package/dist/cli/rescue-unchanged-delete.test.js +305 -0
  252. package/dist/cli/rescue-unchanged-delete.test.js.map +1 -0
  253. package/dist/cli/rescue.reindex.test.d.ts +2 -0
  254. package/dist/cli/rescue.reindex.test.d.ts.map +1 -0
  255. package/dist/cli/rescue.reindex.test.js +72 -0
  256. package/dist/cli/rescue.reindex.test.js.map +1 -0
  257. package/dist/cli/rescue.test.d.ts +2 -0
  258. package/dist/cli/rescue.test.d.ts.map +1 -0
  259. package/dist/cli/rescue.test.js +127 -0
  260. package/dist/cli/rescue.test.js.map +1 -0
  261. package/dist/cli/share-plan-limit-presign.test.d.ts +2 -0
  262. package/dist/cli/share-plan-limit-presign.test.d.ts.map +1 -0
  263. package/dist/cli/share-plan-limit-presign.test.js +271 -0
  264. package/dist/cli/share-plan-limit-presign.test.js.map +1 -0
  265. package/dist/cli/share-presign-transport.test.d.ts +22 -0
  266. package/dist/cli/share-presign-transport.test.d.ts.map +1 -0
  267. package/dist/cli/share-presign-transport.test.js +388 -0
  268. package/dist/cli/share-presign-transport.test.js.map +1 -0
  269. package/dist/cli/share.test.d.ts +5 -0
  270. package/dist/cli/share.test.d.ts.map +1 -0
  271. package/dist/cli/share.test.js +12336 -0
  272. package/dist/cli/share.test.js.map +1 -0
  273. package/dist/cli/streaming-pull-planner.bench.test.d.ts +15 -0
  274. package/dist/cli/streaming-pull-planner.bench.test.d.ts.map +1 -0
  275. package/dist/cli/streaming-pull-planner.bench.test.js +273 -0
  276. package/dist/cli/streaming-pull-planner.bench.test.js.map +1 -0
  277. package/dist/cli/sync-scope.test.d.ts +22 -0
  278. package/dist/cli/sync-scope.test.d.ts.map +1 -0
  279. package/dist/cli/sync-scope.test.js +903 -0
  280. package/dist/cli/sync-scope.test.js.map +1 -0
  281. package/dist/cli/sync.test.d.ts +5 -0
  282. package/dist/cli/sync.test.d.ts.map +1 -0
  283. package/dist/cli/sync.test.js +9028 -0
  284. package/dist/cli/sync.test.js.map +1 -0
  285. package/dist/cli/tombstones.test.d.ts +2 -0
  286. package/dist/cli/tombstones.test.d.ts.map +1 -0
  287. package/dist/cli/tombstones.test.js +120 -0
  288. package/dist/cli/tombstones.test.js.map +1 -0
  289. package/dist/cli/watch-event-push-conflict.test.d.ts +25 -0
  290. package/dist/cli/watch-event-push-conflict.test.d.ts.map +1 -0
  291. package/dist/cli/watch-event-push-conflict.test.js +230 -0
  292. package/dist/cli/watch-event-push-conflict.test.js.map +1 -0
  293. package/dist/client-info.test.d.ts +11 -0
  294. package/dist/client-info.test.d.ts.map +1 -0
  295. package/dist/client-info.test.js +168 -0
  296. package/dist/client-info.test.js.map +1 -0
  297. package/dist/cognito-auth-lock-no-hard-links.test.d.ts +11 -0
  298. package/dist/cognito-auth-lock-no-hard-links.test.d.ts.map +1 -0
  299. package/dist/cognito-auth-lock-no-hard-links.test.js +76 -0
  300. package/dist/cognito-auth-lock-no-hard-links.test.js.map +1 -0
  301. package/dist/cognito-auth.test.d.ts +9 -0
  302. package/dist/cognito-auth.test.d.ts.map +1 -0
  303. package/dist/cognito-auth.test.js +745 -0
  304. package/dist/cognito-auth.test.js.map +1 -0
  305. package/dist/company-resolver.test.d.ts +7 -0
  306. package/dist/company-resolver.test.d.ts.map +1 -0
  307. package/dist/company-resolver.test.js +535 -0
  308. package/dist/company-resolver.test.js.map +1 -0
  309. package/dist/company-slug.test.d.ts +7 -0
  310. package/dist/company-slug.test.d.ts.map +1 -0
  311. package/dist/company-slug.test.js +43 -0
  312. package/dist/company-slug.test.js.map +1 -0
  313. package/dist/company-vault-transport.test.d.ts +12 -0
  314. package/dist/company-vault-transport.test.d.ts.map +1 -0
  315. package/dist/company-vault-transport.test.js +97 -0
  316. package/dist/company-vault-transport.test.js.map +1 -0
  317. package/dist/context.test.d.ts +7 -0
  318. package/dist/context.test.d.ts.map +1 -0
  319. package/dist/context.test.js +646 -0
  320. package/dist/context.test.js.map +1 -0
  321. package/dist/entity-resolver.test.d.ts +10 -0
  322. package/dist/entity-resolver.test.d.ts.map +1 -0
  323. package/dist/entity-resolver.test.js +244 -0
  324. package/dist/entity-resolver.test.js.map +1 -0
  325. package/dist/getindigo-dead-refs-contract.test.d.ts +2 -0
  326. package/dist/getindigo-dead-refs-contract.test.d.ts.map +1 -0
  327. package/dist/getindigo-dead-refs-contract.test.js +58 -0
  328. package/dist/getindigo-dead-refs-contract.test.js.map +1 -0
  329. package/dist/hermetic-test-env.test.d.ts +2 -0
  330. package/dist/hermetic-test-env.test.d.ts.map +1 -0
  331. package/dist/hermetic-test-env.test.js +61 -0
  332. package/dist/hermetic-test-env.test.js.map +1 -0
  333. package/dist/hq-root-recovery.test.d.ts +2 -0
  334. package/dist/hq-root-recovery.test.d.ts.map +1 -0
  335. package/dist/hq-root-recovery.test.js +65 -0
  336. package/dist/hq-root-recovery.test.js.map +1 -0
  337. package/dist/ignore.test.d.ts +10 -0
  338. package/dist/ignore.test.d.ts.map +1 -0
  339. package/dist/ignore.test.js +958 -0
  340. package/dist/ignore.test.js.map +1 -0
  341. package/dist/index.test.d.ts +2 -0
  342. package/dist/index.test.d.ts.map +1 -0
  343. package/dist/index.test.js +26 -0
  344. package/dist/index.test.js.map +1 -0
  345. package/dist/journal-area-ledger-read-boundary.test.d.ts +2 -0
  346. package/dist/journal-area-ledger-read-boundary.test.d.ts.map +1 -0
  347. package/dist/journal-area-ledger-read-boundary.test.js +425 -0
  348. package/dist/journal-area-ledger-read-boundary.test.js.map +1 -0
  349. package/dist/journal-baseline.test.d.ts +2 -0
  350. package/dist/journal-baseline.test.d.ts.map +1 -0
  351. package/dist/journal-baseline.test.js +218 -0
  352. package/dist/journal-baseline.test.js.map +1 -0
  353. package/dist/journal-decode-window.test.d.ts +2 -0
  354. package/dist/journal-decode-window.test.d.ts.map +1 -0
  355. package/dist/journal-decode-window.test.js +99 -0
  356. package/dist/journal-decode-window.test.js.map +1 -0
  357. package/dist/journal-delta-writes.test.d.ts +2 -0
  358. package/dist/journal-delta-writes.test.d.ts.map +1 -0
  359. package/dist/journal-delta-writes.test.js +159 -0
  360. package/dist/journal-delta-writes.test.js.map +1 -0
  361. package/dist/journal-ledger-index.test.d.ts +15 -0
  362. package/dist/journal-ledger-index.test.d.ts.map +1 -0
  363. package/dist/journal-ledger-index.test.js +269 -0
  364. package/dist/journal-ledger-index.test.js.map +1 -0
  365. package/dist/journal-public-boundary.test.d.ts +2 -0
  366. package/dist/journal-public-boundary.test.d.ts.map +1 -0
  367. package/dist/journal-public-boundary.test.js +216 -0
  368. package/dist/journal-public-boundary.test.js.map +1 -0
  369. package/dist/journal-row-store.test.d.ts +2 -0
  370. package/dist/journal-row-store.test.d.ts.map +1 -0
  371. package/dist/journal-row-store.test.js +729 -0
  372. package/dist/journal-row-store.test.js.map +1 -0
  373. package/dist/journal-snapshot-memory-helpers.d.ts +35 -0
  374. package/dist/journal-snapshot-memory-helpers.d.ts.map +1 -0
  375. package/dist/journal-snapshot-memory-helpers.js +298 -0
  376. package/dist/journal-snapshot-memory-helpers.js.map +1 -0
  377. package/dist/journal-snapshot-memory.test.d.ts +2 -0
  378. package/dist/journal-snapshot-memory.test.d.ts.map +1 -0
  379. package/dist/journal-snapshot-memory.test.js +55 -0
  380. package/dist/journal-snapshot-memory.test.js.map +1 -0
  381. package/dist/journal-snapshot-v4-memory.test.d.ts +2 -0
  382. package/dist/journal-snapshot-v4-memory.test.d.ts.map +1 -0
  383. package/dist/journal-snapshot-v4-memory.test.js +24 -0
  384. package/dist/journal-snapshot-v4-memory.test.js.map +1 -0
  385. package/dist/journal-snapshot-v4-writer-memory.test.d.ts +2 -0
  386. package/dist/journal-snapshot-v4-writer-memory.test.d.ts.map +1 -0
  387. package/dist/journal-snapshot-v4-writer-memory.test.js +76 -0
  388. package/dist/journal-snapshot-v4-writer-memory.test.js.map +1 -0
  389. package/dist/journal-snapshot-v4-writer.test.d.ts +2 -0
  390. package/dist/journal-snapshot-v4-writer.test.d.ts.map +1 -0
  391. package/dist/journal-snapshot-v4-writer.test.js +282 -0
  392. package/dist/journal-snapshot-v4-writer.test.js.map +1 -0
  393. package/dist/journal-snapshot-v4.test.d.ts +2 -0
  394. package/dist/journal-snapshot-v4.test.d.ts.map +1 -0
  395. package/dist/journal-snapshot-v4.test.js +281 -0
  396. package/dist/journal-snapshot-v4.test.js.map +1 -0
  397. package/dist/journal-store.test.d.ts +2 -0
  398. package/dist/journal-store.test.d.ts.map +1 -0
  399. package/dist/journal-store.test.js +1227 -0
  400. package/dist/journal-store.test.js.map +1 -0
  401. package/dist/journal-streaming.heap.test.d.ts +2 -0
  402. package/dist/journal-streaming.heap.test.d.ts.map +1 -0
  403. package/dist/journal-streaming.heap.test.js +190 -0
  404. package/dist/journal-streaming.heap.test.js.map +1 -0
  405. package/dist/journal.test.d.ts +9 -0
  406. package/dist/journal.test.d.ts.map +1 -0
  407. package/dist/journal.test.js +1074 -0
  408. package/dist/journal.test.js.map +1 -0
  409. package/dist/kms10-etag-safe-pull.test.d.ts +2 -0
  410. package/dist/kms10-etag-safe-pull.test.d.ts.map +1 -0
  411. package/dist/kms10-etag-safe-pull.test.js +53 -0
  412. package/dist/kms10-etag-safe-pull.test.js.map +1 -0
  413. package/dist/lib/cloud-authoritative.test.d.ts +2 -0
  414. package/dist/lib/cloud-authoritative.test.d.ts.map +1 -0
  415. package/dist/lib/cloud-authoritative.test.js +42 -0
  416. package/dist/lib/cloud-authoritative.test.js.map +1 -0
  417. package/dist/lib/conflict-reconcile.test.d.ts +7 -0
  418. package/dist/lib/conflict-reconcile.test.d.ts.map +1 -0
  419. package/dist/lib/conflict-reconcile.test.js +246 -0
  420. package/dist/lib/conflict-reconcile.test.js.map +1 -0
  421. package/dist/lib/conflict.test.d.ts +9 -0
  422. package/dist/lib/conflict.test.d.ts.map +1 -0
  423. package/dist/lib/conflict.test.js +340 -0
  424. package/dist/lib/conflict.test.js.map +1 -0
  425. package/dist/lib/describe-error.test.d.ts +2 -0
  426. package/dist/lib/describe-error.test.d.ts.map +1 -0
  427. package/dist/lib/describe-error.test.js +148 -0
  428. package/dist/lib/describe-error.test.js.map +1 -0
  429. package/dist/lib/machine-id.test.d.ts +8 -0
  430. package/dist/lib/machine-id.test.d.ts.map +1 -0
  431. package/dist/lib/machine-id.test.js +228 -0
  432. package/dist/lib/machine-id.test.js.map +1 -0
  433. package/dist/lib/net-errors.test.d.ts +2 -0
  434. package/dist/lib/net-errors.test.d.ts.map +1 -0
  435. package/dist/lib/net-errors.test.js +111 -0
  436. package/dist/lib/net-errors.test.js.map +1 -0
  437. package/dist/lib/ontology-entity-meta.test.d.ts +2 -0
  438. package/dist/lib/ontology-entity-meta.test.d.ts.map +1 -0
  439. package/dist/lib/ontology-entity-meta.test.js +79 -0
  440. package/dist/lib/ontology-entity-meta.test.js.map +1 -0
  441. package/dist/lib/ontology-entity-push.test.d.ts +2 -0
  442. package/dist/lib/ontology-entity-push.test.d.ts.map +1 -0
  443. package/dist/lib/ontology-entity-push.test.js +156 -0
  444. package/dist/lib/ontology-entity-push.test.js.map +1 -0
  445. package/dist/lib/personal-connector-settings-sync.test.d.ts +2 -0
  446. package/dist/lib/personal-connector-settings-sync.test.d.ts.map +1 -0
  447. package/dist/lib/personal-connector-settings-sync.test.js +34 -0
  448. package/dist/lib/personal-connector-settings-sync.test.js.map +1 -0
  449. package/dist/lib/readlink-safe.test.d.ts +2 -0
  450. package/dist/lib/readlink-safe.test.d.ts.map +1 -0
  451. package/dist/lib/readlink-safe.test.js +34 -0
  452. package/dist/lib/readlink-safe.test.js.map +1 -0
  453. package/dist/lib/s3-content-checksum.test.d.ts +2 -0
  454. package/dist/lib/s3-content-checksum.test.d.ts.map +1 -0
  455. package/dist/lib/s3-content-checksum.test.js +26 -0
  456. package/dist/lib/s3-content-checksum.test.js.map +1 -0
  457. package/dist/lib/skill-register-landed-bytes.test.d.ts +2 -0
  458. package/dist/lib/skill-register-landed-bytes.test.d.ts.map +1 -0
  459. package/dist/lib/skill-register-landed-bytes.test.js +83 -0
  460. package/dist/lib/skill-register-landed-bytes.test.js.map +1 -0
  461. package/dist/local-path-codec.test.d.ts +14 -0
  462. package/dist/local-path-codec.test.d.ts.map +1 -0
  463. package/dist/local-path-codec.test.js +122 -0
  464. package/dist/local-path-codec.test.js.map +1 -0
  465. package/dist/machine-auth.test.d.ts +14 -0
  466. package/dist/machine-auth.test.d.ts.map +1 -0
  467. package/dist/machine-auth.test.js +1492 -0
  468. package/dist/machine-auth.test.js.map +1 -0
  469. package/dist/machine-token-cache-isolation.test.d.ts +24 -0
  470. package/dist/machine-token-cache-isolation.test.d.ts.map +1 -0
  471. package/dist/machine-token-cache-isolation.test.js +284 -0
  472. package/dist/machine-token-cache-isolation.test.js.map +1 -0
  473. package/dist/manifest/US-002.acceptance.test.d.ts +11 -0
  474. package/dist/manifest/US-002.acceptance.test.d.ts.map +1 -0
  475. package/dist/manifest/US-002.acceptance.test.js +160 -0
  476. package/dist/manifest/US-002.acceptance.test.js.map +1 -0
  477. package/dist/manifest/US-004.acceptance.test.d.ts +12 -0
  478. package/dist/manifest/US-004.acceptance.test.d.ts.map +1 -0
  479. package/dist/manifest/US-004.acceptance.test.js +173 -0
  480. package/dist/manifest/US-004.acceptance.test.js.map +1 -0
  481. package/dist/manifest/bench-gate.d.ts +30 -0
  482. package/dist/manifest/bench-gate.d.ts.map +1 -0
  483. package/dist/manifest/bench-gate.js +47 -0
  484. package/dist/manifest/bench-gate.js.map +1 -0
  485. package/dist/manifest/bench-gate.test.d.ts +2 -0
  486. package/dist/manifest/bench-gate.test.d.ts.map +1 -0
  487. package/dist/manifest/bench-gate.test.js +67 -0
  488. package/dist/manifest/bench-gate.test.js.map +1 -0
  489. package/dist/manifest/build-manifest-resident-parity.test.d.ts +2 -0
  490. package/dist/manifest/build-manifest-resident-parity.test.d.ts.map +1 -0
  491. package/dist/manifest/build-manifest-resident-parity.test.js +69 -0
  492. package/dist/manifest/build-manifest-resident-parity.test.js.map +1 -0
  493. package/dist/manifest/build-manifest.bench.test.d.ts +22 -0
  494. package/dist/manifest/build-manifest.bench.test.d.ts.map +1 -0
  495. package/dist/manifest/build-manifest.bench.test.js +931 -0
  496. package/dist/manifest/build-manifest.bench.test.js.map +1 -0
  497. package/dist/manifest/build-manifest.test.d.ts +10 -0
  498. package/dist/manifest/build-manifest.test.d.ts.map +1 -0
  499. package/dist/manifest/build-manifest.test.js +1220 -0
  500. package/dist/manifest/build-manifest.test.js.map +1 -0
  501. package/dist/manifest/contract.test.d.ts +17 -0
  502. package/dist/manifest/contract.test.d.ts.map +1 -0
  503. package/dist/manifest/contract.test.js +346 -0
  504. package/dist/manifest/contract.test.js.map +1 -0
  505. package/dist/manifest/import-graph.test.d.ts +25 -0
  506. package/dist/manifest/import-graph.test.d.ts.map +1 -0
  507. package/dist/manifest/import-graph.test.js +120 -0
  508. package/dist/manifest/import-graph.test.js.map +1 -0
  509. package/dist/manifest/ledger-shard-isolation.test.d.ts +18 -0
  510. package/dist/manifest/ledger-shard-isolation.test.d.ts.map +1 -0
  511. package/dist/manifest/ledger-shard-isolation.test.js +153 -0
  512. package/dist/manifest/ledger-shard-isolation.test.js.map +1 -0
  513. package/dist/manifest/snapshot-store.test.d.ts +11 -0
  514. package/dist/manifest/snapshot-store.test.d.ts.map +1 -0
  515. package/dist/manifest/snapshot-store.test.js +206 -0
  516. package/dist/manifest/snapshot-store.test.js.map +1 -0
  517. package/dist/manifest/upload-manifest.test.d.ts +10 -0
  518. package/dist/manifest/upload-manifest.test.d.ts.map +1 -0
  519. package/dist/manifest/upload-manifest.test.js +1335 -0
  520. package/dist/manifest/upload-manifest.test.js.map +1 -0
  521. package/dist/manifest-reconcile.test.d.ts +2 -0
  522. package/dist/manifest-reconcile.test.d.ts.map +1 -0
  523. package/dist/manifest-reconcile.test.js +1032 -0
  524. package/dist/manifest-reconcile.test.js.map +1 -0
  525. package/dist/object-io.test.d.ts +11 -0
  526. package/dist/object-io.test.d.ts.map +1 -0
  527. package/dist/object-io.test.js +2376 -0
  528. package/dist/object-io.test.js.map +1 -0
  529. package/dist/operation-lock.test.d.ts +5 -0
  530. package/dist/operation-lock.test.d.ts.map +1 -0
  531. package/dist/operation-lock.test.js +796 -0
  532. package/dist/operation-lock.test.js.map +1 -0
  533. package/dist/outcome-telemetry.test.d.ts +9 -0
  534. package/dist/outcome-telemetry.test.d.ts.map +1 -0
  535. package/dist/outcome-telemetry.test.js +663 -0
  536. package/dist/outcome-telemetry.test.js.map +1 -0
  537. package/dist/outposts/client.test.d.ts +9 -0
  538. package/dist/outposts/client.test.d.ts.map +1 -0
  539. package/dist/outposts/client.test.js +415 -0
  540. package/dist/outposts/client.test.js.map +1 -0
  541. package/dist/outposts/command.test.d.ts +18 -0
  542. package/dist/outposts/command.test.d.ts.map +1 -0
  543. package/dist/outposts/command.test.js +1230 -0
  544. package/dist/outposts/command.test.js.map +1 -0
  545. package/dist/outposts/replica-sync.test.d.ts +2 -0
  546. package/dist/outposts/replica-sync.test.d.ts.map +1 -0
  547. package/dist/outposts/replica-sync.test.js +225 -0
  548. package/dist/outposts/replica-sync.test.js.map +1 -0
  549. package/dist/outposts/self-deploy.test.d.ts +2 -0
  550. package/dist/outposts/self-deploy.test.d.ts.map +1 -0
  551. package/dist/outposts/self-deploy.test.js +218 -0
  552. package/dist/outposts/self-deploy.test.js.map +1 -0
  553. package/dist/outposts/session-heartbeat-bounds.test.d.ts +25 -0
  554. package/dist/outposts/session-heartbeat-bounds.test.d.ts.map +1 -0
  555. package/dist/outposts/session-heartbeat-bounds.test.js +159 -0
  556. package/dist/outposts/session-heartbeat-bounds.test.js.map +1 -0
  557. package/dist/outposts/session-heartbeat-guard.test.d.ts +16 -0
  558. package/dist/outposts/session-heartbeat-guard.test.d.ts.map +1 -0
  559. package/dist/outposts/session-heartbeat-guard.test.js +88 -0
  560. package/dist/outposts/session-heartbeat-guard.test.js.map +1 -0
  561. package/dist/outposts/session-heartbeat-publisher.test.d.ts +10 -0
  562. package/dist/outposts/session-heartbeat-publisher.test.d.ts.map +1 -0
  563. package/dist/outposts/session-heartbeat-publisher.test.js +153 -0
  564. package/dist/outposts/session-heartbeat-publisher.test.js.map +1 -0
  565. package/dist/outposts/session-heartbeat-retain-guard.test.d.ts +18 -0
  566. package/dist/outposts/session-heartbeat-retain-guard.test.d.ts.map +1 -0
  567. package/dist/outposts/session-heartbeat-retain-guard.test.js +106 -0
  568. package/dist/outposts/session-heartbeat-retain-guard.test.js.map +1 -0
  569. package/dist/outposts/session-heartbeat-scan.test.d.ts +20 -0
  570. package/dist/outposts/session-heartbeat-scan.test.d.ts.map +1 -0
  571. package/dist/outposts/session-heartbeat-scan.test.js +242 -0
  572. package/dist/outposts/session-heartbeat-scan.test.js.map +1 -0
  573. package/dist/outposts/session-heartbeat.test.d.ts +11 -0
  574. package/dist/outposts/session-heartbeat.test.d.ts.map +1 -0
  575. package/dist/outposts/session-heartbeat.test.js +387 -0
  576. package/dist/outposts/session-heartbeat.test.js.map +1 -0
  577. package/dist/outposts/session-host-auth.test.d.ts +16 -0
  578. package/dist/outposts/session-host-auth.test.d.ts.map +1 -0
  579. package/dist/outposts/session-host-auth.test.js +284 -0
  580. package/dist/outposts/session-host-auth.test.js.map +1 -0
  581. package/dist/outposts/session-host-command.test.d.ts +10 -0
  582. package/dist/outposts/session-host-command.test.d.ts.map +1 -0
  583. package/dist/outposts/session-host-command.test.js +182 -0
  584. package/dist/outposts/session-host-command.test.js.map +1 -0
  585. package/dist/outposts/session-host-connection.test.d.ts +18 -0
  586. package/dist/outposts/session-host-connection.test.d.ts.map +1 -0
  587. package/dist/outposts/session-host-connection.test.js +392 -0
  588. package/dist/outposts/session-host-connection.test.js.map +1 -0
  589. package/dist/outposts/session-host-fakes.d.ts +61 -0
  590. package/dist/outposts/session-host-fakes.d.ts.map +1 -0
  591. package/dist/outposts/session-host-fakes.js +115 -0
  592. package/dist/outposts/session-host-fakes.js.map +1 -0
  593. package/dist/outposts/session-host-ndjson.test.d.ts +11 -0
  594. package/dist/outposts/session-host-ndjson.test.d.ts.map +1 -0
  595. package/dist/outposts/session-host-ndjson.test.js +73 -0
  596. package/dist/outposts/session-host-ndjson.test.js.map +1 -0
  597. package/dist/outposts/session-host-protocol.test.d.ts +15 -0
  598. package/dist/outposts/session-host-protocol.test.d.ts.map +1 -0
  599. package/dist/outposts/session-host-protocol.test.js +0 -0
  600. package/dist/outposts/session-host-protocol.test.js.map +1 -0
  601. package/dist/outposts/session-host-server.test.d.ts +10 -0
  602. package/dist/outposts/session-host-server.test.d.ts.map +1 -0
  603. package/dist/outposts/session-host-server.test.js +118 -0
  604. package/dist/outposts/session-host-server.test.js.map +1 -0
  605. package/dist/outposts/session-host-sessions.test.d.ts +18 -0
  606. package/dist/outposts/session-host-sessions.test.d.ts.map +1 -0
  607. package/dist/outposts/session-host-sessions.test.js +439 -0
  608. package/dist/outposts/session-host-sessions.test.js.map +1 -0
  609. package/dist/outposts/terminal.test.d.ts +2 -0
  610. package/dist/outposts/terminal.test.d.ts.map +1 -0
  611. package/dist/outposts/terminal.test.js +146 -0
  612. package/dist/outposts/terminal.test.js.map +1 -0
  613. package/dist/outposts/transport.test.d.ts +10 -0
  614. package/dist/outposts/transport.test.d.ts.map +1 -0
  615. package/dist/outposts/transport.test.js +205 -0
  616. package/dist/outposts/transport.test.js.map +1 -0
  617. package/dist/packed-journal-phase2.test.d.ts +2 -0
  618. package/dist/packed-journal-phase2.test.d.ts.map +1 -0
  619. package/dist/packed-journal-phase2.test.js +273 -0
  620. package/dist/packed-journal-phase2.test.js.map +1 -0
  621. package/dist/path-ancestors.test.d.ts +2 -0
  622. package/dist/path-ancestors.test.d.ts.map +1 -0
  623. package/dist/path-ancestors.test.js +21 -0
  624. package/dist/path-ancestors.test.js.map +1 -0
  625. package/dist/personal-vault-exclusions.test.d.ts +22 -0
  626. package/dist/personal-vault-exclusions.test.d.ts.map +1 -0
  627. package/dist/personal-vault-exclusions.test.js +294 -0
  628. package/dist/personal-vault-exclusions.test.js.map +1 -0
  629. package/dist/personal-vault.test.d.ts +18 -0
  630. package/dist/personal-vault.test.d.ts.map +1 -0
  631. package/dist/personal-vault.test.js +1106 -0
  632. package/dist/personal-vault.test.js.map +1 -0
  633. package/dist/plan-limit-pause.test.d.ts +2 -0
  634. package/dist/plan-limit-pause.test.d.ts.map +1 -0
  635. package/dist/plan-limit-pause.test.js +150 -0
  636. package/dist/plan-limit-pause.test.js.map +1 -0
  637. package/dist/plan-limit.fixtures.d.ts +34 -0
  638. package/dist/plan-limit.fixtures.d.ts.map +1 -0
  639. package/dist/plan-limit.fixtures.js +96 -0
  640. package/dist/plan-limit.fixtures.js.map +1 -0
  641. package/dist/plan-limit.test.d.ts +2 -0
  642. package/dist/plan-limit.test.d.ts.map +1 -0
  643. package/dist/plan-limit.test.js +132 -0
  644. package/dist/plan-limit.test.js.map +1 -0
  645. package/dist/prefix-coalesce.test.d.ts +2 -0
  646. package/dist/prefix-coalesce.test.d.ts.map +1 -0
  647. package/dist/prefix-coalesce.test.js +260 -0
  648. package/dist/prefix-coalesce.test.js.map +1 -0
  649. package/dist/private-folder-transport.test.d.ts +2 -0
  650. package/dist/private-folder-transport.test.d.ts.map +1 -0
  651. package/dist/private-folder-transport.test.js +33 -0
  652. package/dist/private-folder-transport.test.js.map +1 -0
  653. package/dist/public-surface.test.d.ts +15 -0
  654. package/dist/public-surface.test.d.ts.map +1 -0
  655. package/dist/public-surface.test.js +110 -0
  656. package/dist/public-surface.test.js.map +1 -0
  657. package/dist/qmd-reindex.test.d.ts +14 -0
  658. package/dist/qmd-reindex.test.d.ts.map +1 -0
  659. package/dist/qmd-reindex.test.js +904 -0
  660. package/dist/qmd-reindex.test.js.map +1 -0
  661. package/dist/read-only-state-dir.test.d.ts +27 -0
  662. package/dist/read-only-state-dir.test.d.ts.map +1 -0
  663. package/dist/read-only-state-dir.test.js +210 -0
  664. package/dist/read-only-state-dir.test.js.map +1 -0
  665. package/dist/remote-pull.test.d.ts +2 -0
  666. package/dist/remote-pull.test.d.ts.map +1 -0
  667. package/dist/remote-pull.test.js +1147 -0
  668. package/dist/remote-pull.test.js.map +1 -0
  669. package/dist/s3-download-stream-hash.test.d.ts +2 -0
  670. package/dist/s3-download-stream-hash.test.d.ts.map +1 -0
  671. package/dist/s3-download-stream-hash.test.js +70 -0
  672. package/dist/s3-download-stream-hash.test.js.map +1 -0
  673. package/dist/s3.list-cost.test.d.ts +2 -0
  674. package/dist/s3.list-cost.test.d.ts.map +1 -0
  675. package/dist/s3.list-cost.test.js +51 -0
  676. package/dist/s3.list-cost.test.js.map +1 -0
  677. package/dist/s3.rename-retry.test.d.ts +2 -0
  678. package/dist/s3.rename-retry.test.d.ts.map +1 -0
  679. package/dist/s3.rename-retry.test.js +217 -0
  680. package/dist/s3.rename-retry.test.js.map +1 -0
  681. package/dist/s3.symlink-materialize.test.d.ts +18 -0
  682. package/dist/s3.symlink-materialize.test.d.ts.map +1 -0
  683. package/dist/s3.symlink-materialize.test.js +591 -0
  684. package/dist/s3.symlink-materialize.test.js.map +1 -0
  685. package/dist/s3.test.d.ts +9 -0
  686. package/dist/s3.test.d.ts.map +1 -0
  687. package/dist/s3.test.js +2091 -0
  688. package/dist/s3.test.js.map +1 -0
  689. package/dist/s3.windows-portability.test.d.ts +12 -0
  690. package/dist/s3.windows-portability.test.d.ts.map +1 -0
  691. package/dist/s3.windows-portability.test.js +228 -0
  692. package/dist/s3.windows-portability.test.js.map +1 -0
  693. package/dist/schemas/signal-types.test.d.ts +2 -0
  694. package/dist/schemas/signal-types.test.d.ts.map +1 -0
  695. package/dist/schemas/signal-types.test.js +65 -0
  696. package/dist/schemas/signal-types.test.js.map +1 -0
  697. package/dist/schemas/source-channels.test.d.ts +2 -0
  698. package/dist/schemas/source-channels.test.d.ts.map +1 -0
  699. package/dist/schemas/source-channels.test.js +65 -0
  700. package/dist/schemas/source-channels.test.js.map +1 -0
  701. package/dist/scope-shrink.test.d.ts +13 -0
  702. package/dist/scope-shrink.test.d.ts.map +1 -0
  703. package/dist/scope-shrink.test.js +558 -0
  704. package/dist/scope-shrink.test.js.map +1 -0
  705. package/dist/session-log-capture.test.d.ts +2 -0
  706. package/dist/session-log-capture.test.d.ts.map +1 -0
  707. package/dist/session-log-capture.test.js +533 -0
  708. package/dist/session-log-capture.test.js.map +1 -0
  709. package/dist/session-log-retention.test.d.ts +2 -0
  710. package/dist/session-log-retention.test.d.ts.map +1 -0
  711. package/dist/session-log-retention.test.js +383 -0
  712. package/dist/session-log-retention.test.js.map +1 -0
  713. package/dist/signals/get.test.d.ts +5 -0
  714. package/dist/signals/get.test.d.ts.map +1 -0
  715. package/dist/signals/get.test.js +254 -0
  716. package/dist/signals/get.test.js.map +1 -0
  717. package/dist/signals/list.test.d.ts +9 -0
  718. package/dist/signals/list.test.d.ts.map +1 -0
  719. package/dist/signals/list.test.js +330 -0
  720. package/dist/signals/list.test.js.map +1 -0
  721. package/dist/skill-telemetry.test.d.ts +2 -0
  722. package/dist/skill-telemetry.test.d.ts.map +1 -0
  723. package/dist/skill-telemetry.test.js +1484 -0
  724. package/dist/skill-telemetry.test.js.map +1 -0
  725. package/dist/sources/get.test.d.ts +5 -0
  726. package/dist/sources/get.test.d.ts.map +1 -0
  727. package/dist/sources/get.test.js +236 -0
  728. package/dist/sources/get.test.js.map +1 -0
  729. package/dist/sources/list.test.d.ts +8 -0
  730. package/dist/sources/list.test.d.ts.map +1 -0
  731. package/dist/sources/list.test.js +318 -0
  732. package/dist/sources/list.test.js.map +1 -0
  733. package/dist/sts-credential-refresh.test.d.ts +2 -0
  734. package/dist/sts-credential-refresh.test.d.ts.map +1 -0
  735. package/dist/sts-credential-refresh.test.js +181 -0
  736. package/dist/sts-credential-refresh.test.js.map +1 -0
  737. package/dist/swallowed-error-sites.test.d.ts +2 -0
  738. package/dist/swallowed-error-sites.test.d.ts.map +1 -0
  739. package/dist/swallowed-error-sites.test.js +209 -0
  740. package/dist/swallowed-error-sites.test.js.map +1 -0
  741. package/dist/swallowed-error-w32.test.d.ts +2 -0
  742. package/dist/swallowed-error-w32.test.d.ts.map +1 -0
  743. package/dist/swallowed-error-w32.test.js +186 -0
  744. package/dist/swallowed-error-w32.test.js.map +1 -0
  745. package/dist/swallowed-error-w33.test.d.ts +2 -0
  746. package/dist/swallowed-error-w33.test.d.ts.map +1 -0
  747. package/dist/swallowed-error-w33.test.js +136 -0
  748. package/dist/swallowed-error-w33.test.js.map +1 -0
  749. package/dist/swallowed-error-w34.test.d.ts +2 -0
  750. package/dist/swallowed-error-w34.test.d.ts.map +1 -0
  751. package/dist/swallowed-error-w34.test.js +110 -0
  752. package/dist/swallowed-error-w34.test.js.map +1 -0
  753. package/dist/swallowed-error-w35.test.d.ts +2 -0
  754. package/dist/swallowed-error-w35.test.d.ts.map +1 -0
  755. package/dist/swallowed-error-w35.test.js +237 -0
  756. package/dist/swallowed-error-w35.test.js.map +1 -0
  757. package/dist/sync/area-ledger-auto-migration.test.d.ts +2 -0
  758. package/dist/sync/area-ledger-auto-migration.test.d.ts.map +1 -0
  759. package/dist/sync/area-ledger-auto-migration.test.js +291 -0
  760. package/dist/sync/area-ledger-auto-migration.test.js.map +1 -0
  761. package/dist/sync/area-ledger-migration.test.d.ts +2 -0
  762. package/dist/sync/area-ledger-migration.test.d.ts.map +1 -0
  763. package/dist/sync/area-ledger-migration.test.js +554 -0
  764. package/dist/sync/area-ledger-migration.test.js.map +1 -0
  765. package/dist/sync/area-ledger-recovery.bench.test.d.ts +2 -0
  766. package/dist/sync/area-ledger-recovery.bench.test.d.ts.map +1 -0
  767. package/dist/sync/area-ledger-recovery.bench.test.js +60 -0
  768. package/dist/sync/area-ledger-recovery.bench.test.js.map +1 -0
  769. package/dist/sync/area-ledger-writer-lock.bench.test.d.ts +2 -0
  770. package/dist/sync/area-ledger-writer-lock.bench.test.d.ts.map +1 -0
  771. package/dist/sync/area-ledger-writer-lock.bench.test.js +57 -0
  772. package/dist/sync/area-ledger-writer-lock.bench.test.js.map +1 -0
  773. package/dist/sync/area-ledger.test.d.ts +2 -0
  774. package/dist/sync/area-ledger.test.d.ts.map +1 -0
  775. package/dist/sync/area-ledger.test.js +1401 -0
  776. package/dist/sync/area-ledger.test.js.map +1 -0
  777. package/dist/sync/area-resolver.test.d.ts +2 -0
  778. package/dist/sync/area-resolver.test.d.ts.map +1 -0
  779. package/dist/sync/area-resolver.test.js +234 -0
  780. package/dist/sync/area-resolver.test.js.map +1 -0
  781. package/dist/sync/base-version-resolver.test.d.ts +2 -0
  782. package/dist/sync/base-version-resolver.test.d.ts.map +1 -0
  783. package/dist/sync/base-version-resolver.test.js +24 -0
  784. package/dist/sync/base-version-resolver.test.js.map +1 -0
  785. package/dist/sync/candidate-uploader.test.d.ts +2 -0
  786. package/dist/sync/candidate-uploader.test.d.ts.map +1 -0
  787. package/dist/sync/candidate-uploader.test.js +132 -0
  788. package/dist/sync/candidate-uploader.test.js.map +1 -0
  789. package/dist/sync/child-process-sync-worker-env.test.d.ts +2 -0
  790. package/dist/sync/child-process-sync-worker-env.test.d.ts.map +1 -0
  791. package/dist/sync/child-process-sync-worker-env.test.js +38 -0
  792. package/dist/sync/child-process-sync-worker-env.test.js.map +1 -0
  793. package/dist/sync/child-process-sync-worker-errors.test.d.ts +2 -0
  794. package/dist/sync/child-process-sync-worker-errors.test.d.ts.map +1 -0
  795. package/dist/sync/child-process-sync-worker-errors.test.js +121 -0
  796. package/dist/sync/child-process-sync-worker-errors.test.js.map +1 -0
  797. package/dist/sync/child-process-sync-worker.test.d.ts +2 -0
  798. package/dist/sync/child-process-sync-worker.test.d.ts.map +1 -0
  799. package/dist/sync/child-process-sync-worker.test.js +279 -0
  800. package/dist/sync/child-process-sync-worker.test.js.map +1 -0
  801. package/dist/sync/content-hash.test.d.ts +2 -0
  802. package/dist/sync/content-hash.test.d.ts.map +1 -0
  803. package/dist/sync/content-hash.test.js +16 -0
  804. package/dist/sync/content-hash.test.js.map +1 -0
  805. package/dist/sync/delta-client.test.d.ts +2 -0
  806. package/dist/sync/delta-client.test.d.ts.map +1 -0
  807. package/dist/sync/delta-client.test.js +97 -0
  808. package/dist/sync/delta-client.test.js.map +1 -0
  809. package/dist/sync/durable-apply.test.d.ts +2 -0
  810. package/dist/sync/durable-apply.test.d.ts.map +1 -0
  811. package/dist/sync/durable-apply.test.js +187 -0
  812. package/dist/sync/durable-apply.test.js.map +1 -0
  813. package/dist/sync/event-sync.test.d.ts +14 -0
  814. package/dist/sync/event-sync.test.d.ts.map +1 -0
  815. package/dist/sync/event-sync.test.js +1717 -0
  816. package/dist/sync/event-sync.test.js.map +1 -0
  817. package/dist/sync/feature-flags.test.d.ts +24 -0
  818. package/dist/sync/feature-flags.test.d.ts.map +1 -0
  819. package/dist/sync/feature-flags.test.js +594 -0
  820. package/dist/sync/feature-flags.test.js.map +1 -0
  821. package/dist/sync/fsync-compat.test.d.ts +2 -0
  822. package/dist/sync/fsync-compat.test.d.ts.map +1 -0
  823. package/dist/sync/fsync-compat.test.js +52 -0
  824. package/dist/sync/fsync-compat.test.js.map +1 -0
  825. package/dist/sync/full-pass-cap-governor.bench.test.d.ts +2 -0
  826. package/dist/sync/full-pass-cap-governor.bench.test.d.ts.map +1 -0
  827. package/dist/sync/full-pass-cap-governor.bench.test.js +179 -0
  828. package/dist/sync/full-pass-cap-governor.bench.test.js.map +1 -0
  829. package/dist/sync/full-pass-caps.test.d.ts +2 -0
  830. package/dist/sync/full-pass-caps.test.d.ts.map +1 -0
  831. package/dist/sync/full-pass-caps.test.js +550 -0
  832. package/dist/sync/full-pass-caps.test.js.map +1 -0
  833. package/dist/sync/idle-full-reconcile.test.d.ts +2 -0
  834. package/dist/sync/idle-full-reconcile.test.d.ts.map +1 -0
  835. package/dist/sync/idle-full-reconcile.test.js +62 -0
  836. package/dist/sync/idle-full-reconcile.test.js.map +1 -0
  837. package/dist/sync/inbound-event-admission.test.d.ts +2 -0
  838. package/dist/sync/inbound-event-admission.test.d.ts.map +1 -0
  839. package/dist/sync/inbound-event-admission.test.js +128 -0
  840. package/dist/sync/inbound-event-admission.test.js.map +1 -0
  841. package/dist/sync/journal-ledger-stream.test.d.ts +12 -0
  842. package/dist/sync/journal-ledger-stream.test.d.ts.map +1 -0
  843. package/dist/sync/journal-ledger-stream.test.js +134 -0
  844. package/dist/sync/journal-ledger-stream.test.js.map +1 -0
  845. package/dist/sync/lease-client.test.d.ts +2 -0
  846. package/dist/sync/lease-client.test.d.ts.map +1 -0
  847. package/dist/sync/lease-client.test.js +119 -0
  848. package/dist/sync/lease-client.test.js.map +1 -0
  849. package/dist/sync/logger.test.d.ts +19 -0
  850. package/dist/sync/logger.test.d.ts.map +1 -0
  851. package/dist/sync/logger.test.js +204 -0
  852. package/dist/sync/logger.test.js.map +1 -0
  853. package/dist/sync/metrics.test.d.ts +19 -0
  854. package/dist/sync/metrics.test.d.ts.map +1 -0
  855. package/dist/sync/metrics.test.js +357 -0
  856. package/dist/sync/metrics.test.js.map +1 -0
  857. package/dist/sync/multipart-uploader.test.d.ts +2 -0
  858. package/dist/sync/multipart-uploader.test.d.ts.map +1 -0
  859. package/dist/sync/multipart-uploader.test.js +141 -0
  860. package/dist/sync/multipart-uploader.test.js.map +1 -0
  861. package/dist/sync/mutation-client.test.d.ts +2 -0
  862. package/dist/sync/mutation-client.test.d.ts.map +1 -0
  863. package/dist/sync/mutation-client.test.js +100 -0
  864. package/dist/sync/mutation-client.test.js.map +1 -0
  865. package/dist/sync/mutation-session.test.d.ts +2 -0
  866. package/dist/sync/mutation-session.test.d.ts.map +1 -0
  867. package/dist/sync/mutation-session.test.js +190 -0
  868. package/dist/sync/mutation-session.test.js.map +1 -0
  869. package/dist/sync/parallel-sync-coordinator.test.d.ts +2 -0
  870. package/dist/sync/parallel-sync-coordinator.test.d.ts.map +1 -0
  871. package/dist/sync/parallel-sync-coordinator.test.js +564 -0
  872. package/dist/sync/parallel-sync-coordinator.test.js.map +1 -0
  873. package/dist/sync/path-leases.test.d.ts +2 -0
  874. package/dist/sync/path-leases.test.d.ts.map +1 -0
  875. package/dist/sync/path-leases.test.js +51 -0
  876. package/dist/sync/path-leases.test.js.map +1 -0
  877. package/dist/sync/per-area-maintenance.test.d.ts +2 -0
  878. package/dist/sync/per-area-maintenance.test.d.ts.map +1 -0
  879. package/dist/sync/per-area-maintenance.test.js +100 -0
  880. package/dist/sync/per-area-maintenance.test.js.map +1 -0
  881. package/dist/sync/push-event.test.d.ts +15 -0
  882. package/dist/sync/push-event.test.d.ts.map +1 -0
  883. package/dist/sync/push-event.test.js +282 -0
  884. package/dist/sync/push-event.test.js.map +1 -0
  885. package/dist/sync/push-receiver.test.d.ts +25 -0
  886. package/dist/sync/push-receiver.test.d.ts.map +1 -0
  887. package/dist/sync/push-receiver.test.js +2851 -0
  888. package/dist/sync/push-receiver.test.js.map +1 -0
  889. package/dist/sync/push-transport.test.d.ts +2 -0
  890. package/dist/sync/push-transport.test.d.ts.map +1 -0
  891. package/dist/sync/push-transport.test.js +70 -0
  892. package/dist/sync/push-transport.test.js.map +1 -0
  893. package/dist/sync/push-walk-matchers.bench.test.d.ts +2 -0
  894. package/dist/sync/push-walk-matchers.bench.test.d.ts.map +1 -0
  895. package/dist/sync/push-walk-matchers.bench.test.js +230 -0
  896. package/dist/sync/push-walk-matchers.bench.test.js.map +1 -0
  897. package/dist/sync/realtime-network-integration.test.d.ts +2 -0
  898. package/dist/sync/realtime-network-integration.test.d.ts.map +1 -0
  899. package/dist/sync/realtime-network-integration.test.js +83 -0
  900. package/dist/sync/realtime-network-integration.test.js.map +1 -0
  901. package/dist/sync/realtime-rollout.test.d.ts +2 -0
  902. package/dist/sync/realtime-rollout.test.d.ts.map +1 -0
  903. package/dist/sync/realtime-rollout.test.js +94 -0
  904. package/dist/sync/realtime-rollout.test.js.map +1 -0
  905. package/dist/sync/realtime-telemetry.test.d.ts +2 -0
  906. package/dist/sync/realtime-telemetry.test.d.ts.map +1 -0
  907. package/dist/sync/realtime-telemetry.test.js +300 -0
  908. package/dist/sync/realtime-telemetry.test.js.map +1 -0
  909. package/dist/sync/receiver-origin-config.test.d.ts +2 -0
  910. package/dist/sync/receiver-origin-config.test.d.ts.map +1 -0
  911. package/dist/sync/receiver-origin-config.test.js +39 -0
  912. package/dist/sync/receiver-origin-config.test.js.map +1 -0
  913. package/dist/sync/reconcile-cursor.test.d.ts +2 -0
  914. package/dist/sync/reconcile-cursor.test.d.ts.map +1 -0
  915. package/dist/sync/reconcile-cursor.test.js +139 -0
  916. package/dist/sync/reconcile-cursor.test.js.map +1 -0
  917. package/dist/sync/remote-file-spool.test.d.ts +2 -0
  918. package/dist/sync/remote-file-spool.test.d.ts.map +1 -0
  919. package/dist/sync/remote-file-spool.test.js +79 -0
  920. package/dist/sync/remote-file-spool.test.js.map +1 -0
  921. package/dist/sync/scope-inventory-client.test.d.ts +2 -0
  922. package/dist/sync/scope-inventory-client.test.d.ts.map +1 -0
  923. package/dist/sync/scope-inventory-client.test.js +110 -0
  924. package/dist/sync/scope-inventory-client.test.js.map +1 -0
  925. package/dist/sync/secret-path-policy.test.d.ts +2 -0
  926. package/dist/sync/secret-path-policy.test.d.ts.map +1 -0
  927. package/dist/sync/secret-path-policy.test.js +183 -0
  928. package/dist/sync/secret-path-policy.test.js.map +1 -0
  929. package/dist/sync/snapshot-client.test.d.ts +2 -0
  930. package/dist/sync/snapshot-client.test.d.ts.map +1 -0
  931. package/dist/sync/snapshot-client.test.js +169 -0
  932. package/dist/sync/snapshot-client.test.js.map +1 -0
  933. package/dist/sync/state-store.test.d.ts +2 -0
  934. package/dist/sync/state-store.test.d.ts.map +1 -0
  935. package/dist/sync/state-store.test.js +1556 -0
  936. package/dist/sync/state-store.test.js.map +1 -0
  937. package/dist/sync/sync-contract.test.d.ts +2 -0
  938. package/dist/sync/sync-contract.test.d.ts.map +1 -0
  939. package/dist/sync/sync-contract.test.js +141 -0
  940. package/dist/sync/sync-contract.test.js.map +1 -0
  941. package/dist/sync/targeted-pull-prefixes.test.d.ts +2 -0
  942. package/dist/sync/targeted-pull-prefixes.test.d.ts.map +1 -0
  943. package/dist/sync/targeted-pull-prefixes.test.js +33 -0
  944. package/dist/sync/targeted-pull-prefixes.test.js.map +1 -0
  945. package/dist/sync/targeted-upsert-exact-list.test.d.ts +2 -0
  946. package/dist/sync/targeted-upsert-exact-list.test.d.ts.map +1 -0
  947. package/dist/sync/targeted-upsert-exact-list.test.js +247 -0
  948. package/dist/sync/targeted-upsert-exact-list.test.js.map +1 -0
  949. package/dist/sync/unchanged-push-events.test.d.ts +2 -0
  950. package/dist/sync/unchanged-push-events.test.d.ts.map +1 -0
  951. package/dist/sync/unchanged-push-events.test.js +76 -0
  952. package/dist/sync/unchanged-push-events.test.js.map +1 -0
  953. package/dist/sync/uploader-finalization.test.d.ts +2 -0
  954. package/dist/sync/uploader-finalization.test.d.ts.map +1 -0
  955. package/dist/sync/uploader-finalization.test.js +107 -0
  956. package/dist/sync/uploader-finalization.test.js.map +1 -0
  957. package/dist/sync-core.test.d.ts +2 -0
  958. package/dist/sync-core.test.d.ts.map +1 -0
  959. package/dist/sync-core.test.js +189 -0
  960. package/dist/sync-core.test.js.map +1 -0
  961. package/dist/sync-progress.test.d.ts +2 -0
  962. package/dist/sync-progress.test.d.ts.map +1 -0
  963. package/dist/sync-progress.test.js +277 -0
  964. package/dist/sync-progress.test.js.map +1 -0
  965. package/dist/telemetry-events.test.d.ts +2 -0
  966. package/dist/telemetry-events.test.d.ts.map +1 -0
  967. package/dist/telemetry-events.test.js +113 -0
  968. package/dist/telemetry-events.test.js.map +1 -0
  969. package/dist/telemetry.test.d.ts +11 -0
  970. package/dist/telemetry.test.d.ts.map +1 -0
  971. package/dist/telemetry.test.js +1603 -0
  972. package/dist/telemetry.test.js.map +1 -0
  973. package/dist/vault-client.test.d.ts +7 -0
  974. package/dist/vault-client.test.d.ts.map +1 -0
  975. package/dist/vault-client.test.js +1334 -0
  976. package/dist/vault-client.test.js.map +1 -0
  977. package/dist/watch-coverage.test.d.ts +2 -0
  978. package/dist/watch-coverage.test.d.ts.map +1 -0
  979. package/dist/watch-coverage.test.js +56 -0
  980. package/dist/watch-coverage.test.js.map +1 -0
  981. package/dist/watch-owner-lease.test.d.ts +2 -0
  982. package/dist/watch-owner-lease.test.d.ts.map +1 -0
  983. package/dist/watch-owner-lease.test.js +364 -0
  984. package/dist/watch-owner-lease.test.js.map +1 -0
  985. package/dist/watch-parent.test.d.ts +2 -0
  986. package/dist/watch-parent.test.d.ts.map +1 -0
  987. package/dist/watch-parent.test.js +131 -0
  988. package/dist/watch-parent.test.js.map +1 -0
  989. package/dist/watch-roots.test.d.ts +18 -0
  990. package/dist/watch-roots.test.d.ts.map +1 -0
  991. package/dist/watch-roots.test.js +395 -0
  992. package/dist/watch-roots.test.js.map +1 -0
  993. package/dist/watcher-continuity-hot-path.test.d.ts +2 -0
  994. package/dist/watcher-continuity-hot-path.test.d.ts.map +1 -0
  995. package/dist/watcher-continuity-hot-path.test.js +40 -0
  996. package/dist/watcher-continuity-hot-path.test.js.map +1 -0
  997. package/dist/watcher-event-gate.test.d.ts +16 -0
  998. package/dist/watcher-event-gate.test.d.ts.map +1 -0
  999. package/dist/watcher-event-gate.test.js +191 -0
  1000. package/dist/watcher-event-gate.test.js.map +1 -0
  1001. package/dist/watcher-replan-sweep.test.d.ts +2 -0
  1002. package/dist/watcher-replan-sweep.test.d.ts.map +1 -0
  1003. package/dist/watcher-replan-sweep.test.js +260 -0
  1004. package/dist/watcher-replan-sweep.test.js.map +1 -0
  1005. package/dist/watcher-stdout.test.d.ts +2 -0
  1006. package/dist/watcher-stdout.test.d.ts.map +1 -0
  1007. package/dist/watcher-stdout.test.js +86 -0
  1008. package/dist/watcher-stdout.test.js.map +1 -0
  1009. package/dist/watcher.test.d.ts +2 -0
  1010. package/dist/watcher.test.d.ts.map +1 -0
  1011. package/dist/watcher.test.js +4329 -0
  1012. package/dist/watcher.test.js.map +1 -0
  1013. package/dist/watcher.warmup-cancel.test.d.ts +2 -0
  1014. package/dist/watcher.warmup-cancel.test.d.ts.map +1 -0
  1015. package/dist/watcher.warmup-cancel.test.js +59 -0
  1016. package/dist/watcher.warmup-cancel.test.js.map +1 -0
  1017. package/dist/watcher.warmup-responsive.test.d.ts +2 -0
  1018. package/dist/watcher.warmup-responsive.test.d.ts.map +1 -0
  1019. package/dist/watcher.warmup-responsive.test.js +62 -0
  1020. package/dist/watcher.warmup-responsive.test.js.map +1 -0
  1021. package/package.json +2 -2
@@ -0,0 +1,4329 @@
1
+ import { afterEach, beforeEach, describe, it, expect, vi } from "vitest";
2
+ import { EventEmitter } from "node:events";
3
+ import * as fs from "fs";
4
+ import * as os from "os";
5
+ import * as path from "path";
6
+ import { createHash } from "node:crypto";
7
+ import { monitorEventLoopDelay } from "node:perf_hooks";
8
+ import { watch } from "chokidar";
9
+ import { FakeClock, WatchPushDriver, TreeWatcher, ChokidarWatchBudget, createWatchPathFilter, toChokidarIgnored, PushEventEmitter, PUBLISH_OUTCOME_JOURNALD_CEILING_BYTES, PUBLISH_OUTCOME_SUCCESS_SAMPLE_CAP, resolveEventDebounceConfig, summarizePublishBatchOutcome, DEFAULT_EVENT_DEBOUNCE_MS, DEFAULT_EVENT_MAX_WAIT_MS, DEFAULT_EVENT_SMALL_BATCH_DEBOUNCE_MS, DEFAULT_EVENT_SMALL_BATCH_MAX_PATHS, DEFAULT_EVENT_SMALL_BATCH_MAX_BYTES, DEFAULT_PUBLISH_MIN_INTERVAL_MS, EVENT_DEBOUNCE_MS_ENV, EVENT_MAX_WAIT_MS_ENV, EVENT_SMALL_BATCH_DEBOUNCE_MS_ENV, EVENT_SMALL_BATCH_MAX_PATHS_ENV, EVENT_SMALL_BATCH_MAX_BYTES_ENV, DEFAULT_TREE_WATCHER_MAX_WATCHED_PATHS, MAX_TREE_WATCHER_MAX_WATCHED_PATHS, TREE_WATCHER_MAX_WATCHED_PATHS_ENV, resolveMaxWatchedPaths, PUBLISH_MIN_INTERVAL_MS_ENV, resolvePublishMinIntervalMs, DurablePublishedContentHashes, DURABLE_PUBLISHED_HASH_BATCH_FLUSH_MS, replayDurablePublishedContentHashRecordsForTest, startScopedRecursiveWatch, startNativeRootWatch, startTreeWatch, selectTreeWatchBackend } from "./watcher.js";
10
+ import { StateStore, StateStoreLockError } from "./sync/state-store.js";
11
+ import { HttpPushTransport, PushScopeForbiddenError, RealtimeUnavailableError, } from "./sync/push-transport.js";
12
+ import { computePersonalVaultPaths } from "./personal-vault.js";
13
+ /**
14
+ * US-001 — Phase 1 test harness: watch-triggered push seam + latency assertion.
15
+ *
16
+ * These tests drive the debounce/coalesce core ({@link WatchPushDriver}) with an
17
+ * injected {@link FakeClock} and an injected spy push fn — no real chokidar
18
+ * watcher, no real S3, no real 10-minute sleep. US-002/US-003 build the real
19
+ * watcher + targeted-push fn on top of this same seam, so the tests here also
20
+ * serve as regression guards for the contract those stories depend on.
21
+ */
22
+ const DEBOUNCE = 2000;
23
+ describe("scoped watcher resource errors", () => {
24
+ let root;
25
+ beforeEach(() => {
26
+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "watch-resource-error-")));
27
+ });
28
+ afterEach(() => {
29
+ fs.rmSync(root, { recursive: true, force: true });
30
+ });
31
+ it("does not reopen a directory watch after EMFILE", () => {
32
+ const docs = path.join(root, "docs");
33
+ fs.mkdirSync(docs);
34
+ class FakeWatcher extends EventEmitter {
35
+ close() {
36
+ this.emit("close");
37
+ return this;
38
+ }
39
+ }
40
+ const handles = new Map();
41
+ const watchedPaths = [];
42
+ const backend = startScopedRecursiveWatch(root, createWatchPathFilter(root, false), () => { }, () => { }, undefined, {
43
+ recursiveWatches: false,
44
+ listChildDirs: (dir) => dir === root ? [docs] : [],
45
+ watchDirectory: (dir) => {
46
+ const watchPath = dir.toString();
47
+ watchedPaths.push(watchPath);
48
+ const handle = new FakeWatcher();
49
+ handles.set(watchPath, handle);
50
+ return handle;
51
+ },
52
+ });
53
+ try {
54
+ expect(watchedPaths.filter((dir) => dir === docs)).toHaveLength(1);
55
+ handles.get(docs).emit("error", Object.assign(new Error("too many open files"), { code: "EMFILE" }));
56
+ expect(watchedPaths.filter((dir) => dir === docs)).toHaveLength(1);
57
+ }
58
+ finally {
59
+ backend.close();
60
+ }
61
+ });
62
+ });
63
+ function publishedHashRecords(count) {
64
+ const maxPaths = Math.max(1, Math.floor(count / 2));
65
+ let seed = 0x14c0ffee;
66
+ const next = () => {
67
+ seed = (seed * 1_664_525 + 1_013_904_223) >>> 0;
68
+ return seed;
69
+ };
70
+ return Array.from({ length: count }, (_, index) => {
71
+ const relativePath = `path-${next() % maxPaths}`;
72
+ return next() % 5 === 0
73
+ ? { sequence: index + 1, type: 0x5032, flags: 0, payload: { relativePath } }
74
+ : {
75
+ sequence: index + 1,
76
+ type: 0x5031,
77
+ flags: 0,
78
+ payload: { relativePath, contentHash: `sha256:${next()}`, maxPaths },
79
+ };
80
+ });
81
+ }
82
+ /**
83
+ * Build a driver wired to a FakeClock and a spy push fn. Returns everything a
84
+ * test needs to drive and assert against the seam. This helper is the reusable
85
+ * "test harness" the story asks for.
86
+ */
87
+ function makeHarness(opts) {
88
+ const clock = new FakeClock();
89
+ const push = vi.fn(() => { });
90
+ const driver = new WatchPushDriver({
91
+ debounceMs: opts?.debounceMs ?? DEBOUNCE,
92
+ clock,
93
+ push,
94
+ });
95
+ return {
96
+ clock,
97
+ push,
98
+ driver,
99
+ /** Emit a synthetic file-change event into the driver. */
100
+ emitChange: () => driver.notifyChange(),
101
+ /** Advance virtual time. */
102
+ advance: (ms) => clock.advance(ms),
103
+ };
104
+ }
105
+ async function flushImmediate() {
106
+ await new Promise((resolve) => setImmediate(resolve));
107
+ }
108
+ describe("FakeClock", () => {
109
+ it("fires a timer exactly when its deadline is reached", () => {
110
+ const clock = new FakeClock();
111
+ const fn = vi.fn();
112
+ clock.setTimeout(fn, 100);
113
+ clock.advance(99);
114
+ expect(fn).not.toHaveBeenCalled();
115
+ clock.advance(1);
116
+ expect(fn).toHaveBeenCalledTimes(1);
117
+ });
118
+ it("does not fire a cleared timer", () => {
119
+ const clock = new FakeClock();
120
+ const fn = vi.fn();
121
+ const handle = clock.setTimeout(fn, 100);
122
+ clock.clearTimeout(handle);
123
+ clock.advance(1000);
124
+ expect(fn).not.toHaveBeenCalled();
125
+ expect(clock.pendingTimerCount()).toBe(0);
126
+ });
127
+ it("reports pending timer count for leak checks", () => {
128
+ const clock = new FakeClock();
129
+ clock.setTimeout(() => { }, 100);
130
+ clock.setTimeout(() => { }, 200);
131
+ expect(clock.pendingTimerCount()).toBe(2);
132
+ clock.advance(100);
133
+ expect(clock.pendingTimerCount()).toBe(1);
134
+ });
135
+ });
136
+ describe("TreeWatcher adaptive watch budget", () => {
137
+ it("uses half of Linux max_user_watches, bounded by the floor and ceiling", () => {
138
+ const readFileSync = vi.fn(() => "1048576\n");
139
+ expect(resolveMaxWatchedPaths(undefined, {
140
+ platform: "linux",
141
+ env: {},
142
+ readFileSync,
143
+ })).toBe(MAX_TREE_WATCHER_MAX_WATCHED_PATHS);
144
+ expect(readFileSync).toHaveBeenCalledWith("/proc/sys/fs/inotify/max_user_watches", "utf8");
145
+ expect(resolveMaxWatchedPaths(undefined, {
146
+ platform: "linux",
147
+ env: {},
148
+ readFileSync: () => "40000\n",
149
+ })).toBe(DEFAULT_TREE_WATCHER_MAX_WATCHED_PATHS);
150
+ expect(resolveMaxWatchedPaths(undefined, {
151
+ platform: "linux",
152
+ env: {},
153
+ readFileSync: () => "8192\n",
154
+ })).toBe(4096);
155
+ });
156
+ it("keeps an explicit environment override authoritative", () => {
157
+ expect(resolveMaxWatchedPaths(undefined, {
158
+ platform: "linux",
159
+ env: { [TREE_WATCHER_MAX_WATCHED_PATHS_ENV]: "500000" },
160
+ readFileSync: () => {
161
+ throw new Error("must not read when overridden");
162
+ },
163
+ })).toBe(500_000);
164
+ });
165
+ it("falls back to the established constant off Linux or when proc is unreadable", () => {
166
+ expect(resolveMaxWatchedPaths(undefined, {
167
+ platform: "darwin",
168
+ env: {},
169
+ readFileSync: () => "1048576\n",
170
+ })).toBe(DEFAULT_TREE_WATCHER_MAX_WATCHED_PATHS);
171
+ expect(resolveMaxWatchedPaths(undefined, {
172
+ platform: "linux",
173
+ env: {},
174
+ readFileSync: () => {
175
+ throw new Error("proc unavailable");
176
+ },
177
+ })).toBe(DEFAULT_TREE_WATCHER_MAX_WATCHED_PATHS);
178
+ });
179
+ });
180
+ describe("TreeWatcher pending backlog caps", () => {
181
+ it("collects only warm-up mutations plus journal-backed deletions in one local scan", () => {
182
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watcher-warmup-"));
183
+ try {
184
+ for (let i = 0; i < 12; i++)
185
+ fs.writeFileSync(path.join(dir, `unchanged-${i}.md`), "old");
186
+ const settle = Date.now() + 50;
187
+ while (Date.now() < settle) { /* let old ctime settle below the cutoff */ }
188
+ const cutoff = Date.now();
189
+ while (Date.now() < cutoff + 50) { /* filesystems may round ctime down */ }
190
+ const fresh = path.join(dir, "created-during-warmup.md");
191
+ fs.writeFileSync(fresh, "new");
192
+ const capture = vi.fn(() => []);
193
+ const watcher = new TreeWatcher({
194
+ hqRoot: dir,
195
+ pathFilter: () => true,
196
+ captureLocalDeleteSnapshots: capture,
197
+ });
198
+ const result = watcher.collectWarmupCatchup(cutoff, ["gone-during-warmup.md"]);
199
+ expect([...result.batch.paths.values()]).toEqual([
200
+ "created-during-warmup.md",
201
+ "gone-during-warmup.md",
202
+ ]);
203
+ expect(result.batch.changes?.get(path.join(dir, "gone-during-warmup.md")))
204
+ .toMatchObject({ kind: "unlink" });
205
+ expect(capture).toHaveBeenCalledWith("gone-during-warmup.md", "unlink");
206
+ expect(result.scannedPaths).toBe(13);
207
+ }
208
+ finally {
209
+ fs.rmSync(dir, { recursive: true, force: true });
210
+ }
211
+ });
212
+ it("yields through a 50k-row warm-up journal catch-up without losing coverage", async () => {
213
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watcher-warmup-yield-"));
214
+ try {
215
+ const watcher = new TreeWatcher({ hqRoot: dir, pathFilter: () => true });
216
+ const journalRows = Array.from({ length: 50_000 }, (_, index) => `personal/missing-${index}.md`);
217
+ const histogram = monitorEventLoopDelay({ resolution: 1 });
218
+ let eventLoopTicks = 0;
219
+ let keepTicking = true;
220
+ const tick = () => {
221
+ if (!keepTicking)
222
+ return;
223
+ eventLoopTicks += 1;
224
+ setImmediate(tick);
225
+ };
226
+ histogram.enable();
227
+ setImmediate(tick);
228
+ const result = await watcher.collectWarmupCatchupAsync(Date.now(), journalRows);
229
+ keepTicking = false;
230
+ await flushImmediate();
231
+ histogram.disable();
232
+ expect(result.scannedPaths).toBe(0);
233
+ expect(result.batch.paths.size).toBe(50_000);
234
+ expect(eventLoopTicks).toBeGreaterThan(1);
235
+ expect(Number(histogram.max) / 1_000_000).toBeLessThan(50);
236
+ }
237
+ finally {
238
+ fs.rmSync(dir, { recursive: true, force: true });
239
+ }
240
+ });
241
+ it("uses async filesystem calls and prunes excluded trees during warm-up", async () => {
242
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watcher-warmup-async-fs-"));
243
+ const allowed = path.join(dir, "core", "knowledge", "public");
244
+ const nodeModules = path.join(dir, "core", "workers", "demo", "node_modules", "pkg");
245
+ const target = path.join(dir, "core", "packages", "demo", "target", "debug");
246
+ fs.mkdirSync(allowed, { recursive: true });
247
+ fs.mkdirSync(nodeModules, { recursive: true });
248
+ fs.mkdirSync(target, { recursive: true });
249
+ fs.writeFileSync(path.join(allowed, "keep.md"), "keep");
250
+ fs.writeFileSync(path.join(nodeModules, "skip.js"), "skip");
251
+ fs.writeFileSync(path.join(target, "skip.o"), "skip");
252
+ try {
253
+ const watcher = new TreeWatcher({
254
+ hqRoot: dir,
255
+ pathFilter: createWatchPathFilter(dir, false),
256
+ });
257
+ const result = await watcher.collectWarmupCatchupAsync(Date.now() - 10_000);
258
+ expect(result.scannedPaths).toBeGreaterThan(0);
259
+ expect([...result.batch.paths.values()]).toEqual([
260
+ "core/knowledge/public/keep.md",
261
+ ]);
262
+ }
263
+ finally {
264
+ fs.rmSync(dir, { recursive: true, force: true });
265
+ }
266
+ });
267
+ it("stops a yielding warm-up catch-up without scheduling the remaining chunks", async () => {
268
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watcher-warmup-stop-"));
269
+ const originalSetImmediate = globalThis.setImmediate;
270
+ let releaseFirstYield;
271
+ let firstYieldReached;
272
+ const firstYield = new Promise((resolve) => {
273
+ firstYieldReached = resolve;
274
+ });
275
+ const setImmediateSpy = vi.spyOn(globalThis, "setImmediate").mockImplementation(((callback, ...args) => {
276
+ if (!releaseFirstYield) {
277
+ releaseFirstYield = () => callback(...args);
278
+ firstYieldReached?.();
279
+ return undefined;
280
+ }
281
+ return originalSetImmediate(callback, ...args);
282
+ }));
283
+ try {
284
+ const watcher = new TreeWatcher({ hqRoot: dir, pathFilter: () => true });
285
+ const journalRows = Array.from({ length: 256 }, (_, index) => `personal/missing-${index}.md`);
286
+ const catchup = watcher.collectWarmupCatchupAsync(Date.now(), journalRows);
287
+ await firstYield;
288
+ watcher.stop();
289
+ releaseFirstYield?.();
290
+ const result = await catchup;
291
+ expect(result.cancelled).toBe(true);
292
+ expect(result.batch.paths.size).toBeLessThan(journalRows.length);
293
+ expect(setImmediateSpy).toHaveBeenCalledTimes(1);
294
+ }
295
+ finally {
296
+ setImmediateSpy.mockRestore();
297
+ fs.rmSync(dir, { recursive: true, force: true });
298
+ }
299
+ });
300
+ it("keeps a warm-up epoch only for a queued deletion capture, and only while it runs", async () => {
301
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watcher-warmup-epochs-"));
302
+ try {
303
+ for (let i = 0; i < 6; i++)
304
+ fs.writeFileSync(path.join(dir, `unchanged-${i}.md`), "old");
305
+ const settle = Date.now() + 50;
306
+ while (Date.now() < settle) { /* let old ctime settle below the cutoff */ }
307
+ const cutoff = Date.now();
308
+ while (Date.now() < cutoff + 50) { /* filesystems may round ctime down */ }
309
+ for (let i = 0; i < 4; i++)
310
+ fs.writeFileSync(path.join(dir, `fresh-${i}.md`), "new");
311
+ let resolveCapture;
312
+ const watcher = new TreeWatcher({
313
+ hqRoot: dir,
314
+ pathFilter: () => true,
315
+ queueLocalDeleteSnapshots: async () => {
316
+ await new Promise((resolve) => { resolveCapture = resolve; });
317
+ return [];
318
+ },
319
+ });
320
+ const result = watcher.collectWarmupCatchup(cutoff, ["gone-during-warmup.md"]);
321
+ expect([...result.batch.paths.values()].sort()).toEqual([
322
+ "fresh-0.md", "fresh-1.md", "fresh-2.md", "fresh-3.md", "gone-during-warmup.md",
323
+ ]);
324
+ // Four live changes were recorded, but only the deletion has a capture
325
+ // in flight, so only the deletion holds an epoch.
326
+ expect(watcher.censusSizes().deleteSnapshotEpochs).toBe(1);
327
+ await new Promise((resolve) => setImmediate(resolve)); // the queued job starts
328
+ resolveCapture();
329
+ await new Promise((resolve) => setImmediate(resolve));
330
+ expect(watcher.censusSizes().deleteSnapshotEpochs).toBe(0);
331
+ watcher.dispose();
332
+ }
333
+ finally {
334
+ fs.rmSync(dir, { recursive: true, force: true });
335
+ }
336
+ });
337
+ it("does not report a journal row as deleted when its file exists behind a symlinked directory", () => {
338
+ // The warm-up walk never descends through a symlinked directory (a Dirent
339
+ // symlink is not a directory), so rows journaled under such a path were
340
+ // never `observed` and every one of them came back as an `unlink` even
341
+ // though the file was right there. On one HQ, `.codex/claude -> ../.claude`
342
+ // made 11.4k present state files look deleted on every runner start: 11.4k
343
+ // delete roots, 11.4k queued delete-intent writes, and a delete plan that
344
+ // then refused each one. A journal row the walk missed must be stat'ed like
345
+ // any walked file: absent -> unlink, present and unchanged -> nothing,
346
+ // present and touched since the cutoff -> change.
347
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watcher-warmup-symlink-dir-"));
348
+ try {
349
+ fs.mkdirSync(path.join(dir, ".claude", "state"), { recursive: true });
350
+ fs.writeFileSync(path.join(dir, ".claude", "state", "stable.txt"), "old");
351
+ fs.mkdirSync(path.join(dir, ".codex"));
352
+ fs.symlinkSync(path.join("..", ".claude"), path.join(dir, ".codex", "claude"), "dir");
353
+ const settle = Date.now() + 50;
354
+ while (Date.now() < settle) { /* let old ctime settle below the cutoff */ }
355
+ const cutoff = Date.now();
356
+ while (Date.now() < cutoff + 50) { /* filesystems may round ctime down */ }
357
+ fs.writeFileSync(path.join(dir, ".claude", "state", "fresh.txt"), "new");
358
+ const capture = vi.fn(() => []);
359
+ const watcher = new TreeWatcher({
360
+ hqRoot: dir,
361
+ pathFilter: () => true,
362
+ captureLocalDeleteSnapshots: capture,
363
+ });
364
+ const result = watcher.collectWarmupCatchup(cutoff, [
365
+ ".codex/claude/state/stable.txt",
366
+ ".codex/claude/state/fresh.txt",
367
+ ".codex/claude/state/gone.txt",
368
+ ]);
369
+ const kinds = Object.fromEntries([...result.batch.paths].map(([absolute, relative]) => [relative, result.batch.changes?.get(absolute)?.kind]));
370
+ expect(kinds).toEqual({
371
+ ".claude/state/fresh.txt": "change",
372
+ ".codex/claude/state/fresh.txt": "change",
373
+ ".codex/claude/state/gone.txt": "unlink",
374
+ });
375
+ expect(capture).toHaveBeenCalledTimes(1);
376
+ expect(capture).toHaveBeenCalledWith(".codex/claude/state/gone.txt", "unlink");
377
+ }
378
+ finally {
379
+ fs.rmSync(dir, { recursive: true, force: true });
380
+ }
381
+ });
382
+ it("canonicalizes a legacy journal key before adding its warm-up deletion to the batch", () => {
383
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watcher-warmup-posix-key-"));
384
+ try {
385
+ const capture = vi.fn(() => []);
386
+ const watcher = new TreeWatcher({
387
+ hqRoot: dir,
388
+ pathFilter: () => true,
389
+ captureLocalDeleteSnapshots: capture,
390
+ });
391
+ const result = watcher.collectWarmupCatchup(Date.now(), [
392
+ "projects\\forecast\\x.csv",
393
+ ]);
394
+ const absolute = path.join(dir, "projects", "forecast", "x.csv");
395
+ expect([...result.batch.paths.entries()]).toEqual([
396
+ [absolute, "projects/forecast/x.csv"],
397
+ ]);
398
+ expect(capture).toHaveBeenCalledWith("projects/forecast/x.csv", "unlink");
399
+ }
400
+ finally {
401
+ fs.rmSync(dir, { recursive: true, force: true });
402
+ }
403
+ });
404
+ it("recovers a warm-up path even when the event backlog dropped it", () => {
405
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watcher-warmup-overflow-"));
406
+ try {
407
+ const retained = path.join(dir, "retained.md");
408
+ fs.writeFileSync(retained, "old");
409
+ const settle = Date.now() + 50;
410
+ while (Date.now() < settle) { /* let old ctime settle below the cutoff */ }
411
+ const cutoff = Date.now();
412
+ while (Date.now() < cutoff + 50) { /* filesystems may round ctime down */ }
413
+ const dropped = path.join(dir, "dropped-during-warmup.md");
414
+ fs.writeFileSync(dropped, "new");
415
+ const watcher = new TreeWatcher({
416
+ hqRoot: dir,
417
+ pathFilter: () => true,
418
+ maxPendingPaths: 1,
419
+ maxPendingBytes: 100_000,
420
+ });
421
+ watcher.handleEvent(retained);
422
+ watcher.handleEvent(dropped);
423
+ const result = watcher.collectWarmupCatchup(cutoff);
424
+ expect([...result.batch.paths.values()]).toEqual(["dropped-during-warmup.md"]);
425
+ }
426
+ finally {
427
+ fs.rmSync(dir, { recursive: true, force: true });
428
+ }
429
+ });
430
+ it("honors the pending-path environment cap in the production constructor", () => {
431
+ vi.stubEnv("HQ_SYNC_MAX_PENDING_PATHS", "3");
432
+ vi.stubEnv("HQ_SYNC_MAX_PENDING_BYTES", "100000");
433
+ try {
434
+ const clock = new FakeClock();
435
+ const changed = vi.fn();
436
+ const watcher = new TreeWatcher({
437
+ hqRoot: ROOT,
438
+ clock,
439
+ debounceMs: DEBOUNCE,
440
+ pathFilter: () => true,
441
+ });
442
+ watcher.onChange(changed);
443
+ for (let i = 0; i < 4; i++) {
444
+ watcher.handleEvent(path.join(ROOT, `env-cap-${i}.md`));
445
+ }
446
+ clock.advance(DEBOUNCE);
447
+ expect(changed.mock.calls[0][1].paths.size).toBe(3);
448
+ expect(changed.mock.calls[0][1].overflowed).toBe(true);
449
+ }
450
+ finally {
451
+ vi.unstubAllEnvs();
452
+ }
453
+ });
454
+ it("honors the pending-byte environment cap in the production constructor", () => {
455
+ vi.stubEnv("HQ_SYNC_MAX_PENDING_PATHS", "100");
456
+ vi.stubEnv("HQ_SYNC_MAX_PENDING_BYTES", "1");
457
+ try {
458
+ const clock = new FakeClock();
459
+ const changed = vi.fn();
460
+ const watcher = new TreeWatcher({
461
+ hqRoot: ROOT,
462
+ clock,
463
+ debounceMs: DEBOUNCE,
464
+ pathFilter: () => true,
465
+ });
466
+ watcher.onChange(changed);
467
+ watcher.handleEvent(path.join(ROOT, "byte-cap.md"));
468
+ clock.advance(DEBOUNCE);
469
+ expect(changed.mock.calls[0][1].paths.size).toBe(0);
470
+ expect(changed.mock.calls[0][1].overflowed).toBe(true);
471
+ }
472
+ finally {
473
+ vi.unstubAllEnvs();
474
+ }
475
+ });
476
+ it.each([
477
+ ["HQ_SYNC_MAX_PENDING_PATHS", "0"],
478
+ ["HQ_SYNC_MAX_PENDING_PATHS", "0.5"],
479
+ ["HQ_SYNC_MAX_PENDING_PATHS", "-1"],
480
+ ["HQ_SYNC_MAX_PENDING_PATHS", "not-a-number"],
481
+ ["HQ_SYNC_MAX_PENDING_BYTES", "0"],
482
+ ["HQ_SYNC_MAX_PENDING_BYTES", "0.5"],
483
+ ["HQ_SYNC_MAX_PENDING_BYTES", "-1"],
484
+ ["HQ_SYNC_MAX_PENDING_BYTES", "not-a-number"],
485
+ ])("warns once and falls back for invalid %s=%s", (name, value) => {
486
+ vi.stubEnv(name, value);
487
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => { });
488
+ try {
489
+ new TreeWatcher({ hqRoot: ROOT });
490
+ expect(warn).toHaveBeenCalledOnce();
491
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining(name));
492
+ }
493
+ finally {
494
+ warn.mockRestore();
495
+ vi.unstubAllEnvs();
496
+ }
497
+ });
498
+ it("keeps a burst at the configured cap without marking it overflowed", () => {
499
+ vi.stubEnv("HQ_SYNC_MAX_PENDING_PATHS", "4");
500
+ vi.stubEnv("HQ_SYNC_MAX_PENDING_BYTES", "100000");
501
+ try {
502
+ const clock = new FakeClock();
503
+ const changed = vi.fn();
504
+ const overflow = vi.fn();
505
+ const watcher = new TreeWatcher({
506
+ hqRoot: ROOT,
507
+ clock,
508
+ debounceMs: DEBOUNCE,
509
+ pathFilter: () => true,
510
+ onBacklogOverflow: overflow,
511
+ });
512
+ watcher.onChange(changed);
513
+ for (let i = 0; i < 4; i++) {
514
+ watcher.handleEvent(path.join(ROOT, `below-cap-${i}.md`));
515
+ }
516
+ clock.advance(DEBOUNCE);
517
+ expect(overflow).not.toHaveBeenCalled();
518
+ expect(changed.mock.calls[0][1]).not.toHaveProperty("overflowed");
519
+ }
520
+ finally {
521
+ vi.unstubAllEnvs();
522
+ }
523
+ });
524
+ it("reports the hit cap and cumulative dropped count in every overflow episode", () => {
525
+ const clock = new FakeClock();
526
+ const overflow = vi.fn();
527
+ const watcher = new TreeWatcher({
528
+ hqRoot: ROOT,
529
+ clock,
530
+ debounceMs: DEBOUNCE,
531
+ pathFilter: () => true,
532
+ maxPendingPaths: 1,
533
+ maxPendingBytes: 100_000,
534
+ onBacklogOverflow: overflow,
535
+ });
536
+ watcher.handleEvent(path.join(ROOT, "kept-first.md"));
537
+ watcher.handleEvent(path.join(ROOT, "dropped-first.md"));
538
+ clock.advance(DEBOUNCE);
539
+ watcher.handleEvent(path.join(ROOT, "kept-second.md"));
540
+ clock.advance(10);
541
+ watcher.handleEvent(path.join(ROOT, "dropped-second.md"));
542
+ expect(overflow).toHaveBeenCalledTimes(2);
543
+ expect(overflow.mock.calls[0][0]).toMatchObject({
544
+ capHit: "paths",
545
+ totalDroppedPaths: 1,
546
+ maxPendingPaths: 1,
547
+ maxPendingBytes: 100_000,
548
+ pendingPaths: 1,
549
+ inFlightPassMs: 0,
550
+ });
551
+ expect(overflow.mock.calls[1][0]).toMatchObject({
552
+ capHit: "paths",
553
+ totalDroppedPaths: 2,
554
+ inFlightPassMs: 10,
555
+ });
556
+ });
557
+ it("logs every default overflow record with the cumulative total and hit cap", () => {
558
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => { });
559
+ try {
560
+ const watcher = new TreeWatcher({
561
+ hqRoot: ROOT,
562
+ pathFilter: () => true,
563
+ maxPendingPaths: 1,
564
+ maxPendingBytes: 100_000,
565
+ });
566
+ watcher.handleEvent(path.join(ROOT, "kept.md"));
567
+ watcher.handleEvent(path.join(ROOT, "dropped-one.md"));
568
+ watcher.handleEvent(path.join(ROOT, "dropped-two.md"));
569
+ expect(warn).toHaveBeenCalledTimes(2);
570
+ expect(warn).toHaveBeenLastCalledWith(expect.stringContaining("backlog cap exceeded"), expect.objectContaining({
571
+ capHit: "paths",
572
+ totalDroppedPaths: 2,
573
+ pendingPaths: 1,
574
+ maxPendingPaths: 1,
575
+ maxPendingBytes: 100_000,
576
+ inFlightPassMs: expect.any(Number),
577
+ }));
578
+ }
579
+ finally {
580
+ warn.mockRestore();
581
+ }
582
+ });
583
+ it("omits route hints when an overflow exceeds the route-evidence cap", () => {
584
+ const clock = new FakeClock();
585
+ const changed = vi.fn();
586
+ const watcher = new TreeWatcher({
587
+ hqRoot: ROOT,
588
+ clock,
589
+ debounceMs: DEBOUNCE,
590
+ pathFilter: () => true,
591
+ maxPendingPaths: 1,
592
+ maxPendingBytes: 100_000,
593
+ onBacklogOverflow: () => { },
594
+ });
595
+ watcher.onChange(changed);
596
+ watcher.handleEvent(path.join(ROOT, "companies", "kept", "a.md"));
597
+ for (let i = 0; i < 33; i++) {
598
+ watcher.handleEvent(path.join(ROOT, "companies", `dropped-${i}`, "a.md"));
599
+ }
600
+ clock.advance(DEBOUNCE);
601
+ expect(changed.mock.calls[0][1]).toMatchObject({ overflowed: true });
602
+ expect(changed.mock.calls[0][1]).not.toHaveProperty("droppedRouteHints");
603
+ });
604
+ });
605
+ describe("US-001: WatchPushDriver — debounced push seam", () => {
606
+ it("calls the injected push fn exactly once within debounce+grace after a synthetic change", async () => {
607
+ const h = makeHarness();
608
+ h.emitChange();
609
+ // Before the window elapses, no push.
610
+ h.advance(DEBOUNCE - 1);
611
+ expect(h.push).not.toHaveBeenCalled();
612
+ // Crossing the debounce boundary fires the push exactly once.
613
+ h.advance(1);
614
+ await Promise.resolve();
615
+ expect(h.push).toHaveBeenCalledTimes(1);
616
+ });
617
+ it("coalesces N rapid changes within the window to exactly 1 push", async () => {
618
+ const h = makeHarness();
619
+ // 5 synthetic changes spread across less than one debounce window.
620
+ for (let i = 0; i < 5; i++) {
621
+ h.emitChange();
622
+ h.advance(100); // total 500ms << 2000ms debounce
623
+ }
624
+ // Window has not fully elapsed since the LAST change yet.
625
+ expect(h.push).not.toHaveBeenCalled();
626
+ // Let the quiet window after the final change elapse.
627
+ h.advance(DEBOUNCE);
628
+ await Promise.resolve();
629
+ expect(h.push).toHaveBeenCalledTimes(1);
630
+ });
631
+ it("treats two separate bursts as two pushes", async () => {
632
+ const h = makeHarness();
633
+ h.emitChange();
634
+ h.advance(DEBOUNCE);
635
+ await Promise.resolve();
636
+ expect(h.push).toHaveBeenCalledTimes(1);
637
+ h.emitChange();
638
+ h.advance(DEBOUNCE);
639
+ await Promise.resolve();
640
+ expect(h.push).toHaveBeenCalledTimes(2);
641
+ });
642
+ it("never overlaps an in-flight push; a mid-push change re-triggers one follow-up pass", async () => {
643
+ const clock = new FakeClock();
644
+ let release;
645
+ const inFlight = new Promise((r) => {
646
+ release = r;
647
+ });
648
+ let calls = 0;
649
+ const push = vi.fn(() => {
650
+ calls += 1;
651
+ // First push hangs until released; later pushes resolve immediately.
652
+ return calls === 1 ? inFlight : Promise.resolve();
653
+ });
654
+ const driver = new WatchPushDriver({ debounceMs: DEBOUNCE, clock, push });
655
+ // First burst -> first push starts and hangs.
656
+ driver.notifyChange();
657
+ clock.advance(DEBOUNCE);
658
+ await Promise.resolve();
659
+ expect(push).toHaveBeenCalledTimes(1);
660
+ expect(driver.isPushing()).toBe(true);
661
+ // A change arrives while the first push is in flight: must NOT start a
662
+ // concurrent push.
663
+ driver.notifyChange();
664
+ clock.advance(DEBOUNCE);
665
+ await Promise.resolve();
666
+ expect(push).toHaveBeenCalledTimes(1);
667
+ // Release the first push; the collapsed mid-push change re-arms.
668
+ release();
669
+ await inFlight;
670
+ await Promise.resolve();
671
+ // Re-armed window must elapse before the follow-up push fires.
672
+ clock.advance(DEBOUNCE);
673
+ await Promise.resolve();
674
+ expect(push).toHaveBeenCalledTimes(2);
675
+ driver.dispose();
676
+ });
677
+ it("F17: rejected watch push is caught instead of surfacing as an unhandled rejection", async () => {
678
+ const clock = new FakeClock();
679
+ const rejection = new Error("push failed");
680
+ const push = vi.fn(async () => {
681
+ throw rejection;
682
+ });
683
+ const driver = new WatchPushDriver({ debounceMs: DEBOUNCE, clock, push });
684
+ const unhandled = [];
685
+ const onUnhandled = (reason) => {
686
+ unhandled.push(reason);
687
+ };
688
+ process.prependListener("unhandledRejection", onUnhandled);
689
+ try {
690
+ driver.notifyChange();
691
+ clock.advance(DEBOUNCE);
692
+ await Promise.resolve();
693
+ await flushImmediate();
694
+ expect(push).toHaveBeenCalledTimes(1);
695
+ expect(driver.isPushing()).toBe(false);
696
+ expect(unhandled).toEqual([]);
697
+ }
698
+ finally {
699
+ process.removeListener("unhandledRejection", onUnhandled);
700
+ driver.dispose();
701
+ }
702
+ });
703
+ it("respects a custom debounce window", async () => {
704
+ const h = makeHarness({ debounceMs: 500 });
705
+ h.emitChange();
706
+ h.advance(499);
707
+ expect(h.push).not.toHaveBeenCalled();
708
+ h.advance(1);
709
+ await Promise.resolve();
710
+ expect(h.push).toHaveBeenCalledTimes(1);
711
+ });
712
+ });
713
+ describe("US-001: WatchPushDriver — teardown leaves no leaked timers", () => {
714
+ it("dispose() cancels a pending debounce timer", () => {
715
+ const h = makeHarness();
716
+ h.emitChange();
717
+ expect(h.clock.pendingTimerCount()).toBe(1);
718
+ h.driver.dispose();
719
+ expect(h.clock.pendingTimerCount()).toBe(0);
720
+ // A push must not fire after dispose, even if time advances.
721
+ h.advance(DEBOUNCE * 10);
722
+ expect(h.push).not.toHaveBeenCalled();
723
+ });
724
+ it("notifyChange() after dispose is a no-op and schedules nothing", () => {
725
+ const h = makeHarness();
726
+ h.driver.dispose();
727
+ h.emitChange();
728
+ expect(h.clock.pendingTimerCount()).toBe(0);
729
+ h.advance(DEBOUNCE * 10);
730
+ expect(h.push).not.toHaveBeenCalled();
731
+ });
732
+ it("dispose() is idempotent", () => {
733
+ const h = makeHarness();
734
+ h.emitChange();
735
+ h.driver.dispose();
736
+ h.driver.dispose();
737
+ expect(h.clock.pendingTimerCount()).toBe(0);
738
+ });
739
+ it("a fully drained burst leaves zero pending timers", async () => {
740
+ const h = makeHarness();
741
+ for (let i = 0; i < 5; i++)
742
+ h.emitChange();
743
+ h.advance(DEBOUNCE);
744
+ await Promise.resolve();
745
+ expect(h.push).toHaveBeenCalledTimes(1);
746
+ expect(h.clock.pendingTimerCount()).toBe(0);
747
+ });
748
+ });
749
+ /**
750
+ * US-002 — file-watcher module (debounced, ignore-aware, exclusion-aware).
751
+ *
752
+ * `createWatchPathFilter` is pure (no chokidar) so the exclusion logic is
753
+ * tested directly against absolute paths. `TreeWatcher` is then exercised via
754
+ * its `handleEvent` seam + FakeClock so debounce/coalesce/lifecycle assert
755
+ * deterministically without spinning a real chokidar instance.
756
+ */
757
+ const ROOT = "/tmp/hq-root";
758
+ describe("US-002: createWatchPathFilter — ignore-list matching", () => {
759
+ const filter = createWatchPathFilter(ROOT, false);
760
+ it("emits for an ordinary tracked file", () => {
761
+ expect(filter(path.join(ROOT, "personal/notes.md"))).toBe(true);
762
+ });
763
+ it("does NOT emit for a .env file (DEFAULT_IGNORES secret)", () => {
764
+ expect(filter(path.join(ROOT, ".env"))).toBe(false);
765
+ expect(filter(path.join(ROOT, "personal/.env.local"))).toBe(false);
766
+ });
767
+ it("does NOT emit for AppleDouble files", () => {
768
+ expect(filter(path.join(ROOT, "._README.md"))).toBe(false);
769
+ expect(filter(path.join(ROOT, "core/connectors/._README.md"))).toBe(false);
770
+ });
771
+ it("does NOT emit for restore staging paths", () => {
772
+ expect(filter(path.join(ROOT, "core/packages.hq-restore-9980"), true)).toBe(false);
773
+ expect(filter(path.join(ROOT, "core/packages.hq-restore-9980/connectors/README.md"))).toBe(false);
774
+ expect(filter(path.join(ROOT, "core/README.md.hq-restore-probe-9980-m6bx"))).toBe(false);
775
+ });
776
+ it("does NOT emit for node_modules / dist build artifacts", () => {
777
+ expect(filter(path.join(ROOT, "node_modules/foo/index.js"))).toBe(false);
778
+ expect(filter(path.join(ROOT, "dist/bundle.js"))).toBe(false);
779
+ });
780
+ it("does NOT emit for the watched root itself or paths outside it", () => {
781
+ expect(filter(ROOT)).toBe(false);
782
+ expect(filter("/some/other/place/file.txt")).toBe(false);
783
+ });
784
+ });
785
+ describe("US-002: createWatchPathFilter — personal-vault exclusions", () => {
786
+ const personal = createWatchPathFilter(ROOT, true);
787
+ const nonPersonal = createWatchPathFilter(ROOT, false);
788
+ it("does NOT emit for PERSONAL_VAULT_DEFAULT_EXCLUSIONS in personalMode (output/, .beads/)", () => {
789
+ expect(personal(path.join(ROOT, "personal/output/x.txt"))).toBe(false);
790
+ expect(personal(path.join(ROOT, "personal/.beads/issues.db"))).toBe(false);
791
+ });
792
+ it("does NOT emit for PERSONAL_VAULT_EXCLUDED_TOP_LEVEL in personalMode (.git/companies/repos/workspace)", () => {
793
+ expect(personal(path.join(ROOT, "companies/indigo/board.json"))).toBe(false);
794
+ expect(personal(path.join(ROOT, "workspace/threads/x.json"))).toBe(false);
795
+ expect(personal(path.join(ROOT, "repos/private/foo/file.ts"))).toBe(false);
796
+ });
797
+ // ── DEV-1778 continuity-pointer carve-out ───────────────────────────────
798
+ it("DOES emit for workspace/threads/handoff.json (the continuity pointer)", () => {
799
+ expect(personal(path.join(ROOT, "workspace/threads/handoff.json"))).toBe(true);
800
+ });
801
+ it("emits for the pointer's active continuity thread file", () => {
802
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "watch-active-thread-")));
803
+ const thread = path.join(root, "workspace", "threads", "x.json");
804
+ try {
805
+ fs.mkdirSync(path.dirname(thread), { recursive: true });
806
+ fs.writeFileSync(thread, "{}");
807
+ fs.writeFileSync(path.join(root, "workspace", "threads", "handoff.json"), JSON.stringify({ thread_path: "workspace/threads/x.json" }));
808
+ const scoped = createWatchPathFilter(root, true);
809
+ expect(scoped(thread)).toBe(true);
810
+ }
811
+ finally {
812
+ fs.rmSync(root, { recursive: true, force: true });
813
+ }
814
+ });
815
+ it("covers every present personal-vault root, while preserving .hqignore exclusions", () => {
816
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "watch-scope-invariant-")));
817
+ const activeThread = path.join(root, "workspace", "threads", "x.json");
818
+ try {
819
+ fs.mkdirSync(path.join(root, "personal"), { recursive: true });
820
+ fs.mkdirSync(path.join(root, ".codex"), { recursive: true });
821
+ fs.mkdirSync(path.join(root, "companies", "local"), { recursive: true });
822
+ fs.mkdirSync(path.join(root, "workspace", "agency", "team"), { recursive: true });
823
+ fs.mkdirSync(path.join(root, "workspace", ".session-logs"), { recursive: true });
824
+ fs.mkdirSync(path.dirname(activeThread), { recursive: true });
825
+ fs.writeFileSync(path.join(root, "personal", "note.md"), "note");
826
+ fs.writeFileSync(path.join(root, ".codex", "settings.json"), "{}");
827
+ fs.writeFileSync(path.join(root, "companies", "manifest.yaml"), "companies: {}\n");
828
+ fs.writeFileSync(path.join(root, "companies", "local", "note.md"), "local");
829
+ fs.writeFileSync(path.join(root, "workspace", "agency", "team", "state.json"), "{}");
830
+ fs.writeFileSync(path.join(root, "workspace", ".session-logs", "session.jsonl"), "{}\n");
831
+ fs.writeFileSync(activeThread, "{}");
832
+ fs.writeFileSync(path.join(root, "workspace", "threads", "handoff.json"), JSON.stringify({ thread_path: "workspace/threads/x.json" }));
833
+ fs.writeFileSync(path.join(root, ".hqignore"), "workspace/agency/ignored/\n");
834
+ const filter = createWatchPathFilter(root, true);
835
+ const uncovered = computePersonalVaultPaths(root).filter((scopeRoot) => !filter(scopeRoot, fs.lstatSync(scopeRoot).isDirectory()));
836
+ // Scope roots must be watched, unless a future change introduces an
837
+ // explicit, reasoned exclusion. There are deliberately no such
838
+ // exclusions in this representative personal scope.
839
+ expect(uncovered).toEqual([]);
840
+ expect(filter(path.join(root, "workspace", "agency", "ignored"), true)).toBe(false);
841
+ }
842
+ finally {
843
+ fs.rmSync(root, { recursive: true, force: true });
844
+ }
845
+ });
846
+ it("still does NOT emit for other workspace/ files (carve-out is pointer-only)", () => {
847
+ // The pointer is the ONLY re-include — sibling threads, the journal, and
848
+ // unrelated workspace litter stay machine-local.
849
+ expect(personal(path.join(ROOT, "workspace/threads/T-old.json"))).toBe(false);
850
+ expect(personal(path.join(ROOT, "workspace/threads/INDEX.md"))).toBe(false);
851
+ expect(personal(path.join(ROOT, "workspace/locks/x.lock"))).toBe(false);
852
+ // The pointer queried as a directory is not an emit target either.
853
+ expect(personal(path.join(ROOT, "workspace/threads/handoff.json"), true)).toBe(false);
854
+ });
855
+ it("allows chokidar to DESCEND through the pointer's ancestor dirs (dir probe)", () => {
856
+ // Without this the Linux chokidar backend prunes `workspace/` before ever
857
+ // reaching the leaf. Ancestor dirs return true ONLY when queried as dirs.
858
+ expect(personal(path.join(ROOT, "workspace"), true)).toBe(true);
859
+ expect(personal(path.join(ROOT, "workspace/threads"), true)).toBe(true);
860
+ // A non-ancestor dir under workspace/ is still pruned.
861
+ expect(personal(path.join(ROOT, "workspace/locks"), true)).toBe(false);
862
+ // Ancestor dirs queried as FILES are not emit targets.
863
+ expect(personal(path.join(ROOT, "workspace"), false)).toBe(false);
864
+ });
865
+ // ── workspace/agency subtree carve-out (personal mode) ──────────────────
866
+ // The personal push uploads workspace/agency/** (computeAgencySyncPaths), so
867
+ // the personal watcher must emit those changes event-driven, not leave them
868
+ // for the 60s poll. Mirrors the continuity-pointer carve-out, for a subtree.
869
+ it("DOES emit for workspace/agency files in personalMode (synced subtree)", () => {
870
+ expect(personal(path.join(ROOT, "workspace/agency/indigo/nick/chat.jsonl"))).toBe(true);
871
+ expect(personal(path.join(ROOT, "workspace/agency/indigo/nick/status.json"))).toBe(true);
872
+ // The agency root itself, as a file event, also emits.
873
+ expect(personal(path.join(ROOT, "workspace/agency"))).toBe(true);
874
+ });
875
+ it("allows chokidar to DESCEND to workspace/agency in personalMode (dir probes)", () => {
876
+ // workspace/ and workspace/agency queried as dirs must return true so the
877
+ // chokidar backend descends instead of pruning workspace/ at the top.
878
+ expect(personal(path.join(ROOT, "workspace"), true)).toBe(true);
879
+ expect(personal(path.join(ROOT, "workspace/agency"), true)).toBe(true);
880
+ expect(personal(path.join(ROOT, "workspace/agency/indigo"), true)).toBe(true);
881
+ });
882
+ it("agency carve-out is exact-segment (does NOT leak to workspace/agencyX)", () => {
883
+ // Only workspace/agency (and its subtree) is re-included; a sibling whose
884
+ // name merely starts with 'agency' stays excluded like other workspace litter.
885
+ expect(personal(path.join(ROOT, "workspace/agencyX/foo.txt"))).toBe(false);
886
+ expect(personal(path.join(ROOT, "workspace/agency-notes.md"))).toBe(false);
887
+ });
888
+ it("agency carve-out does not re-include other workspace/ litter", () => {
889
+ // Regression: the new carve-out must not widen the workspace exclusion for
890
+ // anything other than agency + the continuity pointer.
891
+ expect(personal(path.join(ROOT, "workspace/locks/x.lock"))).toBe(false);
892
+ expect(personal(path.join(ROOT, "workspace/threads/T-old.json"))).toBe(false);
893
+ expect(personal(path.join(ROOT, "workspace/worktrees/x/a.ts"))).toBe(false);
894
+ });
895
+ // ── workspace/.session-logs subtree carve-out (personal mode) ────────────
896
+ // The personal push uploads workspace/.session-logs/** (reindex-captured
897
+ // Claude Code transcripts, computeSessionLogsSyncPaths), so the personal
898
+ // watcher must emit those changes event-driven. Mirrors the agency carve-out.
899
+ it("DOES emit for workspace/.session-logs files in personalMode (synced subtree)", () => {
900
+ expect(personal(path.join(ROOT, "workspace/.session-logs/session.jsonl"))).toBe(true);
901
+ expect(personal(path.join(ROOT, "workspace/.session-logs/tool-results/r.txt"))).toBe(true);
902
+ // The subtree root itself, as a file event, also emits.
903
+ expect(personal(path.join(ROOT, "workspace/.session-logs"))).toBe(true);
904
+ });
905
+ it("allows chokidar to DESCEND to workspace/.session-logs in personalMode (dir probes)", () => {
906
+ expect(personal(path.join(ROOT, "workspace"), true)).toBe(true);
907
+ expect(personal(path.join(ROOT, "workspace/.session-logs"), true)).toBe(true);
908
+ expect(personal(path.join(ROOT, "workspace/.session-logs/tool-results"), true)).toBe(true);
909
+ });
910
+ it("session-logs carve-out is exact-segment (does NOT leak to a similarly-named sibling)", () => {
911
+ expect(personal(path.join(ROOT, "workspace/.session-logs-old/foo.txt"))).toBe(false);
912
+ expect(personal(path.join(ROOT, "workspace/.session-logsX.md"))).toBe(false);
913
+ });
914
+ it("does not apply the carve-out in non-personal mode", () => {
915
+ // In non-personal mode the excluded-top-level layer never runs, so the
916
+ // carve-out is irrelevant; handoff.json passes via the ordinary ignore
917
+ // stack like any other tracked file (no special-casing needed).
918
+ expect(nonPersonal(path.join(ROOT, "workspace/threads/handoff.json"))).toBe(true);
919
+ });
920
+ it("DOES emit for an included top-level personal path in personalMode", () => {
921
+ expect(personal(path.join(ROOT, "personal/notes.md"))).toBe(true);
922
+ expect(personal(path.join(ROOT, "core/policies/x.md"))).toBe(true);
923
+ });
924
+ it("non-personal mode does NOT apply the excluded-top-level buckets", () => {
925
+ // companies/ is only excluded by the personal-vault layer; in non-personal
926
+ // mode the ignore stack alone governs and lets it through.
927
+ expect(nonPersonal(path.join(ROOT, "companies/indigo/board.json"))).toBe(true);
928
+ });
929
+ // ── Never-synced heavy buckets pruned in BOTH modes ─────────────────────
930
+ // In --companies mode personalMode=false, so the excluded-top-level layer
931
+ // never ran and the watcher descended into the local git worktrees
932
+ // (workspace/worktrees/, ~200k transient files from agent coding runs) and
933
+ // the on-box repos checkout (repos/). Neither ever vault-syncs in any mode,
934
+ // so watching them only burns inotify watches (near the OS limit) + CPU on
935
+ // build churn it discards, and can trip the overflow→full-reconcile fallback.
936
+ it("non-personal mode EXCLUDES never-synced heavy buckets (workspace/worktrees, repos)", () => {
937
+ expect(nonPersonal(path.join(ROOT, "workspace/worktrees/hq-console/src/a.ts"))).toBe(false);
938
+ // The bucket dir itself is pruned so chokidar never descends into it.
939
+ expect(nonPersonal(path.join(ROOT, "workspace/worktrees"), true)).toBe(false);
940
+ expect(nonPersonal(path.join(ROOT, "repos/private/hq-cloud/src/x.ts"))).toBe(false);
941
+ expect(nonPersonal(path.join(ROOT, "repos"), true)).toBe(false);
942
+ });
943
+ it("non-personal mode STILL watches synced content (companies/, workspace/agency, continuity)", () => {
944
+ expect(nonPersonal(path.join(ROOT, "companies/indigo/board.json"))).toBe(true);
945
+ expect(nonPersonal(path.join(ROOT, "workspace/agency/indigo/nick/status.json"))).toBe(true);
946
+ expect(nonPersonal(path.join(ROOT, "workspace/threads/handoff.json"))).toBe(true);
947
+ // chokidar must still descend into workspace/ to reach agency + continuity.
948
+ expect(nonPersonal(path.join(ROOT, "workspace"), true)).toBe(true);
949
+ // A worktrees SIBLING under workspace/ is unaffected (only worktrees pruned).
950
+ expect(nonPersonal(path.join(ROOT, "workspace/agency"), true)).toBe(true);
951
+ });
952
+ it("combined personal + company mode retains company trees without admitting unrelated workspace churn", () => {
953
+ const combined = createWatchPathFilter(ROOT, true, {
954
+ includeCompanyPaths: true,
955
+ });
956
+ expect(combined(path.join(ROOT, "personal/rt-hour.md"))).toBe(true);
957
+ expect(combined(path.join(ROOT, "companies/indigo/board.json"))).toBe(true);
958
+ expect(combined(path.join(ROOT, "workspace/locks/sync.lock"))).toBe(false);
959
+ expect(combined(path.join(ROOT, "workspace/agency/indigo/chat.jsonl"))).toBe(true);
960
+ });
961
+ it("personal mode still excludes worktrees + repos (regression, unchanged)", () => {
962
+ expect(personal(path.join(ROOT, "workspace/worktrees/x/a.ts"))).toBe(false);
963
+ expect(personal(path.join(ROOT, "repos/private/x/a.ts"))).toBe(false);
964
+ });
965
+ });
966
+ describe("US-002: chokidar descent scope", () => {
967
+ let dir;
968
+ beforeEach(() => {
969
+ dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "watch-scope-")));
970
+ // This is the real HQ allowlist shape. The synthetic heavy directories
971
+ // deliberately sit both under an in-scope company and under the two
972
+ // never-synced top-level buckets from #156.
973
+ fs.writeFileSync(path.join(dir, ".hqinclude"), "companies/*/knowledge/\n");
974
+ fs.mkdirSync(path.join(dir, "companies", "acme", "knowledge", "node_modules", "heavy"), { recursive: true });
975
+ fs.writeFileSync(path.join(dir, "companies", "acme", "knowledge", "node_modules", "heavy", "index.js"), "module.exports = 1;\n");
976
+ fs.mkdirSync(path.join(dir, "repos", "checkout", "heavy"), { recursive: true });
977
+ fs.mkdirSync(path.join(dir, "workspace", "worktrees", "repo", "node_modules", "heavy"), { recursive: true });
978
+ });
979
+ afterEach(() => {
980
+ fs.rmSync(dir, { recursive: true, force: true });
981
+ });
982
+ it("defers a file-shaped pre-stat candidate to the stat-aware directory verdict", () => {
983
+ const filter = createWatchPathFilter(dir, false);
984
+ const nodeModules = path.join(dir, "companies", "acme", "knowledge", "node_modules");
985
+ // `node_modules/` is directory-only. A no-stat chokidar probe cannot know
986
+ // whether this is a new file or a directory, so it must survive long
987
+ // enough to receive the stat-aware verdict below.
988
+ expect(filter(nodeModules, false)).toBe(true);
989
+ expect(filter(nodeModules, true)).toBe(false);
990
+ const ignored = toChokidarIgnored(filter, dir);
991
+ expect(ignored(nodeModules)).toBe(false);
992
+ expect(ignored(nodeModules, fs.lstatSync(nodeModules))).toBe(true);
993
+ // The allowlist's exact ancestor matcher remains the only carve-out: the
994
+ // watcher can still reach companies/<slug>/knowledge without opening every
995
+ // otherwise-file-shaped ignored directory below it.
996
+ expect(ignored(path.join(dir, "companies"))).toBe(false);
997
+ expect(ignored(path.join(dir, "companies", "acme"))).toBe(false);
998
+ });
999
+ it("prunes ignored directories during chokidar's pre-stat descent probe", async () => {
1000
+ const filter = createWatchPathFilter(dir, false);
1001
+ const chokidarWatcher = watch(dir, {
1002
+ ignored: toChokidarIgnored(filter, dir),
1003
+ ignoreInitial: true,
1004
+ persistent: false,
1005
+ });
1006
+ try {
1007
+ await new Promise((resolve, reject) => {
1008
+ chokidarWatcher.once("ready", resolve);
1009
+ chokidarWatcher.once("error", reject);
1010
+ });
1011
+ const descended = Object.keys(chokidarWatcher.getWatched())
1012
+ .map((watchedPath) => path.resolve(watchedPath))
1013
+ .sort();
1014
+ expect(descended).toContain(path.join(dir, "companies", "acme", "knowledge"));
1015
+ expect(descended).not.toContain(path.join(dir, "companies", "acme", "knowledge", "node_modules"));
1016
+ expect(descended).not.toContain(path.join(dir, "repos"));
1017
+ expect(descended).not.toContain(path.join(dir, "workspace", "worktrees"));
1018
+ }
1019
+ finally {
1020
+ await chokidarWatcher.close();
1021
+ }
1022
+ });
1023
+ });
1024
+ describe("chokidar polling symlink boundaries", () => {
1025
+ async function waitFor(check) {
1026
+ const deadline = Date.now() + 6000;
1027
+ while (Date.now() < deadline) {
1028
+ if (check())
1029
+ return;
1030
+ await new Promise((resolve) => setTimeout(resolve, 25));
1031
+ }
1032
+ expect(check()).toBe(true);
1033
+ }
1034
+ async function waitReady(backend) {
1035
+ await new Promise((resolve, reject) => {
1036
+ if (!backend.onReady)
1037
+ return resolve();
1038
+ const timer = setTimeout(() => reject(new Error("watcher did not become ready")), 6000);
1039
+ backend.onReady(() => {
1040
+ clearTimeout(timer);
1041
+ resolve();
1042
+ });
1043
+ });
1044
+ }
1045
+ it("polls ordinary paths without descending or budgeting symlink targets, while reporting the link entry", async () => {
1046
+ const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "watch-poll-link-root-")));
1047
+ const external = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "watch-poll-link-target-")));
1048
+ const link = path.join(root, ".agents");
1049
+ const events = [];
1050
+ const budgetExceeded = vi.fn();
1051
+ const errors = [];
1052
+ try {
1053
+ fs.mkdirSync(path.join(external, "many", "nested", "directories", "under", "the", "alias"), { recursive: true });
1054
+ fs.mkdirSync(path.join(root, ".codex"), { recursive: true });
1055
+ fs.writeFileSync(path.join(root, ".codex", "config.toml"), "model = 'test'\n");
1056
+ fs.mkdirSync(path.join(root, "workspace", "agency", "scratch"), { recursive: true });
1057
+ fs.writeFileSync(path.join(root, "workspace", "agency", "scratch", "notes.md"), "notes\n");
1058
+ fs.symlinkSync(external, link, "dir");
1059
+ const filter = createWatchPathFilter(root, true);
1060
+ expect(filter(path.join(root, ".codex", "config.toml"))).toBe(true);
1061
+ expect(filter(path.join(root, "workspace", "agency", "scratch", "notes.md"))).toBe(true);
1062
+ const backend = startTreeWatch(root, filter, (absolutePath, kind) => events.push({ path: absolutePath, kind }), (error) => errors.push(error), 7, budgetExceeded, undefined, true);
1063
+ try {
1064
+ await waitReady(backend);
1065
+ expect(backend.mode).toBe("polling");
1066
+ // Root + .codex + workspace/agency/scratch; the link target costs no watches.
1067
+ expect(backend.watchedPathCount()).toBe(5);
1068
+ expect(budgetExceeded).not.toHaveBeenCalled();
1069
+ expect(errors).toEqual([]);
1070
+ fs.unlinkSync(link);
1071
+ await waitFor(() => events.some((event) => event.path === link && event.kind === "unlink"));
1072
+ fs.symlinkSync(external, link, "dir");
1073
+ await waitFor(() => events.some((event) => event.path === link && event.kind === "add"));
1074
+ expect(backend.watchedPathCount()).toBe(5);
1075
+ }
1076
+ finally {
1077
+ backend.close();
1078
+ }
1079
+ }
1080
+ finally {
1081
+ fs.rmSync(root, { recursive: true, force: true });
1082
+ fs.rmSync(external, { recursive: true, force: true });
1083
+ }
1084
+ });
1085
+ it("continues watching when the supplied HQ root is itself a symlink", async () => {
1086
+ const realRoot = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "watch-poll-real-root-")));
1087
+ const parent = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "watch-poll-root-link-")));
1088
+ const linkedRoot = path.join(parent, "hq");
1089
+ const events = [];
1090
+ const errors = [];
1091
+ fs.mkdirSync(path.join(realRoot, "workspace", "agency", "scratch"), { recursive: true });
1092
+ fs.symlinkSync(realRoot, linkedRoot, "dir");
1093
+ const filter = createWatchPathFilter(linkedRoot, true);
1094
+ const backend = startTreeWatch(linkedRoot, filter, (absolutePath) => events.push(absolutePath), (error) => errors.push(error), 20, () => { }, undefined, true);
1095
+ try {
1096
+ await waitReady(backend);
1097
+ const file = path.join(linkedRoot, "workspace", "agency", "scratch", "after-ready.md");
1098
+ // A single write in the same turn as ready can be absorbed as the
1099
+ // fs.watchFile polling baseline and never emitted. Rewriting that same
1100
+ // file cannot prove the baseline: a content change does not update the
1101
+ // directory mtime, and a new size every 300ms never satisfies
1102
+ // awaitWriteFinish's 500ms stable-size window. A reported add for a
1103
+ // later probe file is that proof. Then write the asserted file once.
1104
+ // The whole wait stays inside the existing 6000ms waitFor deadline.
1105
+ // The asserted path must be the symlink spelling.
1106
+ const deadline = Date.now() + 6000;
1107
+ const scratch = path.dirname(file);
1108
+ const probes = new Set();
1109
+ let probeN = 0;
1110
+ let lastProbeAt = 0;
1111
+ const probeSeen = () => events.some((event) => probes.has(event));
1112
+ while (Date.now() < deadline && !probeSeen()) {
1113
+ const now = Date.now();
1114
+ if (now - lastProbeAt >= 300) {
1115
+ probeN += 1;
1116
+ const probe = path.join(scratch, `baseline-probe-${probeN}.md`);
1117
+ probes.add(probe);
1118
+ fs.writeFileSync(probe, `probe ${probeN}\n`);
1119
+ lastProbeAt = now;
1120
+ }
1121
+ await new Promise((resolve) => setTimeout(resolve, 25));
1122
+ }
1123
+ fs.writeFileSync(file, "observed\n");
1124
+ while (Date.now() < deadline && !events.includes(file)) {
1125
+ await new Promise((resolve) => setTimeout(resolve, 25));
1126
+ }
1127
+ expect(events.includes(file)).toBe(true);
1128
+ expect(errors).toEqual([]);
1129
+ }
1130
+ finally {
1131
+ backend.close();
1132
+ fs.rmSync(linkedRoot, { recursive: true, force: true });
1133
+ fs.rmSync(parent, { recursive: true, force: true });
1134
+ fs.rmSync(realRoot, { recursive: true, force: true });
1135
+ }
1136
+ });
1137
+ });
1138
+ describe("US-002: TreeWatcher — debounce coalesce (FakeClock seam)", () => {
1139
+ function makeWatcher(opts) {
1140
+ const clock = new FakeClock();
1141
+ const changed = vi.fn();
1142
+ const watcher = new TreeWatcher({
1143
+ hqRoot: ROOT,
1144
+ debounceMs: opts?.debounceMs ?? DEBOUNCE,
1145
+ personalMode: opts?.personalMode ?? false,
1146
+ clock,
1147
+ });
1148
+ watcher.onChange(changed);
1149
+ return { clock, changed, watcher };
1150
+ }
1151
+ it("coalesces 5 rapid changes within the window into exactly 1 changed signal", () => {
1152
+ const { clock, changed, watcher } = makeWatcher();
1153
+ for (let i = 0; i < 5; i++) {
1154
+ watcher.handleEvent(path.join(ROOT, `personal/file-${i}.md`));
1155
+ clock.advance(20); // 100ms total << 2000ms debounce
1156
+ }
1157
+ expect(changed).not.toHaveBeenCalled();
1158
+ clock.advance(DEBOUNCE);
1159
+ expect(changed).toHaveBeenCalledTimes(1);
1160
+ expect(watcher.pendingTimerCount()).toBe(0);
1161
+ });
1162
+ it("fires once after the quiet window for a single change", () => {
1163
+ const { clock, changed, watcher } = makeWatcher();
1164
+ watcher.handleEvent(path.join(ROOT, "personal/a.md"));
1165
+ clock.advance(DEBOUNCE - 1);
1166
+ expect(changed).not.toHaveBeenCalled();
1167
+ clock.advance(1);
1168
+ expect(changed).toHaveBeenCalledTimes(1);
1169
+ });
1170
+ it("flushes a quiet, known-small batch through the 60s debounce window", () => {
1171
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watcher-small-debounce-"));
1172
+ try {
1173
+ const small = path.join(dir, "small.md");
1174
+ fs.writeFileSync(small, "sixteen-byte-doc");
1175
+ const clock = new FakeClock();
1176
+ const changed = vi.fn();
1177
+ const watcher = new TreeWatcher({
1178
+ hqRoot: dir,
1179
+ debounceMs: 60_000,
1180
+ smallBatchDebounceMs: 60_000,
1181
+ smallBatchMaxPaths: 8,
1182
+ smallBatchMaxBytes: 1024 * 1024,
1183
+ clock,
1184
+ pathFilter: () => true,
1185
+ });
1186
+ watcher.onChange(changed);
1187
+ watcher.handleEvent(small);
1188
+ // The old 2.5s small-batch fast path must no longer fire.
1189
+ clock.advance(2_500);
1190
+ expect(changed).not.toHaveBeenCalled();
1191
+ clock.advance(57_499);
1192
+ expect(changed).not.toHaveBeenCalled();
1193
+ clock.advance(1);
1194
+ expect(changed).toHaveBeenCalledTimes(1);
1195
+ expect(changed.mock.calls[0][1].paths.get(small)).toBe("small.md");
1196
+ watcher.dispose();
1197
+ }
1198
+ finally {
1199
+ fs.rmSync(dir, { recursive: true, force: true });
1200
+ }
1201
+ });
1202
+ it("keeps a burst above the small-path cap on the 60s debounce", () => {
1203
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watcher-burst-debounce-"));
1204
+ try {
1205
+ const clock = new FakeClock();
1206
+ const changed = vi.fn();
1207
+ const watcher = new TreeWatcher({
1208
+ hqRoot: dir,
1209
+ debounceMs: 60_000,
1210
+ smallBatchDebounceMs: 60_000,
1211
+ smallBatchMaxPaths: 8,
1212
+ smallBatchMaxBytes: 1024 * 1024,
1213
+ clock,
1214
+ pathFilter: () => true,
1215
+ });
1216
+ watcher.onChange(changed);
1217
+ for (let index = 0; index < 9; index += 1) {
1218
+ const file = path.join(dir, `burst-${index}.md`);
1219
+ fs.writeFileSync(file, "small");
1220
+ watcher.handleEvent(file);
1221
+ clock.advance(100);
1222
+ }
1223
+ // The final event landed at t=800ms; the loop's final 100ms advance is
1224
+ // outside the quiet window, so stop one millisecond before t=60_800ms.
1225
+ clock.advance(59_899);
1226
+ expect(changed).not.toHaveBeenCalled();
1227
+ clock.advance(1);
1228
+ expect(changed).toHaveBeenCalledTimes(1);
1229
+ expect(changed.mock.calls[0][1].paths.size).toBe(9);
1230
+ watcher.dispose();
1231
+ }
1232
+ finally {
1233
+ fs.rmSync(dir, { recursive: true, force: true });
1234
+ }
1235
+ });
1236
+ it("preserves max-wait for a continuous small batch that never becomes quiet", () => {
1237
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watcher-small-max-wait-"));
1238
+ try {
1239
+ const file = path.join(dir, "continuous.md");
1240
+ fs.writeFileSync(file, "small");
1241
+ const clock = new FakeClock();
1242
+ const changed = vi.fn();
1243
+ const watcher = new TreeWatcher({
1244
+ hqRoot: dir,
1245
+ debounceMs: 60_000,
1246
+ maxWaitMs: 120_000,
1247
+ smallBatchDebounceMs: 60_000,
1248
+ smallBatchMaxPaths: 8,
1249
+ smallBatchMaxBytes: 1024 * 1024,
1250
+ clock,
1251
+ pathFilter: () => true,
1252
+ });
1253
+ watcher.onChange(changed);
1254
+ for (let elapsed = 0; elapsed < 120_000; elapsed += 2_000) {
1255
+ watcher.handleEvent(file);
1256
+ if (elapsed < 118_000)
1257
+ clock.advance(2_000);
1258
+ }
1259
+ expect(changed).not.toHaveBeenCalled();
1260
+ clock.advance(2_000);
1261
+ expect(changed).toHaveBeenCalledTimes(1);
1262
+ watcher.dispose();
1263
+ }
1264
+ finally {
1265
+ fs.rmSync(dir, { recursive: true, force: true });
1266
+ }
1267
+ });
1268
+ it("keeps a duplicate directory delete out of the short debounce lane", () => {
1269
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watcher-delete-debounce-"));
1270
+ try {
1271
+ const deleted = path.join(dir, "deleted-directory");
1272
+ const clock = new FakeClock();
1273
+ const changed = vi.fn();
1274
+ const watcher = new TreeWatcher({
1275
+ hqRoot: dir,
1276
+ debounceMs: 60_000,
1277
+ smallBatchDebounceMs: 60_000,
1278
+ smallBatchMaxPaths: 8,
1279
+ smallBatchMaxBytes: 1024 * 1024,
1280
+ clock,
1281
+ pathFilter: () => true,
1282
+ });
1283
+ watcher.onChange(changed);
1284
+ watcher.handleEvent(deleted, "unlinkDir");
1285
+ watcher.handleEvent(deleted, "unlink");
1286
+ clock.advance(59_999);
1287
+ expect(changed).not.toHaveBeenCalled();
1288
+ clock.advance(1);
1289
+ expect(changed).toHaveBeenCalledTimes(1);
1290
+ expect(changed.mock.calls[0][1].changes.get(deleted)).toMatchObject({
1291
+ kind: "unlinkDir",
1292
+ });
1293
+ watcher.dispose();
1294
+ }
1295
+ finally {
1296
+ fs.rmSync(dir, { recursive: true, force: true });
1297
+ }
1298
+ });
1299
+ it("keeps an overflowed batch out of the short debounce lane", () => {
1300
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watcher-overflow-debounce-"));
1301
+ try {
1302
+ const first = path.join(dir, "first.md");
1303
+ const dropped = path.join(dir, "dropped.md");
1304
+ fs.writeFileSync(first, "small");
1305
+ fs.writeFileSync(dropped, "small");
1306
+ const clock = new FakeClock();
1307
+ const changed = vi.fn();
1308
+ const watcher = new TreeWatcher({
1309
+ hqRoot: dir,
1310
+ debounceMs: 60_000,
1311
+ smallBatchDebounceMs: 60_000,
1312
+ smallBatchMaxPaths: 8,
1313
+ smallBatchMaxBytes: 1024 * 1024,
1314
+ maxPendingPaths: 1,
1315
+ maxPendingBytes: 1024 * 1024,
1316
+ clock,
1317
+ pathFilter: () => true,
1318
+ onBacklogOverflow: () => undefined,
1319
+ });
1320
+ watcher.onChange(changed);
1321
+ watcher.handleEvent(first);
1322
+ watcher.handleEvent(dropped);
1323
+ clock.advance(59_999);
1324
+ expect(changed).not.toHaveBeenCalled();
1325
+ clock.advance(1);
1326
+ expect(changed).toHaveBeenCalledTimes(1);
1327
+ expect(changed.mock.calls[0][1]).toMatchObject({ overflowed: true });
1328
+ watcher.dispose();
1329
+ }
1330
+ finally {
1331
+ fs.rmSync(dir, { recursive: true, force: true });
1332
+ }
1333
+ });
1334
+ it("does NOT emit for an ignored / excluded path", () => {
1335
+ const { clock, changed, watcher } = makeWatcher({ personalMode: true });
1336
+ watcher.handleEvent(path.join(ROOT, ".env"));
1337
+ watcher.handleEvent(path.join(ROOT, "personal/output/big.bin"));
1338
+ watcher.handleEvent(path.join(ROOT, "companies/indigo/board.json"));
1339
+ clock.advance(DEBOUNCE * 2);
1340
+ expect(changed).not.toHaveBeenCalled();
1341
+ expect(watcher.pendingTimerCount()).toBe(0);
1342
+ });
1343
+ it("max-wait ceiling: a continuous event stream still emits one coalesced batch", () => {
1344
+ const clock = new FakeClock();
1345
+ const changed = vi.fn();
1346
+ const watcher = new TreeWatcher({
1347
+ hqRoot: ROOT,
1348
+ debounceMs: 60_000,
1349
+ maxWaitMs: 120_000,
1350
+ personalMode: false,
1351
+ clock,
1352
+ });
1353
+ watcher.onChange(changed);
1354
+ // Events every 10s — the quiet window (60s) never elapses, so only the
1355
+ // max-wait ceiling can fire. Events land at t=0s..110s.
1356
+ for (let i = 0; i < 12; i++) {
1357
+ watcher.handleEvent(path.join(ROOT, `personal/file-${i % 3}.md`));
1358
+ if (i < 11)
1359
+ clock.advance(10_000);
1360
+ }
1361
+ expect(changed).not.toHaveBeenCalled();
1362
+ clock.advance(10_000); // reaches t=120s — the ceiling since the FIRST event
1363
+ expect(changed).toHaveBeenCalledTimes(1);
1364
+ // One coalesced batch carrying every distinct path of the stream.
1365
+ const batch = changed.mock.calls[0][1];
1366
+ expect([...batch.paths.values()].sort()).toEqual([
1367
+ "personal/file-0.md",
1368
+ "personal/file-1.md",
1369
+ "personal/file-2.md",
1370
+ ]);
1371
+ // The ceiling resets between windows: a fresh burst gets a fresh window
1372
+ // and settles on the ordinary quiet period.
1373
+ watcher.handleEvent(path.join(ROOT, "personal/next.md"));
1374
+ clock.advance(60_000);
1375
+ expect(changed).toHaveBeenCalledTimes(2);
1376
+ expect(watcher.pendingTimerCount()).toBe(0);
1377
+ watcher.dispose();
1378
+ });
1379
+ it("max-wait ceiling never fires before one quiet window (floored at debounceMs)", () => {
1380
+ const clock = new FakeClock();
1381
+ const changed = vi.fn();
1382
+ const watcher = new TreeWatcher({
1383
+ hqRoot: ROOT,
1384
+ debounceMs: 60_000,
1385
+ maxWaitMs: 1, // absurdly low — must be floored to the quiet window
1386
+ personalMode: false,
1387
+ clock,
1388
+ });
1389
+ watcher.onChange(changed);
1390
+ watcher.handleEvent(path.join(ROOT, "personal/a.md"));
1391
+ clock.advance(59_999);
1392
+ expect(changed).not.toHaveBeenCalled();
1393
+ clock.advance(1);
1394
+ expect(changed).toHaveBeenCalledTimes(1);
1395
+ watcher.dispose();
1396
+ });
1397
+ it("without maxWaitMs the legacy pure quiet-window behavior is preserved", () => {
1398
+ const { clock, changed, watcher } = makeWatcher();
1399
+ // Keep resetting the quiet window far past any would-be ceiling.
1400
+ for (let i = 0; i < 200; i++) {
1401
+ watcher.handleEvent(path.join(ROOT, "personal/a.md"));
1402
+ clock.advance(DEBOUNCE - 1);
1403
+ }
1404
+ expect(changed).not.toHaveBeenCalled();
1405
+ clock.advance(DEBOUNCE);
1406
+ expect(changed).toHaveBeenCalledTimes(1);
1407
+ });
1408
+ it("treats two separate bursts as two changed signals", () => {
1409
+ const { clock, changed, watcher } = makeWatcher();
1410
+ watcher.handleEvent(path.join(ROOT, "personal/a.md"));
1411
+ clock.advance(DEBOUNCE);
1412
+ expect(changed).toHaveBeenCalledTimes(1);
1413
+ watcher.handleEvent(path.join(ROOT, "personal/b.md"));
1414
+ clock.advance(DEBOUNCE);
1415
+ expect(changed).toHaveBeenCalledTimes(2);
1416
+ });
1417
+ it("R-F13: caps watcher backlog and keeps EMFILE polling fallback removed", () => {
1418
+ const clock = new FakeClock();
1419
+ const changed = vi.fn();
1420
+ const overflow = vi.fn();
1421
+ const watcher = new TreeWatcher({
1422
+ hqRoot: ROOT,
1423
+ debounceMs: DEBOUNCE,
1424
+ clock,
1425
+ pathFilter: () => true,
1426
+ maxPendingPaths: 3,
1427
+ maxPendingBytes: 10_000,
1428
+ onBacklogOverflow: overflow,
1429
+ });
1430
+ watcher.onChange(changed);
1431
+ for (let i = 0; i < 10; i++) {
1432
+ watcher.handleEvent(path.join(ROOT, `bulk-${i}.md`));
1433
+ }
1434
+ expect(overflow).toHaveBeenCalledTimes(1);
1435
+ clock.advance(DEBOUNCE);
1436
+ expect(changed).toHaveBeenCalledTimes(1);
1437
+ const batch = changed.mock.calls[0][1];
1438
+ expect(batch.paths.size).toBe(3);
1439
+ expect(batch.overflowed).toBe(true);
1440
+ expect(batch.droppedPaths).toBe(7);
1441
+ const source = fs.readFileSync(path.join(process.cwd(), "src/watcher.ts"), "utf8");
1442
+ expect(source).not.toContain("startPollingTreeWatch");
1443
+ expect(source).not.toContain("snapshotWatchTree");
1444
+ });
1445
+ it("overflow records one dropped-route hint per touched route so the drain can stay targeted", () => {
1446
+ const clock = new FakeClock();
1447
+ const changed = vi.fn();
1448
+ const watcher = new TreeWatcher({
1449
+ hqRoot: ROOT,
1450
+ debounceMs: DEBOUNCE,
1451
+ clock,
1452
+ pathFilter: () => true,
1453
+ maxPendingPaths: 2,
1454
+ maxPendingBytes: 10_000,
1455
+ onBacklogOverflow: () => { },
1456
+ });
1457
+ watcher.onChange(changed);
1458
+ // Two retained, then drops spanning two company routes + personal.
1459
+ watcher.handleEvent(path.join(ROOT, "companies", "indigo", "kept-a.md"));
1460
+ watcher.handleEvent(path.join(ROOT, "companies", "indigo", "kept-b.md"));
1461
+ watcher.handleEvent(path.join(ROOT, "companies", "indigo", "dropped-1.md"));
1462
+ watcher.handleEvent(path.join(ROOT, "companies", "acme", "dropped-2.md"));
1463
+ watcher.handleEvent(path.join(ROOT, "notes", "dropped-3.md"));
1464
+ clock.advance(DEBOUNCE);
1465
+ const batch = changed.mock.calls[0][1];
1466
+ expect(batch.overflowed).toBe(true);
1467
+ expect(batch.droppedPaths).toBe(3);
1468
+ // One representative relative path per route (companies/indigo,
1469
+ // companies/acme, personal) — enough to reconstruct the touched-route
1470
+ // set without holding the dropped paths themselves.
1471
+ expect(batch.droppedRouteHints?.sort()).toEqual([
1472
+ "companies/acme/dropped-2.md",
1473
+ "companies/indigo/dropped-1.md",
1474
+ "notes/dropped-3.md",
1475
+ ]);
1476
+ // Next window starts clean: a non-overflow batch carries no hints.
1477
+ changed.mockClear();
1478
+ watcher.handleEvent(path.join(ROOT, "companies", "indigo", "later.md"));
1479
+ clock.advance(DEBOUNCE);
1480
+ const nextBatch = changed.mock.calls[0][1];
1481
+ expect(nextBatch.overflowed).toBeUndefined();
1482
+ expect(nextBatch.droppedRouteHints).toBeUndefined();
1483
+ });
1484
+ it("stops descending at the hard watch budget, reports, and degrades to polling", () => {
1485
+ const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "watch-cap-")));
1486
+ fs.mkdirSync(path.join(dir, "personal", "a", "deep"), { recursive: true });
1487
+ fs.mkdirSync(path.join(dir, "personal", "b", "deep"), { recursive: true });
1488
+ const clock = new FakeClock();
1489
+ const degraded = vi.fn();
1490
+ const changed = vi.fn();
1491
+ const descended = [];
1492
+ let backendClosed = false;
1493
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => undefined);
1494
+ try {
1495
+ const watcher = new TreeWatcher({
1496
+ hqRoot: dir,
1497
+ clock,
1498
+ debounceMs: DEBOUNCE,
1499
+ maxWatchedPaths: 3,
1500
+ onDegraded: degraded,
1501
+ // This faked backend drives chokidar's real ignored predicate through
1502
+ // its pre-stat and post-stat calls, without needing an inotify slot on
1503
+ // a host already exhausted by another process.
1504
+ backendFactory: ({ hqRoot, shouldEmit, maxWatchedPaths, onWatchBudgetExceeded, }) => {
1505
+ const budget = new ChokidarWatchBudget(maxWatchedPaths, onWatchBudgetExceeded);
1506
+ const ignored = toChokidarIgnored(shouldEmit, hqRoot, budget);
1507
+ const visit = (candidate) => {
1508
+ if (ignored(candidate))
1509
+ return;
1510
+ const stats = fs.lstatSync(candidate);
1511
+ if (ignored(candidate, stats))
1512
+ return;
1513
+ if (!stats.isDirectory())
1514
+ return;
1515
+ descended.push(path.resolve(candidate));
1516
+ for (const entry of fs.readdirSync(candidate)) {
1517
+ visit(path.join(candidate, entry));
1518
+ }
1519
+ };
1520
+ visit(hqRoot);
1521
+ return {
1522
+ close: () => {
1523
+ backendClosed = true;
1524
+ },
1525
+ needsKnownKinds: false,
1526
+ watchedPathCount: () => descended.length,
1527
+ };
1528
+ },
1529
+ });
1530
+ watcher.onChange(changed);
1531
+ watcher.start();
1532
+ expect(descended).toHaveLength(3);
1533
+ expect(descended).not.toContain(path.join(dir, "personal", "a", "deep"));
1534
+ expect(degraded).toHaveBeenCalledWith(expect.objectContaining({
1535
+ reason: "watch_budget_exhausted",
1536
+ maxWatchedPaths: 3,
1537
+ watchedPaths: 3,
1538
+ offendingPath: expect.stringContaining(path.join("personal", "a", "deep")),
1539
+ }));
1540
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('"type":"watch-scope-excluded"'));
1541
+ expect(warn).toHaveBeenCalledWith(expect.stringContaining('"excludedRoot"'));
1542
+ expect(backendClosed).toBe(true);
1543
+ expect(watcher.isWatching()).toBe(false);
1544
+ clock.advance(DEBOUNCE);
1545
+ expect(changed).toHaveBeenCalledWith(undefined, expect.objectContaining({ overflowed: true }));
1546
+ }
1547
+ finally {
1548
+ warn.mockRestore();
1549
+ fs.rmSync(dir, { recursive: true, force: true });
1550
+ }
1551
+ });
1552
+ it.each(["ENOSPC", "EMFILE", "ENFILE"])("keeps event watching through polling when a backend emits runtime %s", (errorCode) => {
1553
+ const clock = new FakeClock();
1554
+ const degraded = vi.fn();
1555
+ const changed = vi.fn();
1556
+ const telemetry = [];
1557
+ const telemetryClient = {
1558
+ postTelemetryEvents: vi.fn(async (batch) => {
1559
+ telemetry.push(batch);
1560
+ return { ok: true, written: batch.events.length, skipped: [] };
1561
+ }),
1562
+ };
1563
+ let closeCalls = 0;
1564
+ const watcher = new TreeWatcher({
1565
+ hqRoot: ROOT,
1566
+ clock,
1567
+ debounceMs: DEBOUNCE,
1568
+ onDegraded: degraded,
1569
+ telemetryClient,
1570
+ backendFactory: ({ forcePolling, onError }) => {
1571
+ const backend = {
1572
+ close: () => {
1573
+ closeCalls += 1;
1574
+ },
1575
+ needsKnownKinds: false,
1576
+ mode: forcePolling ? "polling" : "chokidar",
1577
+ watchedPathCount: () => forcePolling ? 200 : 0,
1578
+ };
1579
+ if (!forcePolling) {
1580
+ queueMicrotask(() => onError(Object.assign(new Error("watch resource limit"), {
1581
+ code: errorCode,
1582
+ path: path.join(ROOT, "companies", "acme", "knowledge"),
1583
+ })));
1584
+ }
1585
+ return backend;
1586
+ },
1587
+ });
1588
+ watcher.onChange(changed);
1589
+ watcher.start();
1590
+ return new Promise((resolve) => queueMicrotask(resolve)).then(() => {
1591
+ expect(closeCalls).toBe(1);
1592
+ expect(watcher.isWatching()).toBe(true);
1593
+ expect(watcher.watchMode()).toBe("polling");
1594
+ expect(watcher.watchedPathCount()).toBe(200);
1595
+ const reason = errorCode === "ENOSPC" ? "inotify_enospc" : "watch_resource_exhausted";
1596
+ expect(degraded).toHaveBeenCalledWith(expect.objectContaining({
1597
+ reason,
1598
+ errorCode,
1599
+ offendingPath: path.join(ROOT, "companies", "acme", "knowledge"),
1600
+ }));
1601
+ expect(telemetry).toEqual([
1602
+ expect.objectContaining({
1603
+ events: [
1604
+ expect.objectContaining({
1605
+ eventName: "watcher_degraded",
1606
+ source: "watcher",
1607
+ properties: expect.objectContaining({
1608
+ reason,
1609
+ offendingTopLevel: "companies",
1610
+ }),
1611
+ }),
1612
+ ],
1613
+ }),
1614
+ ]);
1615
+ clock.advance(DEBOUNCE);
1616
+ expect(changed).toHaveBeenCalledWith(undefined, expect.objectContaining({ overflowed: true }));
1617
+ });
1618
+ });
1619
+ it("keeps a large synthetic watch set alive across multiple debounced passes", () => {
1620
+ const clock = new FakeClock();
1621
+ const changed = vi.fn();
1622
+ const handles = new Set(Array.from({ length: 20_000 }, (_, i) => `dir-${i}`));
1623
+ const watcher = new TreeWatcher({
1624
+ hqRoot: ROOT,
1625
+ clock,
1626
+ debounceMs: DEBOUNCE,
1627
+ backendFactory: () => ({
1628
+ close: () => handles.clear(),
1629
+ mode: "chokidar",
1630
+ needsKnownKinds: false,
1631
+ watchedPathCount: () => handles.size,
1632
+ }),
1633
+ });
1634
+ watcher.onChange(changed);
1635
+ watcher.start();
1636
+ for (let pass = 0; pass < 3; pass += 1) {
1637
+ watcher.handleEvent(path.join(ROOT, "personal", `change-${pass}.md`));
1638
+ clock.advance(DEBOUNCE);
1639
+ expect(watcher.isWatching()).toBe(true);
1640
+ expect(watcher.watchedPathCount()).toBe(20_000);
1641
+ }
1642
+ expect(changed).toHaveBeenCalledTimes(3);
1643
+ watcher.dispose();
1644
+ });
1645
+ it("continues initial discovery while the watched-path count is still growing", () => {
1646
+ const clock = new FakeClock();
1647
+ const degraded = vi.fn();
1648
+ let watchedPaths = 0;
1649
+ const watcher = new TreeWatcher({
1650
+ hqRoot: ROOT,
1651
+ clock,
1652
+ discoveryTimeoutMs: 100,
1653
+ onDegraded: degraded,
1654
+ backendFactory: () => ({
1655
+ close: () => { },
1656
+ mode: "chokidar",
1657
+ needsKnownKinds: false,
1658
+ watchedPathCount: () => watchedPaths,
1659
+ // Deliberately never ready: this models a large, still-discovering tree.
1660
+ onReady: () => () => { },
1661
+ }),
1662
+ });
1663
+ watcher.start();
1664
+ watchedPaths = 9_220;
1665
+ clock.advance(100);
1666
+ watchedPaths = 14_588;
1667
+ clock.advance(100);
1668
+ expect(watcher.isWatching()).toBe(true);
1669
+ expect(watcher.watchMode()).toBe("chokidar");
1670
+ expect(degraded).not.toHaveBeenCalled();
1671
+ watcher.dispose();
1672
+ });
1673
+ it("stands down loudly when polling discovery also times out", () => {
1674
+ const clock = new FakeClock();
1675
+ const degraded = vi.fn();
1676
+ let closeCalls = 0;
1677
+ const watcher = new TreeWatcher({
1678
+ hqRoot: ROOT,
1679
+ clock,
1680
+ discoveryTimeoutMs: 100,
1681
+ onDegraded: degraded,
1682
+ backendFactory: ({ forcePolling }) => ({
1683
+ close: () => { closeCalls += 1; },
1684
+ mode: forcePolling ? "polling" : "chokidar",
1685
+ needsKnownKinds: false,
1686
+ watchedPathCount: () => forcePolling ? 20 : 10,
1687
+ // Deliberately never invokes its listener: this simulates discovery
1688
+ // that hangs before chokidar can report ready.
1689
+ onReady: () => () => { },
1690
+ }),
1691
+ });
1692
+ watcher.start();
1693
+ clock.advance(100);
1694
+ expect(watcher.isWatching()).toBe(true);
1695
+ expect(watcher.watchMode()).toBe("polling");
1696
+ clock.advance(100);
1697
+ expect(watcher.isWatching()).toBe(false);
1698
+ expect(closeCalls).toBe(2);
1699
+ expect(degraded).toHaveBeenLastCalledWith(expect.objectContaining({
1700
+ reason: "initial_discovery_timeout",
1701
+ action: "stopped",
1702
+ watchedPaths: 20,
1703
+ }));
1704
+ });
1705
+ it("does not retain one rename-kind entry for every changed file", () => {
1706
+ const clock = new FakeClock();
1707
+ const watcher = new TreeWatcher({
1708
+ hqRoot: ROOT,
1709
+ clock,
1710
+ pathFilter: () => true,
1711
+ maxPendingPaths: 20_000,
1712
+ maxPendingBytes: 20_000_000,
1713
+ });
1714
+ for (let i = 0; i < 10_000; i++) {
1715
+ watcher.handleEvent(path.join(ROOT, "personal", `file-${i}.md`));
1716
+ }
1717
+ expect(watcher.knownDirectoryCount()).toBe(0);
1718
+ watcher.stop();
1719
+ });
1720
+ });
1721
+ describe("US-002: TreeWatcher — lifecycle (real chokidar over a temp dir)", () => {
1722
+ let dir;
1723
+ beforeEach(() => {
1724
+ // realpathSync resolves macOS's /var -> /private/var symlink so chokidar's
1725
+ // canonicalized event paths stay inside hqRoot (path.relative would
1726
+ // otherwise yield a `..`-prefixed path and the filter would reject them).
1727
+ dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "treewatcher-")));
1728
+ });
1729
+ afterEach(() => {
1730
+ fs.rmSync(dir, { recursive: true, force: true });
1731
+ });
1732
+ it("start() is idempotent — a second start does not open a second watcher", () => {
1733
+ const w = new TreeWatcher({ hqRoot: dir });
1734
+ w.start();
1735
+ expect(w.isWatching()).toBe(true);
1736
+ w.start(); // no throw, no second instance
1737
+ expect(w.isWatching()).toBe(true);
1738
+ w.stop();
1739
+ expect(w.isWatching()).toBe(false);
1740
+ });
1741
+ it("stop() closes the watcher and clears pending timers; dispose() is permanent", () => {
1742
+ const clock = new FakeClock();
1743
+ const w = new TreeWatcher({ hqRoot: dir, clock });
1744
+ w.start();
1745
+ w.handleEvent(path.join(dir, "x.md"));
1746
+ expect(w.pendingTimerCount()).toBe(1);
1747
+ w.stop();
1748
+ expect(w.pendingTimerCount()).toBe(0);
1749
+ expect(w.isWatching()).toBe(false);
1750
+ // After dispose, events are inert and start is a no-op.
1751
+ w.dispose();
1752
+ w.handleEvent(path.join(dir, "y.md"));
1753
+ expect(w.pendingTimerCount()).toBe(0);
1754
+ w.start();
1755
+ expect(w.isWatching()).toBe(false);
1756
+ });
1757
+ it("emits a debounced changed signal for a real file write", async () => {
1758
+ const w = new TreeWatcher({ hqRoot: dir, debounceMs: 50 });
1759
+ const changed = vi.fn();
1760
+ w.onChange(changed);
1761
+ w.start();
1762
+ // Give chokidar a beat to set up its watch before writing.
1763
+ await new Promise((r) => setTimeout(r, 200));
1764
+ fs.writeFileSync(path.join(dir, "hello.md"), "hi");
1765
+ await new Promise((r) => setTimeout(r, 1500));
1766
+ expect(changed).toHaveBeenCalled();
1767
+ w.dispose();
1768
+ }, 10_000);
1769
+ });
1770
+ describe("PushEventEmitter — directory and delete tombstone handling", () => {
1771
+ let dir;
1772
+ beforeEach(() => {
1773
+ dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "pushemit-")));
1774
+ });
1775
+ afterEach(() => {
1776
+ fs.rmSync(dir, { recursive: true, force: true });
1777
+ });
1778
+ it("replays randomized hash records with the same LRU state as the legacy reducer", () => {
1779
+ const records = publishedHashRecords(4_096);
1780
+ expect(replayDurablePublishedContentHashRecordsForTest(records, true))
1781
+ .toEqual(replayDurablePublishedContentHashRecordsForTest(records, false));
1782
+ });
1783
+ it("replays legacy records followed by a batch with the exact single-record LRU state", () => {
1784
+ const batchEntries = [
1785
+ { kind: "delete", relativePath: "alpha" },
1786
+ { kind: "set", relativePath: "gamma", contentHash: "sha256:gamma", maxPaths: 2 },
1787
+ { kind: "set", relativePath: "beta", contentHash: "sha256:beta-new", maxPaths: 2 },
1788
+ ];
1789
+ const legacyThenBatch = [
1790
+ { sequence: 1, type: 0x5031, flags: 0, payload: { relativePath: "alpha", contentHash: "sha256:alpha", maxPaths: 2 } },
1791
+ { sequence: 2, type: 0x5031, flags: 0, payload: { relativePath: "beta", contentHash: "sha256:beta", maxPaths: 2 } },
1792
+ { sequence: 3, type: 0x5033, flags: 0, payload: { entries: batchEntries } },
1793
+ ];
1794
+ const equivalentSingles = [
1795
+ ...legacyThenBatch.slice(0, 2),
1796
+ ...batchEntries.map((entry, index) => ({
1797
+ sequence: index + 3,
1798
+ type: entry.kind === "set" ? 0x5031 : 0x5032,
1799
+ flags: 0,
1800
+ payload: entry.kind === "set"
1801
+ ? { relativePath: entry.relativePath, contentHash: entry.contentHash, maxPaths: entry.maxPaths }
1802
+ : { relativePath: entry.relativePath },
1803
+ })),
1804
+ ];
1805
+ const batched = replayDurablePublishedContentHashRecordsForTest(legacyThenBatch);
1806
+ expect(JSON.stringify(batched)).toBe(JSON.stringify(replayDurablePublishedContentHashRecordsForTest(equivalentSingles)));
1807
+ expect(batched).toEqual(replayDurablePublishedContentHashRecordsForTest(legacyThenBatch, false));
1808
+ });
1809
+ it("coalesces pull marks into one append and persists only the final mutation for a path", async () => {
1810
+ const clock = new FakeClock();
1811
+ const appendGenerated = vi.spyOn(StateStore.prototype, "appendGeneratedIfAsync");
1812
+ const stateDir = path.join(dir, "coalesced-state");
1813
+ const emitter = makeEmitter({ clock, lastPublishedContentHashStateDir: stateDir });
1814
+ const finalContent = "final revision\n";
1815
+ const finalHash = `sha256:${createHash("sha256").update(finalContent).digest("hex")}`;
1816
+ try {
1817
+ for (let index = 0; index < 128; index++) {
1818
+ emitter.markContentPublished(`path-${index}.md`, `sha256:${index}`);
1819
+ }
1820
+ emitter.markContentPublished("same.md", "sha256:obsolete");
1821
+ emitter.markContentPublished("same.md", finalHash);
1822
+ clock.advance(DURABLE_PUBLISHED_HASH_BATCH_FLUSH_MS);
1823
+ await flushImmediate();
1824
+ expect(appendGenerated).toHaveBeenCalledTimes(1);
1825
+ await emitter.dispose();
1826
+ const samePath = path.join(dir, "same.md");
1827
+ fs.writeFileSync(samePath, finalContent);
1828
+ const published = [];
1829
+ await makeEmitter({ published, lastPublishedContentHashStateDir: stateDir }).emitForBatch({
1830
+ paths: new Map([[samePath, "same.md"]]),
1831
+ });
1832
+ expect(published).toEqual([]);
1833
+ }
1834
+ finally {
1835
+ appendGenerated.mockRestore();
1836
+ }
1837
+ });
1838
+ it("drops a stale guarded mutation at flush time without dropping the rest of its batch", async () => {
1839
+ const clock = new FakeClock();
1840
+ const hashes = new DurablePublishedContentHashes(path.join(dir, "predicate-state"), "test", 4, {}, clock);
1841
+ let shouldPersist = true;
1842
+ const stale = hashes.setIfCurrent("stale.md", "sha256:stale", 4, () => shouldPersist);
1843
+ const kept = hashes.set("kept.md", "sha256:kept", 4, false);
1844
+ shouldPersist = false;
1845
+ await hashes.dispose();
1846
+ await expect(stale).resolves.toBe(false);
1847
+ await expect(kept).resolves.toBeUndefined();
1848
+ expect(hashes.get("stale.md")).toBeUndefined();
1849
+ expect(hashes.get("kept.md")).toBe("sha256:kept");
1850
+ });
1851
+ it("flushes pending durable pull marks while disposing", async () => {
1852
+ const appendGenerated = vi.spyOn(StateStore.prototype, "appendGeneratedIfAsync");
1853
+ const emitter = makeEmitter({ lastPublishedContentHashStateDir: path.join(dir, "dispose-state") });
1854
+ try {
1855
+ emitter.markContentPublished("pending.md", "sha256:pending");
1856
+ await emitter.dispose();
1857
+ expect(appendGenerated).toHaveBeenCalledTimes(1);
1858
+ }
1859
+ finally {
1860
+ appendGenerated.mockRestore();
1861
+ }
1862
+ });
1863
+ it("reports and retries a failed durable hash append as one physical batch", async () => {
1864
+ const clock = new FakeClock();
1865
+ const onError = vi.fn();
1866
+ const appendGenerated = vi.spyOn(StateStore.prototype, "appendGeneratedIfAsync")
1867
+ .mockRejectedValueOnce(new StateStoreLockError("timed out acquiring append.lock"));
1868
+ const emitter = makeEmitter({
1869
+ clock,
1870
+ onError,
1871
+ lastPublishedContentHashStateDir: path.join(dir, "batch-lock-timeout-state"),
1872
+ });
1873
+ try {
1874
+ for (let index = 0; index < 128; index += 1) {
1875
+ emitter.markContentPublished(`batch-${index}.md`, `sha256:${index}`);
1876
+ }
1877
+ clock.advance(DURABLE_PUBLISHED_HASH_BATCH_FLUSH_MS);
1878
+ await flushImmediate();
1879
+ expect(onError).toHaveBeenCalledTimes(1);
1880
+ expect(onError.mock.calls[0]?.[0]).toMatchObject({ name: "StateStoreLockError" });
1881
+ expect((onError.mock.calls[0]?.[0]).message).toContain("128 mutations");
1882
+ expect(clock.pendingTimerCount()).toBe(1);
1883
+ }
1884
+ finally {
1885
+ await emitter.dispose();
1886
+ appendGenerated.mockRestore();
1887
+ }
1888
+ });
1889
+ it("does not revive a superseded mutation while its failed batch is retrying", async () => {
1890
+ const clock = new FakeClock();
1891
+ let releaseRetry;
1892
+ const retryGate = new Promise((resolve) => { releaseRetry = resolve; });
1893
+ let retryEntered;
1894
+ const retryStarted = new Promise((resolve) => { retryEntered = resolve; });
1895
+ const originalAppendGeneratedIfAsync = StateStore.prototype.appendGeneratedIfAsync;
1896
+ const appendGenerated = vi.spyOn(StateStore.prototype, "appendGeneratedIfAsync")
1897
+ .mockRejectedValueOnce(new StateStoreLockError("timed out acquiring append.lock"))
1898
+ .mockImplementationOnce(async function (type, preparePayload, flags) {
1899
+ retryEntered();
1900
+ await retryGate;
1901
+ return originalAppendGeneratedIfAsync.call(this, type, preparePayload, flags);
1902
+ });
1903
+ const hashes = new DurablePublishedContentHashes(path.join(dir, "superseded-batch-retry-state"), "test", 4, {}, clock);
1904
+ try {
1905
+ const stale = hashes.setIfCurrent("same.md", "sha256:stale", 4, () => true);
1906
+ await expect(stale).resolves.toBe(false);
1907
+ expect(clock.pendingTimerCount()).toBe(1);
1908
+ clock.advance(250);
1909
+ await retryStarted;
1910
+ const newer = hashes.set("same.md", "sha256:newer", 4, false);
1911
+ releaseRetry();
1912
+ await flushImmediate();
1913
+ clock.advance(DURABLE_PUBLISHED_HASH_BATCH_FLUSH_MS);
1914
+ await expect(newer).resolves.toBeUndefined();
1915
+ expect(hashes.get("same.md")).toBe("sha256:newer");
1916
+ }
1917
+ finally {
1918
+ await hashes.dispose();
1919
+ appendGenerated.mockRestore();
1920
+ }
1921
+ });
1922
+ it("rechecks a guarded mutation when its failed batch retries", async () => {
1923
+ const clock = new FakeClock();
1924
+ let shouldPersist = true;
1925
+ const appendGenerated = vi.spyOn(StateStore.prototype, "appendGeneratedIfAsync")
1926
+ .mockRejectedValueOnce(new StateStoreLockError("timed out acquiring append.lock"));
1927
+ const hashes = new DurablePublishedContentHashes(path.join(dir, "guarded-batch-retry-state"), "test", 4, {}, clock);
1928
+ try {
1929
+ const stale = hashes.setIfCurrent("stale.md", "sha256:stale", 4, () => shouldPersist);
1930
+ await expect(stale).resolves.toBe(false);
1931
+ shouldPersist = false;
1932
+ clock.advance(250);
1933
+ await flushImmediate();
1934
+ expect(hashes.get("stale.md")).toBeUndefined();
1935
+ expect(appendGenerated).toHaveBeenCalledTimes(2);
1936
+ }
1937
+ finally {
1938
+ await hashes.dispose();
1939
+ appendGenerated.mockRestore();
1940
+ }
1941
+ });
1942
+ it("drains an active publish into the durable memo before disposing", async () => {
1943
+ let releasePublish;
1944
+ const publishGate = new Promise((resolve) => { releasePublish = resolve; });
1945
+ let publishEntered;
1946
+ const publishStarted = new Promise((resolve) => { publishEntered = resolve; });
1947
+ const published = [];
1948
+ const stateDir = path.join(dir, "dispose-publish-drain-state");
1949
+ const changed = path.join(dir, "dispose-publish-drain.md");
1950
+ fs.writeFileSync(changed, "drain me\n");
1951
+ const emitter = makeEmitter({
1952
+ lastPublishedContentHashStateDir: stateDir,
1953
+ transport: {
1954
+ start: async () => { },
1955
+ dispose: async () => { },
1956
+ connected: true,
1957
+ publish: async (event) => {
1958
+ publishEntered();
1959
+ await publishGate;
1960
+ published.push(event);
1961
+ },
1962
+ },
1963
+ });
1964
+ const publishing = emitter.emitForBatch({ paths: new Map([[changed, "dispose-publish-drain.md"]]) });
1965
+ await publishStarted;
1966
+ let disposed = false;
1967
+ const disposing = emitter.dispose().then(() => { disposed = true; });
1968
+ await Promise.resolve();
1969
+ expect(disposed).toBe(false);
1970
+ releasePublish();
1971
+ await Promise.all([publishing, disposing]);
1972
+ const afterRestart = [];
1973
+ await makeEmitter({
1974
+ published: afterRestart,
1975
+ lastPublishedContentHashStateDir: stateDir,
1976
+ }).emitForBatch({ paths: new Map([[changed, "dispose-publish-drain.md"]]) });
1977
+ expect(published).toHaveLength(1);
1978
+ expect(afterRestart).toEqual([]);
1979
+ });
1980
+ it("leaves the durable memo open when a publish outlives the shutdown drain", async () => {
1981
+ const clock = new FakeClock();
1982
+ const onError = vi.fn();
1983
+ let releasePublish;
1984
+ const publishGate = new Promise((resolve) => { releasePublish = resolve; });
1985
+ let publishEntered;
1986
+ const publishStarted = new Promise((resolve) => { publishEntered = resolve; });
1987
+ const stateDir = path.join(dir, "dispose-timeout-state");
1988
+ const changed = path.join(dir, "dispose-timeout.md");
1989
+ fs.writeFileSync(changed, "late publish\n");
1990
+ const emitter = makeEmitter({
1991
+ clock,
1992
+ onError,
1993
+ lastPublishedContentHashStateDir: stateDir,
1994
+ transport: {
1995
+ start: async () => { },
1996
+ dispose: async () => { },
1997
+ connected: true,
1998
+ publish: async () => {
1999
+ publishEntered();
2000
+ await publishGate;
2001
+ },
2002
+ },
2003
+ });
2004
+ const publishing = emitter.emitForBatch({ paths: new Map([[changed, "dispose-timeout.md"]]) });
2005
+ await publishStarted;
2006
+ const disposing = emitter.dispose();
2007
+ clock.advance(60_000);
2008
+ await disposing;
2009
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: expect.stringContaining("timed out draining active publish") }), {});
2010
+ releasePublish();
2011
+ await publishing;
2012
+ await flushImmediate();
2013
+ const afterRestart = [];
2014
+ await makeEmitter({
2015
+ published: afterRestart,
2016
+ lastPublishedContentHashStateDir: stateDir,
2017
+ }).emitForBatch({ paths: new Map([[changed, "dispose-timeout.md"]]) });
2018
+ expect(afterRestart).toEqual([]);
2019
+ });
2020
+ it("returns one disposal barrier until the final durable batch is appended", async () => {
2021
+ let releaseAppend;
2022
+ const appendGate = new Promise((resolve) => { releaseAppend = resolve; });
2023
+ let appendEntered;
2024
+ const appendStarted = new Promise((resolve) => { appendEntered = resolve; });
2025
+ const originalAppendGeneratedIfAsync = StateStore.prototype.appendGeneratedIfAsync;
2026
+ const appendGenerated = vi.spyOn(StateStore.prototype, "appendGeneratedIfAsync")
2027
+ .mockImplementationOnce(async function (type, preparePayload, flags) {
2028
+ appendEntered();
2029
+ await appendGate;
2030
+ return originalAppendGeneratedIfAsync.call(this, type, preparePayload, flags);
2031
+ });
2032
+ const emitter = makeEmitter({ lastPublishedContentHashStateDir: path.join(dir, "concurrent-dispose-state") });
2033
+ try {
2034
+ emitter.markContentPublished("pending.md", "sha256:pending");
2035
+ const firstDispose = emitter.dispose();
2036
+ await appendStarted;
2037
+ let secondDisposed = false;
2038
+ const secondDispose = emitter.dispose();
2039
+ expect(secondDispose).toBe(firstDispose);
2040
+ void secondDispose.then(() => { secondDisposed = true; });
2041
+ await Promise.resolve();
2042
+ expect(secondDisposed).toBe(false);
2043
+ releaseAppend();
2044
+ await Promise.all([firstDispose, secondDispose]);
2045
+ expect(secondDisposed).toBe(true);
2046
+ expect(appendGenerated).toHaveBeenCalledTimes(1);
2047
+ }
2048
+ finally {
2049
+ appendGenerated.mockRestore();
2050
+ }
2051
+ });
2052
+ it("replays __proto__ hash records with the same state as the legacy reducer", async () => {
2053
+ const records = [
2054
+ { sequence: 1, type: 0x5031, flags: 0, payload: { relativePath: "__proto__", contentHash: "sha256:proto", maxPaths: 4 } },
2055
+ { sequence: 2, type: 0x5031, flags: 0, payload: { relativePath: "ordinary", contentHash: "sha256:ordinary", maxPaths: 4 } },
2056
+ ];
2057
+ const keyed = replayDurablePublishedContentHashRecordsForTest(records, true);
2058
+ expect(keyed).toEqual(replayDurablePublishedContentHashRecordsForTest(records, false));
2059
+ expect(keyed.hashes["__proto__"]).toBe("sha256:proto");
2060
+ records.push({ sequence: 3, type: 0x5032, flags: 0, payload: { relativePath: "__proto__" } });
2061
+ records.push({ sequence: 4, type: 0x5032, flags: 0, payload: { relativePath: "ordinary" } });
2062
+ expect(replayDurablePublishedContentHashRecordsForTest(records, true))
2063
+ .toEqual(replayDurablePublishedContentHashRecordsForTest(records, false));
2064
+ // This restart uses DurablePublishedContentHashes.get("__proto__") to
2065
+ // decide whether a successfully acknowledged hash may be suppressed.
2066
+ const filePath = path.join(dir, "proto-sentinel.md");
2067
+ const stateDir = path.join(dir, "proto-state");
2068
+ const batch = { paths: new Map([[filePath, "__proto__"]]) };
2069
+ fs.writeFileSync(filePath, "proto content\n");
2070
+ await makeEmitter({ lastPublishedContentHashStateDir: stateDir }).emitForBatch(batch);
2071
+ const afterRestart = [];
2072
+ await makeEmitter({ published: afterRestart, lastPublishedContentHashStateDir: stateDir }).emitForBatch(batch);
2073
+ expect(afterRestart).toEqual([]);
2074
+ });
2075
+ it("replays fifty thousand hash records with sub-quadratic scaling", () => {
2076
+ const replayFor = (count) => {
2077
+ const started = performance.now();
2078
+ replayDurablePublishedContentHashRecordsForTest(publishedHashRecords(count));
2079
+ return performance.now() - started;
2080
+ };
2081
+ const small = replayFor(5_000);
2082
+ const large = replayFor(50_000);
2083
+ // The keyed reducer does a constant number of Map/object operations per
2084
+ // record. Keep ample room for slow CI while rejecting a quadratic replay.
2085
+ expect(large).toBeLessThan(small * 20 + 100);
2086
+ });
2087
+ function makeEmitter(opts) {
2088
+ const published = opts?.published ?? [];
2089
+ const transport = opts?.transport ?? {
2090
+ start: async () => { },
2091
+ dispose: async () => { },
2092
+ connected: true,
2093
+ publish: async (event) => {
2094
+ published.push(event);
2095
+ },
2096
+ };
2097
+ return new PushEventEmitter({
2098
+ originTenantId: "tenant-indigo",
2099
+ originDeviceId: "device-a",
2100
+ transport,
2101
+ flagProvider: { isEnabled: () => true },
2102
+ now: () => new Date("2026-06-18T12:00:00.000Z"),
2103
+ clock: opts?.clock,
2104
+ getSequenceNumber: opts?.getSequenceNumber,
2105
+ onError: opts?.onError,
2106
+ lastPublishedContentHashMaxPaths: opts?.lastPublishedContentHashMaxPaths,
2107
+ publishMinIntervalMs: opts?.publishMinIntervalMs ?? 0,
2108
+ ...(opts?.lastPublishedContentHashStateDir
2109
+ ? { lastPublishedContentHashStateDir: opts.lastPublishedContentHashStateDir }
2110
+ : {}),
2111
+ ...(opts?.initialPublishedContentHashes
2112
+ ? { initialPublishedContentHashes: opts.initialPublishedContentHashes }
2113
+ : {}),
2114
+ ...(opts?.publishedContentHashLookup
2115
+ ? { publishedContentHashLookup: opts.publishedContentHashLookup }
2116
+ : {}),
2117
+ ...(opts?.caseFoldingVolume !== undefined
2118
+ ? { caseFoldingVolume: opts.caseFoldingVolume }
2119
+ : {}),
2120
+ });
2121
+ }
2122
+ it("lazily rechecks the journal baseline on a durable-cache miss without pinning a full snapshot", async () => {
2123
+ const published = [];
2124
+ const relativePath = "companies/indigo/seeded-lazily.md";
2125
+ const filePath = path.join(dir, relativePath);
2126
+ const content = "already uploaded\n";
2127
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
2128
+ fs.writeFileSync(filePath, content);
2129
+ const hash = `sha256:${createHash("sha256").update(content).digest("hex")}`;
2130
+ const lookup = vi.fn((path) => path === relativePath ? hash : undefined);
2131
+ const emitter = makeEmitter({
2132
+ published,
2133
+ lastPublishedContentHashStateDir: path.join(dir, "lazy-baseline-state"),
2134
+ publishedContentHashLookup: lookup,
2135
+ });
2136
+ await emitter.emitForBatch({ paths: new Map([[filePath, relativePath]]) });
2137
+ expect(lookup).toHaveBeenCalledWith(relativePath);
2138
+ expect(published).toEqual([]);
2139
+ // A failed/unknown lazy lookup must never suppress a genuine local edit.
2140
+ const changedPath = path.join(dir, "companies/indigo/unknown-baseline.md");
2141
+ fs.writeFileSync(changedPath, "local edit\n");
2142
+ await emitter.emitForBatch({
2143
+ paths: new Map([[changedPath, "companies/indigo/unknown-baseline.md"]]),
2144
+ });
2145
+ expect(published).toHaveLength(1);
2146
+ });
2147
+ it("F13: watcher batch event publishing applies bounded backpressure", async () => {
2148
+ const paths = new Map();
2149
+ for (let i = 0; i < 32; i++) {
2150
+ const rel = `bulk-${i}.md`;
2151
+ const abs = path.join(dir, rel);
2152
+ fs.writeFileSync(abs, `file ${i}`);
2153
+ paths.set(abs, rel);
2154
+ }
2155
+ let inFlight = 0;
2156
+ let maxInFlight = 0;
2157
+ let releaseGate;
2158
+ const gate = new Promise((resolve) => {
2159
+ releaseGate = resolve;
2160
+ });
2161
+ const transport = {
2162
+ start: async () => { },
2163
+ dispose: async () => { },
2164
+ connected: true,
2165
+ publish: async () => {
2166
+ inFlight += 1;
2167
+ maxInFlight = Math.max(maxInFlight, inFlight);
2168
+ await gate;
2169
+ inFlight -= 1;
2170
+ },
2171
+ };
2172
+ const emitter = new PushEventEmitter({
2173
+ originTenantId: "tenant-indigo",
2174
+ originDeviceId: "device-a",
2175
+ transport,
2176
+ flagProvider: { isEnabled: () => true },
2177
+ now: () => new Date("2026-06-18T12:00:00.000Z"),
2178
+ });
2179
+ const run = emitter.emitForBatch({ paths });
2180
+ try {
2181
+ for (let i = 0; i < 200 && maxInFlight <= 16; i++) {
2182
+ await flushImmediate();
2183
+ }
2184
+ releaseGate();
2185
+ await run;
2186
+ expect(maxInFlight).toBeLessThanOrEqual(16);
2187
+ }
2188
+ finally {
2189
+ releaseGate();
2190
+ await run.catch(() => { });
2191
+ }
2192
+ });
2193
+ it("skips directory changes silently without publishing or reporting an error", async () => {
2194
+ const published = [];
2195
+ const onError = vi.fn();
2196
+ const subdir = path.join(dir, "folder");
2197
+ fs.mkdirSync(subdir);
2198
+ const emitter = makeEmitter({ published, onError });
2199
+ await emitter.emitForBatch({ paths: new Map([[subdir, "folder"]]) });
2200
+ expect(published).toEqual([]);
2201
+ expect(onError).not.toHaveBeenCalled();
2202
+ });
2203
+ it("emits and publishes a delete tombstone when the changed file is gone", async () => {
2204
+ const published = [];
2205
+ const onError = vi.fn();
2206
+ const emitter = makeEmitter({
2207
+ published,
2208
+ onError,
2209
+ getSequenceNumber: () => 99,
2210
+ caseFoldingVolume: true,
2211
+ });
2212
+ const missing = path.join(dir, "deleted.md");
2213
+ await emitter.emitForBatch({ paths: new Map([[missing, "deleted.md"]]) });
2214
+ expect(onError).not.toHaveBeenCalled();
2215
+ expect(published).toEqual([
2216
+ {
2217
+ kind: "delete",
2218
+ relativePath: "deleted.md",
2219
+ originDeviceId: "device-a",
2220
+ originTenantId: "tenant-indigo",
2221
+ sequenceNumber: 99,
2222
+ eventTimestamp: "2026-06-18T12:00:00.000Z",
2223
+ },
2224
+ ]);
2225
+ expect(published[0]).not.toHaveProperty("contentHash");
2226
+ expect(published[0]).not.toHaveProperty("mtime");
2227
+ expect(published[0]).not.toHaveProperty("sizeBytes");
2228
+ });
2229
+ it("clears a pull-applied delete marker after a re-upload without a realtime emit", async () => {
2230
+ const published = [];
2231
+ const emitter = makeEmitter({ published });
2232
+ const recreatedPath = path.join(dir, "recreated.md");
2233
+ fs.writeFileSync(recreatedPath, "recreated content");
2234
+ emitter.markContentDeleted("recreated.md");
2235
+ // A successful scoped upload clears the marker even when publishing was
2236
+ // unavailable, so the next genuine unlink cannot be swallowed.
2237
+ emitter.clearContentDeleted("recreated.md");
2238
+ fs.unlinkSync(recreatedPath);
2239
+ await emitter.emitForBatch({
2240
+ paths: new Map([[recreatedPath, "recreated.md"]]),
2241
+ });
2242
+ expect(published.map(({ kind, relativePath }) => ({ kind, relativePath })))
2243
+ .toEqual([{ kind: "delete", relativePath: "recreated.md" }]);
2244
+ await emitter.dispose();
2245
+ });
2246
+ it("keeps a case-only directory rename on the journal's existing remote spelling", async () => {
2247
+ const contentByPath = new Map([
2248
+ ["a.md", "a content"],
2249
+ ["b.md", "b content"],
2250
+ ]);
2251
+ const renamedDir = path.join(dir, "dir");
2252
+ fs.mkdirSync(renamedDir, { recursive: true });
2253
+ const paths = new Map();
2254
+ const knownHashes = new Map();
2255
+ const remote = new Map();
2256
+ for (const [name, content] of contentByPath) {
2257
+ const localPath = path.join(renamedDir, name);
2258
+ fs.writeFileSync(localPath, content);
2259
+ const oldKey = `Dir/${name}`;
2260
+ const newKey = `dir/${name}`;
2261
+ knownHashes.set(oldKey, `sha256:${createHash("sha256").update(content).digest("hex")}`);
2262
+ remote.set(oldKey, content);
2263
+ paths.set(path.join(dir, "Dir", name), oldKey);
2264
+ paths.set(localPath, newKey);
2265
+ }
2266
+ // APFS and NTFS already resolve `Dir` to this folder; a case-sensitive
2267
+ // host gets the same lookup through a symlink.
2268
+ if (!fs.existsSync(path.join(dir, "Dir")))
2269
+ fs.symlinkSync("dir", path.join(dir, "Dir"), "dir");
2270
+ const published = [];
2271
+ const emitter = makeEmitter({
2272
+ published,
2273
+ publishedContentHashLookup: (relativePath) => knownHashes.get(relativePath),
2274
+ caseFoldingVolume: true,
2275
+ });
2276
+ await emitter.emitForBatch({ paths });
2277
+ for (const event of published) {
2278
+ if (event.kind === "delete")
2279
+ remote.delete(event.relativePath);
2280
+ else
2281
+ remote.set(event.relativePath, contentByPath.get(path.basename(event.relativePath)));
2282
+ }
2283
+ expect(published.some((event) => event.kind === "delete")).toBe(false);
2284
+ expect([...remote.entries()].sort(([a], [b]) => a.localeCompare(b))).toEqual([
2285
+ ["Dir/a.md", "a content"],
2286
+ ["Dir/b.md", "b content"],
2287
+ ]);
2288
+ });
2289
+ it("canonicalizes native-separator event keys and leaves POSIX keys byte-identical", async () => {
2290
+ const published = [];
2291
+ const onError = vi.fn();
2292
+ const legacyPath = path.join(dir, "legacy.csv");
2293
+ const posixPath = path.join(dir, "already-posix.csv");
2294
+ fs.writeFileSync(legacyPath, "legacy\n");
2295
+ fs.writeFileSync(posixPath, "posix\n");
2296
+ const emitter = makeEmitter({ published, onError });
2297
+ const windowsKey = "projects\\forecast\\x.csv";
2298
+ await emitter.emitForBatch({
2299
+ paths: new Map([[legacyPath, windowsKey]]),
2300
+ });
2301
+ await emitter.emitForBatch({
2302
+ paths: new Map([[posixPath, "projects/forecast/already-posix.csv"]]),
2303
+ });
2304
+ if (path.sep === "\\") {
2305
+ expect(published.map((event) => event.relativePath)).toEqual([
2306
+ "projects/forecast/x.csv",
2307
+ "projects/forecast/already-posix.csv",
2308
+ ]);
2309
+ expect(onError).not.toHaveBeenCalled();
2310
+ }
2311
+ else {
2312
+ // POSIX: `\\` is a filename character. Do not remap onto a nested key.
2313
+ expect(published.map((event) => event.relativePath)).toEqual([
2314
+ "projects/forecast/already-posix.csv",
2315
+ ]);
2316
+ expect(onError).toHaveBeenCalled();
2317
+ }
2318
+ });
2319
+ it("canonicalizes a native-separator tombstone only when `\\` is path.sep", async () => {
2320
+ const published = [];
2321
+ const onError = vi.fn();
2322
+ const missing = path.join(dir, "deleted.csv");
2323
+ const emitter = makeEmitter({ published, onError });
2324
+ await emitter.emitForBatch({
2325
+ paths: new Map([[missing, "projects\\forecast\\deleted.csv"]]),
2326
+ });
2327
+ if (path.sep === "\\") {
2328
+ expect(published).toEqual([
2329
+ expect.objectContaining({
2330
+ kind: "delete",
2331
+ relativePath: "projects/forecast/deleted.csv",
2332
+ }),
2333
+ ]);
2334
+ expect(onError).not.toHaveBeenCalled();
2335
+ }
2336
+ else {
2337
+ expect(published).toEqual([]);
2338
+ expect(onError).toHaveBeenCalled();
2339
+ }
2340
+ });
2341
+ it("publishes N unchanged watcher announcements exactly once", async () => {
2342
+ const published = [];
2343
+ const unchanged = path.join(dir, "unchanged-session-log.jsonl");
2344
+ fs.writeFileSync(unchanged, '{"tool":"read"}\n');
2345
+ const emitter = makeEmitter({ published });
2346
+ const batch = { paths: new Map([[unchanged, "workspace/.session-logs/unchanged-session-log.jsonl"]]) };
2347
+ for (let i = 0; i < 5; i += 1) {
2348
+ await emitter.emitForBatch(batch);
2349
+ }
2350
+ expect(published).toHaveLength(1);
2351
+ expect(published[0]).toMatchObject({
2352
+ kind: "upsert",
2353
+ relativePath: "workspace/.session-logs/unchanged-session-log.jsonl",
2354
+ });
2355
+ });
2356
+ it("publishes again when content changes", async () => {
2357
+ const published = [];
2358
+ const changed = path.join(dir, "changed-session-log.jsonl");
2359
+ fs.writeFileSync(changed, "A\n");
2360
+ const emitter = makeEmitter({ published });
2361
+ const batch = { paths: new Map([[changed, "workspace/.session-logs/changed-session-log.jsonl"]]) };
2362
+ await emitter.emitForBatch(batch);
2363
+ fs.writeFileSync(changed, "B\n");
2364
+ await emitter.emitForBatch(batch);
2365
+ expect(published).toHaveLength(2);
2366
+ expect(published.map((event) => event.contentHash)).toEqual([
2367
+ expect.stringMatching(/^sha256:/),
2368
+ expect.stringMatching(/^sha256:/),
2369
+ ]);
2370
+ expect(published[0].contentHash).not.toBe(published[1].contentHash);
2371
+ });
2372
+ it("does not echo a pull-applied upsert but publishes a later local edit", async () => {
2373
+ const published = [];
2374
+ const applied = path.join(dir, "companies", "indigo", "remote-note.md");
2375
+ const relativePath = "companies/indigo/remote-note.md";
2376
+ const remoteContent = "from remote\n";
2377
+ fs.mkdirSync(path.dirname(applied), { recursive: true });
2378
+ fs.writeFileSync(applied, remoteContent);
2379
+ const emitter = makeEmitter({ published });
2380
+ // The pull completed its file write and journal update, then the runner
2381
+ // bridged that upsert into the live emitter before the watcher settled.
2382
+ emitter.markContentPublished(relativePath, `sha256:${createHash("sha256").update(remoteContent).digest("hex")}`);
2383
+ await emitter.emitForBatch({ paths: new Map([[applied, relativePath]]) });
2384
+ expect(published).toEqual([]);
2385
+ fs.writeFileSync(applied, "local follow-up\n");
2386
+ await emitter.emitForBatch({ paths: new Map([[applied, relativePath]]) });
2387
+ expect(published).toHaveLength(1);
2388
+ expect(published[0]).toMatchObject({
2389
+ kind: "upsert",
2390
+ relativePath,
2391
+ contentHash: `sha256:${createHash("sha256")
2392
+ .update("local follow-up\n")
2393
+ .digest("hex")}`,
2394
+ });
2395
+ });
2396
+ it("publishes a local edit immediately after a pull mark despite the publish interval", async () => {
2397
+ const clock = new FakeClock();
2398
+ const published = [];
2399
+ const applied = path.join(dir, "companies", "indigo", "remote-interval-note.md");
2400
+ const relativePath = "companies/indigo/remote-interval-note.md";
2401
+ const remoteContent = "from remote\n";
2402
+ fs.mkdirSync(path.dirname(applied), { recursive: true });
2403
+ fs.writeFileSync(applied, remoteContent);
2404
+ const emitter = makeEmitter({ published, publishMinIntervalMs: 60_000, clock });
2405
+ emitter.markContentPublished(relativePath, `sha256:${createHash("sha256").update(remoteContent).digest("hex")}`);
2406
+ fs.writeFileSync(applied, "local follow-up\n");
2407
+ await emitter.emitForBatch({ paths: new Map([[applied, relativePath]]) });
2408
+ expect(published).toHaveLength(1);
2409
+ expect(published[0]).toMatchObject({
2410
+ kind: "upsert",
2411
+ relativePath,
2412
+ contentHash: `sha256:${createHash("sha256")
2413
+ .update("local follow-up\n")
2414
+ .digest("hex")}`,
2415
+ });
2416
+ });
2417
+ it("keeps a newer pull mark when an older local publish completes", async () => {
2418
+ const published = [];
2419
+ const applied = path.join(dir, "companies", "indigo", "publish-race.md");
2420
+ const relativePath = "companies/indigo/publish-race.md";
2421
+ const oldContent = "local old bytes\n";
2422
+ const remoteContent = "remote newer bytes\n";
2423
+ fs.mkdirSync(path.dirname(applied), { recursive: true });
2424
+ fs.writeFileSync(applied, oldContent);
2425
+ let releasePublish;
2426
+ let publishStartedResolve;
2427
+ const publishStarted = new Promise((resolve) => {
2428
+ publishStartedResolve = resolve;
2429
+ });
2430
+ const publishGate = new Promise((resolve) => {
2431
+ releasePublish = resolve;
2432
+ });
2433
+ const emitter = makeEmitter({
2434
+ published,
2435
+ transport: {
2436
+ start: async () => { },
2437
+ dispose: async () => { },
2438
+ connected: true,
2439
+ publish: async (event) => {
2440
+ published.push(event);
2441
+ publishStartedResolve?.();
2442
+ await publishGate;
2443
+ },
2444
+ },
2445
+ });
2446
+ const oldPublish = emitter.emitForBatch({ paths: new Map([[applied, relativePath]]) });
2447
+ await publishStarted;
2448
+ emitter.markContentPublished(relativePath, `sha256:${createHash("sha256").update(remoteContent).digest("hex")}`);
2449
+ releasePublish?.();
2450
+ await oldPublish;
2451
+ fs.writeFileSync(applied, remoteContent);
2452
+ await emitter.emitForBatch({ paths: new Map([[applied, relativePath]]) });
2453
+ // The remote bytes remain suppressed: old publish completion could not
2454
+ // overwrite the newer pull mark in the per-path publication ledger.
2455
+ expect(published).toHaveLength(1);
2456
+ expect(published[0]).toMatchObject({
2457
+ kind: "upsert",
2458
+ relativePath,
2459
+ contentHash: `sha256:${createHash("sha256").update(oldContent).digest("hex")}`,
2460
+ });
2461
+ });
2462
+ it("bounds publishedContentHashGenerations to the published-hash cap (was an unbounded Map)", () => {
2463
+ const maxPaths = 8;
2464
+ const K = 12;
2465
+ const emitter = makeEmitter({ lastPublishedContentHashMaxPaths: maxPaths });
2466
+ for (let i = 0; i < maxPaths + K; i++) {
2467
+ emitter.markContentPublished(`companies/indigo/gen-${i}.md`, `sha256:h${i}`);
2468
+ }
2469
+ const sizes = emitter.censusSizes();
2470
+ // The generations map used to be a plain Map with no eviction, so it grew to
2471
+ // maxPaths + K and stayed there for the whole watch session — the unbounded
2472
+ // retention this fix removes. It must now hold no more than its bounded
2473
+ // sibling's cap.
2474
+ expect(sizes.publishedContentHashGenerations).toBeLessThanOrEqual(maxPaths);
2475
+ expect(sizes.lastPublishedContentHashes).toBeLessThanOrEqual(maxPaths);
2476
+ // Sanity: we really did drive more distinct paths than the cap.
2477
+ expect(maxPaths + K).toBeGreaterThan(maxPaths);
2478
+ });
2479
+ it("bounds the generations map without breaking pull-apply echo suppression for a hot path", async () => {
2480
+ const published = [];
2481
+ const maxPaths = 4;
2482
+ const emitter = makeEmitter({ published, lastPublishedContentHashMaxPaths: maxPaths });
2483
+ // Churn several cold paths first: each takes a fresh monotonic generation and
2484
+ // evicts older ones from the now-bounded map.
2485
+ for (let i = 0; i < maxPaths * 4; i++) {
2486
+ emitter.markContentPublished(`companies/indigo/cold-${i}.md`, `sha256:c${i}`);
2487
+ }
2488
+ // The pulled path is marked LAST, so it is the hot, retained entry.
2489
+ const applied = path.join(dir, "companies", "indigo", "hot-note.md");
2490
+ const relativePath = "companies/indigo/hot-note.md";
2491
+ const remoteContent = "from remote\n";
2492
+ fs.mkdirSync(path.dirname(applied), { recursive: true });
2493
+ fs.writeFileSync(applied, remoteContent);
2494
+ emitter.markContentPublished(relativePath, `sha256:${createHash("sha256").update(remoteContent).digest("hex")}`);
2495
+ // The identical local write is still suppressed as an echo (contract #456).
2496
+ await emitter.emitForBatch({ paths: new Map([[applied, relativePath]]) });
2497
+ expect(published).toEqual([]);
2498
+ // A genuinely new local edit still publishes.
2499
+ fs.writeFileSync(applied, "local follow-up\n");
2500
+ await emitter.emitForBatch({ paths: new Map([[applied, relativePath]]) });
2501
+ expect(published).toHaveLength(1);
2502
+ });
2503
+ it("keeps generation currency fail-closed under the bounded map: a newer pull mark still wins the publish race", async () => {
2504
+ const published = [];
2505
+ const maxPaths = 4;
2506
+ const applied = path.join(dir, "companies", "indigo", "fail-closed-race.md");
2507
+ const relativePath = "companies/indigo/fail-closed-race.md";
2508
+ const oldContent = "local old bytes\n";
2509
+ const remoteContent = "remote newer bytes\n";
2510
+ fs.mkdirSync(path.dirname(applied), { recursive: true });
2511
+ fs.writeFileSync(applied, oldContent);
2512
+ let releasePublish;
2513
+ let publishStartedResolve;
2514
+ const publishStarted = new Promise((resolve) => {
2515
+ publishStartedResolve = resolve;
2516
+ });
2517
+ const publishGate = new Promise((resolve) => {
2518
+ releasePublish = resolve;
2519
+ });
2520
+ const emitter = makeEmitter({
2521
+ published,
2522
+ lastPublishedContentHashMaxPaths: maxPaths,
2523
+ transport: {
2524
+ start: async () => { },
2525
+ dispose: async () => { },
2526
+ connected: true,
2527
+ publish: async (event) => {
2528
+ published.push(event);
2529
+ publishStartedResolve?.();
2530
+ await publishGate;
2531
+ },
2532
+ },
2533
+ });
2534
+ // Mark the path with an UNRELATED hash before the publish starts, so the
2535
+ // in-flight publish captures a NON-ZERO generation yet is NOT echo-suppressed
2536
+ // (the file's bytes differ from the marked hash).
2537
+ emitter.markContentPublished(relativePath, "sha256:00decoy00");
2538
+ const oldPublish = emitter.emitForBatch({ paths: new Map([[applied, relativePath]]) });
2539
+ await publishStarted;
2540
+ // A pull applies newer bytes while the old publish is in flight, taking a
2541
+ // fresh monotonic generation the captured value can never match.
2542
+ emitter.markContentPublished(relativePath, `sha256:${createHash("sha256").update(remoteContent).digest("hex")}`);
2543
+ releasePublish?.();
2544
+ await oldPublish;
2545
+ fs.writeFileSync(applied, remoteContent);
2546
+ await emitter.emitForBatch({ paths: new Map([[applied, relativePath]]) });
2547
+ // The stale in-flight publish could not resurrect its captured generation to
2548
+ // overwrite the newer pull mark, so the remote bytes stay suppressed.
2549
+ expect(published.filter((event) => event.relativePath === relativePath)).toHaveLength(1);
2550
+ expect(published[published.length - 1]).toMatchObject({
2551
+ kind: "upsert",
2552
+ relativePath,
2553
+ contentHash: `sha256:${createHash("sha256").update(oldContent).digest("hex")}`,
2554
+ });
2555
+ });
2556
+ it("does not resurrect an evicted generation to record a stale publish (ABA at the eviction boundary)", async () => {
2557
+ const published = [];
2558
+ const maxPaths = 2;
2559
+ const applied = path.join(dir, "companies", "indigo", "aba-race.md");
2560
+ const relativePath = "companies/indigo/aba-race.md";
2561
+ const oldContent = "local old bytes\n";
2562
+ const remoteContent = "remote newer bytes\n";
2563
+ const oldHash = `sha256:${createHash("sha256").update(oldContent).digest("hex")}`;
2564
+ fs.mkdirSync(path.dirname(applied), { recursive: true });
2565
+ fs.writeFileSync(applied, oldContent);
2566
+ let releasePublish;
2567
+ let firstStartedResolve;
2568
+ const firstStarted = new Promise((resolve) => {
2569
+ firstStartedResolve = resolve;
2570
+ });
2571
+ const publishGate = new Promise((resolve) => {
2572
+ releasePublish = resolve;
2573
+ });
2574
+ let publishCount = 0;
2575
+ const emitter = makeEmitter({
2576
+ published,
2577
+ lastPublishedContentHashMaxPaths: maxPaths,
2578
+ transport: {
2579
+ start: async () => { },
2580
+ dispose: async () => { },
2581
+ connected: true,
2582
+ publish: async (event) => {
2583
+ published.push(event);
2584
+ publishCount += 1;
2585
+ // Gate only the FIRST publish so it is still in flight while the pull
2586
+ // mark and eviction happen underneath it.
2587
+ if (publishCount === 1) {
2588
+ firstStartedResolve?.();
2589
+ await publishGate;
2590
+ }
2591
+ },
2592
+ },
2593
+ });
2594
+ // The path has NEVER been marked, so the in-flight publish captures the
2595
+ // never-marked sentinel — the exact ABA precondition.
2596
+ const firstPublish = emitter.emitForBatch({ paths: new Map([[applied, relativePath]]) });
2597
+ await firstStarted;
2598
+ // A pull applies newer bytes for this path while the publish is in flight...
2599
+ emitter.markContentPublished(relativePath, `sha256:${createHash("sha256").update(remoteContent).digest("hex")}`);
2600
+ // ...then enough other paths are marked to evict this path's generation entry,
2601
+ // collapsing it back to the absent sentinel.
2602
+ for (let i = 0; i < maxPaths * 4; i += 1) {
2603
+ emitter.markContentPublished(`companies/indigo/aba-churn-${i}.md`, `sha256:z${i}`);
2604
+ }
2605
+ releasePublish?.();
2606
+ await firstPublish;
2607
+ // The stale completion must NOT have recorded oldHash for this path. If it
2608
+ // had (the ABA bug), the genuine local revert to oldContent below would be
2609
+ // wrongly suppressed as an echo and never published — silent data loss.
2610
+ await emitter.emitForBatch({ paths: new Map([[applied, relativePath]]) });
2611
+ const forPath = published.filter((event) => event.relativePath === relativePath);
2612
+ expect(forPath).toHaveLength(2);
2613
+ expect(forPath[1]).toMatchObject({ kind: "upsert", relativePath, contentHash: oldHash });
2614
+ });
2615
+ it("stamps an upsert with the byte length of the content it hashes", async () => {
2616
+ const published = [];
2617
+ const file = path.join(dir, "sized-content.bin");
2618
+ const content = Buffer.from([0, 1, 2, 3, 4, 5, 6]);
2619
+ fs.writeFileSync(file, content);
2620
+ await makeEmitter({ published }).emitForBatch({
2621
+ paths: new Map([[file, "sized-content.bin"]]),
2622
+ });
2623
+ expect(published).toHaveLength(1);
2624
+ expect(published[0]).toMatchObject({
2625
+ kind: "upsert",
2626
+ sizeBytes: content.byteLength,
2627
+ contentHash: `sha256:${createHash("sha256").update(content).digest("hex")}`,
2628
+ });
2629
+ });
2630
+ it("coalesces ten rewrites of one path into an immediate and trailing latest publish", async () => {
2631
+ const clock = new FakeClock();
2632
+ const published = [];
2633
+ const rewritten = path.join(dir, "high-churn-prd.json");
2634
+ const relativePath = "personal/projects/churn/prd.json";
2635
+ const emitter = makeEmitter({ published, publishMinIntervalMs: 60_000, clock });
2636
+ const batch = { paths: new Map([[rewritten, relativePath]]) };
2637
+ for (let version = 0; version < 10; version += 1) {
2638
+ fs.writeFileSync(rewritten, `{"version":${version}}\n`);
2639
+ await emitter.emitForBatch(batch);
2640
+ if (version < 9)
2641
+ clock.advance(5_000);
2642
+ }
2643
+ expect(published).toHaveLength(1);
2644
+ clock.advance(15_000);
2645
+ await emitter.emitForBatch({ paths: new Map() });
2646
+ expect(published).toHaveLength(2);
2647
+ expect(clock.pendingTimerCount()).toBe(0);
2648
+ expect(published[1]).toMatchObject({ kind: "upsert", relativePath });
2649
+ expect(published[1].contentHash).toBe(`sha256:${createHash("sha256").update('{"version":9}\n').digest("hex")}`);
2650
+ });
2651
+ it("suppresses a deferred continuation queued behind a realtime-unavailable denial", async () => {
2652
+ const clock = new FakeClock();
2653
+ const published = [];
2654
+ const deferred = path.join(dir, "deferred-after-denial.json");
2655
+ const active = path.join(dir, "active-denial.json");
2656
+ const deferredRelativePath = "personal/projects/deferred-after-denial.json";
2657
+ let releaseDenial;
2658
+ let activePublishStarted;
2659
+ const denialGate = new Promise((resolve) => {
2660
+ releaseDenial = resolve;
2661
+ });
2662
+ const activeStarted = new Promise((resolve) => {
2663
+ activePublishStarted = resolve;
2664
+ });
2665
+ const emitter = makeEmitter({
2666
+ published,
2667
+ clock,
2668
+ publishMinIntervalMs: 60_000,
2669
+ transport: {
2670
+ start: async () => { },
2671
+ dispose: async () => { },
2672
+ connected: true,
2673
+ publish: async (event) => {
2674
+ published.push(event);
2675
+ if (event.relativePath === "personal/projects/active-denial.json") {
2676
+ activePublishStarted?.();
2677
+ await denialGate;
2678
+ throw new RealtimeUnavailableError({ status: 403, operation: "test push" });
2679
+ }
2680
+ },
2681
+ },
2682
+ });
2683
+ fs.writeFileSync(deferred, '{"revision":1}\n');
2684
+ await emitter.emitForBatch({ paths: new Map([[deferred, deferredRelativePath]]) });
2685
+ fs.writeFileSync(deferred, '{"revision":2}\n');
2686
+ await emitter.emitForBatch({ paths: new Map([[deferred, deferredRelativePath]]) });
2687
+ fs.writeFileSync(active, '{"active":true}\n');
2688
+ const activeRun = emitter.emitForBatch({
2689
+ paths: new Map([[active, "personal/projects/active-denial.json"]]),
2690
+ });
2691
+ await activeStarted;
2692
+ clock.advance(60_000);
2693
+ releaseDenial?.();
2694
+ await activeRun;
2695
+ for (let i = 0; i < 6; i++)
2696
+ await Promise.resolve();
2697
+ expect(emitter.realtimeUnavailable).toBe(true);
2698
+ expect(published.map((event) => event.relativePath)).toEqual([
2699
+ deferredRelativePath,
2700
+ "personal/projects/active-denial.json",
2701
+ ]);
2702
+ });
2703
+ it("keeps publishing other companies after a company membership denial", async () => {
2704
+ const deniedRelativePath = "companies/liverecover/projects/denied.md";
2705
+ const allowedRelativePath = "companies/indigo/projects/allowed.md";
2706
+ const denied = path.join(dir, deniedRelativePath);
2707
+ const allowed = path.join(dir, allowedRelativePath);
2708
+ fs.mkdirSync(path.dirname(denied), { recursive: true });
2709
+ fs.mkdirSync(path.dirname(allowed), { recursive: true });
2710
+ fs.writeFileSync(denied, "denied\n");
2711
+ fs.writeFileSync(allowed, "allowed\n");
2712
+ const observedPaths = [];
2713
+ const fetch = vi.fn(async (_url, init) => {
2714
+ const relativePath = JSON.parse(init?.body ?? "{}").relativePath;
2715
+ observedPaths.push(relativePath);
2716
+ return relativePath === deniedRelativePath
2717
+ ? {
2718
+ ok: false,
2719
+ status: 403,
2720
+ text: async () => JSON.stringify({
2721
+ error: "cross-tenant",
2722
+ code: "cross-tenant-push-rejected",
2723
+ }),
2724
+ }
2725
+ : { ok: true, status: 200, text: async () => "" };
2726
+ });
2727
+ const onError = vi.fn();
2728
+ const emitter = makeEmitter({
2729
+ onError,
2730
+ transport: new HttpPushTransport({
2731
+ apiUrl: "https://api.example.com",
2732
+ authToken: "token",
2733
+ fetchImpl: fetch,
2734
+ }),
2735
+ });
2736
+ await emitter.emitForBatch({ paths: new Map([[denied, deniedRelativePath]]) });
2737
+ await emitter.emitForBatch({ paths: new Map([[allowed, allowedRelativePath]]) });
2738
+ expect(fetch).toHaveBeenCalledTimes(2);
2739
+ expect(observedPaths).toEqual([deniedRelativePath, allowedRelativePath]);
2740
+ expect(emitter.realtimeUnavailable).toBe(false);
2741
+ expect(onError).toHaveBeenCalledTimes(1);
2742
+ expect(onError).toHaveBeenCalledWith(expect.any(PushScopeForbiddenError), { relativePath: deniedRelativePath });
2743
+ });
2744
+ it("suppresses repeated membership-denied publishes for one company scope", async () => {
2745
+ const relativePath = "companies/liverecover/projects/retry-loop.md";
2746
+ const file = path.join(dir, relativePath);
2747
+ fs.mkdirSync(path.dirname(file), { recursive: true });
2748
+ fs.writeFileSync(file, "still local\n");
2749
+ const fetch = vi.fn(async () => ({
2750
+ ok: false,
2751
+ status: 403,
2752
+ text: async () => JSON.stringify({
2753
+ error: "cross-tenant",
2754
+ code: "cross-tenant-push-rejected",
2755
+ }),
2756
+ }));
2757
+ const onError = vi.fn();
2758
+ const emitter = makeEmitter({
2759
+ onError,
2760
+ transport: new HttpPushTransport({
2761
+ apiUrl: "https://api.example.com",
2762
+ authToken: "token",
2763
+ fetchImpl: fetch,
2764
+ }),
2765
+ });
2766
+ const batch = { paths: new Map([[file, relativePath]]) };
2767
+ await emitter.emitForBatch(batch);
2768
+ await emitter.emitForBatch(batch);
2769
+ await emitter.emitForBatch(batch);
2770
+ expect(fetch).toHaveBeenCalledTimes(1);
2771
+ expect(onError).toHaveBeenCalledTimes(1);
2772
+ expect(onError).toHaveBeenCalledWith(expect.any(PushScopeForbiddenError), { relativePath });
2773
+ });
2774
+ it("publishes the uploaded deferred revision when the local file changes before flush", async () => {
2775
+ const clock = new FakeClock();
2776
+ const published = [];
2777
+ const rewritten = path.join(dir, "captured-deferred-revision.json");
2778
+ const relativePath = "personal/projects/captured/prd.json";
2779
+ const emitter = makeEmitter({ published, publishMinIntervalMs: 60_000, clock });
2780
+ const batch = { paths: new Map([[rewritten, relativePath]]) };
2781
+ fs.writeFileSync(rewritten, '{"revision":"uploaded"}\n');
2782
+ await emitter.emitForBatch(batch);
2783
+ fs.writeFileSync(rewritten, '{"revision":"deferred-uploaded"}\n');
2784
+ await emitter.emitForBatch(batch);
2785
+ const expectedHash = `sha256:${createHash("sha256")
2786
+ .update('{"revision":"deferred-uploaded"}\n')
2787
+ .digest("hex")}`;
2788
+ // This local revision has not completed its scoped push yet. The trailing
2789
+ // announcement must remain bound to the previously uploaded bytes.
2790
+ fs.writeFileSync(rewritten, '{"revision":"newer-local"}\n');
2791
+ clock.advance(60_000);
2792
+ await emitter.emitForBatch({ paths: new Map() });
2793
+ expect(published).toHaveLength(2);
2794
+ expect(published[1]).toMatchObject({
2795
+ kind: "upsert",
2796
+ relativePath,
2797
+ contentHash: expectedHash,
2798
+ });
2799
+ expect(published[1].contentHash).not.toBe(`sha256:${createHash("sha256")
2800
+ .update('{"revision":"newer-local"}\n')
2801
+ .digest("hex")}`);
2802
+ });
2803
+ it("skips the trailing publish when the final rewrite restores the last published hash", async () => {
2804
+ const clock = new FakeClock();
2805
+ const published = [];
2806
+ const rewritten = path.join(dir, "reverted-prd.json");
2807
+ const relativePath = "personal/projects/reverted/prd.json";
2808
+ const emitter = makeEmitter({ published, publishMinIntervalMs: 60_000, clock });
2809
+ const batch = { paths: new Map([[rewritten, relativePath]]) };
2810
+ fs.writeFileSync(rewritten, "A\n");
2811
+ await emitter.emitForBatch(batch);
2812
+ fs.writeFileSync(rewritten, "B\n");
2813
+ await emitter.emitForBatch(batch);
2814
+ fs.writeFileSync(rewritten, "A\n");
2815
+ await emitter.emitForBatch(batch);
2816
+ clock.advance(60_000);
2817
+ await emitter.emitForBatch({ paths: new Map() });
2818
+ expect(published).toHaveLength(1);
2819
+ expect(clock.pendingTimerCount()).toBe(0);
2820
+ expect(published[0]).toMatchObject({ kind: "upsert", relativePath });
2821
+ });
2822
+ it("publishes a delete immediately while an upsert is deferred", async () => {
2823
+ const clock = new FakeClock();
2824
+ const published = [];
2825
+ const deleted = path.join(dir, "delete-during-quiet.jsonl");
2826
+ const relativePath = "workspace/.session-logs/delete-during-quiet.jsonl";
2827
+ const emitter = makeEmitter({ published, publishMinIntervalMs: 60_000, clock });
2828
+ const batch = { paths: new Map([[deleted, relativePath]]) };
2829
+ fs.writeFileSync(deleted, "A\n");
2830
+ await emitter.emitForBatch(batch);
2831
+ fs.writeFileSync(deleted, "B\n");
2832
+ await emitter.emitForBatch(batch);
2833
+ fs.rmSync(deleted);
2834
+ await emitter.emitForBatch(batch);
2835
+ expect(published.map((event) => event.kind)).toEqual(["upsert", "delete"]);
2836
+ clock.advance(60_000);
2837
+ await emitter.emitForBatch({ paths: new Map() });
2838
+ expect(published).toHaveLength(2);
2839
+ });
2840
+ it("does not make a second path wait behind another path's quiet interval", async () => {
2841
+ const published = [];
2842
+ const first = path.join(dir, "first-high-churn.jsonl");
2843
+ const second = path.join(dir, "independent.jsonl");
2844
+ const emitter = makeEmitter({ published, publishMinIntervalMs: 60_000 });
2845
+ fs.writeFileSync(first, "A\n");
2846
+ fs.writeFileSync(second, "B\n");
2847
+ await emitter.emitForBatch({ paths: new Map([[first, "workspace/.session-logs/first.jsonl"]]) });
2848
+ fs.writeFileSync(first, "A2\n");
2849
+ await emitter.emitForBatch({ paths: new Map([[first, "workspace/.session-logs/first.jsonl"]]) });
2850
+ await emitter.emitForBatch({ paths: new Map([[second, "workspace/.session-logs/second.jsonl"]]) });
2851
+ expect(published.map((event) => event.relativePath)).toEqual([
2852
+ "workspace/.session-logs/first.jsonl",
2853
+ "workspace/.session-logs/second.jsonl",
2854
+ ]);
2855
+ });
2856
+ it("publishes a content revert because it compares only with the last publication", async () => {
2857
+ const published = [];
2858
+ const reverted = path.join(dir, "reverted-session-log.jsonl");
2859
+ fs.writeFileSync(reverted, "A\n");
2860
+ const emitter = makeEmitter({ published });
2861
+ const batch = { paths: new Map([[reverted, "workspace/.session-logs/reverted-session-log.jsonl"]]) };
2862
+ await emitter.emitForBatch(batch);
2863
+ fs.writeFileSync(reverted, "B\n");
2864
+ await emitter.emitForBatch(batch);
2865
+ fs.writeFileSync(reverted, "A\n");
2866
+ await emitter.emitForBatch(batch);
2867
+ expect(published).toHaveLength(3);
2868
+ expect(published[0].contentHash).toBe(published[2].contentHash);
2869
+ expect(published[0].contentHash).not.toBe(published[1].contentHash);
2870
+ });
2871
+ it("re-announces a revert after an intervening changed publication fails", async () => {
2872
+ const published = [];
2873
+ let fail = false;
2874
+ const changed = path.join(dir, "failed-revert-session-log.jsonl");
2875
+ fs.writeFileSync(changed, "A\n");
2876
+ const emitter = new PushEventEmitter({
2877
+ originTenantId: "tenant-indigo",
2878
+ originDeviceId: "device-a",
2879
+ flagProvider: { isEnabled: () => true },
2880
+ publishMinIntervalMs: 0,
2881
+ transport: {
2882
+ start: async () => { },
2883
+ dispose: async () => { },
2884
+ connected: true,
2885
+ publish: async (event) => {
2886
+ if (fail)
2887
+ throw new Error("push unavailable");
2888
+ published.push(event);
2889
+ },
2890
+ },
2891
+ onError: vi.fn(),
2892
+ });
2893
+ const batch = { paths: new Map([[changed, "workspace/.session-logs/failed-revert-session-log.jsonl"]]) };
2894
+ await emitter.emitForBatch(batch);
2895
+ fs.writeFileSync(changed, "B\n");
2896
+ fail = true;
2897
+ await emitter.emitForBatch(batch);
2898
+ fs.writeFileSync(changed, "A\n");
2899
+ fail = false;
2900
+ await emitter.emitForBatch(batch);
2901
+ expect(published).toHaveLength(2);
2902
+ expect(published[0].contentHash).toBe(published[1].contentHash);
2903
+ });
2904
+ it("always publishes deletes after an unchanged touch and clears the path state", async () => {
2905
+ const published = [];
2906
+ const deleted = path.join(dir, "deleted-after-touch.jsonl");
2907
+ fs.writeFileSync(deleted, "A\n");
2908
+ const emitter = makeEmitter({ published });
2909
+ const batch = { paths: new Map([[deleted, "workspace/.session-logs/deleted-after-touch.jsonl"]]) };
2910
+ await emitter.emitForBatch(batch);
2911
+ await emitter.emitForBatch(batch);
2912
+ fs.rmSync(deleted);
2913
+ await emitter.emitForBatch(batch);
2914
+ fs.writeFileSync(deleted, "A\n");
2915
+ await emitter.emitForBatch(batch);
2916
+ expect(published).toHaveLength(3);
2917
+ expect(published.map((event) => event.kind)).toEqual(["upsert", "delete", "upsert"]);
2918
+ });
2919
+ it("re-announces a same-content recreation after a failed delete", async () => {
2920
+ const published = [];
2921
+ let fail = false;
2922
+ const deleted = path.join(dir, "failed-delete-session-log.jsonl");
2923
+ fs.writeFileSync(deleted, "A\n");
2924
+ const emitter = new PushEventEmitter({
2925
+ originTenantId: "tenant-indigo",
2926
+ originDeviceId: "device-a",
2927
+ flagProvider: { isEnabled: () => true },
2928
+ transport: {
2929
+ start: async () => { },
2930
+ dispose: async () => { },
2931
+ connected: true,
2932
+ publish: async (event) => {
2933
+ if (fail)
2934
+ throw new Error("push unavailable");
2935
+ published.push(event);
2936
+ },
2937
+ },
2938
+ onError: vi.fn(),
2939
+ });
2940
+ const batch = { paths: new Map([[deleted, "workspace/.session-logs/failed-delete-session-log.jsonl"]]) };
2941
+ await emitter.emitForBatch(batch);
2942
+ fs.rmSync(deleted);
2943
+ fail = true;
2944
+ await emitter.emitForBatch(batch);
2945
+ fs.writeFileSync(deleted, "A\n");
2946
+ fail = false;
2947
+ await emitter.emitForBatch(batch);
2948
+ expect(published.map((event) => event.kind)).toEqual(["upsert", "upsert"]);
2949
+ });
2950
+ it("bounds last-published content state and only re-publishes an evicted path", async () => {
2951
+ const published = [];
2952
+ const emitter = makeEmitter({ published, lastPublishedContentHashMaxPaths: 2 });
2953
+ const paths = ["first.jsonl", "second.jsonl", "third.jsonl"].map((name) => {
2954
+ const absolute = path.join(dir, name);
2955
+ fs.writeFileSync(absolute, `${name}\n`);
2956
+ return [absolute, `workspace/.session-logs/${name}`];
2957
+ });
2958
+ for (const entry of paths)
2959
+ await emitter.emitForBatch({ paths: new Map([entry]) });
2960
+ await emitter.emitForBatch({ paths: new Map([paths[0]]) });
2961
+ await emitter.emitForBatch({ paths: new Map([paths[2]]) });
2962
+ expect(published.map((event) => event.relativePath)).toEqual([
2963
+ "workspace/.session-logs/first.jsonl",
2964
+ "workspace/.session-logs/second.jsonl",
2965
+ "workspace/.session-logs/third.jsonl",
2966
+ "workspace/.session-logs/first.jsonl",
2967
+ ]);
2968
+ });
2969
+ it("restart simulation: preserves published hashes so an unchanged first pass emits zero upserts", async () => {
2970
+ const published = [];
2971
+ const journaled = path.join(dir, "pre-populated-journal.jsonl");
2972
+ fs.writeFileSync(journaled, "A\n");
2973
+ const batch = { paths: new Map([[journaled, "workspace/.session-logs/pre-populated-journal.jsonl"]]) };
2974
+ const stateDir = path.join(dir, "state");
2975
+ await makeEmitter({ published, lastPublishedContentHashStateDir: stateDir }).emitForBatch(batch);
2976
+ await makeEmitter({ published, lastPublishedContentHashStateDir: stateDir }).emitForBatch(batch);
2977
+ expect(published).toHaveLength(1);
2978
+ fs.writeFileSync(journaled, "B\n");
2979
+ await makeEmitter({ published, lastPublishedContentHashStateDir: stateDir }).emitForBatch(batch);
2980
+ expect(published).toHaveLength(2);
2981
+ expect(published[1].contentHash).not.toBe(published[0].contentHash);
2982
+ });
2983
+ it("restart simulation: publishes a tombstone for a delete during downtime", async () => {
2984
+ const published = [];
2985
+ const deleted = path.join(dir, "deleted-during-downtime.md");
2986
+ const batch = { paths: new Map([[deleted, "deleted-during-downtime.md"]]) };
2987
+ const stateDir = path.join(dir, "state");
2988
+ fs.writeFileSync(deleted, "A\n");
2989
+ await makeEmitter({ published, lastPublishedContentHashStateDir: stateDir }).emitForBatch(batch);
2990
+ fs.rmSync(deleted);
2991
+ await makeEmitter({ published, lastPublishedContentHashStateDir: stateDir }).emitForBatch(batch);
2992
+ expect(published.map((event) => event.kind)).toEqual(["upsert", "delete"]);
2993
+ });
2994
+ it("journal baseline suppresses unchanged files when durable state is first created", async () => {
2995
+ const published = [];
2996
+ const existing = path.join(dir, "journaled-before-upgrade.md");
2997
+ const relativePath = "companies/indigo/journaled-before-upgrade.md";
2998
+ fs.writeFileSync(existing, "already synced\n");
2999
+ const contentHash = `sha256:${createHash("sha256").update("already synced\n").digest("hex")}`;
3000
+ await makeEmitter({
3001
+ published,
3002
+ lastPublishedContentHashStateDir: path.join(dir, "baseline-state"),
3003
+ initialPublishedContentHashes: { [relativePath]: contentHash },
3004
+ }).emitForBatch({ paths: new Map([[existing, relativePath]]) });
3005
+ expect(published).toEqual([]);
3006
+ });
3007
+ it("does not seed suppression for a journaled local divergence", async () => {
3008
+ const published = [];
3009
+ const changed = path.join(dir, "changed-while-down.md");
3010
+ const relativePath = "companies/indigo/changed-while-down.md";
3011
+ fs.writeFileSync(changed, "changed while down\n");
3012
+ const contentHash = `sha256:${createHash("sha256").update("changed while down\n").digest("hex")}`;
3013
+ await makeEmitter({
3014
+ published,
3015
+ lastPublishedContentHashStateDir: path.join(dir, "divergent-state"),
3016
+ }).emitForBatch({ paths: new Map([[changed, relativePath]]) });
3017
+ expect(published).toHaveLength(1);
3018
+ expect(published[0]).toMatchObject({ kind: "upsert", contentHash });
3019
+ });
3020
+ it("fresh durable state publishes the first uploaded file", async () => {
3021
+ const published = [];
3022
+ const fresh = path.join(dir, "fresh-device.md");
3023
+ fs.writeFileSync(fresh, "first upload\n");
3024
+ await makeEmitter({
3025
+ published,
3026
+ lastPublishedContentHashStateDir: path.join(dir, "fresh-state"),
3027
+ }).emitForBatch({ paths: new Map([[fresh, "fresh-device.md"]]) });
3028
+ expect(published).toHaveLength(1);
3029
+ expect(published[0]).toMatchObject({ kind: "upsert", relativePath: "fresh-device.md" });
3030
+ });
3031
+ it("retries a durable publish-state lock timeout without rejecting the watcher announce", async () => {
3032
+ const clock = new FakeClock();
3033
+ const onError = vi.fn();
3034
+ const originalAppendGeneratedIfAsync = StateStore.prototype.appendGeneratedIfAsync;
3035
+ const appendGeneratedIfAsync = vi.spyOn(StateStore.prototype, "appendGeneratedIfAsync")
3036
+ .mockImplementationOnce(function (type, preparePayload, flags) {
3037
+ return originalAppendGeneratedIfAsync.call(this, type, preparePayload, flags);
3038
+ })
3039
+ .mockRejectedValueOnce(new StateStoreLockError("timed out acquiring append.lock"));
3040
+ const published = [];
3041
+ const changed = path.join(dir, "lock-timeout.md");
3042
+ fs.writeFileSync(changed, "lock timeout\n");
3043
+ try {
3044
+ await expect(makeEmitter({
3045
+ clock,
3046
+ onError,
3047
+ published,
3048
+ lastPublishedContentHashStateDir: path.join(dir, "lock-timeout-state"),
3049
+ }).emitForBatch({ paths: new Map([[changed, "lock-timeout.md"]]) })).resolves.toBeUndefined();
3050
+ expect(published).toHaveLength(1);
3051
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ name: "StateStoreLockError" }), { relativePath: "lock-timeout.md" });
3052
+ expect(appendGeneratedIfAsync).toHaveBeenCalledTimes(2); // invalidate before the guarded durable set
3053
+ const appendsBeforeRetry = appendGeneratedIfAsync.mock.calls.length;
3054
+ clock.advance(250);
3055
+ await Promise.resolve();
3056
+ await Promise.resolve();
3057
+ expect(appendGeneratedIfAsync).toHaveBeenCalledTimes(appendsBeforeRetry + 1);
3058
+ }
3059
+ finally {
3060
+ appendGeneratedIfAsync.mockRestore();
3061
+ }
3062
+ });
3063
+ it("cancels a stale durable-state retry after persisting a newer hash", async () => {
3064
+ const clock = new FakeClock();
3065
+ const originalAppendGeneratedIfAsync = StateStore.prototype.appendGeneratedIfAsync;
3066
+ const appendGeneratedIfAsync = vi.spyOn(StateStore.prototype, "appendGeneratedIfAsync")
3067
+ .mockImplementationOnce(function (type, preparePayload, flags) {
3068
+ return originalAppendGeneratedIfAsync.call(this, type, preparePayload, flags);
3069
+ })
3070
+ .mockRejectedValueOnce(new StateStoreLockError("timed out acquiring append.lock"));
3071
+ const stateDir = path.join(dir, "superseded-retry-state");
3072
+ const changed = path.join(dir, "superseded-retry.md");
3073
+ const published = [];
3074
+ fs.writeFileSync(changed, "A\n");
3075
+ try {
3076
+ const emitter = makeEmitter({ clock, published, lastPublishedContentHashStateDir: stateDir });
3077
+ await emitter.emitForBatch({ paths: new Map([[changed, "superseded-retry.md"]]) });
3078
+ expect(clock.pendingTimerCount()).toBe(1);
3079
+ fs.writeFileSync(changed, "B\n");
3080
+ await emitter.emitForBatch({ paths: new Map([[changed, "superseded-retry.md"]]) });
3081
+ expect(clock.pendingTimerCount()).toBe(0);
3082
+ const appendsAfterNewerSuccess = appendGeneratedIfAsync.mock.calls.length;
3083
+ clock.advance(10_000);
3084
+ await Promise.resolve();
3085
+ expect(appendGeneratedIfAsync).toHaveBeenCalledTimes(appendsAfterNewerSuccess);
3086
+ const afterRestart = [];
3087
+ await makeEmitter({
3088
+ published: afterRestart,
3089
+ lastPublishedContentHashStateDir: stateDir,
3090
+ }).emitForBatch({ paths: new Map([[changed, "superseded-retry.md"]]) });
3091
+ expect(afterRestart).toEqual([]);
3092
+ }
3093
+ finally {
3094
+ appendGeneratedIfAsync.mockRestore();
3095
+ }
3096
+ });
3097
+ it("drops permanent durable-state persistence errors without scheduling retries", async () => {
3098
+ const clock = new FakeClock();
3099
+ const onError = vi.fn();
3100
+ const originalAppendGeneratedIfAsync = StateStore.prototype.appendGeneratedIfAsync;
3101
+ const appendGeneratedIfAsync = vi.spyOn(StateStore.prototype, "appendGeneratedIfAsync")
3102
+ .mockImplementationOnce(function (type, preparePayload, flags) {
3103
+ return originalAppendGeneratedIfAsync.call(this, type, preparePayload, flags);
3104
+ })
3105
+ .mockRejectedValue(new Error("EACCES: state directory is unwritable"));
3106
+ const changed = path.join(dir, "permanent-state-error.md");
3107
+ fs.writeFileSync(changed, "cannot persist\n");
3108
+ try {
3109
+ await makeEmitter({
3110
+ clock,
3111
+ onError,
3112
+ lastPublishedContentHashStateDir: path.join(dir, "permanent-state-error"),
3113
+ }).emitForBatch({ paths: new Map([[changed, "permanent-state-error.md"]]) });
3114
+ expect(onError).toHaveBeenCalledTimes(1);
3115
+ expect(onError).toHaveBeenCalledWith(expect.objectContaining({ message: expect.stringContaining("EACCES") }), { relativePath: "permanent-state-error.md" });
3116
+ expect(clock.pendingTimerCount()).toBe(0);
3117
+ const appendsAfterFailure = appendGeneratedIfAsync.mock.calls.length;
3118
+ clock.advance(60_000);
3119
+ await Promise.resolve();
3120
+ expect(appendGeneratedIfAsync).toHaveBeenCalledTimes(appendsAfterFailure);
3121
+ expect(onError).toHaveBeenCalledTimes(1);
3122
+ }
3123
+ finally {
3124
+ appendGeneratedIfAsync.mockRestore();
3125
+ }
3126
+ });
3127
+ it("emits push telemetry only when publication fails", async () => {
3128
+ const posts = [];
3129
+ const telemetryClient = {
3130
+ postTelemetryEvents: vi.fn(async (batch) => {
3131
+ posts.push(batch);
3132
+ return { ok: true, written: batch.events.length, skipped: [] };
3133
+ }),
3134
+ };
3135
+ const changed = path.join(dir, "changed.md");
3136
+ fs.writeFileSync(changed, "changed");
3137
+ const success = new PushEventEmitter({
3138
+ originTenantId: "tenant-indigo",
3139
+ originDeviceId: "device-a",
3140
+ transport: {
3141
+ start: async () => { },
3142
+ dispose: async () => { },
3143
+ connected: true,
3144
+ publish: async () => { },
3145
+ },
3146
+ flagProvider: { isEnabled: () => true },
3147
+ telemetryClient,
3148
+ });
3149
+ await success.emitForBatch({ paths: new Map([[changed, "changed.md"]]) });
3150
+ await flushImmediate();
3151
+ expect(posts).toEqual([]);
3152
+ const failed = new PushEventEmitter({
3153
+ originTenantId: "tenant-indigo",
3154
+ originDeviceId: "device-a",
3155
+ transport: {
3156
+ start: async () => { },
3157
+ dispose: async () => { },
3158
+ connected: true,
3159
+ publish: async () => {
3160
+ throw new Error("network down");
3161
+ },
3162
+ },
3163
+ flagProvider: { isEnabled: () => true },
3164
+ telemetryClient,
3165
+ onError: vi.fn(),
3166
+ });
3167
+ await failed.emitForBatch({ paths: new Map([[changed, "changed.md"]]) });
3168
+ await flushImmediate();
3169
+ expect(posts.flatMap((post) => post.events)).toEqual([
3170
+ expect.objectContaining({
3171
+ eventName: "push_event_failed",
3172
+ properties: {
3173
+ kind: "upsert",
3174
+ count: 1,
3175
+ status: "failure",
3176
+ stage: "publish",
3177
+ },
3178
+ }),
3179
+ ]);
3180
+ });
3181
+ it("emits one outcome record with the correct mixed-batch attempt denominator", async () => {
3182
+ const first = path.join(dir, "first.md");
3183
+ const second = path.join(dir, "second.md");
3184
+ fs.writeFileSync(first, "first");
3185
+ fs.writeFileSync(second, "second");
3186
+ const outcomes = [];
3187
+ const emitter = new PushEventEmitter({
3188
+ originTenantId: "tenant-indigo",
3189
+ originDeviceId: "device-a",
3190
+ transport: {
3191
+ start: async () => { },
3192
+ dispose: async () => { },
3193
+ connected: true,
3194
+ publish: async (event) => {
3195
+ if (event.relativePath === "second.md") {
3196
+ throw new Error("second publish failed");
3197
+ }
3198
+ },
3199
+ },
3200
+ flagProvider: { isEnabled: () => true },
3201
+ getSequenceNumber: (() => {
3202
+ let next = 41;
3203
+ return () => next++;
3204
+ })(),
3205
+ onError: vi.fn(),
3206
+ onPublishOutcome: (outcome) => outcomes.push(outcome),
3207
+ });
3208
+ await emitter.emitForBatch({
3209
+ paths: new Map([
3210
+ [first, "first.md"],
3211
+ [second, "second.md"],
3212
+ ]),
3213
+ });
3214
+ expect(outcomes).toHaveLength(1);
3215
+ expect(outcomes[0]).toMatchObject({
3216
+ attempted: 2,
3217
+ succeeded: 1,
3218
+ failed: 1,
3219
+ });
3220
+ expect(outcomes[0].omitted).toBe(0);
3221
+ expect(outcomes[0].attempts).toContainEqual(expect.objectContaining({
3222
+ error: expect.objectContaining({ message: "second publish failed" }),
3223
+ }));
3224
+ });
3225
+ it("caps successful attempt evidence while retaining every failure and full-set latency statistics", () => {
3226
+ const successes = Array.from({ length: 1_000 }, (_, index) => ({
3227
+ sequenceNumber: index,
3228
+ elapsedMs: index + 1,
3229
+ abortedAtIssue: false,
3230
+ }));
3231
+ const failures = Array.from({ length: 16 }, (_, index) => ({
3232
+ sequenceNumber: 10_000 + index,
3233
+ elapsedMs: 60_000 + index,
3234
+ abortedAtIssue: false,
3235
+ error: {
3236
+ name: "AbortError",
3237
+ message: `publish timeout ${index}`,
3238
+ stack: "at Timeout._onTimeout (push-transport.js:195)",
3239
+ },
3240
+ }));
3241
+ const outcome = summarizePublishBatchOutcome([...successes, ...failures]);
3242
+ const serialized = JSON.stringify(outcome);
3243
+ const retainedFailures = outcome.attempts.filter((attempt) => attempt.error !== undefined);
3244
+ const retainedSuccesses = outcome.attempts.filter((attempt) => attempt.error === undefined);
3245
+ expect(outcome).toMatchObject({
3246
+ attempted: 1_016,
3247
+ succeeded: 1_000,
3248
+ failed: 16,
3249
+ omitted: 1_000 - PUBLISH_OUTCOME_SUCCESS_SAMPLE_CAP,
3250
+ successfulElapsedMs: { min: 1, median: 500.5, max: 1_000 },
3251
+ });
3252
+ expect(retainedSuccesses).toEqual(successes.slice(0, 3));
3253
+ expect(retainedFailures).toEqual(failures);
3254
+ for (const aggregate of ["attempted", "succeeded", "failed"]) {
3255
+ expect(serialized.indexOf(`"${aggregate}"`)).toBeLessThan(serialized.indexOf('"attempts"'));
3256
+ }
3257
+ expect(Buffer.byteLength(serialized)).toBeLessThan(PUBLISH_OUTCOME_JOURNALD_CEILING_BYTES);
3258
+ });
3259
+ });
3260
+ describe("TreeWatcher wire-key codec boundary (US-002)", () => {
3261
+ it("emits the canonical vault key for an encoded win32 farm name (verbatim local name on POSIX)", () => {
3262
+ const hqRoot = path.join(os.tmpdir(), "hq-watch-codec-test-root");
3263
+ const clock = new FakeClock();
3264
+ const watcher = new TreeWatcher({
3265
+ hqRoot,
3266
+ clock,
3267
+ debounceMs: 100,
3268
+ pathFilter: () => true,
3269
+ });
3270
+ const rels = [];
3271
+ watcher.onChange((_first, batch) => {
3272
+ if (batch)
3273
+ rels.push(...batch.paths.values());
3274
+ });
3275
+ watcher.handleEvent(path.join(hqRoot, ".claude", "skills", "indigo%3Acall-prep-brief"));
3276
+ clock.advance(200);
3277
+ // The batch rel is a WIRE identifier (PushEvent.relativePath / targeted
3278
+ // push route). On win32 the encoded local farm name must decode back to
3279
+ // the canonical key or event-driven push re-mints the junk key family;
3280
+ // on POSIX the local name IS the key verbatim (codec is identity there).
3281
+ const expectedRel = process.platform === "win32"
3282
+ ? ".claude/skills/indigo:call-prep-brief"
3283
+ : ".claude/skills/indigo%3Acall-prep-brief";
3284
+ expect(rels).toEqual([expectedRel]);
3285
+ watcher.dispose();
3286
+ });
3287
+ });
3288
+ describe("TreeWatcher deferred delete snapshots", () => {
3289
+ it("does not let a thrown delete-capture callback kill later watcher delivery", () => {
3290
+ const hqRoot = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watch-capture-error-"));
3291
+ const clock = new FakeClock();
3292
+ const watcher = new TreeWatcher({
3293
+ hqRoot,
3294
+ clock,
3295
+ debounceMs: 25,
3296
+ pathFilter: () => true,
3297
+ queueLocalDeleteSnapshots: () => {
3298
+ throw new Error("capture failed");
3299
+ },
3300
+ });
3301
+ const batches = [];
3302
+ watcher.onChange((_first, batch) => batches.push([...(batch?.paths.values() ?? [])]));
3303
+ expect(() => watcher.handleEvent(path.join(hqRoot, "deleted.md"), "unlink")).not.toThrow();
3304
+ expect(() => watcher.handleEvent(path.join(hqRoot, "later.md"), "add")).not.toThrow();
3305
+ clock.advance(25);
3306
+ expect(batches).toEqual([["deleted.md", "later.md"]]);
3307
+ watcher.dispose();
3308
+ fs.rmSync(hqRoot, { recursive: true, force: true });
3309
+ });
3310
+ it("marks a queued unlink stale when a newer revision arrives", async () => {
3311
+ const hqRoot = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watch-capture-stale-"));
3312
+ const clock = new FakeClock();
3313
+ let resolveCapture;
3314
+ let observedCurrent = true;
3315
+ const watcher = new TreeWatcher({
3316
+ hqRoot,
3317
+ clock,
3318
+ debounceMs: 25,
3319
+ pathFilter: () => true,
3320
+ queueLocalDeleteSnapshots: async (_relative, _kind, isCurrent) => {
3321
+ await new Promise((resolve) => { resolveCapture = resolve; });
3322
+ observedCurrent = isCurrent();
3323
+ return [];
3324
+ },
3325
+ });
3326
+ watcher.handleEvent(path.join(hqRoot, "recreated.md"), "unlink");
3327
+ await Promise.resolve();
3328
+ watcher.handleEvent(path.join(hqRoot, "recreated.md"), "add");
3329
+ resolveCapture();
3330
+ await Promise.resolve();
3331
+ expect(observedCurrent).toBe(false);
3332
+ watcher.dispose();
3333
+ fs.rmSync(hqRoot, { recursive: true, force: true });
3334
+ });
3335
+ it("batches one watcher turn and keeps per-path current checks", async () => {
3336
+ const hqRoot = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watch-capture-batch-"));
3337
+ const clock = new FakeClock();
3338
+ const observed = [];
3339
+ const queueBatch = async (captures) => {
3340
+ const results = captures.map((capture) => {
3341
+ const current = capture.isCurrent();
3342
+ observed.push({ relativePath: capture.relativePath, current });
3343
+ return current ? [{
3344
+ journalSlug: "indigo",
3345
+ journalPath: capture.relativePath,
3346
+ deleteScopeRoot: "",
3347
+ absolutePath: path.join(hqRoot, capture.relativePath),
3348
+ remoteEtag: "etag",
3349
+ localHash: "hash",
3350
+ localKind: "file",
3351
+ }] : [];
3352
+ });
3353
+ return results;
3354
+ };
3355
+ const watcher = new TreeWatcher({
3356
+ hqRoot,
3357
+ clock,
3358
+ debounceMs: 25,
3359
+ pathFilter: () => true,
3360
+ queueLocalDeleteSnapshotsBatch: queueBatch,
3361
+ });
3362
+ try {
3363
+ const recreated = path.join(hqRoot, "recreated.md");
3364
+ const deleted = path.join(hqRoot, "deleted.md");
3365
+ watcher.handleEvent(recreated, "unlink");
3366
+ watcher.handleEvent(recreated, "add");
3367
+ watcher.handleEvent(deleted, "unlink");
3368
+ await settle();
3369
+ expect(observed).toEqual([
3370
+ { relativePath: "recreated.md", current: false },
3371
+ { relativePath: "deleted.md", current: true },
3372
+ ]);
3373
+ await settle();
3374
+ expect(watcher.censusSizes().deleteSnapshotEpochs).toBe(0);
3375
+ }
3376
+ finally {
3377
+ watcher.dispose();
3378
+ fs.rmSync(hqRoot, { recursive: true, force: true });
3379
+ }
3380
+ });
3381
+ // `deleteSnapshotEpochs` exists to let a newer revision of a path
3382
+ // invalidate a delete-snapshot capture that is still queued or running. A
3383
+ // long-lived runner touches hundreds of thousands of distinct paths, so a
3384
+ // key may live in that map only while such a capture is in flight; any
3385
+ // other write into it is a leak keyed by path.
3386
+ it("batches warmup missing-file snapshots through the queued capture path", async () => {
3387
+ const hqRoot = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watch-warmup-capture-batch-"));
3388
+ const observed = [];
3389
+ const queueBatch = async (captures) => {
3390
+ observed.push(captures.map((capture) => capture.relativePath));
3391
+ return captures.map(() => []);
3392
+ };
3393
+ const watcher = new TreeWatcher({
3394
+ hqRoot,
3395
+ pathFilter: () => true,
3396
+ queueLocalDeleteSnapshotsBatch: queueBatch,
3397
+ });
3398
+ try {
3399
+ const catchup = await watcher.collectWarmupCatchupAsync(Date.now(), [
3400
+ "missing-one.md",
3401
+ "missing-two.md",
3402
+ ]);
3403
+ await Promise.all([...(catchup.batch.changes?.values() ?? [])].map((change) => change.deleteSnapshotCapture ?? Promise.resolve([])));
3404
+ await settle();
3405
+ expect(observed).toEqual([["missing-one.md", "missing-two.md"]]);
3406
+ }
3407
+ finally {
3408
+ watcher.dispose();
3409
+ fs.rmSync(hqRoot, { recursive: true, force: true });
3410
+ }
3411
+ });
3412
+ const settle = () => new Promise((resolve) => setImmediate(resolve));
3413
+ it("retires a superseded capture's epoch when that capture completes", async () => {
3414
+ const hqRoot = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watch-epoch-retire-"));
3415
+ const clock = new FakeClock();
3416
+ let resolveCapture;
3417
+ let observedCurrent = true;
3418
+ const watcher = new TreeWatcher({
3419
+ hqRoot,
3420
+ clock,
3421
+ debounceMs: 25,
3422
+ pathFilter: () => true,
3423
+ queueLocalDeleteSnapshots: async (_relative, _kind, isCurrent) => {
3424
+ await new Promise((resolve) => { resolveCapture = resolve; });
3425
+ observedCurrent = isCurrent();
3426
+ return [];
3427
+ },
3428
+ });
3429
+ try {
3430
+ const target = path.join(hqRoot, "recreated.md");
3431
+ watcher.handleEvent(target, "unlink");
3432
+ await Promise.resolve();
3433
+ expect(watcher.censusSizes().deleteSnapshotEpochs).toBe(1);
3434
+ // The newer revision invalidates the running capture but must keep the
3435
+ // marker until that capture has actually observed it.
3436
+ watcher.handleEvent(target, "add");
3437
+ expect(watcher.censusSizes().deleteSnapshotEpochs).toBe(1);
3438
+ resolveCapture();
3439
+ await settle();
3440
+ expect(observedCurrent).toBe(false);
3441
+ expect(watcher.censusSizes().deleteSnapshotEpochs).toBe(0);
3442
+ }
3443
+ finally {
3444
+ watcher.dispose();
3445
+ fs.rmSync(hqRoot, { recursive: true, force: true });
3446
+ }
3447
+ });
3448
+ it("never creates an epoch for a live event or for a synchronous capture", () => {
3449
+ const hqRoot = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watch-epoch-live-"));
3450
+ const clock = new FakeClock();
3451
+ const capture = vi.fn(() => []);
3452
+ const watcher = new TreeWatcher({
3453
+ hqRoot,
3454
+ clock,
3455
+ debounceMs: 25,
3456
+ pathFilter: () => true,
3457
+ captureLocalDeleteSnapshots: capture,
3458
+ });
3459
+ try {
3460
+ watcher.handleEvent(path.join(hqRoot, "added.md"), "add");
3461
+ watcher.handleEvent(path.join(hqRoot, "edited.md"), "change");
3462
+ watcher.handleEvent(path.join(hqRoot, "made"), "addDir");
3463
+ watcher.handleEvent(path.join(hqRoot, "gone.md"), "unlink");
3464
+ watcher.handleEvent(path.join(hqRoot, "gone-dir"), "unlinkDir");
3465
+ clock.advance(25);
3466
+ expect(capture).toHaveBeenCalledTimes(2);
3467
+ // A synchronous capture has already run by the time the event returns:
3468
+ // there is nothing left to invalidate, so there is nothing to remember.
3469
+ expect(watcher.censusSizes().deleteSnapshotEpochs).toBe(0);
3470
+ }
3471
+ finally {
3472
+ watcher.dispose();
3473
+ fs.rmSync(hqRoot, { recursive: true, force: true });
3474
+ }
3475
+ });
3476
+ it("shares one epoch across overlapping captures of a path and retires it with the last", async () => {
3477
+ const hqRoot = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watch-epoch-overlap-"));
3478
+ const clock = new FakeClock();
3479
+ const resolvers = [];
3480
+ const observed = [];
3481
+ const watcher = new TreeWatcher({
3482
+ hqRoot,
3483
+ clock,
3484
+ debounceMs: 25,
3485
+ pathFilter: () => true,
3486
+ queueLocalDeleteSnapshots: async (_relative, _kind, isCurrent) => {
3487
+ await new Promise((resolve) => { resolvers.push(resolve); });
3488
+ observed.push(isCurrent());
3489
+ return [];
3490
+ },
3491
+ });
3492
+ try {
3493
+ const target = path.join(hqRoot, "twice.md");
3494
+ watcher.handleEvent(target, "unlink");
3495
+ await Promise.resolve();
3496
+ watcher.handleEvent(target, "unlink"); // second delete in the window queues behind the first
3497
+ expect(watcher.censusSizes().deleteSnapshotEpochs).toBe(1);
3498
+ resolvers.shift()();
3499
+ await settle();
3500
+ // The first capture was superseded by the second; the second is still
3501
+ // queued, so the path keeps its marker.
3502
+ expect(observed).toEqual([false]);
3503
+ expect(watcher.censusSizes().deleteSnapshotEpochs).toBe(1);
3504
+ resolvers.shift()();
3505
+ await settle();
3506
+ expect(observed).toEqual([false, true]);
3507
+ expect(watcher.censusSizes().deleteSnapshotEpochs).toBe(0);
3508
+ }
3509
+ finally {
3510
+ watcher.dispose();
3511
+ fs.rmSync(hqRoot, { recursive: true, force: true });
3512
+ }
3513
+ });
3514
+ it("leaves no epoch for a path whose capture the full queue rejected", async () => {
3515
+ const hqRoot = fs.mkdtempSync(path.join(os.tmpdir(), "hq-watch-epoch-full-"));
3516
+ const clock = new FakeClock();
3517
+ const resolvers = [];
3518
+ const observed = [];
3519
+ const watcher = new TreeWatcher({
3520
+ hqRoot,
3521
+ clock,
3522
+ debounceMs: 25,
3523
+ pathFilter: () => true,
3524
+ maxPendingPaths: 2,
3525
+ queueLocalDeleteSnapshots: async (relative, _kind, isCurrent) => {
3526
+ await new Promise((resolve) => { resolvers.push(resolve); });
3527
+ observed.push(`${relative}:${isCurrent()}`);
3528
+ return [];
3529
+ },
3530
+ });
3531
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
3532
+ try {
3533
+ const a = path.join(hqRoot, "a.md");
3534
+ const b = path.join(hqRoot, "b.md");
3535
+ watcher.handleEvent(a, "unlink");
3536
+ await Promise.resolve();
3537
+ resolvers.shift()();
3538
+ await settle(); // a's capture is done; a is still pending in the window
3539
+ expect(observed).toEqual(["a.md:true"]);
3540
+ expect(watcher.censusSizes().deleteSnapshotEpochs).toBe(0);
3541
+ watcher.handleEvent(b, "unlink");
3542
+ watcher.handleEvent(b, "unlink"); // two captures queued for b: the queue is full
3543
+ // A third delete of `a` finds the queue full. Nothing is in flight for
3544
+ // `a`, so nothing may be recorded for it either.
3545
+ watcher.handleEvent(a, "unlink");
3546
+ expect(watcher.censusSizes().deleteSnapshotEpochs).toBe(1);
3547
+ // A full queue must still supersede a capture that IS in flight for the
3548
+ // path, exactly as it did before, and that path's marker still retires.
3549
+ watcher.handleEvent(b, "unlink");
3550
+ await settle(); // the first queued capture for b starts
3551
+ resolvers.shift()();
3552
+ await settle(); // ...and the second, queued behind it
3553
+ resolvers.shift()();
3554
+ await settle();
3555
+ expect(observed).toEqual(["a.md:true", "b.md:false", "b.md:false"]);
3556
+ expect(watcher.censusSizes().deleteSnapshotEpochs).toBe(0);
3557
+ }
3558
+ finally {
3559
+ consoleError.mockRestore();
3560
+ watcher.dispose();
3561
+ fs.rmSync(hqRoot, { recursive: true, force: true });
3562
+ }
3563
+ });
3564
+ });
3565
+ describe("TreeWatcher untracked delete drop", () => {
3566
+ // Atomic writers (`.name.<pid>.<random>.tmp` renamed into place, editor
3567
+ // swap files) create and remove a path within one debounce window. Such a
3568
+ // path has no journal row, so its unlink has nothing to delete remotely and
3569
+ // no revision to bind: queueing it only cost a delete-snapshot capture, a
3570
+ // pending-map slot, and a targeted push that found nothing on disk. On the
3571
+ // controller these were 370 of 380 agency watcher events per minute.
3572
+ function makeRoot() {
3573
+ return fs.mkdtempSync(path.join(os.tmpdir(), "hq-watch-untracked-"));
3574
+ }
3575
+ it("drops a file unlink that has no journal row before it reaches a batch", () => {
3576
+ const hqRoot = makeRoot();
3577
+ const clock = new FakeClock();
3578
+ const capture = vi.fn(() => []);
3579
+ const watcher = new TreeWatcher({
3580
+ hqRoot,
3581
+ clock,
3582
+ debounceMs: 25,
3583
+ pathFilter: () => true,
3584
+ captureLocalDeleteSnapshots: capture,
3585
+ isUntrackedDelete: (relativePath) => relativePath.endsWith(".tmp"),
3586
+ });
3587
+ const batches = [];
3588
+ watcher.onChange((_first, batch) => batches.push([...(batch?.paths.values() ?? [])]));
3589
+ try {
3590
+ watcher.handleEvent(path.join(hqRoot, "notes", ".draft.md.123.abc.tmp"), "unlink");
3591
+ watcher.handleEvent(path.join(hqRoot, "notes", "kept.md"), "unlink");
3592
+ clock.advance(25);
3593
+ expect(batches).toEqual([["notes/kept.md"]]);
3594
+ // The dropped path never paid for a delete-snapshot capture.
3595
+ expect(capture).toHaveBeenCalledTimes(1);
3596
+ expect(capture).toHaveBeenCalledWith("notes/kept.md", "unlink");
3597
+ expect(watcher.untrackedDeletesDropped()).toBe(1);
3598
+ // Neither path leaves an epoch behind: the kept unlink was captured
3599
+ // synchronously (nothing in flight to invalidate) and the dropped one
3600
+ // never had a capture at all.
3601
+ expect(watcher.censusSizes().deleteSnapshotEpochs).toBe(0);
3602
+ }
3603
+ finally {
3604
+ watcher.dispose();
3605
+ fs.rmSync(hqRoot, { recursive: true, force: true });
3606
+ }
3607
+ });
3608
+ it("leaves no delete-snapshot epoch behind for an atomic write cancelled inside its own window", () => {
3609
+ // Every agency writer saves through `.<name>.<pid>.<random>.tmp` and
3610
+ // renames it into place, so the watcher sees an `add` and then an
3611
+ // `unlink` of a name it will never see again. 370 of those a minute on
3612
+ // the controller: if each one left a key in a per-path map, the map
3613
+ // would grow by half a million randomised paths a day.
3614
+ const hqRoot = makeRoot();
3615
+ const clock = new FakeClock();
3616
+ const queue = vi.fn(async () => []);
3617
+ const watcher = new TreeWatcher({
3618
+ hqRoot,
3619
+ clock,
3620
+ debounceMs: 25,
3621
+ pathFilter: () => true,
3622
+ queueLocalDeleteSnapshots: queue,
3623
+ isUntrackedDelete: (relativePath) => relativePath.endsWith(".tmp"),
3624
+ });
3625
+ const changed = vi.fn();
3626
+ watcher.onChange(changed);
3627
+ try {
3628
+ for (let i = 0; i < 250; i++) {
3629
+ const temp = path.join(hqRoot, "workspace", "agency", `.ledger.json.${i}.${(i * 7919).toString(36)}.tmp`);
3630
+ watcher.handleEvent(temp, "add");
3631
+ watcher.handleEvent(temp, "unlink");
3632
+ }
3633
+ clock.advance(1_000);
3634
+ expect(queue).not.toHaveBeenCalled();
3635
+ expect(changed).not.toHaveBeenCalled();
3636
+ expect(watcher.untrackedDeletesDropped()).toBe(250);
3637
+ expect(watcher.pendingTimerCount()).toBe(0);
3638
+ expect(watcher.censusSizes()).toMatchObject({ deleteSnapshotEpochs: 0, knownKinds: 0 });
3639
+ }
3640
+ finally {
3641
+ watcher.dispose();
3642
+ fs.rmSync(hqRoot, { recursive: true, force: true });
3643
+ }
3644
+ });
3645
+ it("resolves a vanished rename to an unlink, purges the path's earlier queued add, and leaves no timer armed", () => {
3646
+ const hqRoot = makeRoot();
3647
+ const clock = new FakeClock();
3648
+ const seam = vi.fn((relativePath) => relativePath.endsWith(".tmp"));
3649
+ const watcher = new TreeWatcher({
3650
+ hqRoot,
3651
+ clock,
3652
+ debounceMs: 25,
3653
+ pathFilter: () => true,
3654
+ isUntrackedDelete: seam,
3655
+ });
3656
+ const changed = vi.fn();
3657
+ watcher.onChange(changed);
3658
+ try {
3659
+ const temp = path.join(hqRoot, "state.json.tmp");
3660
+ fs.writeFileSync(temp, "{}");
3661
+ watcher.handleEvent(temp, "rename"); // exists → add
3662
+ expect(watcher.pendingTimerCount()).toBe(1);
3663
+ fs.rmSync(temp);
3664
+ watcher.handleEvent(temp, "rename"); // ENOENT → unlink → untracked → dropped
3665
+ // The create and the delete cancelled out inside one window. Nothing is
3666
+ // left to emit, so the window closes without waking the push at all.
3667
+ expect(seam).toHaveBeenCalledWith("state.json.tmp");
3668
+ expect(watcher.pendingTimerCount()).toBe(0);
3669
+ clock.advance(1_000);
3670
+ expect(changed).not.toHaveBeenCalled();
3671
+ expect(watcher.untrackedDeletesDropped()).toBe(1);
3672
+ }
3673
+ finally {
3674
+ watcher.dispose();
3675
+ fs.rmSync(hqRoot, { recursive: true, force: true });
3676
+ }
3677
+ });
3678
+ it("keeps journaled unlinks and never consults the seam for live files or directory deletes", () => {
3679
+ const hqRoot = makeRoot();
3680
+ const clock = new FakeClock();
3681
+ const seam = vi.fn(() => false);
3682
+ const capture = vi.fn(() => []);
3683
+ const watcher = new TreeWatcher({
3684
+ hqRoot,
3685
+ clock,
3686
+ debounceMs: 25,
3687
+ pathFilter: () => true,
3688
+ captureLocalDeleteSnapshots: capture,
3689
+ isUntrackedDelete: seam,
3690
+ });
3691
+ const batches = [];
3692
+ watcher.onChange((_first, batch) => batches.push(batch?.paths ?? new Map()));
3693
+ try {
3694
+ const live = path.join(hqRoot, "live.md");
3695
+ fs.writeFileSync(live, "x");
3696
+ watcher.handleEvent(live, "add");
3697
+ // A directory with no row of its own may still cover journaled
3698
+ // descendants; only the capture's prefix scan can tell, so directory
3699
+ // deletes always go through.
3700
+ watcher.handleEvent(path.join(hqRoot, "gone-dir"), "unlinkDir");
3701
+ watcher.handleEvent(path.join(hqRoot, "journaled.md"), "unlink");
3702
+ clock.advance(25);
3703
+ expect(seam).toHaveBeenCalledTimes(1);
3704
+ expect(seam).toHaveBeenCalledWith("journaled.md");
3705
+ expect([...(batches[0]?.values() ?? [])].sort()).toEqual(["gone-dir", "journaled.md", "live.md"]);
3706
+ expect(capture).toHaveBeenCalledWith("gone-dir", "unlinkDir");
3707
+ expect(capture).toHaveBeenCalledWith("journaled.md", "unlink");
3708
+ expect(watcher.untrackedDeletesDropped()).toBe(0);
3709
+ }
3710
+ finally {
3711
+ watcher.dispose();
3712
+ fs.rmSync(hqRoot, { recursive: true, force: true });
3713
+ }
3714
+ });
3715
+ it("keeps the unlink when the seam throws", () => {
3716
+ const hqRoot = makeRoot();
3717
+ const clock = new FakeClock();
3718
+ const watcher = new TreeWatcher({
3719
+ hqRoot,
3720
+ clock,
3721
+ debounceMs: 25,
3722
+ pathFilter: () => true,
3723
+ isUntrackedDelete: () => {
3724
+ throw new Error("journal unavailable");
3725
+ },
3726
+ });
3727
+ const batches = [];
3728
+ watcher.onChange((_first, batch) => batches.push([...(batch?.paths.values() ?? [])]));
3729
+ const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined);
3730
+ try {
3731
+ expect(() => watcher.handleEvent(path.join(hqRoot, "maybe.md"), "unlink")).not.toThrow();
3732
+ clock.advance(25);
3733
+ // Dropping is an optimisation; keeping the event is the safe default.
3734
+ expect(batches).toEqual([["maybe.md"]]);
3735
+ expect(watcher.untrackedDeletesDropped()).toBe(0);
3736
+ }
3737
+ finally {
3738
+ consoleError.mockRestore();
3739
+ watcher.dispose();
3740
+ fs.rmSync(hqRoot, { recursive: true, force: true });
3741
+ }
3742
+ });
3743
+ it("a dropped unlink supersedes an in-flight queued capture for the same path", async () => {
3744
+ const hqRoot = makeRoot();
3745
+ const clock = new FakeClock();
3746
+ let untracked = false;
3747
+ let resolveCapture;
3748
+ let observedCurrent;
3749
+ const watcher = new TreeWatcher({
3750
+ hqRoot,
3751
+ clock,
3752
+ debounceMs: 25,
3753
+ pathFilter: () => true,
3754
+ isUntrackedDelete: () => untracked,
3755
+ queueLocalDeleteSnapshots: async (_relative, _kind, isCurrent) => {
3756
+ await new Promise((resolve) => { resolveCapture = resolve; });
3757
+ observedCurrent = isCurrent();
3758
+ return [];
3759
+ },
3760
+ });
3761
+ try {
3762
+ const target = path.join(hqRoot, "flip.md");
3763
+ watcher.handleEvent(target, "unlink"); // journal view cold: kept, capture queued
3764
+ await Promise.resolve();
3765
+ untracked = true;
3766
+ watcher.handleEvent(target, "unlink"); // journal view warm: no row → dropped
3767
+ resolveCapture();
3768
+ await Promise.resolve();
3769
+ // The queued capture must not bind a revision for a path the watcher
3770
+ // has since discarded.
3771
+ expect(observedCurrent).toBe(false);
3772
+ expect(watcher.pendingTimerCount()).toBe(0);
3773
+ expect(watcher.untrackedDeletesDropped()).toBe(1);
3774
+ }
3775
+ finally {
3776
+ watcher.dispose();
3777
+ fs.rmSync(hqRoot, { recursive: true, force: true });
3778
+ }
3779
+ });
3780
+ });
3781
+ // ---------------------------------------------------------------------------
3782
+ // Event-pass debounce configuration (HQ_SYNC_EVENT_DEBOUNCE_MS / _MAX_WAIT_MS)
3783
+ // ---------------------------------------------------------------------------
3784
+ describe("resolveEventDebounceConfig", () => {
3785
+ const ENV_KEYS = [
3786
+ EVENT_DEBOUNCE_MS_ENV,
3787
+ EVENT_MAX_WAIT_MS_ENV,
3788
+ EVENT_SMALL_BATCH_DEBOUNCE_MS_ENV,
3789
+ EVENT_SMALL_BATCH_MAX_PATHS_ENV,
3790
+ EVENT_SMALL_BATCH_MAX_BYTES_ENV,
3791
+ ];
3792
+ let saved;
3793
+ beforeEach(() => {
3794
+ saved = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));
3795
+ for (const k of ENV_KEYS)
3796
+ delete process.env[k];
3797
+ });
3798
+ afterEach(() => {
3799
+ for (const k of ENV_KEYS) {
3800
+ if (saved[k] === undefined)
3801
+ delete process.env[k];
3802
+ else
3803
+ process.env[k] = saved[k];
3804
+ }
3805
+ });
3806
+ it("defaults to a 60s quiet window, a 60s small-batch window, and a 120s max-wait ceiling", () => {
3807
+ expect(DEFAULT_EVENT_DEBOUNCE_MS).toBe(60_000);
3808
+ expect(DEFAULT_EVENT_SMALL_BATCH_DEBOUNCE_MS).toBe(60_000);
3809
+ expect(DEFAULT_EVENT_MAX_WAIT_MS).toBe(120_000);
3810
+ expect(resolveEventDebounceConfig({})).toEqual({
3811
+ debounceMs: 60_000,
3812
+ maxWaitMs: 120_000,
3813
+ smallBatchDebounceMs: 60_000,
3814
+ smallBatchMaxPaths: DEFAULT_EVENT_SMALL_BATCH_MAX_PATHS,
3815
+ smallBatchMaxBytes: DEFAULT_EVENT_SMALL_BATCH_MAX_BYTES,
3816
+ });
3817
+ expect(resolveEventDebounceConfig()).toEqual({
3818
+ debounceMs: DEFAULT_EVENT_DEBOUNCE_MS,
3819
+ maxWaitMs: DEFAULT_EVENT_MAX_WAIT_MS,
3820
+ smallBatchDebounceMs: DEFAULT_EVENT_SMALL_BATCH_DEBOUNCE_MS,
3821
+ smallBatchMaxPaths: DEFAULT_EVENT_SMALL_BATCH_MAX_PATHS,
3822
+ smallBatchMaxBytes: DEFAULT_EVENT_SMALL_BATCH_MAX_BYTES,
3823
+ });
3824
+ });
3825
+ it("honors env overrides", () => {
3826
+ process.env[EVENT_DEBOUNCE_MS_ENV] = "5000";
3827
+ process.env[EVENT_MAX_WAIT_MS_ENV] = "30000";
3828
+ process.env[EVENT_SMALL_BATCH_DEBOUNCE_MS_ENV] = "2000";
3829
+ process.env[EVENT_SMALL_BATCH_MAX_PATHS_ENV] = "6";
3830
+ process.env[EVENT_SMALL_BATCH_MAX_BYTES_ENV] = "4096";
3831
+ expect(resolveEventDebounceConfig()).toEqual({
3832
+ debounceMs: 5000,
3833
+ maxWaitMs: 30_000,
3834
+ smallBatchDebounceMs: 2000,
3835
+ smallBatchMaxPaths: 6,
3836
+ smallBatchMaxBytes: 4096,
3837
+ });
3838
+ });
3839
+ it("lets HQ_SYNC_EVENT_DEBOUNCE_MS override the quiet window independently", () => {
3840
+ expect(resolveEventDebounceConfig({
3841
+ [EVENT_DEBOUNCE_MS_ENV]: "90000",
3842
+ })).toEqual({
3843
+ debounceMs: 90_000,
3844
+ maxWaitMs: 120_000,
3845
+ smallBatchDebounceMs: 60_000,
3846
+ smallBatchMaxPaths: DEFAULT_EVENT_SMALL_BATCH_MAX_PATHS,
3847
+ smallBatchMaxBytes: DEFAULT_EVENT_SMALL_BATCH_MAX_BYTES,
3848
+ });
3849
+ });
3850
+ it("lets HQ_SYNC_EVENT_SMALL_BATCH_DEBOUNCE_MS override the small-batch window independently", () => {
3851
+ expect(resolveEventDebounceConfig({
3852
+ [EVENT_SMALL_BATCH_DEBOUNCE_MS_ENV]: "10000",
3853
+ })).toEqual({
3854
+ debounceMs: 60_000,
3855
+ maxWaitMs: 120_000,
3856
+ smallBatchDebounceMs: 10_000,
3857
+ smallBatchMaxPaths: DEFAULT_EVENT_SMALL_BATCH_MAX_PATHS,
3858
+ smallBatchMaxBytes: DEFAULT_EVENT_SMALL_BATCH_MAX_BYTES,
3859
+ });
3860
+ });
3861
+ it("clamps a small-batch override above the quiet window down to the quiet window", () => {
3862
+ expect(resolveEventDebounceConfig({
3863
+ [EVENT_DEBOUNCE_MS_ENV]: "30000",
3864
+ [EVENT_SMALL_BATCH_DEBOUNCE_MS_ENV]: "50000",
3865
+ })).toEqual({
3866
+ debounceMs: 30_000,
3867
+ maxWaitMs: 120_000,
3868
+ smallBatchDebounceMs: 30_000,
3869
+ smallBatchMaxPaths: DEFAULT_EVENT_SMALL_BATCH_MAX_PATHS,
3870
+ smallBatchMaxBytes: DEFAULT_EVENT_SMALL_BATCH_MAX_BYTES,
3871
+ });
3872
+ });
3873
+ it("treats 0, negative, and non-numeric values as unset (defaults)", () => {
3874
+ for (const bad of ["0", "-5", "banana", ""]) {
3875
+ process.env[EVENT_DEBOUNCE_MS_ENV] = bad;
3876
+ process.env[EVENT_MAX_WAIT_MS_ENV] = bad;
3877
+ expect(resolveEventDebounceConfig()).toEqual({
3878
+ debounceMs: DEFAULT_EVENT_DEBOUNCE_MS,
3879
+ maxWaitMs: DEFAULT_EVENT_MAX_WAIT_MS,
3880
+ smallBatchDebounceMs: DEFAULT_EVENT_SMALL_BATCH_DEBOUNCE_MS,
3881
+ smallBatchMaxPaths: DEFAULT_EVENT_SMALL_BATCH_MAX_PATHS,
3882
+ smallBatchMaxBytes: DEFAULT_EVENT_SMALL_BATCH_MAX_BYTES,
3883
+ });
3884
+ }
3885
+ });
3886
+ it("floors the max-wait ceiling at the quiet window", () => {
3887
+ process.env[EVENT_DEBOUNCE_MS_ENV] = "60000";
3888
+ process.env[EVENT_MAX_WAIT_MS_ENV] = "10000";
3889
+ expect(resolveEventDebounceConfig()).toEqual({
3890
+ debounceMs: 60_000,
3891
+ maxWaitMs: 60_000,
3892
+ smallBatchDebounceMs: DEFAULT_EVENT_SMALL_BATCH_DEBOUNCE_MS,
3893
+ smallBatchMaxPaths: DEFAULT_EVENT_SMALL_BATCH_MAX_PATHS,
3894
+ smallBatchMaxBytes: DEFAULT_EVENT_SMALL_BATCH_MAX_BYTES,
3895
+ });
3896
+ });
3897
+ it("accepts an injected env record without touching process.env", () => {
3898
+ expect(resolveEventDebounceConfig({
3899
+ [EVENT_DEBOUNCE_MS_ENV]: "1000",
3900
+ [EVENT_MAX_WAIT_MS_ENV]: "2000",
3901
+ [EVENT_SMALL_BATCH_DEBOUNCE_MS_ENV]: "750",
3902
+ [EVENT_SMALL_BATCH_MAX_PATHS_ENV]: "4",
3903
+ [EVENT_SMALL_BATCH_MAX_BYTES_ENV]: "1024",
3904
+ })).toEqual({
3905
+ debounceMs: 1000,
3906
+ maxWaitMs: 2000,
3907
+ smallBatchDebounceMs: 750,
3908
+ smallBatchMaxPaths: 4,
3909
+ smallBatchMaxBytes: 1024,
3910
+ });
3911
+ });
3912
+ });
3913
+ describe("resolvePublishMinIntervalMs", () => {
3914
+ it("defaults to 60 seconds, accepts zero to disable coalescing, and rejects invalid values", () => {
3915
+ expect(resolvePublishMinIntervalMs({})).toBe(DEFAULT_PUBLISH_MIN_INTERVAL_MS);
3916
+ expect(resolvePublishMinIntervalMs({ [PUBLISH_MIN_INTERVAL_MS_ENV]: "0" })).toBe(0);
3917
+ expect(resolvePublishMinIntervalMs({ [PUBLISH_MIN_INTERVAL_MS_ENV]: "invalid" })).toBe(DEFAULT_PUBLISH_MIN_INTERVAL_MS);
3918
+ expect(resolvePublishMinIntervalMs({ [PUBLISH_MIN_INTERVAL_MS_ENV]: "-1" })).toBe(DEFAULT_PUBLISH_MIN_INTERVAL_MS);
3919
+ });
3920
+ it("uses the environment override in milliseconds", () => {
3921
+ expect(resolvePublishMinIntervalMs({ [PUBLISH_MIN_INTERVAL_MS_ENV]: "1234.9" })).toBe(1234);
3922
+ });
3923
+ });
3924
+ /**
3925
+ * Linux folder-only backend.
3926
+ *
3927
+ * On Linux there is no recursive `fs.watch`, and chokidar's answer was one
3928
+ * inotify watch per directory PLUS one per file. On a real HQ root that was
3929
+ * ~74k directories and ~878k files — ~950k watches, ~16 KB each — while the
3930
+ * safety cap counted only the directories and so never fired. A directory
3931
+ * watch already reports content changes to the files directly inside it, so
3932
+ * the per-file watches bought nothing. These tests pin the replacement: the
3933
+ * scoped native backend driven with `recursiveWatches: false`, taking exactly
3934
+ * one shallow watch per in-scope directory and none per file.
3935
+ */
3936
+ describe("Linux folder-only native backend (startScopedRecursiveWatch, recursiveWatches: false)", () => {
3937
+ let root;
3938
+ const isLinux = process.platform === "linux";
3939
+ beforeEach(() => {
3940
+ root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "folder-watch-")));
3941
+ });
3942
+ afterEach(() => {
3943
+ fs.rmSync(root, { recursive: true, force: true });
3944
+ });
3945
+ /** In-scope tree: root, docs, docs/deep, notes — 4 dirs, 8 files, plus an excluded node_modules. */
3946
+ function seedTree() {
3947
+ const dirs = [
3948
+ path.join(root, "docs"),
3949
+ path.join(root, "docs", "deep"),
3950
+ path.join(root, "notes"),
3951
+ ];
3952
+ for (const d of dirs)
3953
+ fs.mkdirSync(d, { recursive: true });
3954
+ const files = [];
3955
+ for (const d of [root, ...dirs]) {
3956
+ for (const n of ["one.md", "two.md"]) {
3957
+ const f = path.join(d, n);
3958
+ fs.writeFileSync(f, "x");
3959
+ files.push(f);
3960
+ }
3961
+ }
3962
+ const nm = path.join(root, "docs", "node_modules", "pkg");
3963
+ fs.mkdirSync(nm, { recursive: true });
3964
+ fs.writeFileSync(path.join(nm, "index.js"), "1");
3965
+ return { inScopeDirs: [root, ...dirs], files };
3966
+ }
3967
+ /** Count this process's live inotify watch descriptors (Linux only). */
3968
+ function inotifyWatchDescriptors() {
3969
+ let total = 0;
3970
+ for (const fd of fs.readdirSync("/proc/self/fdinfo")) {
3971
+ try {
3972
+ const info = fs.readFileSync(path.join("/proc/self/fdinfo", fd), "utf8");
3973
+ total += (info.match(/^inotify wd:/gm) ?? []).length;
3974
+ }
3975
+ catch {
3976
+ /* fd closed between readdir and read */
3977
+ }
3978
+ }
3979
+ return total;
3980
+ }
3981
+ async function waitFor(check, ms = 4000) {
3982
+ const deadline = Date.now() + ms;
3983
+ while (Date.now() < deadline) {
3984
+ if (check())
3985
+ return;
3986
+ await new Promise((r) => setTimeout(r, 25));
3987
+ }
3988
+ expect(check()).toBe(true);
3989
+ }
3990
+ function waitForReady(backend) {
3991
+ return new Promise((resolve) => {
3992
+ if (backend.onReady)
3993
+ backend.onReady(resolve);
3994
+ else
3995
+ resolve();
3996
+ });
3997
+ }
3998
+ function startFolderOnly(opts = {}) {
3999
+ const shouldEmit = opts.includeAll
4000
+ ? () => true
4001
+ : createWatchPathFilter(root, false);
4002
+ return startScopedRecursiveWatch(root, shouldEmit, opts.onEvent ?? (() => { }), opts.onError ?? ((err) => { throw err; }), undefined, {
4003
+ recursiveWatches: false,
4004
+ maxWatchedPaths: opts.maxWatchedPaths,
4005
+ onWatchBudgetExceeded: opts.onWatchBudgetExceeded,
4006
+ listChildDirs: opts.listChildDirs,
4007
+ watchDirectory: opts.watchDirectory,
4008
+ directoryIdentity: opts.directoryIdentity,
4009
+ });
4010
+ }
4011
+ it("takes exactly one watch per in-scope directory and none per file", async () => {
4012
+ const { inScopeDirs } = seedTree();
4013
+ const before = isLinux ? inotifyWatchDescriptors() : 0;
4014
+ const backend = startFolderOnly();
4015
+ try {
4016
+ await waitForReady(backend);
4017
+ expect(backend.mode).toBe("native");
4018
+ expect(backend.attachFailures).toBe(0);
4019
+ // 4 in-scope directories; 8 in-scope files and an excluded subtree add nothing.
4020
+ expect(backend.watchedPathCount()).toBe(inScopeDirs.length);
4021
+ if (isLinux) {
4022
+ // Measured immediately, before any drain window: a whole-tree
4023
+ // bootstrap watch would show up here as extra descriptors.
4024
+ expect(inotifyWatchDescriptors() - before).toBe(inScopeDirs.length);
4025
+ }
4026
+ }
4027
+ finally {
4028
+ backend.close();
4029
+ }
4030
+ if (isLinux)
4031
+ expect(inotifyWatchDescriptors()).toBe(before);
4032
+ });
4033
+ it("reports a content change to a file inside a watched folder without a file watch", async () => {
4034
+ const { files } = seedTree();
4035
+ const seen = [];
4036
+ const backend = startFolderOnly({ onEvent: (p) => seen.push(p) });
4037
+ try {
4038
+ await new Promise((r) => setTimeout(r, 150));
4039
+ const target = files.find((f) => f.includes(path.join("docs", "deep")));
4040
+ fs.appendFileSync(target, "more");
4041
+ await waitFor(() => seen.includes(target));
4042
+ }
4043
+ finally {
4044
+ backend.close();
4045
+ }
4046
+ });
4047
+ it("attaches a folder created after start, then reports files written inside it", async () => {
4048
+ seedTree();
4049
+ const seen = [];
4050
+ const backend = startFolderOnly({ onEvent: (p) => seen.push(p) });
4051
+ try {
4052
+ await new Promise((r) => setTimeout(r, 150));
4053
+ const before = backend.watchedPathCount();
4054
+ const created = path.join(root, "notes", "later");
4055
+ fs.mkdirSync(created);
4056
+ await waitFor(() => backend.watchedPathCount() === before + 1);
4057
+ const file = path.join(created, "fresh.md");
4058
+ fs.writeFileSync(file, "hello");
4059
+ await waitFor(() => seen.includes(file));
4060
+ }
4061
+ finally {
4062
+ backend.close();
4063
+ }
4064
+ });
4065
+ it("scans a folder that already holds files when it attaches, so nothing arrives silently", async () => {
4066
+ seedTree();
4067
+ const seen = [];
4068
+ const backend = startFolderOnly({ onEvent: (p) => seen.push(p) });
4069
+ try {
4070
+ await new Promise((r) => setTimeout(r, 150));
4071
+ // Build the subtree OUTSIDE the watched root, then move it in with one
4072
+ // rename: the folder watch only ever sees the directory appear, never
4073
+ // the files inside it. Chokidar walked such a directory on addDir;
4074
+ // the folder-only backend must do the same.
4075
+ const staging = fs.mkdtempSync(path.join(os.tmpdir(), "folder-watch-stage-"));
4076
+ fs.mkdirSync(path.join(staging, "inner"));
4077
+ fs.writeFileSync(path.join(staging, "a.md"), "a");
4078
+ fs.writeFileSync(path.join(staging, "inner", "b.md"), "b");
4079
+ const dest = path.join(root, "docs", "moved");
4080
+ fs.renameSync(staging, dest);
4081
+ await waitFor(() => seen.includes(path.join(dest, "a.md")) &&
4082
+ seen.includes(path.join(dest, "inner", "b.md")));
4083
+ expect(backend.watchedPathCount()).toBe(4 + 2);
4084
+ }
4085
+ finally {
4086
+ backend.close();
4087
+ }
4088
+ });
4089
+ it("re-attaches when a watched folder is swapped for a new one at the same path (Linux inode change)", async () => {
4090
+ seedTree();
4091
+ const seen = [];
4092
+ const backend = startFolderOnly({ onEvent: (p) => seen.push(p) });
4093
+ try {
4094
+ await new Promise((r) => setTimeout(r, 150));
4095
+ expect(backend.watchedPathCount()).toBe(4);
4096
+ // Atomic swap: the old `docs` moves out of the tree and a replacement
4097
+ // (built outside, so its creation is never observed) lands at the same
4098
+ // pathname — both renames complete before any watch callback runs. On
4099
+ // Linux the old handle follows the moved-away INODE, so without an
4100
+ // identity check the backend would keep it, consider `docs` covered,
4101
+ // and never hear another event from the replacement subtree.
4102
+ const staging = fs.mkdtempSync(path.join(os.tmpdir(), "folder-watch-swap-"));
4103
+ fs.mkdirSync(path.join(staging, "deep"));
4104
+ fs.writeFileSync(path.join(staging, "a.md"), "a");
4105
+ fs.writeFileSync(path.join(staging, "deep", "b.md"), "b");
4106
+ const parked = fs.mkdtempSync(path.join(os.tmpdir(), "folder-watch-parked-"));
4107
+ const docs = path.join(root, "docs");
4108
+ fs.renameSync(docs, path.join(parked, "docs"));
4109
+ fs.renameSync(staging, docs);
4110
+ // The replacement's existing files are announced, exactly like a
4111
+ // populated folder moved in from outside.
4112
+ await waitFor(() => seen.includes(path.join(docs, "a.md")) &&
4113
+ seen.includes(path.join(docs, "deep", "b.md")));
4114
+ // A later write inside the replacement is reported: the new inode is
4115
+ // watched, and the stale handles (docs + docs/deep) are gone — still
4116
+ // root, docs, docs/deep, notes.
4117
+ const after = path.join(docs, "deep", "after.md");
4118
+ fs.writeFileSync(after, "after");
4119
+ await waitFor(() => seen.includes(after));
4120
+ expect(backend.watchedPathCount()).toBe(4);
4121
+ // The moved-away tree must not keep reporting under its OLD path.
4122
+ seen.length = 0;
4123
+ fs.writeFileSync(path.join(parked, "docs", "stale.md"), "stale");
4124
+ await new Promise((r) => setTimeout(r, 300));
4125
+ expect(seen.filter((p) => p.startsWith(docs + path.sep))).toEqual([]);
4126
+ fs.rmSync(parked, { recursive: true, force: true });
4127
+ }
4128
+ finally {
4129
+ backend.close();
4130
+ }
4131
+ });
4132
+ it("probeCoverage reports root-missing when the HQ root is gone", () => {
4133
+ seedTree();
4134
+ const backend = startFolderOnly();
4135
+ try {
4136
+ expect(backend.probeCoverage()).toEqual({ ok: true });
4137
+ fs.rmSync(root, { recursive: true, force: true });
4138
+ const probe = backend.probeCoverage();
4139
+ expect(probe.ok).toBe(false);
4140
+ if (!probe.ok)
4141
+ expect(probe.reason).toBe("root-missing");
4142
+ }
4143
+ finally {
4144
+ backend.close();
4145
+ }
4146
+ });
4147
+ it("covers a folder created after its parent was listed but before the plan attached (walk/attach race)", async () => {
4148
+ seedTree();
4149
+ const seen = [];
4150
+ const late = path.join(root, "notes", "late");
4151
+ const watchEvents = new Map();
4152
+ // The plan walk lists `notes`, then — before any watch existed on the
4153
+ // old code path — `notes/late` appears. The snapshot plan never holds
4154
+ // it, and a shallow watch on `notes` attached only after the whole walk
4155
+ // would never have seen it appear. On a real HQ root the walk takes
4156
+ // seconds; agents create directories the whole time.
4157
+ const listChildDirs = (dir) => {
4158
+ const children = fs
4159
+ .readdirSync(dir, { withFileTypes: true })
4160
+ .filter((e) => e.isDirectory())
4161
+ .map((e) => path.join(dir, e.name));
4162
+ if (dir === path.join(root, "notes"))
4163
+ fs.mkdirSync(late);
4164
+ return children;
4165
+ };
4166
+ const backend = startFolderOnly({
4167
+ onEvent: (p) => seen.push(p),
4168
+ listChildDirs,
4169
+ watchDirectory: ((dir, _options, listener) => {
4170
+ watchEvents.set(path.resolve(String(dir)), listener);
4171
+ const handle = new EventEmitter();
4172
+ handle.close = () => { };
4173
+ return handle;
4174
+ }),
4175
+ });
4176
+ try {
4177
+ await waitForReady(backend);
4178
+ watchEvents.get(path.join(root, "notes"))?.("rename", "late");
4179
+ // root, docs, docs/deep, notes — plus `late`, picked up by the live
4180
+ // watch on `notes` rather than by the plan.
4181
+ await waitFor(() => backend.watchedPathCount() === 5);
4182
+ const file = path.join(late, "inside.md");
4183
+ fs.writeFileSync(file, "x");
4184
+ watchEvents.get(late)?.("rename", "inside.md");
4185
+ await waitFor(() => seen.includes(file));
4186
+ }
4187
+ finally {
4188
+ backend.close();
4189
+ }
4190
+ });
4191
+ it("releases every watch beneath a deleted folder", async () => {
4192
+ seedTree();
4193
+ const backend = startFolderOnly();
4194
+ try {
4195
+ await new Promise((r) => setTimeout(r, 150));
4196
+ expect(backend.watchedPathCount()).toBe(4);
4197
+ fs.rmSync(path.join(root, "docs"), { recursive: true, force: true });
4198
+ // docs and docs/deep both go; root and notes remain.
4199
+ await waitFor(() => backend.watchedPathCount() === 2);
4200
+ if (isLinux) {
4201
+ await waitFor(() => inotifyWatchDescriptors() <= 2);
4202
+ }
4203
+ }
4204
+ finally {
4205
+ backend.close();
4206
+ }
4207
+ });
4208
+ it("stops attaching at the budget and reports the exhaustion exactly once, counting real watches", async () => {
4209
+ seedTree();
4210
+ const exceeded = vi.fn();
4211
+ const backend = startFolderOnly({
4212
+ maxWatchedPaths: 2,
4213
+ onWatchBudgetExceeded: exceeded,
4214
+ });
4215
+ try {
4216
+ await waitForReady(backend);
4217
+ expect(backend.watchedPathCount()).toBe(2);
4218
+ expect(exceeded).toHaveBeenCalledTimes(1);
4219
+ expect(exceeded.mock.calls[0][0]).toMatchObject({
4220
+ watchedPaths: 2,
4221
+ maxWatchedPaths: 2,
4222
+ });
4223
+ expect(typeof exceeded.mock.calls[0][0].offendingPath).toBe("string");
4224
+ }
4225
+ finally {
4226
+ backend.close();
4227
+ }
4228
+ });
4229
+ it("selects the single-root backend on darwin and leaves linux and windows unchanged", () => {
4230
+ expect(selectTreeWatchBackend("linux", false)).toBe("native-shallow");
4231
+ expect(selectTreeWatchBackend("darwin", false)).toBe("native-root");
4232
+ expect(selectTreeWatchBackend("win32", false)).toBe("native-recursive");
4233
+ expect(selectTreeWatchBackend("freebsd", false)).toBe("chokidar");
4234
+ expect(selectTreeWatchBackend("linux", true)).toBe("polling");
4235
+ expect(selectTreeWatchBackend("darwin", true)).toBe("polling");
4236
+ });
4237
+ it("filters native-root callbacks before forwarding them to onEvent", () => {
4238
+ const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "native-root-filter-")));
4239
+ const excludedDir = path.join(dir, "node_modules");
4240
+ fs.mkdirSync(path.join(excludedDir, "pkg"), { recursive: true });
4241
+ fs.writeFileSync(path.join(excludedDir, "pkg", "index.js"), "x");
4242
+ const callback = vi.fn();
4243
+ const handle = new EventEmitter();
4244
+ handle.close = vi.fn();
4245
+ let listener;
4246
+ const backend = startNativeRootWatch(dir, createWatchPathFilter(dir, false), callback, vi.fn(), {
4247
+ watchDirectory: ((root, options, onChange) => {
4248
+ expect(root).toBe(dir);
4249
+ expect(options).toEqual({ recursive: true, persistent: true });
4250
+ listener = onChange;
4251
+ return handle;
4252
+ }),
4253
+ });
4254
+ try {
4255
+ expect(backend.mode).toBe("native-root");
4256
+ expect(backend.watchedPathCount()).toBe(1);
4257
+ listener?.("rename", "companies/indigo/knowledge/note.md");
4258
+ listener?.("rename", "node_modules");
4259
+ listener?.("change", "workspace/node_modules/pkg/index.js");
4260
+ expect(callback).toHaveBeenCalledTimes(1);
4261
+ expect(callback).toHaveBeenCalledWith(path.join(dir, "companies/indigo/knowledge/note.md"), "rename");
4262
+ }
4263
+ finally {
4264
+ backend.close();
4265
+ fs.rmSync(dir, { recursive: true, force: true });
4266
+ }
4267
+ });
4268
+ it("switches a native-root watcher to polling after a systemic watch error", async () => {
4269
+ const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "native-root-fallback-")));
4270
+ const closed = [];
4271
+ const backend = new TreeWatcher({
4272
+ hqRoot: dir,
4273
+ debounceMs: 50,
4274
+ backendFactory: ({ forcePolling, onError }) => {
4275
+ if (forcePolling) {
4276
+ return {
4277
+ close: () => closed.push("polling"),
4278
+ mode: "polling",
4279
+ needsKnownKinds: false,
4280
+ watchedPathCount: () => 1,
4281
+ };
4282
+ }
4283
+ const handle = new EventEmitter();
4284
+ handle.close = vi.fn(() => closed.push("native-root"));
4285
+ const native = startNativeRootWatch(dir, () => true, vi.fn(), onError, {
4286
+ watchDirectory: (() => {
4287
+ queueMicrotask(() => handle.emit("error", Object.assign(new Error("too many open files"), { code: "EMFILE" })));
4288
+ return handle;
4289
+ }),
4290
+ });
4291
+ return native;
4292
+ },
4293
+ });
4294
+ const log = vi.spyOn(console, "error").mockImplementation(() => { });
4295
+ backend.start();
4296
+ try {
4297
+ await new Promise((resolve) => setTimeout(resolve, 0));
4298
+ expect(backend.watchMode()).toBe("polling");
4299
+ expect(backend.watchedPathCount()).toBe(1);
4300
+ expect(closed).toContain("native-root");
4301
+ }
4302
+ finally {
4303
+ backend.dispose();
4304
+ log.mockRestore();
4305
+ fs.rmSync(dir, { recursive: true, force: true });
4306
+ }
4307
+ });
4308
+ it("TreeWatcher on linux starts natively with one watch per directory (no chokidar, no file watches)", async () => {
4309
+ if (!isLinux)
4310
+ return;
4311
+ const { inScopeDirs } = seedTree();
4312
+ const before = inotifyWatchDescriptors();
4313
+ const w = new TreeWatcher({ hqRoot: root, debounceMs: 50 });
4314
+ const changed = vi.fn();
4315
+ w.onChange(changed);
4316
+ w.start();
4317
+ try {
4318
+ await new Promise((resolve) => w.onReady(resolve));
4319
+ expect(w.watchMode()).toBe("native");
4320
+ expect(inotifyWatchDescriptors() - before).toBe(inScopeDirs.length);
4321
+ fs.writeFileSync(path.join(root, "notes", "new.md"), "hi");
4322
+ await waitFor(() => changed.mock.calls.length > 0);
4323
+ }
4324
+ finally {
4325
+ w.dispose();
4326
+ }
4327
+ });
4328
+ });
4329
+ //# sourceMappingURL=watcher.test.js.map