agent-file-tools 0.51.3

Agent File Tools — tree-sitter powered code analysis for AI agents
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
use serde_json::Value;
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};

use super::job::{InspectSnapshot, JobOutcome, JobScope};
use crate::config::{
    Config, MAX_INSPECT_DIAGNOSTICS_TIMEOUT_MS, MIN_INSPECT_DIAGNOSTICS_TIMEOUT_MS,
};
use crate::context::AppContext;
use crate::lsp::diagnostics::{DiagnosticSeverity, StoredDiagnostic};
use crate::lsp::manager::ApplicableServerFailure;
use crate::lsp::registry::servers_for_file;
use crate::lsp::roots::ServerKey;
use crate::lsp::tsconfig_membership::TsconfigMembershipCache;

/// Configured deadline for the blocking root-level quiescence wait. The same
/// config value also drives the plugin-side transport headroom for inspect
/// calls, so a caller that waits the full deadline still returns before the
/// transport gives up.
pub(crate) fn diagnostics_phase_timeout(config: &Config) -> Duration {
    Duration::from_millis(config.inspect.diagnostics_timeout_ms.clamp(
        MIN_INSPECT_DIAGNOSTICS_TIMEOUT_MS,
        MAX_INSPECT_DIAGNOSTICS_TIMEOUT_MS,
    ))
}

#[derive(Debug, Clone)]
struct CollectedDiagnostic {
    diagnostic: StoredDiagnostic,
    provisional: bool,
}

/// A scoped file that no producer has authoritatively analyzed. Warm
/// collection cannot prove per-file cleanliness from the global "some server
/// reported" signal, so scoped payloads name these files instead of rendering
/// a confident empty answer.
#[derive(Debug)]
struct ScopedCoverageGap {
    file: PathBuf,
    reason: &'static str,
}

#[derive(Default)]
struct DiagnosticsCollection {
    diagnostics: Vec<CollectedDiagnostic>,
    server_ran: bool,
    applicability_is_empty: bool,
    servers_pending: BTreeSet<String>,
    producer_failures: BTreeMap<String, String>,
    scope_coverage_gaps: Vec<ScopedCoverageGap>,
}

/// Collect diagnostics for the explicit inspect path.
///
/// Collection never depends on the request scope: scoped and unscoped
/// requests both read the warm working set, so a scope cannot switch the
/// category onto a more expensive collection strategy. Scope only filters
/// which findings the payload renders.
///
/// The authority halves differ by design. An unscoped request makes a
/// full-root claim, so the global `is_reportable` conjunction over the
/// full-root collection decides freshness. A scoped request makes per-file
/// claims: every scoped file must either carry an authoritative producer
/// report or appear as a named gap, because the global "some server
/// reported" bit cannot prove that a specific file nothing ever analyzed is
/// clean. A collection becomes Fresh after every producer has either
/// returned verified results or reached a terminal failure. Terminal
/// producer failures remain named gaps in the payload; pending or otherwise
/// unverified sources still prevent a fresh response.
pub(crate) fn run_diagnostics_category(
    ctx: &AppContext,
    snapshot: &InspectSnapshot,
    scope: &JobScope,
    scope_was_provided: bool,
    applicability_is_empty: bool,
    producer_failures: &[ApplicableServerFailure],
) -> JobOutcome {
    let mut collection = if applicability_is_empty {
        // No applicable producer means there is no diagnostic artifact to wait
        // for; the empty category is authoritative for this applicability snapshot.
        DiagnosticsCollection {
            applicability_is_empty: true,
            ..DiagnosticsCollection::default()
        }
    } else {
        collect_warm_working_set(ctx, snapshot)
    };
    collection.record_producer_failures(producer_failures);

    if scope_was_provided {
        collection.apply_scope(scope);
        collection.record_scope_coverage_gaps(ctx, snapshot, scope);
        // Per-file coverage gaps make the scoped verdict self-certifying:
        // every scoped file is either covered by an authoritative report or
        // named as a gap, so the payload is honest without waiting on global
        // quiescence signals that may describe files outside the scope.
        return JobOutcome::Fresh {
            payload: collection.into_payload(snapshot),
        };
    }

    if collection.is_reportable() {
        JobOutcome::Fresh {
            payload: collection.into_payload(snapshot),
        }
    } else {
        JobOutcome::Pending { in_flight: true }
    }
}

fn collect_warm_working_set(ctx: &AppContext, snapshot: &InspectSnapshot) -> DiagnosticsCollection {
    let mut collection = DiagnosticsCollection::default();
    let mut tsconfig_membership = TsconfigMembershipCache::new();
    {
        let mut lsp = ctx.lsp();
        // The only diagnostics collection path, for scoped and unscoped
        // requests alike: drain already queued LSP events, then read only the
        // warm diagnostics store. It does not open files or spawn servers.
        lsp.drain_events();
        collection.server_ran = lsp.has_any_diagnostic_reports();
        if !collection.server_ran {
            collection.servers_pending.extend(
                lsp.active_server_keys()
                    .into_iter()
                    .map(|key| server_id(&key)),
            );
        }
        collection.servers_pending.extend(
            lsp.provisional_server_keys()
                .into_iter()
                .map(|key| server_id(&key)),
        );
        collection.diagnostics = lsp
            .get_all_diagnostics_with_provisional()
            .into_iter()
            .map(|(diagnostic, provisional)| CollectedDiagnostic {
                diagnostic: diagnostic.clone(),
                provisional,
            })
            .collect();
    }

    collection.diagnostics.retain(|diagnostic| {
        diagnostic
            .diagnostic
            .file
            .starts_with(&snapshot.project_root)
            && !tsconfig_membership.should_skip_diagnostics(&diagnostic.diagnostic.file)
    });
    collection.sort_and_dedup();
    collection
}

/// Per-file diagnostic coverage verdict for scoped requests.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ScopedFileCoverage {
    /// A registered producer holds an authoritative (neither stale nor
    /// warming) report for the file, including an empty checked-clean report.
    Covered,
    /// No LSP producer is registered for this file type.
    NoProducer,
    /// Producers are registered but none has a current report for the file.
    NoReport,
    /// Only warming (provisional) reports exist: the reporting server has not
    /// reached quiescence yet.
    Warming,
}

/// Test hook: force every scoped file to read as authoritatively covered.
/// Mutation control for the per-file authority check — with this forced, a
/// scoped request for a file nothing ever analyzed returns a confident empty
/// payload instead of a named gap, exactly the regression the coverage gap
/// exists to prevent.
pub fn force_scoped_diagnostic_coverage_for_test(forced: bool) {
    FORCE_SCOPED_DIAGNOSTIC_COVERAGE.store(forced, Ordering::SeqCst);
}

static FORCE_SCOPED_DIAGNOSTIC_COVERAGE: AtomicBool = AtomicBool::new(false);

fn scoped_file_coverage(ctx: &AppContext, config: &Config, file: &Path) -> ScopedFileCoverage {
    if FORCE_SCOPED_DIAGNOSTIC_COVERAGE.load(Ordering::SeqCst) {
        return ScopedFileCoverage::Covered;
    }
    if servers_for_file(file, config).is_empty() {
        return ScopedFileCoverage::NoProducer;
    }
    let lsp = ctx.lsp();
    if lsp.has_authoritative_report_for_file(file) {
        return ScopedFileCoverage::Covered;
    }
    if lsp.has_diagnostic_report_for_file(file) {
        // Reports exist but every one is warming (provisional): the server
        // published before reaching quiescence, so its view is not
        // authoritative yet.
        return ScopedFileCoverage::Warming;
    }
    ScopedFileCoverage::NoReport
}

/// Enumerate the files a scoped diagnostics verdict must cover.
///
/// Explicit file roots are always candidates: naming a file is a direct claim
/// on its diagnostics, including the "no producer applies" case. Directory
/// roots are walked with the same filters applicability resolution uses;
/// only files with a registered producer are candidates there, because
/// directories inevitably contain non-code files nobody expects diagnostics
/// for. Files a tsconfig excludes from diagnostics are skipped in both cases.
fn scoped_coverage_candidates(
    snapshot: &InspectSnapshot,
    scope: &JobScope,
    config: &Config,
    tsconfig_membership: &mut TsconfigMembershipCache,
) -> Vec<PathBuf> {
    let roots = if scope.roots().is_empty() {
        vec![snapshot.project_root.clone()]
    } else {
        scope.roots().to_vec()
    };

    let mut candidates = BTreeSet::new();
    for root in roots {
        if root.is_file() {
            if tsconfig_membership.should_skip_diagnostics(&root) {
                continue;
            }
            candidates.insert(crate::inspect::job::canonicalize_normalized(&root));
            continue;
        }

        let walker = ignore::WalkBuilder::new(&root)
            .standard_filters(true)
            .add_custom_ignore_filename(".aftignore")
            .filter_entry(|entry| {
                let name = entry.file_name().to_string_lossy();
                !matches!(
                    name.as_ref(),
                    ".git" | "node_modules" | "target" | "dist" | "build" | ".next" | ".turbo"
                )
            })
            .build();

        for entry in walker {
            let entry = match entry {
                Ok(entry) => entry,
                Err(_) => continue,
            };
            if !entry
                .file_type()
                .is_some_and(|file_type| file_type.is_file())
            {
                continue;
            }
            let path = entry.path();
            if tsconfig_membership.should_skip_diagnostics(path)
                || servers_for_file(path, config).is_empty()
            {
                continue;
            }
            candidates.insert(crate::inspect::job::canonicalize_normalized(path));
        }
    }

    candidates.into_iter().collect()
}

/// Boundary check for the blocking quiescence wait: observes cancellation and
/// the configured deadline at every tick. The deadline error text carries the
/// configured millisecond budget so the agent can see which value fired.
pub(crate) fn check_diagnostics_phase_boundary(
    deadline: Instant,
    timeout: Duration,
) -> Result<(), String> {
    if crate::executor::current_job_cancellation()
        .is_some_and(|token| token.cancel_requested_before_commit())
    {
        return Err("inspect request cancelled during LSP quiescence".to_string());
    }
    if Instant::now() >= deadline {
        return Err(format!(
            "lsp_quiescence_timeout: diagnostics did not complete within {}ms",
            timeout.as_millis()
        ));
    }
    Ok(())
}

impl DiagnosticsCollection {
    fn record_producer_failures(&mut self, failures: &[ApplicableServerFailure]) {
        for failure in failures {
            self.producer_failures
                .entry(server_id(&failure.server_key))
                .or_insert_with(|| failure.reason());
        }
    }

    /// Render-time scope filter over findings. The warm collection is
    /// full-root; a scoped payload keeps only in-scope findings. Warming
    /// (provisional) rows are dropped here because the per-file coverage
    /// check reports their files as named gaps until the responsible server
    /// settles, and a warming row must not read as an authoritative finding.
    fn apply_scope(&mut self, scope: &JobScope) {
        self.diagnostics.retain(|diagnostic| {
            !diagnostic.provisional && scope.contains(&diagnostic.diagnostic.file)
        });
    }

    /// Name every scoped file that no producer has authoritatively analyzed.
    /// The global `server_ran` signal is per-root, not per-file, so without
    /// this check a scoped request for a file nothing ever analyzed would
    /// render as a confident empty answer. Each named file becomes a gap row
    /// (`complete: false`) instead.
    fn record_scope_coverage_gaps(
        &mut self,
        ctx: &AppContext,
        snapshot: &InspectSnapshot,
        scope: &JobScope,
    ) {
        let mut tsconfig_membership = TsconfigMembershipCache::new();
        let candidates =
            scoped_coverage_candidates(snapshot, scope, &snapshot.config, &mut tsconfig_membership);
        for file in candidates {
            let reason = match scoped_file_coverage(ctx, &snapshot.config, &file) {
                ScopedFileCoverage::Covered => continue,
                ScopedFileCoverage::NoProducer => {
                    "no LSP producer is registered for this file type"
                }
                ScopedFileCoverage::NoReport => {
                    "no LSP producer has a current diagnostic report for this file"
                }
                ScopedFileCoverage::Warming => {
                    "the reporting LSP server has not reached quiescence yet"
                }
            };
            self.scope_coverage_gaps
                .push(ScopedCoverageGap { file, reason });
        }
    }

    #[cfg(test)]
    fn is_complete(&self) -> bool {
        self.is_reportable()
            && self.producer_failures.is_empty()
            && self.scope_coverage_gaps.is_empty()
    }

    /// Full-root authority conjunction for the no-scope path: a full-root
    /// verdict over the full-root warm collection. Scoped requests use
    /// per-file authority instead (see `record_scope_coverage_gaps`).
    fn is_reportable(&self) -> bool {
        (self.server_ran || self.applicability_is_empty || !self.producer_failures.is_empty())
            && self.servers_pending.is_empty()
            && self
                .diagnostics
                .iter()
                .all(|diagnostic| !diagnostic.provisional)
    }

    fn into_payload(mut self, snapshot: &InspectSnapshot) -> Value {
        self.sort_and_dedup();
        let (errors, warnings, info, hints) = severity_counts(&self.diagnostics);
        let items = self
            .diagnostics
            .iter()
            .map(|diagnostic| diagnostic_item(snapshot, diagnostic))
            .collect::<Vec<_>>();

        let mut payload = serde_json::json!({
            "errors": errors,
            "warnings": warnings,
            "info": info,
            "hints": hints,
            "items": items,
        });

        let mut gaps: Vec<Value> = self
            .producer_failures
            .into_iter()
            .map(|(producer, reason)| {
                serde_json::json!({
                    "kind": "failed_producer",
                    "producer": producer,
                    "reason": reason,
                })
            })
            .collect();
        gaps.extend(self.scope_coverage_gaps.iter().map(|gap| {
            serde_json::json!({
                "kind": "uncovered_file",
                "file": display_path(snapshot, &gap.file),
                "reason": gap.reason,
            })
        }));
        if !gaps.is_empty() {
            payload["complete"] = Value::Bool(false);
            payload["gaps"] = Value::Array(gaps);
        }
        payload
    }

    fn sort_and_dedup(&mut self) {
        self.diagnostics.sort_by(|left, right| {
            left.diagnostic
                .file
                .cmp(&right.diagnostic.file)
                .then(left.diagnostic.line.cmp(&right.diagnostic.line))
                .then(left.diagnostic.column.cmp(&right.diagnostic.column))
                .then(left.diagnostic.end_line.cmp(&right.diagnostic.end_line))
                .then(left.diagnostic.end_column.cmp(&right.diagnostic.end_column))
                .then(left.diagnostic.severity.as_str().cmp(right.diagnostic.severity.as_str()))
                .then(left.diagnostic.message.cmp(&right.diagnostic.message))
                .then(left.diagnostic.source.cmp(&right.diagnostic.source))
                // Prefer an authoritative copy when multiple servers report the
                // same diagnostic, so detail rows do not retain a warming tag.
                .then(left.provisional.cmp(&right.provisional))
        });
        self.diagnostics.dedup_by(|left, right| {
            left.diagnostic.file == right.diagnostic.file
                && left.diagnostic.line == right.diagnostic.line
                && left.diagnostic.column == right.diagnostic.column
                && left.diagnostic.end_line == right.diagnostic.end_line
                && left.diagnostic.end_column == right.diagnostic.end_column
                && left.diagnostic.severity == right.diagnostic.severity
                && left.diagnostic.message == right.diagnostic.message
                && left.diagnostic.source == right.diagnostic.source
        });
    }
}

fn severity_counts(diagnostics: &[CollectedDiagnostic]) -> (usize, usize, usize, usize) {
    severity_counts_filtered(diagnostics, |diagnostic| !diagnostic.provisional)
}

fn severity_counts_filtered(
    diagnostics: &[CollectedDiagnostic],
    include: impl Fn(&CollectedDiagnostic) -> bool,
) -> (usize, usize, usize, usize) {
    let mut errors = 0;
    let mut warnings = 0;
    let mut info = 0;
    let mut hints = 0;

    for diagnostic in diagnostics {
        if !include(diagnostic)
            || crate::lsp::environmental::is_environmental_diagnostic(&diagnostic.diagnostic)
        {
            continue;
        }
        match diagnostic.diagnostic.severity {
            DiagnosticSeverity::Error => errors += 1,
            DiagnosticSeverity::Warning => warnings += 1,
            DiagnosticSeverity::Information => info += 1,
            DiagnosticSeverity::Hint => hints += 1,
        }
    }

    (errors, warnings, info, hints)
}

/// Detail-row message for `aft_inspect` items (file:line:col severity message).
/// Environmental and warming diagnostics are tagged so summary counts and
/// listed rows explain why a row is excluded from authoritative totals.
fn diagnostic_detail_message(diagnostic: &CollectedDiagnostic) -> String {
    let mut message = diagnostic.diagnostic.message.clone();
    if crate::lsp::environmental::is_environmental_diagnostic(&diagnostic.diagnostic) {
        message.push_str(" [environmental]");
    }
    if diagnostic.provisional {
        message.push_str(" (analyzer warming)");
    }
    message
}

fn diagnostic_item(snapshot: &InspectSnapshot, diagnostic: &CollectedDiagnostic) -> Value {
    serde_json::json!({
        "file": display_path(snapshot, &diagnostic.diagnostic.file),
        "line": diagnostic.diagnostic.line,
        "column": diagnostic.diagnostic.column,
        "severity": diagnostic.diagnostic.severity.as_str(),
        "message": diagnostic_detail_message(diagnostic),
        "source": diagnostic.diagnostic.source.as_deref().unwrap_or("lsp"),
    })
}

fn display_path(snapshot: &InspectSnapshot, path: &Path) -> String {
    path.strip_prefix(&snapshot.project_root)
        .unwrap_or(path)
        .to_string_lossy()
        .replace('\\', "/")
}

fn server_id(key: &ServerKey) -> String {
    key.kind.id_str().to_string()
}

#[cfg(test)]
mod payload_count_tests {
    use std::path::PathBuf;
    use std::sync::{Arc, RwLock};

    use super::{
        check_diagnostics_phase_boundary, diagnostics_phase_timeout, CollectedDiagnostic,
        DiagnosticsCollection, ScopedCoverageGap,
    };
    use crate::config::Config;
    use crate::inspect::job::{InspectSnapshot, JobScope};
    use crate::lsp::diagnostics::{DiagnosticSeverity, StoredDiagnostic};
    use crate::parser::SymbolCache;

    fn snapshot() -> InspectSnapshot {
        InspectSnapshot::new(
            PathBuf::from("/repo"),
            PathBuf::from("/repo/.aft"),
            Arc::new(Config::default()),
            Arc::new(RwLock::new(SymbolCache::new())),
        )
    }

    fn collection() -> DiagnosticsCollection {
        DiagnosticsCollection {
            diagnostics: vec![CollectedDiagnostic {
                diagnostic: StoredDiagnostic {
                    file: PathBuf::from("/repo/src/main.rs"),
                    line: 1,
                    column: 1,
                    end_line: 1,
                    end_column: 2,
                    severity: DiagnosticSeverity::Error,
                    message: "verified result".into(),
                    code: None,
                    source: None,
                },
                provisional: false,
            }],
            server_ran: true,
            ..DiagnosticsCollection::default()
        }
    }

    #[test]
    fn configured_diagnostics_deadline_drives_the_blocking_phase_boundary() {
        let config = Config {
            inspect: crate::config::InspectConfig {
                diagnostics_timeout_ms: 15_000,
                ..crate::config::InspectConfig::default()
            },
            ..Config::default()
        };
        let timeout = diagnostics_phase_timeout(&config);

        assert_eq!(timeout, std::time::Duration::from_millis(15_000));
        assert_eq!(
            check_diagnostics_phase_boundary(std::time::Instant::now(), timeout),
            Err("lsp_quiescence_timeout: diagnostics did not complete within 15000ms".to_string())
        );
    }

    #[test]
    fn empty_applicability_is_vacuously_complete() {
        let collection = DiagnosticsCollection {
            applicability_is_empty: true,
            ..DiagnosticsCollection::default()
        };

        assert!(collection.is_complete());
    }

    #[test]
    fn incomplete_collection_cannot_be_promoted_to_a_payload() {
        let mut collection = collection();
        collection.servers_pending.insert("rust-analyzer".into());
        assert!(!collection.is_complete());
    }

    #[test]
    fn provisional_collection_cannot_be_promoted_to_a_payload() {
        let mut collection = collection();
        collection.diagnostics[0].provisional = true;
        assert!(!collection.is_complete());
    }

    #[test]
    fn fresh_payload_contains_only_authoritative_counts_and_items() {
        let payload = collection().into_payload(&snapshot());
        assert_eq!(payload["errors"], 1);
        assert_eq!(payload["warnings"], 0);
        assert!(payload.get("server_ran").is_none());
        assert!(payload.get("complete").is_none());
        assert!(payload.get("status").is_none());
        assert!(payload.get("provisional_counts").is_none());
    }

    #[test]
    fn terminal_producer_failure_is_a_reportable_named_gap() {
        let mut collection = collection();
        collection
            .producer_failures
            .insert("astro".into(), "initialize failed".into());

        assert!(collection.is_reportable());
        assert!(!collection.is_complete());
        let payload = collection.into_payload(&snapshot());
        assert_eq!(payload["complete"], false);
        assert_eq!(payload["gaps"][0]["kind"], "failed_producer");
        assert_eq!(payload["gaps"][0]["producer"], "astro");
        assert_eq!(payload["gaps"][0]["reason"], "initialize failed");
    }

    #[test]
    fn scope_filter_keeps_only_in_scope_authoritative_findings() {
        let mut collection = collection();
        collection.diagnostics.push(CollectedDiagnostic {
            diagnostic: StoredDiagnostic {
                file: PathBuf::from("/repo/other/outside.rs"),
                line: 1,
                column: 1,
                end_line: 1,
                end_column: 2,
                severity: DiagnosticSeverity::Error,
                message: "outside scope".into(),
                code: None,
                source: None,
            },
            provisional: false,
        });
        collection.diagnostics.push(CollectedDiagnostic {
            diagnostic: StoredDiagnostic {
                file: PathBuf::from("/repo/src/main.rs"),
                line: 9,
                column: 1,
                end_line: 9,
                end_column: 2,
                severity: DiagnosticSeverity::Warning,
                message: "warming lead".into(),
                code: None,
                source: None,
            },
            provisional: true,
        });

        let scope = JobScope::from_roots(
            PathBuf::from("/repo"),
            vec![PathBuf::from("/repo/src/main.rs")],
        );
        collection.apply_scope(&scope);

        assert_eq!(
            collection.diagnostics.len(),
            1,
            "scope must drop out-of-scope rows and warming rows"
        );
        assert_eq!(
            collection.diagnostics[0].diagnostic.file,
            PathBuf::from("/repo/src/main.rs")
        );
        assert!(!collection.diagnostics[0].provisional);
    }

    #[test]
    fn scope_coverage_gap_renders_a_named_incomplete_file() {
        let mut collection = collection();
        collection.scope_coverage_gaps.push(ScopedCoverageGap {
            file: PathBuf::from("/repo/src/lib.rs"),
            reason: "no LSP producer has a current diagnostic report for this file",
        });

        let payload = collection.into_payload(&snapshot());
        assert_eq!(payload["complete"], false);
        let gap = payload["gaps"]
            .as_array()
            .and_then(|gaps| gaps.iter().find(|gap| gap["kind"] == "uncovered_file"))
            .expect("uncovered_file gap");
        assert_eq!(gap["file"], "src/lib.rs");
        assert_eq!(
            gap["reason"],
            "no LSP producer has a current diagnostic report for this file"
        );
    }
}

#[cfg(test)]
mod environmental_count_tests {
    use std::path::PathBuf;

    use super::{severity_counts, CollectedDiagnostic};
    use crate::lsp::diagnostics::{DiagnosticSeverity, StoredDiagnostic};

    fn diag(line: u32, message: &str) -> StoredDiagnostic {
        StoredDiagnostic {
            file: PathBuf::from("/repo/src/mixed.ts"),
            line,
            column: 1,
            end_line: line,
            end_column: 2,
            severity: DiagnosticSeverity::Error,
            message: message.into(),
            code: None,
            source: None,
        }
    }

    #[test]
    fn severity_counts_exclude_environmental_on_same_file() {
        let diagnostics = vec![
            CollectedDiagnostic {
                diagnostic: diag(1, "Cannot find name 'x'."),
                provisional: false,
            },
            CollectedDiagnostic {
                diagnostic: diag(
                    2,
                    "Failed to load schema from https://example.com/schema.json",
                ),
                provisional: false,
            },
        ];
        let (errors, warnings, _, _) = severity_counts(&diagnostics);
        assert_eq!(
            errors, 1,
            "inspect summary must count only non-environmental errors"
        );
        assert_eq!(warnings, 0);
    }
}

#[cfg(test)]
mod environmental_render_tests {
    use std::path::PathBuf;
    use std::sync::{Arc, RwLock};

    use super::diagnostic_item;
    use crate::config::Config;
    use crate::inspect::job::InspectSnapshot;
    use crate::lsp::diagnostics::{DiagnosticSeverity, StoredDiagnostic};
    use crate::parser::SymbolCache;

    fn snapshot() -> InspectSnapshot {
        InspectSnapshot::new(
            PathBuf::from("/repo"),
            PathBuf::from("/repo/.aft"),
            Arc::new(Config::default()),
            Arc::new(RwLock::new(SymbolCache::new())),
        )
    }

    fn stored(message: &str) -> StoredDiagnostic {
        StoredDiagnostic {
            file: PathBuf::from("/repo/package.json"),
            line: 2,
            column: 5,
            end_line: 2,
            end_column: 6,
            severity: DiagnosticSeverity::Error,
            message: message.into(),
            code: None,
            source: Some("json".into()),
        }
    }

    #[test]
    fn detail_row_tags_environmental_message() {
        let item = diagnostic_item(
            &snapshot(),
            &super::CollectedDiagnostic {
                diagnostic: stored("Failed to load schema from https://example.com/schema.json"),
                provisional: false,
            },
        );
        assert_eq!(
            item["message"].as_str(),
            Some("Failed to load schema from https://example.com/schema.json [environmental]")
        );
    }

    #[test]
    fn detail_row_leaves_real_errors_untagged() {
        let item = diagnostic_item(
            &snapshot(),
            &super::CollectedDiagnostic {
                diagnostic: stored("Cannot find name 'typo'."),
                provisional: false,
            },
        );
        assert_eq!(item["message"].as_str(), Some("Cannot find name 'typo'."));
    }

    #[test]
    fn detail_row_tags_warming_diagnostics() {
        let item = diagnostic_item(
            &snapshot(),
            &super::CollectedDiagnostic {
                diagnostic: stored("temporary analyzer result"),
                provisional: true,
            },
        );
        assert_eq!(
            item["message"].as_str(),
            Some("temporary analyzer result (analyzer warming)")
        );
    }
}