@indigoai-us/hq-cloud 6.14.44 → 6.14.45

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.
@@ -0,0 +1,381 @@
1
+ /**
2
+ * REAL-fs regressions for the scoped watch-root backend.
3
+ *
4
+ * These assert on what the OS DELIVERS, not on what TreeWatcher emits. That
5
+ * distinction is the whole point of this backend: the emit filter has always
6
+ * dropped excluded paths correctly, so emissions look identical whether or not
7
+ * the watch set is scoped. What changes is whether the event reaches the
8
+ * process at all — which is the CPU cost this backend exists to remove, and
9
+ * the only way these regressions are observable.
10
+ *
11
+ * So each test drives `startScopedRecursiveWatch` directly and counts raw
12
+ * `onEvent` calls.
13
+ *
14
+ * Checked against the pre-fix backend, three of these fail without their fix —
15
+ * the new-exclusion firehose, the attach-failure report, and the mid-plan
16
+ * window. The mid-plan case only became meaningful once the walk was made
17
+ * deliberately slow: with a microsecond-wide window it was racing FSEvents
18
+ * stream warm-up and flapped between runs, which is a flaky test rather than
19
+ * a regression test.
20
+ *
21
+ * The delete/recreate case passes either way on macOS, because FSEvents
22
+ * watches by PATH — a recreated directory keeps reporting through the stale
23
+ * handle. That does not hold on Windows (`ReadDirectoryChangesW` is
24
+ * handle-based) and is not guaranteed by any API contract, so dropping stale
25
+ * handles is deliberate belt-and-braces and this test is kept as a guard: it
26
+ * pins that the re-plan did not BREAK behavior that already worked.
27
+ */
28
+
29
+ import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
30
+ import { tmpdir } from "node:os";
31
+ import path from "node:path";
32
+
33
+ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
34
+
35
+ import {
36
+ startScopedRecursiveWatch,
37
+ type ScopedWatchBackend,
38
+ } from "../../src/watcher.js";
39
+
40
+ let hqRoot: string;
41
+ let backend: ScopedWatchBackend | null = null;
42
+
43
+ /** `excluded/` anywhere in the tree is out of scope, like `node_modules/`. */
44
+ const makeFilter = (root: string) => (abs: string): boolean => {
45
+ const rel = path.relative(root, abs);
46
+ if (rel === "" || rel.startsWith("..")) return false;
47
+ return !rel.split(path.sep).includes("excluded");
48
+ };
49
+
50
+ beforeEach(async () => {
51
+ hqRoot = await mkdtemp(path.join(tmpdir(), "hqcloud-scoped-cov-"));
52
+ });
53
+
54
+ afterEach(async () => {
55
+ backend?.close();
56
+ backend = null;
57
+ await rm(hqRoot, { recursive: true, force: true });
58
+ });
59
+
60
+ const settle = (ms = 800) => new Promise((r) => setTimeout(r, ms));
61
+
62
+ /** Raw events the OS delivered for paths under `prefix`. */
63
+ function eventsUnder(onEvent: ReturnType<typeof vi.fn>, prefix: string): number {
64
+ return onEvent.mock.calls.filter(
65
+ ([p]) => typeof p === "string" && p.startsWith(prefix),
66
+ ).length;
67
+ }
68
+
69
+ /**
70
+ * Guard against a vacuous pass. Half of these tests assert that ZERO events
71
+ * arrive, which is trivially true if the backend attached no watches at all —
72
+ * so every test first proves the backend is actually live.
73
+ */
74
+ function expectLiveBackend(b: ScopedWatchBackend): void {
75
+ expect(b.attachFailures).toBe(0);
76
+ expect(b.watchedPathCount()).toBeGreaterThan(0);
77
+ }
78
+
79
+ /**
80
+ * This backend is the macOS/Windows one: it is built entirely on recursive
81
+ * `fs.watch`, which Linux does not implement (`startTreeWatch` routes Linux to
82
+ * chokidar instead). Running these there watches nothing, which would let the
83
+ * "expect zero events" cases pass for the wrong reason.
84
+ */
85
+ const SUPPORTS_RECURSIVE_WATCH =
86
+ process.platform === "darwin" || process.platform === "win32";
87
+
88
+ describe.skipIf(!SUPPORTS_RECURSIVE_WATCH)("scoped watch roots — the OS stops reporting excluded trees", () => {
89
+ it(
90
+ "stops delivering events from an excluded directory created AFTER planning",
91
+ async () => {
92
+ // The regression that would defeat the whole change: at plan time the
93
+ // tree is clean, so it collapses to ONE recursive root at hqRoot.
94
+ // Creating `work/excluded/` afterwards puts a high-churn bucket back
95
+ // inside that root. Without re-planning, the creation event looks
96
+ // "already covered" and every write beneath it is delivered again —
97
+ // exactly the firehose this backend removes.
98
+ await mkdir(path.join(hqRoot, "work", "keep"), { recursive: true });
99
+ const onEvent = vi.fn();
100
+ backend = startScopedRecursiveWatch(
101
+ hqRoot,
102
+ makeFilter(hqRoot),
103
+ onEvent,
104
+ () => {},
105
+ );
106
+ expectLiveBackend(backend);
107
+ // Wait out the bootstrap drain window: the temporary whole-tree watch is
108
+ // deliberately held open briefly after planning so in-flight events are
109
+ // not dropped with the handle. This test measures the steady state.
110
+ await settle(2600);
111
+
112
+ const excluded = path.join(hqRoot, "work", "excluded");
113
+ await mkdir(path.join(excluded, "deep"), { recursive: true });
114
+ await settle();
115
+
116
+ onEvent.mockClear();
117
+ for (let i = 0; i < 5; i++) {
118
+ await writeFile(path.join(excluded, "deep", `build-${i}.log`), "noise\n");
119
+ }
120
+ await settle();
121
+
122
+ expect(eventsUnder(onEvent, excluded)).toBe(0);
123
+ },
124
+ 20000,
125
+ );
126
+
127
+ it(
128
+ "still delivers in-scope siblings after re-planning around a new exclusion",
129
+ async () => {
130
+ // Re-planning must SPLIT the root, not tear coverage off the good part.
131
+ const keep = path.join(hqRoot, "work", "keep");
132
+ await mkdir(keep, { recursive: true });
133
+ const onEvent = vi.fn();
134
+ backend = startScopedRecursiveWatch(
135
+ hqRoot,
136
+ makeFilter(hqRoot),
137
+ onEvent,
138
+ () => {},
139
+ );
140
+ expectLiveBackend(backend);
141
+ await settle();
142
+
143
+ await mkdir(path.join(hqRoot, "work", "excluded"), { recursive: true });
144
+ await settle();
145
+
146
+ onEvent.mockClear();
147
+ await writeFile(path.join(keep, "note.md"), "# hi\n");
148
+ await settle();
149
+
150
+ expect(eventsUnder(onEvent, keep)).toBeGreaterThan(0);
151
+ },
152
+ 20000,
153
+ );
154
+
155
+ it(
156
+ "re-attaches after a watched directory is deleted and recreated",
157
+ async () => {
158
+ // A recreated directory has a NEW inode. A stale handle left in the watch
159
+ // set makes the path look covered forever, so nothing under the
160
+ // replacement is ever delivered again.
161
+ const work = path.join(hqRoot, "work");
162
+ const keep = path.join(work, "keep");
163
+ await mkdir(keep, { recursive: true });
164
+ // An exclusion at the root forces `hqRoot` to be SHALLOW, so `work/` is
165
+ // its own recursive root — the handle that goes stale on delete.
166
+ await mkdir(path.join(hqRoot, "excluded"), { recursive: true });
167
+ const onEvent = vi.fn();
168
+ backend = startScopedRecursiveWatch(
169
+ hqRoot,
170
+ makeFilter(hqRoot),
171
+ onEvent,
172
+ () => {},
173
+ );
174
+ expectLiveBackend(backend);
175
+ await settle();
176
+
177
+ await rm(work, { recursive: true, force: true });
178
+ await settle();
179
+ await mkdir(keep, { recursive: true });
180
+ await settle();
181
+
182
+ onEvent.mockClear();
183
+ await writeFile(path.join(keep, "reborn.md"), "# back\n");
184
+ await settle();
185
+
186
+ expect(eventsUnder(onEvent, keep)).toBeGreaterThan(0);
187
+ },
188
+ 25000,
189
+ );
190
+
191
+ it(
192
+ "delivers a change made while the planning walk is still running",
193
+ async () => {
194
+ // Planning is synchronous and takes seconds on a real tree. Without a
195
+ // bootstrap watch over the root first, anything written during that
196
+ // window is invisible to event-driven push until the next cadence poll.
197
+ await mkdir(path.join(hqRoot, "work"), { recursive: true });
198
+ await mkdir(path.join(hqRoot, "excluded"), { recursive: true });
199
+ const target = path.join(hqRoot, "work", "during-plan.md");
200
+
201
+ const onEvent = vi.fn();
202
+ let fired = false;
203
+ const filter = makeFilter(hqRoot);
204
+ /** Block the walk so the planning window is wide and unambiguous. */
205
+ const spin = (ms: number) => {
206
+ const until = Date.now() + ms;
207
+ while (Date.now() < until) {
208
+ /* deliberately synchronous — this IS the planning walk */
209
+ }
210
+ };
211
+ const slowFilter = (abs: string, isDir?: boolean): boolean => {
212
+ // Mutate from inside the planning walk itself — the one moment the
213
+ // tree is being traversed and no scoped watch exists yet.
214
+ if (!fired) {
215
+ fired = true;
216
+ // Let the OS watch stream warm up first — a write in the same
217
+ // microsecond as stream creation is genuinely racy on macOS and
218
+ // would make this test flaky rather than meaningful. Then write, and
219
+ // keep blocking so the write is unambiguously INSIDE the walk.
220
+ spin(600);
221
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
222
+ require("node:fs").writeFileSync(target, "# mid-plan\n");
223
+ spin(400);
224
+ }
225
+ return filter(abs, isDir);
226
+ };
227
+
228
+ backend = startScopedRecursiveWatch(hqRoot, slowFilter, onEvent, () => {});
229
+ expectLiveBackend(backend);
230
+ await settle(1500);
231
+
232
+ expect(fired).toBe(true);
233
+ expect(eventsUnder(onEvent, target)).toBeGreaterThan(0);
234
+ },
235
+ 20000,
236
+ );
237
+
238
+ it(
239
+ "drops watches BELOW a deleted directory, not just the directory itself",
240
+ async () => {
241
+ // The OS reports the removed directory, not each of its descendants, so
242
+ // a drop that only removes the exact path leaks every watch underneath
243
+ // it — open handles that never close, plus a stale recursive root that
244
+ // will mark a later recreation as already-covered. These runners live
245
+ // for many hours, so the leak accumulates.
246
+ const outer = path.join(hqRoot, "outer");
247
+ // `excluded` children make outer and outer/inner SHALLOW, so both they
248
+ // and their in-scope children each hold their own watch.
249
+ await mkdir(path.join(outer, "excluded"), { recursive: true });
250
+ await mkdir(path.join(outer, "inner", "excluded"), { recursive: true });
251
+ await mkdir(path.join(outer, "inner", "keep"), { recursive: true });
252
+ await mkdir(path.join(hqRoot, "excluded"), { recursive: true });
253
+
254
+ const onEvent = vi.fn();
255
+ backend = startScopedRecursiveWatch(
256
+ hqRoot,
257
+ makeFilter(hqRoot),
258
+ onEvent,
259
+ () => {},
260
+ );
261
+ expectLiveBackend(backend);
262
+ const before = backend.watchedPathCount();
263
+ // hqRoot + outer + outer/inner + outer/inner/keep
264
+ expect(before).toBeGreaterThanOrEqual(4);
265
+ await settle(2600);
266
+
267
+ await rm(outer, { recursive: true, force: true });
268
+ await settle();
269
+
270
+ // Every watch at or below `outer` must be gone — only hqRoot remains.
271
+ expect(backend.watchedPathCount()).toBe(1);
272
+ },
273
+ 25000,
274
+ );
275
+
276
+ it(
277
+ "keeps re-planning bounded when several exclusions appear at once",
278
+ async () => {
279
+ // Each newly-created excluded directory under a recursive root forces a
280
+ // re-plan, and a re-plan walks that root's subtree synchronously — so an
281
+ // install creating many excluded directories at once looks like it should
282
+ // cost that walk once per directory, on the event loop.
283
+ //
284
+ // It does not, and this test pins WHY: the first re-plan SPLITS the
285
+ // covering root, so each subsequent exclusion is re-planned against a
286
+ // much smaller root. The work is self-limiting. This is a guard, not a
287
+ // regression test — it passes without any coalescing precisely because
288
+ // the splitting already bounds the cost, and it would start failing if a
289
+ // future change made re-plans walk from the top each time.
290
+ const work = path.join(hqRoot, "work");
291
+ for (const n of ["p1", "p2", "p3", "p4"]) {
292
+ await mkdir(path.join(work, n, "src"), { recursive: true });
293
+ }
294
+ const seen = vi.fn();
295
+ backend = startScopedRecursiveWatch(
296
+ hqRoot,
297
+ makeFilter(hqRoot),
298
+ () => {},
299
+ () => {},
300
+ seen,
301
+ );
302
+ expectLiveBackend(backend);
303
+ await settle(2600);
304
+
305
+ // One directory visit per in-scope dir per walk. Four exclusions
306
+ // appearing together must cost ONE walk, not four.
307
+ const perWalk = seen.mock.calls.length;
308
+ expect(perWalk).toBeGreaterThan(0);
309
+ seen.mockClear();
310
+
311
+ await Promise.all(
312
+ ["p1", "p2", "p3", "p4"].map((n) =>
313
+ mkdir(path.join(work, n, "excluded"), { recursive: true }),
314
+ ),
315
+ );
316
+ await settle(2000);
317
+
318
+ // Allow one full walk plus slack; four independent walks would be ~4x.
319
+ expect(seen.mock.calls.length).toBeLessThan(perWalk * 2);
320
+ },
321
+ 30000,
322
+ );
323
+
324
+ it(
325
+ "does not report an error when a watched directory is simply deleted",
326
+ async () => {
327
+ // A deleted watched root could plausibly be re-added by a re-plan, with
328
+ // fs.watch then throwing ENOENT and surfacing a watcher error plus a full
329
+ // resync for an ordinary delete. It is not, because the stale-handle drop
330
+ // returns before any re-plan is considered. A guard on that ordering:
331
+ // deleting a directory must stay silent.
332
+ const work = path.join(hqRoot, "work");
333
+ await mkdir(path.join(work, "keep"), { recursive: true });
334
+ await mkdir(path.join(hqRoot, "excluded"), { recursive: true });
335
+
336
+ const errors: unknown[] = [];
337
+ backend = startScopedRecursiveWatch(
338
+ hqRoot,
339
+ makeFilter(hqRoot),
340
+ () => {},
341
+ (e) => errors.push(e),
342
+ );
343
+ expectLiveBackend(backend);
344
+ await settle(2600);
345
+
346
+ await rm(work, { recursive: true, force: true });
347
+ await settle(1500);
348
+
349
+ expect(errors).toEqual([]);
350
+ },
351
+ 25000,
352
+ );
353
+
354
+ it("reports attach failures so the caller can reject a partial plan", async () => {
355
+ // Real attach failure, no mocking: `b/` is planned during the walk, then
356
+ // deleted before applyPlan reaches it, so its fs.watch throws ENOENT.
357
+ // A planned root we could not attach is a permanent hole in coverage —
358
+ // the caller must see it and fall back rather than run half-blind.
359
+ const doomed = path.join(hqRoot, "b");
360
+ await mkdir(path.join(hqRoot, "a"), { recursive: true });
361
+ await mkdir(doomed, { recursive: true });
362
+ // An exclusion at the root keeps hqRoot shallow, so `a/` and `b/` are
363
+ // planned as their own recursive roots instead of collapsing into one.
364
+ await mkdir(path.join(hqRoot, "excluded"), { recursive: true });
365
+
366
+ const errors: unknown[] = [];
367
+ const { rmSync } = await import("node:fs");
368
+ backend = startScopedRecursiveWatch(
369
+ hqRoot,
370
+ makeFilter(hqRoot),
371
+ () => {},
372
+ (e) => errors.push(e),
373
+ (dir) => {
374
+ if (dir === doomed) rmSync(doomed, { recursive: true, force: true });
375
+ },
376
+ );
377
+
378
+ expect(backend.attachFailures).toBeGreaterThan(0);
379
+ expect(errors.length).toBeGreaterThan(0);
380
+ }, 20000);
381
+ });