Skip to main content

import_lint_cli/
watch.rs

1//! Watch mode (PLAN-v1.md §7, M6 brief). [`WatchSession`] implements the update policy
2//! (brief D-W1: full re-check every debounced batch, extraction cached; a fresh
3//! `ProjectResolver` + re-walk only on a "structural" change) and is fully drivable
4//! without `notify` (brief D-W3) — see `crates/cli/tests/watch.rs`. [`watch_loop`] is
5//! the thin `notify`/`notify-debouncer-full` layer that maps real filesystem events
6//! to [`ChangeKind`]s and drives a [`WatchSession`] from them (brief D-W2).
7
8use std::collections::{HashMap, HashSet};
9use std::path::{Path, PathBuf};
10use std::sync::Arc;
11use std::sync::atomic::{AtomicBool, Ordering};
12use std::sync::mpsc::RecvTimeoutError;
13use std::time::{Duration, Instant};
14
15use import_lint::{Access, FileModuleInfo, LintConfig, ModuleGraph, ProjectResolver, Provenance};
16use notify::event::{AccessKind, AccessMode, MetadataKind, ModifyKind};
17use notify::{Config as NotifyConfig, EventKind, PollWatcher, RecursiveMode, Watcher};
18use notify_debouncer_full::{
19    DebounceEventResult, DebouncedEvent, Debouncer, FileIdCache, NoCache, new_debouncer,
20    new_debouncer_opt,
21};
22use oxc_allocator::AllocatorPool;
23use oxc_str::CompactStr;
24
25use crate::output::RenderedDiagnostic;
26use crate::overlay::Overlays;
27use crate::report::{ReportOptions, diagnostics_by_file, finish_report};
28use crate::runner::{self, ExtractionCache, RunnerOptions};
29use crate::setup::{self, ConfigLoadError};
30use crate::source_type::source_type_for_path;
31
32/// One classified filesystem change, ready for [`WatchSession::run_cycle`] (M6 brief
33/// D-W3). Pure data — no `notify` types leak into this enum, so session-level tests
34/// (`crates/cli/tests/watch.rs`) can synthesize batches directly without spinning up
35/// a real watcher.
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum ChangeKind {
38    /// An existing lintable file's content changed.
39    ContentEdit(PathBuf),
40    /// A file was created, removed, or renamed anywhere under a watched root, or a
41    /// `package.json` changed anywhere — the filesystem layout may have shifted in a
42    /// way that could change resolution results, so the walk and `ProjectResolver`
43    /// are rebuilt from scratch (M6 brief D-W1).
44    Structural,
45    /// The `.importlintrc.jsonc`/`.importlintrc.json` config file changed.
46    ConfigChanged,
47    /// The project's `tsconfig.json` changed.
48    TsconfigChanged,
49}
50
51/// Inputs [`WatchSession::new`] needs — the same CLI-flag inputs `main.rs`'s
52/// `lint()` takes (see `crates/cli/src/setup.rs`), since a `ConfigChanged` cycle
53/// redoes exactly that computation.
54pub struct WatchSessionOptions {
55    pub cli_paths: Vec<PathBuf>,
56    pub explicit_config: Option<PathBuf>,
57    pub cli_tsconfig: Option<PathBuf>,
58    pub report_unresolved: bool,
59    pub quiet: bool,
60    pub cwd: PathBuf,
61}
62
63/// One completed cycle's result: everything a renderer or a test needs, plus the
64/// counters the M6 brief's extraction-cache test relies on (D-W3).
65pub struct CycleOutcome {
66    pub diagnostics: Vec<RenderedDiagnostic>,
67    pub has_error: bool,
68    /// Number of lint targets actually re-checked this cycle (every lint target
69    /// that has a `FileModuleInfo` — the check phase always re-runs over the full
70    /// set each cycle, D-W1; this is "how big was that recheck", not a delta).
71    pub rechecked_files: usize,
72    /// Number of files actually re-parsed this cycle (extraction cache misses) —
73    /// zero for a cycle with no relevant changes.
74    pub extracted_files: usize,
75    /// Every lint target this cycle, walked or not — the `json` formatter needs
76    /// this to emit an entry for clean files too (ESLint's own behavior), matching
77    /// the non-watch `lint()` path.
78    pub linted_files: Vec<PathBuf>,
79    pub duration: Duration,
80    /// Set when this cycle included a `ConfigChanged` change whose reload failed
81    /// (bad jsonc, unknown field, etc.). The *previous* config is kept and watching
82    /// continues — this is a report string for the UI, never a fatal condition
83    /// (M6 brief D-W1).
84    pub config_error: Option<String>,
85}
86
87/// The paths `watch_loop` should have `notify` watch: each include root
88/// (recursively), plus the config file, tsconfig, and project `package.json`
89/// (non-recursively) if not already covered by a root (M6 brief D-W2).
90#[derive(Debug, Clone, Default, PartialEq, Eq)]
91pub struct WatchTargets {
92    pub roots: Vec<PathBuf>,
93    pub config_path: Option<PathBuf>,
94    pub tsconfig_path: Option<PathBuf>,
95    pub package_json_path: Option<PathBuf>,
96}
97
98impl WatchTargets {
99    fn all_paths(&self) -> Vec<PathBuf> {
100        let mut paths = self.roots.clone();
101        paths.extend(self.config_path.iter().cloned());
102        paths.extend(self.tsconfig_path.iter().cloned());
103        paths.extend(self.package_json_path.iter().cloned());
104        paths
105    }
106}
107
108/// Live watch-mode state (M6 brief D-W3): config, resolved options, the extraction
109/// cache, the current walk result, and the built [`ProjectResolver`] —
110/// [`run_cycle`](WatchSession::run_cycle) redoes the discovery+link+check pipeline
111/// from these without ever touching `notify`.
112pub struct WatchSession {
113    cli_paths: Vec<PathBuf>,
114    explicit_config: Option<PathBuf>,
115    cli_tsconfig: Option<PathBuf>,
116    report_unresolved: bool,
117    quiet: bool,
118    cwd: PathBuf,
119
120    config: LintConfig,
121    project_root: PathBuf,
122    config_path: Option<PathBuf>,
123
124    roots: Vec<PathBuf>,
125    tsconfig_path: Option<PathBuf>,
126
127    resolver: ProjectResolver,
128    pool: AllocatorPool,
129    extraction_cache: ExtractionCache,
130    walked_paths: Vec<PathBuf>,
131
132    /// In-memory overlay content for open editor buffers (L1, `docs/PLAN-lsp.md` §3):
133    /// wins over disk content for any covered path, in both extraction and
134    /// diagnostic line/col rendering. Empty until [`WatchSession::set_overlay`] is
135    /// called — the CLI's own `--watch`/`--watch-poll` path never populates it, only
136    /// the future `import-lint lsp` server (L2) does.
137    overlays: Overlays,
138
139    /// The current module graph, kept alive across cycles (not rebuilt from scratch
140    /// each time) so a content-edit-only cycle can patch it in place instead of
141    /// re-deriving it from the whole project (PLAN-v1.md §7 incremental design).
142    /// Replaced wholesale by [`WatchSession::full_recheck`]; patched in place by
143    /// [`WatchSession::run_fast_cycle`].
144    graph: ModuleGraph,
145    /// Every lint target's own diagnostics (rule violations plus, if
146    /// `report_unresolved`, unresolved-specifier notes) — every diagnostic is
147    /// self-attributed to the importer file it's about (see
148    /// [`crate::report::diagnostics_by_file`]'s doc comment), so this map can be
149    /// updated file-by-file: [`WatchSession::full_recheck`] replaces it wholesale,
150    /// [`WatchSession::run_fast_cycle`] replaces only the dirty subset's entries.
151    /// [`WatchSession::compose_from_map`] flattens this into `last_diagnostics`.
152    diagnostics_map: HashMap<PathBuf, Vec<RenderedDiagnostic>>,
153
154    last_diagnostics: Vec<RenderedDiagnostic>,
155    last_has_error: bool,
156}
157
158/// Bundles what a "structural" (re-walk + fresh resolver) pass produces, so it can
159/// be threaded straight into `extract_and_link_from` without a second extraction
160/// pass over the same paths (see `runner.rs`'s doc comments on `extracted_files`
161/// double-counting).
162struct WalkAndResolver {
163    roots: Vec<PathBuf>,
164    tsconfig_path: Option<PathBuf>,
165    resolver: ProjectResolver,
166    walked_paths: Vec<PathBuf>,
167    initial: runner::Extracted,
168}
169
170fn build_walk_and_resolver(
171    cli_paths: &[PathBuf],
172    cli_tsconfig: Option<&Path>,
173    config: &LintConfig,
174    project_root: &Path,
175    pool: &AllocatorPool,
176    cache: &mut ExtractionCache,
177    overlays: &Overlays,
178) -> WalkAndResolver {
179    let roots = setup::compute_roots(cli_paths, config, project_root);
180    let tsconfig_path = setup::compute_tsconfig(cli_tsconfig, config, project_root);
181    let self_reference_mode = setup::compute_self_reference_mode(config);
182
183    let runner_options = RunnerOptions {
184        roots: roots.clone(),
185        project_root: project_root.to_path_buf(),
186        tsconfig: tsconfig_path.clone(),
187        self_reference_mode,
188        exclude: config.exclude.clone(),
189    };
190
191    let walked_paths = crate::walk::walk_with_excludes(
192        &runner_options.roots,
193        Some(runner_options.project_root.as_path()),
194        &runner_options.exclude,
195    );
196    let initial = runner::extract_with_cache(&walked_paths, pool, cache, overlays);
197    let resolver =
198        runner::build_resolver_from_files(&runner_options, &walked_paths, &initial.files);
199
200    WalkAndResolver {
201        roots,
202        tsconfig_path,
203        resolver,
204        walked_paths,
205        initial,
206    }
207}
208
209struct RecheckStats {
210    rechecked_files: usize,
211    extracted_files: usize,
212    linted_files: Vec<PathBuf>,
213}
214
215impl WatchSession {
216    /// Load the config, resolve options, and perform the initial full pipeline run
217    /// (walk, extract, link, check) — `last_diagnostics`/`last_has_error` reflect
218    /// the project's current state as soon as this returns. Fails only if the
219    /// *initial* config can't be loaded (an explicit `--config` that doesn't exist,
220    /// or a parse error): matching `main.rs`'s non-watch `lint()`, refusing to start
221    /// watch mode on a broken config is the right call. Once running, a bad config
222    /// edit is reported via `CycleOutcome::config_error` and the previous config is
223    /// kept — never fatal (M6 brief D-W1) — see [`WatchSession::run_cycle`].
224    pub fn new(options: WatchSessionOptions) -> Result<Self, ConfigLoadError> {
225        let loaded = setup::load_config(options.explicit_config.as_deref(), &options.cwd)?;
226        let pool = AllocatorPool::new(rayon::current_num_threads());
227        let mut cache = ExtractionCache::new();
228        let overlays = Overlays::default();
229
230        let built = build_walk_and_resolver(
231            &options.cli_paths,
232            options.cli_tsconfig.as_deref(),
233            &loaded.config,
234            &loaded.project_root,
235            &pool,
236            &mut cache,
237            &overlays,
238        );
239
240        let mut session = WatchSession {
241            cli_paths: options.cli_paths,
242            explicit_config: options.explicit_config,
243            cli_tsconfig: options.cli_tsconfig,
244            report_unresolved: options.report_unresolved,
245            quiet: options.quiet,
246            cwd: options.cwd,
247
248            config: loaded.config,
249            project_root: loaded.project_root,
250            config_path: loaded.config_path,
251
252            roots: built.roots,
253            tsconfig_path: built.tsconfig_path,
254
255            resolver: built.resolver,
256            pool,
257            extraction_cache: cache,
258            walked_paths: built.walked_paths,
259            overlays,
260
261            graph: ModuleGraph::build(Vec::new(), HashMap::new(), HashSet::new()),
262            diagnostics_map: HashMap::new(),
263
264            last_diagnostics: Vec::new(),
265            last_has_error: false,
266        };
267        session.full_recheck(built.initial);
268        Ok(session)
269    }
270
271    /// Set (or replace) the in-memory overlay content for `path` (L1, `docs/PLAN-lsp.md`
272    /// §3): overrides its on-disk content in extraction and diagnostic line/col
273    /// rendering until [`WatchSession::clear_overlay`] is called. This only mutates
274    /// overlay state — nothing is re-checked until the caller follows up with
275    /// `run_cycle(&[ChangeKind::ContentEdit(path)])`.
276    ///
277    /// `path` must be the same path identity used everywhere else for this file (a
278    /// canonical path — the same one a `ChangeKind::ContentEdit` for it would carry,
279    /// and the same one the module graph keys its files by). This method does not
280    /// canonicalize `path` itself: canonicalizing here would fail for a file that no
281    /// longer exists on disk, and an overlay must still be settable for such a path
282    /// (an unsaved buffer whose file was deleted on disk) — the caller is expected to
283    /// have already resolved `path` to its canonical form while the file still
284    /// existed (e.g. at the time it was opened).
285    pub fn set_overlay(&mut self, path: PathBuf, content: String) {
286        self.overlays.set(path, content);
287    }
288
289    /// Clear the overlay for `path`, if any (see [`WatchSession::set_overlay`] for
290    /// the path-identity requirement), returning whether one existed. Disk content
291    /// becomes authoritative again for this file; nothing is re-checked until the
292    /// caller follows up with `run_cycle(&[ChangeKind::ContentEdit(path)])`.
293    pub fn clear_overlay(&mut self, path: &Path) -> bool {
294        self.overlays.clear(path)
295    }
296
297    /// The most recently computed diagnostics (from `new()` or the last
298    /// `run_cycle` call).
299    pub fn last_diagnostics(&self) -> &[RenderedDiagnostic] {
300        &self.last_diagnostics
301    }
302
303    pub fn last_has_error(&self) -> bool {
304        self.last_has_error
305    }
306
307    /// Where `watch_loop` should point `notify` right now (M6 brief D-W2):
308    /// recomputed on demand since `roots`/`config_path`/`tsconfig_path` can change
309    /// after a `ConfigChanged`/`TsconfigChanged`/`Structural` reload.
310    pub fn watch_targets(&self) -> WatchTargets {
311        let package_json = self.project_root.join("package.json");
312        let covered_by_a_root = self.roots.iter().any(|root| package_json.starts_with(root));
313        WatchTargets {
314            roots: self.roots.clone(),
315            config_path: self.config_path.clone(),
316            tsconfig_path: self.tsconfig_path.clone(),
317            package_json_path: (!covered_by_a_root).then_some(package_json),
318        }
319    }
320
321    /// Advance the session by one debounced batch of `changes` (M6/M7 brief,
322    /// PLAN-v1.md §7):
323    /// - `ConfigChanged`: reload the config; on success this also forces a full
324    ///   reload (severity/options/include/exclude may have changed the walk itself);
325    ///   on failure, keep the previous config and report the error via
326    ///   `CycleOutcome::config_error` — watching continues either way.
327    /// - `TsconfigChanged` or `Structural`: re-walk the roots and build a fresh
328    ///   `ProjectResolver` (a resolver's cache assumes a frozen filesystem layout),
329    ///   then a full recheck ([`WatchSession::full_recheck`]).
330    /// - Otherwise (every change is a `ContentEdit`, including the empty batch):
331    ///   [`WatchSession::run_fast_cycle`] — re-extract just the changed paths and
332    ///   patch the graph and diagnostics map in place, without a full-project `stat()`
333    ///   sweep, resolve pass, graph rebuild, or check pass. Falls back to a full
334    ///   reload + recheck on its own rare escape hatches (see that method's doc
335    ///   comment) — always correct, just not always fast.
336    ///
337    /// `CycleOutcome::extracted_files` is the number of files that were *actually*
338    /// re-parsed (0 for a batch that touched nothing); `rechecked_files` is the size
339    /// of whatever was actually re-checked this cycle (every lint target on a full
340    /// recheck, just the dirty set on a fast cycle).
341    pub fn run_cycle(&mut self, changes: &[ChangeKind]) -> CycleOutcome {
342        let start = Instant::now();
343        let mut config_error = None;
344        let mut need_full_reload = changes
345            .iter()
346            .any(|c| matches!(c, ChangeKind::TsconfigChanged | ChangeKind::Structural));
347
348        if changes
349            .iter()
350            .any(|c| matches!(c, ChangeKind::ConfigChanged))
351        {
352            match setup::load_config(self.explicit_config.as_deref(), &self.cwd) {
353                Ok(loaded) => {
354                    self.config = loaded.config;
355                    self.project_root = loaded.project_root;
356                    self.config_path = loaded.config_path;
357                    need_full_reload = true;
358                }
359                Err(err) => {
360                    config_error = Some(err.to_string());
361                }
362            }
363        }
364
365        let stats = if need_full_reload {
366            let initial = self.full_reload();
367            self.full_recheck(initial)
368        } else {
369            let changed_paths: Vec<PathBuf> = changes
370                .iter()
371                .filter_map(|change| match change {
372                    ChangeKind::ContentEdit(path) => Some(path.clone()),
373                    _ => None,
374                })
375                .collect();
376            match self.run_fast_cycle(&changed_paths) {
377                Some(stats) => stats,
378                None => {
379                    let initial = self.full_reload();
380                    self.full_recheck(initial)
381                }
382            }
383        };
384
385        CycleOutcome {
386            diagnostics: self.last_diagnostics.clone(),
387            has_error: self.last_has_error,
388            rechecked_files: stats.rechecked_files,
389            extracted_files: stats.extracted_files,
390            linted_files: stats.linted_files,
391            duration: start.elapsed(),
392            config_error,
393        }
394    }
395
396    /// Re-walk `self.roots` (recomputed from the current config) and rebuild the
397    /// resolver, returning the walked set's extraction (already served through
398    /// `self.extraction_cache`) so the caller can feed it straight into
399    /// [`WatchSession::full_recheck`].
400    fn full_reload(&mut self) -> runner::Extracted {
401        let built = build_walk_and_resolver(
402            &self.cli_paths,
403            self.cli_tsconfig.as_deref(),
404            &self.config,
405            &self.project_root,
406            &self.pool,
407            &mut self.extraction_cache,
408            &self.overlays,
409        );
410        self.roots = built.roots;
411        self.tsconfig_path = built.tsconfig_path;
412        self.resolver = built.resolver;
413        self.walked_paths = built.walked_paths;
414        built.initial
415    }
416
417    /// Run the fixpoint extract+link pass from `initial` and the check phase over
418    /// *every* lint target, replacing `self.graph` and `self.diagnostics_map`
419    /// wholesale. Called on session startup, on any
420    /// `Structural`/`ConfigChanged`(-success)/`TsconfigChanged` cycle, and as
421    /// [`WatchSession::run_fast_cycle`]'s fallback when it hits one of its escape
422    /// hatches.
423    fn full_recheck(&mut self, initial: runner::Extracted) -> RecheckStats {
424        let outcome = runner::extract_and_link_from(
425            &self.walked_paths,
426            initial,
427            &self.resolver,
428            &self.pool,
429            &mut self.extraction_cache,
430            &self.overlays,
431        );
432        let rechecked_files = crate::timing::phase("rechecked_files_count", || {
433            outcome
434                .graph
435                .lint_targets
436                .iter()
437                .filter(|path| outcome.graph.file(path).is_some())
438                .count()
439        });
440        let extracted_files = outcome.extracted_files;
441        let linted_files: Vec<PathBuf> = crate::timing::phase("linted_files_clone", || {
442            outcome.graph.lint_targets.iter().cloned().collect()
443        });
444
445        self.graph = outcome.graph;
446
447        let targets: Vec<&Path> = self
448            .graph
449            .lint_targets
450            .iter()
451            .map(PathBuf::as_path)
452            .collect();
453        self.diagnostics_map = crate::timing::phase("build_report_total", || {
454            diagnostics_by_file(
455                &self.graph,
456                &self.config,
457                &self.project_root,
458                &ReportOptions {
459                    report_unresolved: self.report_unresolved,
460                    quiet: self.quiet,
461                },
462                &targets,
463                &self.overlays,
464            )
465        });
466        self.compose_from_map();
467
468        RecheckStats {
469            rechecked_files,
470            extracted_files,
471            linted_files,
472        }
473    }
474
475    /// The fast path for a cycle whose changes are *all* `ContentEdit`s (M7,
476    /// PLAN-v1.md §7's incremental design; `run_cycle` never calls this for a batch
477    /// containing a `Structural`/`ConfigChanged`/`TsconfigChanged`): re-extract just
478    /// `changed_paths`, patch `self.graph` in place (no full-project `stat()` sweep,
479    /// resolve pass, or graph rebuild), and recheck only the dirty subset.
480    ///
481    /// Returns `None` when the batch hits one of these rare escape hatches, in which
482    /// case the caller falls back to [`WatchSession::full_reload`] +
483    /// [`WatchSession::full_recheck`] (always correct, just not fast):
484    /// - a changed path failed to (re-)extract this cycle, or wasn't already a known
485    ///   graph file (`ContentEdit` is documented as an edit to an *existing*
486    ///   lintable file — anything else is out of this method's scope);
487    /// - a changed file's `ambient_modules` differ from before (the resolver's
488    ///   ambient registry is baked in at construction, so it can't be trusted to
489    ///   reflect this edit);
490    /// - one of a changed file's specifiers now resolves internally to a file that
491    ///   isn't in the graph yet (a newly-imported, never-walked file — reaching a
492    ///   fixpoint for that is `extract_and_link_from`'s job, not this method's).
493    fn run_fast_cycle(&mut self, changed_paths: &[PathBuf]) -> Option<RecheckStats> {
494        let mut unique_paths: Vec<PathBuf> = changed_paths.to_vec();
495        unique_paths.sort();
496        unique_paths.dedup();
497
498        for path in &unique_paths {
499            self.extraction_cache.remove(path);
500        }
501        let extracted = runner::extract_with_cache(
502            &unique_paths,
503            &self.pool,
504            &mut self.extraction_cache,
505            &self.overlays,
506        );
507        let extracted_files = extracted.extracted_files;
508
509        let mut new_files: HashMap<PathBuf, Arc<FileModuleInfo>> = HashMap::new();
510        for info in extracted.files {
511            new_files.insert(info.path.clone(), info);
512        }
513
514        for path in &unique_paths {
515            if !new_files.contains_key(path) || !self.graph.files.contains_key(path) {
516                return None;
517            }
518        }
519        for path in &unique_paths {
520            if self.graph.files[path].ambient_modules != new_files[path].ambient_modules {
521                return None;
522            }
523        }
524
525        // Span-insensitive: a JSDoc comment moving lines without changing which
526        // access level applies must not count as a surface change (an importer's
527        // diagnostic span lives in the importer's own source, never the exporter's).
528        let mut surface_changed: HashSet<PathBuf> = HashSet::new();
529        for path in &unique_paths {
530            if export_surface(&self.graph.files[path]) != export_surface(&new_files[path]) {
531                surface_changed.insert(path.clone());
532            }
533        }
534
535        // Graph surgery: replace `files[path]`, recompute each changed file's own
536        // resolutions against the *existing* resolver (other files' resolutions
537        // cannot change from a content edit), and patch the reverse indices.
538        for path in &unique_paths {
539            let old_info = self.graph.files[path].clone();
540            for specifier in &old_info.specifiers {
541                let key = (path.clone(), specifier.clone());
542                if let Some(Provenance::Internal(target)) = self.graph.resolutions.remove(&key) {
543                    if let Some(set) = self.graph.importers.get_mut(&target) {
544                        set.remove(path);
545                    }
546                    if let Some(set) = self.graph.star_importers.get_mut(&target) {
547                        set.remove(path);
548                    }
549                }
550            }
551
552            let new_info = new_files.remove(path).expect("checked above");
553            let star_specifiers: HashSet<&CompactStr> = new_info.star_exports.iter().collect();
554
555            for specifier in &new_info.specifiers {
556                let provenance = self.resolver.resolve(path, specifier);
557                if let Provenance::Internal(target) = &provenance {
558                    if !self.graph.files.contains_key(target) {
559                        // A partially-patched `self.graph` is fine here: the caller
560                        // discards it wholesale via `full_reload`+`full_recheck`.
561                        return None;
562                    }
563                    self.graph
564                        .importers
565                        .entry(target.clone())
566                        .or_default()
567                        .insert(path.clone());
568                    if star_specifiers.contains(specifier) {
569                        self.graph
570                            .star_importers
571                            .entry(target.clone())
572                            .or_default()
573                            .insert(path.clone());
574                    }
575                }
576                self.graph
577                    .resolutions
578                    .insert((path.clone(), specifier.clone()), provenance);
579            }
580
581            self.graph.files.insert(path.clone(), new_info);
582        }
583
584        // Dirty set: the changed files, plus, for each one whose export surface
585        // changed, its direct importers and the star-export closure.
586        let mut dirty: HashSet<PathBuf> = unique_paths.iter().cloned().collect();
587        for path in &unique_paths {
588            if surface_changed.contains(path) {
589                propagate_star_closure(&self.graph, path, &mut dirty);
590            }
591        }
592        dirty.retain(|path| self.graph.lint_targets.contains(path));
593
594        let dirty_refs: Vec<&Path> = dirty.iter().map(PathBuf::as_path).collect();
595        let dirty_result = crate::timing::phase("build_report_total", || {
596            diagnostics_by_file(
597                &self.graph,
598                &self.config,
599                &self.project_root,
600                &ReportOptions {
601                    report_unresolved: self.report_unresolved,
602                    quiet: self.quiet,
603                },
604                &dirty_refs,
605                &self.overlays,
606            )
607        });
608        self.diagnostics_map.extend(dirty_result);
609        self.compose_from_map();
610
611        let linted_files: Vec<PathBuf> = self.graph.lint_targets.iter().cloned().collect();
612
613        Some(RecheckStats {
614            rechecked_files: dirty.len(),
615            extracted_files,
616            linted_files,
617        })
618    }
619
620    /// Flatten `self.diagnostics_map` into `last_diagnostics`/`last_has_error`,
621    /// applying the same sort/`--quiet` composition a full
622    /// [`crate::report::build_report`] pass does (see
623    /// [`crate::report::finish_report`]). Only the diagnostics themselves are cloned
624    /// here — proportional to how many there are, never to how many files exist —
625    /// which is the point of keeping a persistent per-file map across cycles.
626    fn compose_from_map(&mut self) {
627        let report = finish_report(
628            self.diagnostics_map.values().flatten().cloned(),
629            &ReportOptions {
630                report_unresolved: self.report_unresolved,
631                quiet: self.quiet,
632            },
633        );
634        self.last_diagnostics = report.diagnostics;
635        self.last_has_error = report.has_error;
636    }
637}
638
639/// A changed file's export surface for [`WatchSession::run_fast_cycle`]'s
640/// span-insensitive diff (PLAN-v1.md §7): exported name -> access, plus the
641/// `star_exports` specifier list (order-sensitive — reordering two `export * from`
642/// statements can change which one wins a name collision, so any difference here
643/// counts as a surface change). Spans are deliberately excluded.
644#[derive(PartialEq, Eq)]
645struct ExportSurface {
646    export_table: HashMap<CompactStr, Option<Access>>,
647    star_exports: Vec<CompactStr>,
648}
649
650fn export_surface(info: &FileModuleInfo) -> ExportSurface {
651    ExportSurface {
652        export_table: info
653            .export_table
654            .iter()
655            .map(|(name, export)| (name.clone(), export.access))
656            .collect(),
657        star_exports: info.star_exports.clone(),
658    }
659}
660
661/// Extend `dirty` with every file whose one-hop lookup can observe `start`'s export
662/// surface: `start`'s own direct importers, plus — recursively, cycle-guarded — the
663/// importers of every barrel that `export * from start` (and, transitively, every
664/// barrel that itself gets star-exported by another barrel). A bare `export *`
665/// statement is never itself a checked entry (there's no name to check against), so
666/// the barrel itself doesn't need rechecking — only files that resolve a *name*
667/// through it do (PLAN-v1.md §7's dirty-set definition).
668fn propagate_star_closure(graph: &ModuleGraph, start: &Path, dirty: &mut HashSet<PathBuf>) {
669    let mut visited_barrels: HashSet<PathBuf> = HashSet::new();
670    let mut stack: Vec<PathBuf> = vec![start.to_path_buf()];
671    while let Some(file) = stack.pop() {
672        if let Some(direct_importers) = graph.importers.get(&file) {
673            dirty.extend(direct_importers.iter().cloned());
674        }
675        if let Some(barrels) = graph.star_importers.get(&file) {
676            for barrel in barrels {
677                if visited_barrels.insert(barrel.clone()) {
678                    stack.push(barrel.clone());
679                }
680            }
681        }
682    }
683}
684
685/// Classify one debounced filesystem event into zero or more [`ChangeKind`]s (M6
686/// brief D-W2), given the paths that currently have special meaning (`watch`). Pure
687/// function of its inputs — unit-tested directly in `crates/cli/tests/watch.rs`
688/// without a real watcher.
689///
690/// - `Create`/`Remove`/a name change (rename) anywhere -> `Structural`.
691/// - `Modify(Metadata(WriteTime | Any))` is treated as a content change, not
692///   ignored: `PollWatcher` (`--watch-poll`) has no OS-level notion of "data
693///   changed" — a `stat()`-detected mtime bump is the *only* signal it emits for an
694///   edited file, reported as `Modify(Metadata(WriteTime))` rather than
695///   `Modify(Data(_))` (verified against notify 8.2.0's poll backend). Other
696///   metadata-only touches (permissions, ownership, access time, xattrs) are
697///   ignored — they can't affect linting.
698/// - Otherwise (a data write, or the `Access(Close(Write))` event most editors and
699///   atomic-save patterns produce — spike S5) each affected path is classified by
700///   what it is: any `package.json` -> `Structural`; the config file ->
701///   `ConfigChanged`; the tsconfig -> `TsconfigChanged`; a supported source
702///   extension -> `ContentEdit`; anything else is ignored.
703pub fn classify_event(event: &DebouncedEvent, watch: &WatchTargets) -> Vec<ChangeKind> {
704    match event.kind {
705        EventKind::Create(_) | EventKind::Remove(_) => vec![ChangeKind::Structural],
706        EventKind::Modify(ModifyKind::Name(_)) => vec![ChangeKind::Structural],
707        EventKind::Modify(ModifyKind::Metadata(
708            MetadataKind::Permissions | MetadataKind::Ownership | MetadataKind::AccessTime,
709        )) => Vec::new(),
710        EventKind::Modify(_) => event
711            .paths
712            .iter()
713            .filter_map(|path| classify_path(path, watch))
714            .collect(),
715        EventKind::Access(AccessKind::Close(AccessMode::Write)) => event
716            .paths
717            .iter()
718            .filter_map(|path| classify_path(path, watch))
719            .collect(),
720        EventKind::Access(_) | EventKind::Other | EventKind::Any => Vec::new(),
721    }
722}
723
724fn classify_path(path: &Path, watch: &WatchTargets) -> Option<ChangeKind> {
725    if path.file_name().is_some_and(|name| name == "package.json") {
726        return Some(ChangeKind::Structural);
727    }
728    if watch.config_path.as_deref() == Some(path) {
729        return Some(ChangeKind::ConfigChanged);
730    }
731    if watch.tsconfig_path.as_deref() == Some(path) {
732        return Some(ChangeKind::TsconfigChanged);
733    }
734    if source_type_for_path(path).is_some() {
735        return Some(ChangeKind::ContentEdit(path.to_path_buf()));
736    }
737    None
738}
739
740/// Drive `session` from real filesystem events (M6 brief D-W2/D-W3): watches
741/// `session`'s roots/config/tsconfig/package.json via `notify-debouncer-full`,
742/// classifies each debounced batch into [`ChangeKind`]s, and calls
743/// `session.run_cycle` — `on_cycle` is invoked with every [`CycleOutcome`]
744/// (production code renders it to the terminal; tests assert on it directly, per the
745/// M6 brief's "optional test hook").
746///
747/// `poll_interval` selects the watcher backend: `None` uses the platform-recommended
748/// watcher (inotify on Linux); `Some(interval)` uses a `PollWatcher` at that interval
749/// (`--watch-poll` — recommended for WSL2 Windows-side edits and network
750/// filesystems, per `docs/research/spike-s5-watch-wsl2.md`).
751///
752/// Returns once `shutdown` is observed `true` (checked at least once per `debounce`
753/// window via a receive timeout, so tests can stop the loop deterministically).
754pub fn watch_loop(
755    session: &mut WatchSession,
756    debounce: Duration,
757    poll_interval: Option<Duration>,
758    shutdown: &Arc<AtomicBool>,
759    mut on_cycle: impl FnMut(&CycleOutcome),
760) -> notify::Result<()> {
761    let (tx, rx) = std::sync::mpsc::channel::<DebounceEventResult>();
762    // Bounded so a shutdown request is never held up more than one poll behind the
763    // debounce window itself — no point tying it to `debounce`, which can be large.
764    let poll_shutdown_every = Duration::from_millis(200).min(debounce);
765
766    match poll_interval {
767        Some(interval) => {
768            let config = NotifyConfig::default().with_poll_interval(interval);
769            let mut debouncer =
770                new_debouncer_opt::<_, PollWatcher, NoCache>(debounce, None, tx, NoCache, config)?;
771            let mut watched = session.watch_targets();
772            register_watches(&mut debouncer, &watched);
773            run_event_loop(
774                &mut debouncer,
775                &rx,
776                poll_shutdown_every,
777                shutdown,
778                session,
779                &mut watched,
780                &mut on_cycle,
781            );
782        }
783        None => {
784            let mut debouncer = new_debouncer(debounce, None, tx)?;
785            let mut watched = session.watch_targets();
786            register_watches(&mut debouncer, &watched);
787            run_event_loop(
788                &mut debouncer,
789                &rx,
790                poll_shutdown_every,
791                shutdown,
792                session,
793                &mut watched,
794                &mut on_cycle,
795            );
796        }
797    }
798
799    Ok(())
800}
801
802fn register_watches<T: Watcher, C: FileIdCache>(
803    debouncer: &mut Debouncer<T, C>,
804    targets: &WatchTargets,
805) {
806    for root in &targets.roots {
807        if !root.exists() {
808            eprintln!(
809                "import-lint: {}: no such file or directory, not watching",
810                root.display()
811            );
812            continue;
813        }
814        if let Err(err) = debouncer.watch(root, RecursiveMode::Recursive) {
815            eprintln!("import-lint: failed to watch {}: {err}", root.display());
816        }
817    }
818    for extra in [
819        &targets.config_path,
820        &targets.tsconfig_path,
821        &targets.package_json_path,
822    ]
823    .into_iter()
824    .flatten()
825    {
826        if !extra.is_file() {
827            continue;
828        }
829        if let Err(err) = debouncer.watch(extra, RecursiveMode::NonRecursive) {
830            eprintln!("import-lint: failed to watch {}: {err}", extra.display());
831        }
832    }
833}
834
835/// Best-effort: unwatch every path present in `old` but not `new`, and watch every
836/// path present in `new` but not `old`. A `ConfigChanged`/`TsconfigChanged` reload
837/// changing which roots/files matter is expected to be rare, so simplicity wins over
838/// a precise diff (M6 brief D-W1's general stance — M7 will profile if this ever
839/// matters).
840fn reconcile_watches<T: Watcher, C: FileIdCache>(
841    debouncer: &mut Debouncer<T, C>,
842    old: &WatchTargets,
843    new: &WatchTargets,
844) {
845    let new_paths = new.all_paths();
846    for path in old.all_paths() {
847        if !new_paths.contains(&path) {
848            let _ = debouncer.unwatch(&path);
849        }
850    }
851    let old_paths = old.all_paths();
852    for path in new_paths {
853        if old_paths.contains(&path) || !path.exists() {
854            continue;
855        }
856        let mode = if new.roots.contains(&path) {
857            RecursiveMode::Recursive
858        } else {
859            RecursiveMode::NonRecursive
860        };
861        let _ = debouncer.watch(&path, mode);
862    }
863}
864
865#[allow(clippy::too_many_arguments)]
866fn run_event_loop<T: Watcher, C: FileIdCache>(
867    debouncer: &mut Debouncer<T, C>,
868    rx: &std::sync::mpsc::Receiver<DebounceEventResult>,
869    recv_tick: Duration,
870    shutdown: &Arc<AtomicBool>,
871    session: &mut WatchSession,
872    watched: &mut WatchTargets,
873    on_cycle: &mut impl FnMut(&CycleOutcome),
874) {
875    loop {
876        if shutdown.load(Ordering::Relaxed) {
877            return;
878        }
879
880        match rx.recv_timeout(recv_tick) {
881            Ok(Ok(events)) => {
882                let changes: Vec<ChangeKind> = events
883                    .iter()
884                    .flat_map(|event| classify_event(event, watched))
885                    .collect();
886                if changes.is_empty() {
887                    continue;
888                }
889                let outcome = session.run_cycle(&changes);
890                on_cycle(&outcome);
891
892                let new_watched = session.watch_targets();
893                if new_watched != *watched {
894                    reconcile_watches(debouncer, watched, &new_watched);
895                    *watched = new_watched;
896                }
897            }
898            Ok(Err(errors)) => {
899                for err in errors {
900                    eprintln!("import-lint: watch error: {err}");
901                }
902            }
903            Err(RecvTimeoutError::Timeout) => {}
904            Err(RecvTimeoutError::Disconnected) => return,
905        }
906    }
907}
908
909#[cfg(test)]
910mod classify_tests {
911    use super::*;
912    use notify::Event;
913    use notify::event::{CreateKind, RemoveKind, RenameMode};
914    use std::time::Instant;
915
916    fn debounced(kind: EventKind, paths: &[&str]) -> DebouncedEvent {
917        let mut event = Event::new(kind);
918        for path in paths {
919            event = event.add_path(PathBuf::from(path));
920        }
921        DebouncedEvent::new(event, Instant::now())
922    }
923
924    fn targets() -> WatchTargets {
925        WatchTargets {
926            roots: vec![PathBuf::from("/proj/src")],
927            config_path: Some(PathBuf::from("/proj/.importlintrc.jsonc")),
928            tsconfig_path: Some(PathBuf::from("/proj/tsconfig.json")),
929            package_json_path: Some(PathBuf::from("/proj/package.json")),
930        }
931    }
932
933    #[test]
934    fn create_is_structural_regardless_of_path() {
935        let event = debounced(EventKind::Create(CreateKind::File), &["/proj/src/new.ts"]);
936        assert_eq!(
937            classify_event(&event, &targets()),
938            vec![ChangeKind::Structural]
939        );
940    }
941
942    #[test]
943    fn remove_is_structural() {
944        let event = debounced(EventKind::Remove(RemoveKind::File), &["/proj/src/gone.ts"]);
945        assert_eq!(
946            classify_event(&event, &targets()),
947            vec![ChangeKind::Structural]
948        );
949    }
950
951    #[test]
952    fn rename_is_structural() {
953        let event = debounced(
954            EventKind::Modify(ModifyKind::Name(RenameMode::Both)),
955            &["/proj/src/old.ts", "/proj/src/new.ts"],
956        );
957        assert_eq!(
958            classify_event(&event, &targets()),
959            vec![ChangeKind::Structural]
960        );
961    }
962
963    #[test]
964    fn data_modify_of_a_source_file_is_content_edit() {
965        let event = debounced(
966            EventKind::Modify(ModifyKind::Data(notify::event::DataChange::Any)),
967            &["/proj/src/a.ts"],
968        );
969        assert_eq!(
970            classify_event(&event, &targets()),
971            vec![ChangeKind::ContentEdit(PathBuf::from("/proj/src/a.ts"))]
972        );
973    }
974
975    #[test]
976    fn close_write_of_a_source_file_is_content_edit() {
977        let event = debounced(
978            EventKind::Access(AccessKind::Close(AccessMode::Write)),
979            &["/proj/src/a.ts"],
980        );
981        assert_eq!(
982            classify_event(&event, &targets()),
983            vec![ChangeKind::ContentEdit(PathBuf::from("/proj/src/a.ts"))]
984        );
985    }
986
987    #[test]
988    fn access_open_is_ignored() {
989        let event = debounced(
990            EventKind::Access(AccessKind::Open(AccessMode::Read)),
991            &["/proj/src/a.ts"],
992        );
993        assert_eq!(classify_event(&event, &targets()), Vec::<ChangeKind>::new());
994    }
995
996    /// The `PollWatcher` backend has no OS-level notion of "data changed": it
997    /// detects an edited file purely via a `stat()`-observed mtime bump, reported
998    /// as `Modify(Metadata(WriteTime))` rather than `Modify(Data(_))` (verified
999    /// against notify 8.2.0's poll backend — see the `--watch-poll` end-to-end
1000    /// smoke test). This must classify the same as a `Data` modify, or
1001    /// `--watch-poll` never detects any edit.
1002    #[test]
1003    fn metadata_write_time_modify_is_content_edit() {
1004        let event = debounced(
1005            EventKind::Modify(ModifyKind::Metadata(notify::event::MetadataKind::WriteTime)),
1006            &["/proj/src/a.ts"],
1007        );
1008        assert_eq!(
1009            classify_event(&event, &targets()),
1010            vec![ChangeKind::ContentEdit(PathBuf::from("/proj/src/a.ts"))]
1011        );
1012    }
1013
1014    #[test]
1015    fn metadata_permissions_modify_is_ignored() {
1016        let event = debounced(
1017            EventKind::Modify(ModifyKind::Metadata(
1018                notify::event::MetadataKind::Permissions,
1019            )),
1020            &["/proj/src/a.ts"],
1021        );
1022        assert_eq!(classify_event(&event, &targets()), Vec::<ChangeKind>::new());
1023    }
1024
1025    #[test]
1026    fn metadata_access_time_modify_is_ignored() {
1027        let event = debounced(
1028            EventKind::Modify(ModifyKind::Metadata(
1029                notify::event::MetadataKind::AccessTime,
1030            )),
1031            &["/proj/src/a.ts"],
1032        );
1033        assert_eq!(classify_event(&event, &targets()), Vec::<ChangeKind>::new());
1034    }
1035
1036    #[test]
1037    fn package_json_modify_is_structural_even_nested() {
1038        let event = debounced(
1039            EventKind::Modify(ModifyKind::Data(notify::event::DataChange::Any)),
1040            &["/proj/src/nested/package.json"],
1041        );
1042        assert_eq!(
1043            classify_event(&event, &targets()),
1044            vec![ChangeKind::Structural]
1045        );
1046    }
1047
1048    #[test]
1049    fn config_path_modify_is_config_changed() {
1050        let event = debounced(
1051            EventKind::Modify(ModifyKind::Data(notify::event::DataChange::Any)),
1052            &["/proj/.importlintrc.jsonc"],
1053        );
1054        assert_eq!(
1055            classify_event(&event, &targets()),
1056            vec![ChangeKind::ConfigChanged]
1057        );
1058    }
1059
1060    #[test]
1061    fn tsconfig_path_modify_is_tsconfig_changed() {
1062        let event = debounced(
1063            EventKind::Modify(ModifyKind::Data(notify::event::DataChange::Any)),
1064            &["/proj/tsconfig.json"],
1065        );
1066        assert_eq!(
1067            classify_event(&event, &targets()),
1068            vec![ChangeKind::TsconfigChanged]
1069        );
1070    }
1071
1072    #[test]
1073    fn modify_of_an_unrecognized_extension_is_ignored() {
1074        let event = debounced(
1075            EventKind::Modify(ModifyKind::Data(notify::event::DataChange::Any)),
1076            &["/proj/src/readme.md"],
1077        );
1078        assert_eq!(classify_event(&event, &targets()), Vec::<ChangeKind>::new());
1079    }
1080
1081    #[test]
1082    fn event_with_no_special_kind_is_ignored() {
1083        let event = debounced(EventKind::Other, &["/proj/src/a.ts"]);
1084        assert_eq!(classify_event(&event, &targets()), Vec::<ChangeKind>::new());
1085    }
1086
1087    #[test]
1088    fn multiple_paths_classify_independently() {
1089        let event = debounced(
1090            EventKind::Modify(ModifyKind::Data(notify::event::DataChange::Any)),
1091            &["/proj/src/a.ts", "/proj/tsconfig.json", "/proj/README.md"],
1092        );
1093        let mut got = classify_event(&event, &targets());
1094        got.sort_by_key(|c| format!("{c:?}"));
1095        let mut want = vec![
1096            ChangeKind::ContentEdit(PathBuf::from("/proj/src/a.ts")),
1097            ChangeKind::TsconfigChanged,
1098        ];
1099        want.sort_by_key(|c| format!("{c:?}"));
1100        assert_eq!(got, want);
1101    }
1102}