watcher.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. /**
  2. * FileWatcher Tests
  3. *
  4. * Tests for the file watcher that auto-syncs on changes.
  5. *
  6. * **Why inert mode + a synthetic event seam**: the watcher now uses Node's
  7. * native `fs.watch` (recursive on macOS/Windows, per-directory on Linux).
  8. * Under parallel vitest the OS watch subsystems (FSEvents / inotify) serve
  9. * many test files at once and event-delivery latency becomes non-deterministic
  10. * — a real fs change made in `beforeEach` can even leak into a later "should
  11. * NOT sync" assertion. So the unit tests construct the watcher with
  12. * `inertForTests: true` (no OS watcher installed) and drive its filter →
  13. * pendingFiles → debounce pipeline directly via
  14. * `__emitWatchEventForTests(root, relPath)` — deterministic, the same
  15. * convergence point a real event reaches. The debounce timer itself is the
  16. * real `setTimeout` (the unit under test). One end-to-end test ("auto-sync …
  17. * real fs.watch") runs the genuine native watcher against a real file write.
  18. */
  19. import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
  20. import { EventEmitter } from 'events';
  21. import * as fs from 'fs';
  22. import * as path from 'path';
  23. import * as os from 'os';
  24. import {
  25. FileWatcher,
  26. LockUnavailableError,
  27. __emitWatchEventForTests,
  28. __setFsWatchForTests,
  29. type WatchOptions,
  30. } from '../src/sync/watcher';
  31. import CodeGraph from '../src/index';
  32. type SyncFn = () => Promise<{ filesChanged: number; durationMs: number }>;
  33. /**
  34. * Helper to wait for a condition with timeout. Used for assertions that depend
  35. * on the debounce timer (real setTimeout) firing, or on the real watcher's
  36. * event delivery in the end-to-end test.
  37. */
  38. function waitFor(
  39. condition: () => boolean,
  40. timeoutMs = 2000,
  41. intervalMs = 25
  42. ): Promise<void> {
  43. return new Promise((resolve, reject) => {
  44. const start = Date.now();
  45. const check = () => {
  46. if (condition()) return resolve();
  47. if (Date.now() - start > timeoutMs) return reject(new Error('waitFor timed out'));
  48. setTimeout(check, intervalMs);
  49. };
  50. check();
  51. });
  52. }
  53. describe('FileWatcher', () => {
  54. let testDir: string;
  55. // Inert by default — unit tests drive events via __emitWatchEventForTests
  56. // and never depend on real OS watch delivery.
  57. const newWatcher = (syncFn: SyncFn, opts: WatchOptions = {}) =>
  58. new FileWatcher(testDir, syncFn, { inertForTests: true, ...opts });
  59. beforeEach(() => {
  60. testDir = fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-watcher-'));
  61. // Create a source file so the directory isn't empty
  62. const srcDir = path.join(testDir, 'src');
  63. fs.mkdirSync(srcDir);
  64. fs.writeFileSync(path.join(srcDir, 'index.ts'), 'export const x = 1;');
  65. });
  66. afterEach(() => {
  67. __setFsWatchForTests(null); // reset the injected fs.watch seam
  68. vi.restoreAllMocks();
  69. if (fs.existsSync(testDir)) {
  70. fs.rmSync(testDir, { recursive: true, force: true });
  71. }
  72. });
  73. describe('start/stop lifecycle', () => {
  74. it('should start and stop without errors', () => {
  75. const syncFn = vi.fn().mockResolvedValue({ filesChanged: 0, durationMs: 0 });
  76. const watcher = newWatcher(syncFn);
  77. const started = watcher.start();
  78. expect(started).toBe(true);
  79. expect(watcher.isActive()).toBe(true);
  80. watcher.stop();
  81. expect(watcher.isActive()).toBe(false);
  82. });
  83. it('should be idempotent on double start', () => {
  84. const syncFn = vi.fn().mockResolvedValue({ filesChanged: 0, durationMs: 0 });
  85. const watcher = newWatcher(syncFn);
  86. expect(watcher.start()).toBe(true);
  87. expect(watcher.start()).toBe(true); // Should not throw
  88. expect(watcher.isActive()).toBe(true);
  89. watcher.stop();
  90. });
  91. it('should be idempotent on double stop', () => {
  92. const syncFn = vi.fn().mockResolvedValue({ filesChanged: 0, durationMs: 0 });
  93. const watcher = newWatcher(syncFn);
  94. watcher.start();
  95. watcher.stop();
  96. watcher.stop(); // Should not throw
  97. expect(watcher.isActive()).toBe(false);
  98. });
  99. });
  100. describe('watch-resource exhaustion (#876)', () => {
  101. // These exercise the REAL fs.watch path (not inert) with an injected watch
  102. // that throws / emits EMFILE, covering whichever strategy the host platform
  103. // uses — recursive on macOS/Windows, per-directory on Linux. Each uses its
  104. // OWN EMPTY temp dir so exactly one watch is installed and the close-count
  105. // is deterministic across platforms.
  106. const mkEmptyDir = () => fs.mkdtempSync(path.join(os.tmpdir(), 'codegraph-exhaust-'));
  107. it('fails to start and degrades when fs.watch setup exhausts watch resources', () => {
  108. const dir = mkEmptyDir();
  109. const onDegraded = vi.fn();
  110. const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
  111. __setFsWatchForTests(() => {
  112. const err = new Error('too many open files') as NodeJS.ErrnoException;
  113. err.code = 'EMFILE';
  114. throw err;
  115. });
  116. const watcher = new FileWatcher(
  117. dir,
  118. vi.fn().mockResolvedValue({ filesChanged: 0, durationMs: 0 }),
  119. { debounceMs: 100, onDegraded }
  120. );
  121. try {
  122. // Both watch strategies must report startup exhaustion identically.
  123. expect(watcher.start()).toBe(false);
  124. expect(watcher.isActive()).toBe(false);
  125. expect(watcher.isDegraded()).toBe(true);
  126. expect(watcher.getDegradedReason()).toContain('auto-sync disabled');
  127. expect(onDegraded).toHaveBeenCalledTimes(1);
  128. expect(onDegraded).toHaveBeenCalledWith(expect.stringContaining('auto-sync disabled'));
  129. const disableWarnings = warnSpy.mock.calls.filter(
  130. (c) => typeof c[0] === 'string' && c[0].includes('File watcher disabled')
  131. );
  132. expect(disableWarnings).toHaveLength(1);
  133. } finally {
  134. fs.rmSync(dir, { recursive: true, force: true });
  135. }
  136. });
  137. it('degrades exactly once when the live watcher emits EMFILE at runtime', () => {
  138. const dir = mkEmptyDir();
  139. const onDegraded = vi.fn();
  140. const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
  141. const emitter = new EventEmitter();
  142. let closed = 0;
  143. const fakeWatcher = {
  144. on: (event: string, handler: (...a: unknown[]) => void) => {
  145. emitter.on(event, handler);
  146. return fakeWatcher;
  147. },
  148. close: () => {
  149. closed += 1;
  150. },
  151. } as unknown as fs.FSWatcher;
  152. __setFsWatchForTests(() => fakeWatcher);
  153. const watcher = new FileWatcher(
  154. dir,
  155. vi.fn().mockResolvedValue({ filesChanged: 0, durationMs: 0 }),
  156. { debounceMs: 100, onDegraded }
  157. );
  158. try {
  159. expect(watcher.start()).toBe(true);
  160. expect(watcher.isActive()).toBe(true);
  161. const err = new Error('too many open files') as NodeJS.ErrnoException;
  162. err.code = 'EMFILE';
  163. emitter.emit('error', err);
  164. emitter.emit('error', err); // a second burst must NOT degrade / close again
  165. expect(watcher.isActive()).toBe(false);
  166. expect(watcher.isDegraded()).toBe(true);
  167. expect(onDegraded).toHaveBeenCalledTimes(1);
  168. expect(closed).toBe(1);
  169. const disableWarnings = warnSpy.mock.calls.filter(
  170. (c) => typeof c[0] === 'string' && c[0].includes('File watcher disabled')
  171. );
  172. expect(disableWarnings).toHaveLength(1);
  173. } finally {
  174. fs.rmSync(dir, { recursive: true, force: true });
  175. }
  176. });
  177. it('reports isDegraded false / null reason while healthy', () => {
  178. const watcher = newWatcher(vi.fn().mockResolvedValue({ filesChanged: 0, durationMs: 0 }));
  179. watcher.start();
  180. expect(watcher.isDegraded()).toBe(false);
  181. expect(watcher.getDegradedReason()).toBeNull();
  182. watcher.stop();
  183. });
  184. });
  185. describe('lock contention degradation (#876)', () => {
  186. it('disables auto-sync after prolonged lock contention, with bounded retries', async () => {
  187. const syncFn = vi.fn().mockRejectedValue(new LockUnavailableError());
  188. const onSyncComplete = vi.fn();
  189. const onSyncError = vi.fn();
  190. const onDegraded = vi.fn();
  191. const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
  192. const watcher = newWatcher(syncFn, {
  193. debounceMs: 25,
  194. onSyncComplete,
  195. onSyncError,
  196. onDegraded,
  197. });
  198. watcher.start();
  199. await watcher.waitUntilReady();
  200. __emitWatchEventForTests(testDir, 'src/long-lock.ts');
  201. // 5 backoff retries (25·1,2,4,8,16 ms), then degrade on the 6th attempt.
  202. await waitFor(() => !watcher.isActive(), 8000, 20);
  203. expect(syncFn.mock.calls.length).toBeGreaterThanOrEqual(6); // MAX_LOCK_RETRIES + 1
  204. expect(watcher.isDegraded()).toBe(true);
  205. expect(onDegraded).toHaveBeenCalledTimes(1);
  206. expect(onDegraded).toHaveBeenCalledWith(expect.stringContaining('auto-sync disabled'));
  207. // A held lock is neither a sync error nor a completion.
  208. expect(onSyncError).not.toHaveBeenCalled();
  209. expect(onSyncComplete).not.toHaveBeenCalled();
  210. // Degrade stops the watcher, which clears pending state.
  211. expect(watcher.getPendingFiles()).toEqual([]);
  212. const disableWarnings = warnSpy.mock.calls.filter(
  213. (c) => typeof c[0] === 'string' && c[0].includes('File watcher disabled')
  214. );
  215. expect(disableWarnings).toHaveLength(1);
  216. });
  217. it('does NOT degrade on brief contention — backoff resets after a clean sync', async () => {
  218. const syncFn = vi
  219. .fn()
  220. .mockRejectedValueOnce(new LockUnavailableError())
  221. .mockRejectedValueOnce(new LockUnavailableError())
  222. .mockRejectedValueOnce(new LockUnavailableError())
  223. .mockResolvedValue({ filesChanged: 1, durationMs: 5 });
  224. const onDegraded = vi.fn();
  225. const onSyncComplete = vi.fn();
  226. const watcher = newWatcher(syncFn, { debounceMs: 25, onDegraded, onSyncComplete });
  227. watcher.start();
  228. await watcher.waitUntilReady();
  229. __emitWatchEventForTests(testDir, 'src/brief-lock.ts');
  230. await waitFor(() => onSyncComplete.mock.calls.length > 0, 4000, 20);
  231. expect(onDegraded).not.toHaveBeenCalled();
  232. expect(watcher.isDegraded()).toBe(false);
  233. expect(watcher.isActive()).toBe(true);
  234. expect(watcher.getPendingFiles().some((p) => p.path === 'src/brief-lock.ts')).toBe(false);
  235. watcher.stop();
  236. });
  237. });
  238. describe('debounced sync', () => {
  239. it('should trigger sync after file change', async () => {
  240. const syncFn = vi.fn().mockResolvedValue({ filesChanged: 1, durationMs: 10 });
  241. const watcher = newWatcher(syncFn, { debounceMs: 200 });
  242. watcher.start();
  243. await watcher.waitUntilReady();
  244. __emitWatchEventForTests(testDir, 'src/new.ts');
  245. // Wait for debounced sync to fire (real timer; 200ms + epsilon).
  246. await waitFor(() => syncFn.mock.calls.length > 0);
  247. expect(syncFn).toHaveBeenCalled();
  248. watcher.stop();
  249. });
  250. it('should debounce rapid changes into a single sync', async () => {
  251. const syncFn = vi.fn().mockResolvedValue({ filesChanged: 1, durationMs: 10 });
  252. const watcher = newWatcher(syncFn, { debounceMs: 400 });
  253. watcher.start();
  254. await watcher.waitUntilReady();
  255. // Rapid-fire synthesized changes — each call resets the debounce timer.
  256. // Spacing them tighter than the debounce window proves the debounce
  257. // collapses them into one syncFn call.
  258. for (let i = 0; i < 5; i++) {
  259. __emitWatchEventForTests(testDir, `src/file${i}.ts`);
  260. await new Promise((r) => setTimeout(r, 50));
  261. }
  262. // Wait for the single debounced sync.
  263. await waitFor(() => syncFn.mock.calls.length > 0);
  264. // Should have been called once (debounced), not 5 times.
  265. expect(syncFn.mock.calls.length).toBe(1);
  266. watcher.stop();
  267. });
  268. });
  269. describe('filtering', () => {
  270. it('should ignore files not matching include patterns', async () => {
  271. const syncFn = vi.fn().mockResolvedValue({ filesChanged: 0, durationMs: 0 });
  272. const watcher = newWatcher(syncFn, { debounceMs: 200 });
  273. watcher.start();
  274. await watcher.waitUntilReady();
  275. // A non-source-file event — FileWatcher's `isSourceFile` gate must drop
  276. // it before scheduling sync.
  277. __emitWatchEventForTests(testDir, 'src/readme.md');
  278. // Wait a bit longer than debounce — sync should NOT trigger.
  279. await new Promise((r) => setTimeout(r, 400));
  280. expect(syncFn).not.toHaveBeenCalled();
  281. watcher.stop();
  282. });
  283. it('should ignore .codegraph directory changes', async () => {
  284. const syncFn = vi.fn().mockResolvedValue({ filesChanged: 0, durationMs: 0 });
  285. const watcher = newWatcher(syncFn, { debounceMs: 200 });
  286. watcher.start();
  287. await watcher.waitUntilReady();
  288. // A .codegraph event — FileWatcher's `isAlwaysIgnored` filter must drop
  289. // it before scheduling sync.
  290. __emitWatchEventForTests(testDir, '.codegraph/db.sqlite');
  291. await new Promise((r) => setTimeout(r, 400));
  292. expect(syncFn).not.toHaveBeenCalled();
  293. watcher.stop();
  294. });
  295. it('should drop ignored/non-source paths but sync real source edits', async () => {
  296. const syncFn = vi.fn().mockResolvedValue({ filesChanged: 0, durationMs: 0 });
  297. const watcher = newWatcher(syncFn, { debounceMs: 200 });
  298. watcher.start();
  299. await watcher.waitUntilReady();
  300. // node_modules is in the default-ignore set (#407) → dropped by the
  301. // ignore matcher even without a .gitignore.
  302. __emitWatchEventForTests(testDir, 'node_modules/dep/index.js');
  303. // A normal source file still schedules sync (positive control).
  304. __emitWatchEventForTests(testDir, 'src/live.ts');
  305. await waitFor(() => syncFn.mock.calls.length > 0);
  306. expect(syncFn).toHaveBeenCalled();
  307. watcher.stop();
  308. });
  309. });
  310. describe('pending file tracking (#403)', () => {
  311. it('should expose edited paths via getPendingFiles before sync fires', async () => {
  312. // Slow debounce — pending entries are visible until the debounce fires.
  313. // The synthetic event is synchronous, so we can assert immediately.
  314. const syncFn = vi.fn().mockResolvedValue({ filesChanged: 1, durationMs: 10 });
  315. const watcher = newWatcher(syncFn, { debounceMs: 2000 });
  316. watcher.start();
  317. await watcher.waitUntilReady();
  318. expect(watcher.getPendingFiles()).toEqual([]);
  319. __emitWatchEventForTests(testDir, 'src/pending.ts');
  320. const pending = watcher.getPendingFiles();
  321. const paths = pending.map((p) => p.path);
  322. expect(paths).toContain('src/pending.ts');
  323. const entry = pending.find((p) => p.path === 'src/pending.ts')!;
  324. expect(entry.firstSeenMs).toBeGreaterThan(0);
  325. expect(entry.lastSeenMs).toBeGreaterThanOrEqual(entry.firstSeenMs);
  326. // No sync running yet → indexing flag is false.
  327. expect(entry.indexing).toBe(false);
  328. watcher.stop();
  329. });
  330. it('should clear an entry only after a successful sync absorbing that edit', async () => {
  331. const syncFn = vi.fn().mockResolvedValue({ filesChanged: 1, durationMs: 10 });
  332. const watcher = newWatcher(syncFn, { debounceMs: 200 });
  333. watcher.start();
  334. await watcher.waitUntilReady();
  335. __emitWatchEventForTests(testDir, 'src/fresh.ts');
  336. // Watcher saw the change → pendingFiles has the entry IMMEDIATELY.
  337. expect(watcher.getPendingFiles().some((p) => p.path === 'src/fresh.ts')).toBe(true);
  338. // Wait through debounce + sync; the entry should drop out.
  339. await waitFor(() => syncFn.mock.calls.length > 0);
  340. await waitFor(() => !watcher.getPendingFiles().some((p) => p.path === 'src/fresh.ts'));
  341. expect(watcher.getPendingFiles()).toEqual([]);
  342. watcher.stop();
  343. });
  344. it('should keep entries unchanged when sync fails (rescheduled work sees the same set)', async () => {
  345. // No initial-scan-triggered sync, so syncFn outcomes line up 1:1 with
  346. // explicit events.
  347. const syncFn = vi
  348. .fn()
  349. .mockRejectedValueOnce(new Error('boom')) // first sync rejects
  350. .mockResolvedValueOnce({ filesChanged: 1, durationMs: 10 }); // retry succeeds
  351. const onSyncError = vi.fn();
  352. const watcher = newWatcher(syncFn, { debounceMs: 100, onSyncError });
  353. watcher.start();
  354. await watcher.waitUntilReady();
  355. __emitWatchEventForTests(testDir, 'src/will-fail.ts');
  356. // Wait for the sync to reject.
  357. await waitFor(() => onSyncError.mock.calls.length > 0);
  358. // The file is STILL in pendingFiles — failure didn't drop it.
  359. const after = watcher.getPendingFiles();
  360. expect(after.some((p) => p.path === 'src/will-fail.ts')).toBe(true);
  361. // Retry resolves automatically; entry clears.
  362. await waitFor(
  363. () => !watcher.getPendingFiles().some((p) => p.path === 'src/will-fail.ts'),
  364. );
  365. watcher.stop();
  366. });
  367. it('should retain pending files and retry when syncFn throws LockUnavailableError (#449)', async () => {
  368. // CodeGraph.watch() converts the cross-process lock-failure no-op
  369. // into LockUnavailableError so the watcher's retry path picks it up
  370. // instead of falsely clearing pendingFiles. This test exercises the
  371. // contract directly.
  372. const syncFn = vi
  373. .fn()
  374. .mockRejectedValueOnce(new LockUnavailableError())
  375. .mockResolvedValueOnce({ filesChanged: 1, durationMs: 10 });
  376. const onSyncComplete = vi.fn();
  377. const onSyncError = vi.fn();
  378. const watcher = newWatcher(syncFn, {
  379. debounceMs: 100,
  380. onSyncComplete,
  381. onSyncError,
  382. });
  383. watcher.start();
  384. await watcher.waitUntilReady();
  385. __emitWatchEventForTests(testDir, 'src/locked.ts');
  386. await waitFor(() => syncFn.mock.calls.length >= 1);
  387. expect(watcher.getPendingFiles().some((p) => p.path === 'src/locked.ts')).toBe(true);
  388. // A held-lock no-op is not a sync failure — onSyncError stays quiet
  389. // so a long-running external indexer doesn't spam stderr every cycle.
  390. expect(onSyncError).not.toHaveBeenCalled();
  391. expect(onSyncComplete).not.toHaveBeenCalled();
  392. await waitFor(() => syncFn.mock.calls.length >= 2);
  393. await waitFor(
  394. () => !watcher.getPendingFiles().some((p) => p.path === 'src/locked.ts'),
  395. );
  396. expect(onSyncComplete).toHaveBeenCalledTimes(1);
  397. expect(onSyncComplete).toHaveBeenCalledWith({ filesChanged: 1, durationMs: 10 });
  398. expect(onSyncError).not.toHaveBeenCalled();
  399. watcher.stop();
  400. });
  401. });
  402. describe('callbacks', () => {
  403. it('should call onSyncComplete after successful sync', async () => {
  404. const syncFn = vi.fn().mockResolvedValue({ filesChanged: 2, durationMs: 50 });
  405. const onSyncComplete = vi.fn();
  406. const watcher = newWatcher(syncFn, {
  407. debounceMs: 200,
  408. onSyncComplete,
  409. });
  410. watcher.start();
  411. await watcher.waitUntilReady();
  412. __emitWatchEventForTests(testDir, 'src/test.ts');
  413. await waitFor(() => onSyncComplete.mock.calls.length > 0);
  414. expect(onSyncComplete).toHaveBeenCalledWith({ filesChanged: 2, durationMs: 50 });
  415. watcher.stop();
  416. });
  417. it('should call onSyncError when sync throws', async () => {
  418. const syncFn = vi.fn().mockRejectedValue(new Error('sync failed'));
  419. const onSyncError = vi.fn();
  420. const watcher = newWatcher(syncFn, {
  421. debounceMs: 200,
  422. onSyncError,
  423. });
  424. watcher.start();
  425. await watcher.waitUntilReady();
  426. __emitWatchEventForTests(testDir, 'src/test.ts');
  427. await waitFor(() => onSyncError.mock.calls.length > 0);
  428. expect(onSyncError).toHaveBeenCalled();
  429. expect(onSyncError.mock.calls[0]![0]).toBeInstanceOf(Error);
  430. watcher.stop();
  431. });
  432. });
  433. describe('CodeGraph integration', () => {
  434. let cg: CodeGraph;
  435. afterEach(() => {
  436. if (cg) cg.close();
  437. });
  438. it('should watch and unwatch via CodeGraph API', async () => {
  439. cg = CodeGraph.initSync(testDir, {
  440. config: { include: ['**/*.ts'], exclude: [] },
  441. });
  442. await cg.indexAll();
  443. expect(cg.isWatching()).toBe(false);
  444. const started = cg.watch({ debounceMs: 200, inertForTests: true });
  445. expect(started).toBe(true);
  446. expect(cg.isWatching()).toBe(true);
  447. cg.unwatch();
  448. expect(cg.isWatching()).toBe(false);
  449. });
  450. it('should stop watching on close', async () => {
  451. cg = CodeGraph.initSync(testDir, {
  452. config: { include: ['**/*.ts'], exclude: [] },
  453. });
  454. await cg.indexAll();
  455. cg.watch({ debounceMs: 200, inertForTests: true });
  456. expect(cg.isWatching()).toBe(true);
  457. cg.close();
  458. // After close, isWatching should be false
  459. // (we can't call isWatching after close since DB is closed,
  460. // but we verify no errors are thrown)
  461. });
  462. it('should auto-sync when files change while watching (real fs.watch end-to-end)', async () => {
  463. // The one test that exercises the genuine native watcher: a real file
  464. // write must propagate through fs.watch → debounce → sync into the graph.
  465. cg = CodeGraph.initSync(testDir, {
  466. config: { include: ['**/*.ts'], exclude: [] },
  467. });
  468. await cg.indexAll();
  469. const initialStats = cg.getStats();
  470. const initialNodes = initialStats.nodeCount;
  471. cg.watch({ debounceMs: 300 });
  472. // Let the watcher install before writing, so the event isn't missed.
  473. await new Promise((r) => setTimeout(r, 100));
  474. // Real fs write — no synthetic event. The live watcher must catch it.
  475. fs.writeFileSync(
  476. path.join(testDir, 'src', 'added.ts'),
  477. 'export function added() { return 42; }'
  478. );
  479. // Wait for auto-sync to pick it up (real OS event delivery + debounce).
  480. await waitFor(() => {
  481. const stats = cg.getStats();
  482. return stats.nodeCount > initialNodes;
  483. }, 8000);
  484. // The new function should be in the graph.
  485. const results = cg.searchNodes('added');
  486. expect(results.length).toBeGreaterThan(0);
  487. cg.unwatch();
  488. });
  489. });
  490. });