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
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::time::Instant;
use crate::lsp::registry::ServerKind;
use crate::lsp::roots::ServerKey;
/// A single diagnostic from an LSP server.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StoredDiagnostic {
pub file: PathBuf,
pub line: u32,
pub column: u32,
pub end_line: u32,
pub end_column: u32,
pub severity: DiagnosticSeverity,
pub message: String,
pub code: Option<String>,
pub source: Option<String>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DiagnosticSeverity {
Error,
Warning,
Information,
Hint,
}
impl DiagnosticSeverity {
pub fn as_str(self) -> &'static str {
match self {
Self::Error => "error",
Self::Warning => "warning",
Self::Information => "information",
Self::Hint => "hint",
}
}
}
/// One server's published diagnostics for one file, plus bookkeeping that
/// distinguishes "checked clean" (`diagnostics.is_empty()` AND
/// `epoch.is_some()`) from "never checked" (entry not present).
#[derive(Debug, Clone)]
pub struct DiagnosticEntry {
pub diagnostics: Vec<StoredDiagnostic>,
/// Monotonic epoch when this entry was last replaced by a publish or
/// pull response. Used by callers to tell "fresh" results apart from
/// stale cache contents.
pub epoch: u64,
/// Optional resultId from a pull response. Sent back as `previousResultId`
/// on the next pull request to enable `kind: "unchanged"` short-circuiting.
pub result_id: Option<String>,
/// Document version this publish/pull was tagged against, when the
/// server provided one. Servers that participate in versioned text
/// document sync echo `version` on `publishDiagnostics`; we store it
/// so post-edit waiters can reject stale publishes deterministically
/// (`version == target_version`) instead of relying on epoch ordering
/// alone, which has a race when an old-version publish arrives after
/// the pre-edit drain. `None` = server didn't tag the publish.
pub version: Option<i32>,
}
/// Stores diagnostics from all LSP servers, keyed per `(ServerKey, file)`.
///
/// Key design points (driven by the v0.16 LSP audit):
///
/// 1. **Per-server state.** A single file can be served by multiple LSP
/// servers (e.g., pyright + ty, or tsserver + ESLint). The cache key is
/// `(ServerKey, PathBuf)` so each server's view is tracked independently.
///
/// 2. **Empty publishes are kept.** Earlier the store deleted entries on
/// empty publishes, making "checked clean" indistinguishable from "never
/// checked". Now we preserve the entry with `epoch = ...` so callers can
/// answer the question honestly.
///
/// 3. **LRU cap.** `capacity` (default 5000, configurable via
/// `Config::diagnostic_cache_size`) bounds memory. Set to 0 to disable.
/// On insert when at capacity, the least-recently-touched entry is
/// evicted. Eviction is tracked so directory-mode callers can list
/// those files as `unchecked` rather than silently lose them.
pub struct DiagnosticsStore {
/// Primary store keyed by `(ServerKey, canonical file path)`.
entries: HashMap<(ServerKey, PathBuf), DiagnosticEntry>,
/// Insertion/access order for LRU eviction. Most-recently-touched
/// entries are at the END of the vector.
order: Vec<(ServerKey, PathBuf)>,
/// Maximum number of entries before LRU eviction kicks in. 0 = no cap.
capacity: usize,
/// Monotonic epoch counter. Incremented on every publish.
next_epoch: u64,
/// Last time a server published/replaced diagnostics for a specific file.
/// Used as a per-file freshness proof for push-only servers.
last_publish_at_for_file: HashMap<(ServerKey, PathBuf), Instant>,
}
impl DiagnosticsStore {
pub fn new() -> Self {
Self::with_capacity(5000)
}
pub fn with_capacity(capacity: usize) -> Self {
Self {
entries: HashMap::new(),
order: Vec::new(),
capacity,
next_epoch: 0,
last_publish_at_for_file: HashMap::new(),
}
}
/// Set or change the LRU cap. If the new cap is smaller than the
/// current entry count, the oldest entries are evicted immediately
/// to fit.
pub fn set_capacity(&mut self, capacity: usize) {
self.capacity = capacity;
if capacity > 0 {
while self.entries.len() > capacity {
self.evict_lru();
}
}
}
/// Number of currently-tracked entries.
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
/// Replace diagnostics for a `(server_kind, file)` pair using the
/// server's lifecycle root from the active manager. Empty diagnostics
/// are preserved as "checked clean" (NOT deleted as before).
///
/// Note: the `(server, file)` key uses `ServerKey { kind, root }` so
/// concurrent multi-workspace usage doesn't collapse different roots.
/// Callers without the root (legacy push handler) should call
/// `publish_with_kind` which derives the key.
pub fn publish(
&mut self,
server: ServerKey,
file: PathBuf,
diagnostics: Vec<StoredDiagnostic>,
) {
self.publish_with_result_id(server, file, diagnostics, None);
}
/// Replace diagnostics and record a pull `resultId` for the next
/// request. Empty diagnostics are preserved as "checked clean".
pub fn publish_with_result_id(
&mut self,
server: ServerKey,
file: PathBuf,
diagnostics: Vec<StoredDiagnostic>,
result_id: Option<String>,
) {
self.publish_full(server, file, diagnostics, result_id, None);
}
/// Replace diagnostics with full provenance (resultId + document version).
/// `version` should be the LSP `version` field from `publishDiagnostics`
/// when the server provided one, or `None` otherwise.
pub fn publish_full(
&mut self,
server: ServerKey,
file: PathBuf,
diagnostics: Vec<StoredDiagnostic>,
result_id: Option<String>,
version: Option<i32>,
) {
let key = (server, file);
self.next_epoch = self.next_epoch.saturating_add(1);
let entry = DiagnosticEntry {
diagnostics,
epoch: self.next_epoch,
result_id,
version,
};
self.last_publish_at_for_file
.insert(key.clone(), Instant::now());
if self.entries.contains_key(&key) {
self.entries.insert(key.clone(), entry);
self.touch_existing(&key);
} else {
// New entry — apply LRU cap before inserting.
if self.capacity > 0 && self.entries.len() >= self.capacity {
self.evict_lru();
}
self.entries.insert(key.clone(), entry);
self.order.push(key);
}
}
/// Compatibility wrapper for the legacy push path that knows only the
/// `ServerKind`. Builds a `ServerKey` with an empty root, which is
/// adequate for the single-root-per-kind case the manager currently
/// uses for push diagnostics. Multi-root callers should use
/// `publish` directly with a real `ServerKey`.
pub fn publish_with_kind(
&mut self,
kind: ServerKind,
file: PathBuf,
diagnostics: Vec<StoredDiagnostic>,
) {
let key = ServerKey {
kind,
root: PathBuf::new(),
};
self.publish(key, file, diagnostics);
}
/// Get all diagnostics for a specific file (across all servers).
/// Updates LRU position for each touched entry.
pub fn for_file(&self, file: &Path) -> Vec<&StoredDiagnostic> {
self.entries
.iter()
.filter(|((_, stored_file), _)| stored_file == file)
.flat_map(|(_, entry)| entry.diagnostics.iter())
.collect()
}
/// Get the full per-server entry for a file. Useful when callers need
/// to know epoch/resultId, not just the diagnostics array.
pub fn entries_for_file(&self, file: &Path) -> Vec<(&ServerKey, &DiagnosticEntry)> {
self.entries
.iter()
.filter(|((_, stored_file), _)| stored_file == file)
.map(|((key, _), entry)| (key, entry))
.collect()
}
/// True if any server has reported (even an empty result) for this file.
pub fn has_any_report_for_file(&self, file: &Path) -> bool {
self.entries.keys().any(|(_, f)| f == file)
}
/// True if this exact server instance has reported (even an empty result)
/// for this exact file.
pub fn has_report_for_server_file(&self, server: &ServerKey, file: &Path) -> bool {
self.entries
.contains_key(&(server.clone(), file.to_path_buf()))
}
/// True if this exact server instance published/replaced diagnostics for
/// this exact file after `since`. This is intentionally per `(kind, root,
/// file)`; a publish for another file must not prove freshness here.
pub fn has_publish_for_file_after(
&self,
server: &ServerKey,
file: &Path,
since: Instant,
) -> bool {
self.last_publish_at_for_file
.get(&(server.clone(), file.to_path_buf()))
.is_some_and(|published_at| *published_at >= since)
}
/// Get all diagnostics for files under a directory.
pub fn for_directory(&self, dir: &Path) -> Vec<&StoredDiagnostic> {
self.entries
.iter()
.filter(|((_, stored_file), _)| stored_file.starts_with(dir))
.flat_map(|(_, entry)| entry.diagnostics.iter())
.collect()
}
/// All stored diagnostics, flattened.
pub fn all(&self) -> Vec<&StoredDiagnostic> {
self.entries
.values()
.flat_map(|entry| entry.diagnostics.iter())
.collect()
}
/// Count of errors and warnings across the entire warm set (every file any
/// server has published for). Allocation-free — the raw, unfiltered union.
/// Callers that want the agent-status-bar semantics (project-root scoped,
/// tsconfig-membership filtered, cross-server deduped) should use
/// [`filtered_error_warning_counts`](Self::filtered_error_warning_counts).
pub fn error_warning_counts(&self) -> (usize, usize) {
let mut errors = 0usize;
let mut warnings = 0usize;
for entry in self.entries.values() {
for diagnostic in &entry.diagnostics {
match diagnostic.severity {
DiagnosticSeverity::Error => errors += 1,
DiagnosticSeverity::Warning => warnings += 1,
_ => {}
}
}
}
(errors, warnings)
}
/// Error/warning counts after applying a per-file `keep` predicate and
/// de-duplicating diagnostics that multiple servers reported for the same
/// location. This matches `aft_inspect`'s warm semantics
/// (`inspect/diagnostics_category.rs`: project-root filter +
/// tsconfig-membership skip + `sort_and_dedup`) so the agent status bar's
/// E/W agree with `aft_inspect`/`tsc` instead of counting build-excluded
/// files and double-counting multi-server overlaps.
///
/// The store itself holds no tsconfig/project policy — the caller encodes
/// it in `keep` (see `LspManager::filtered_error_warning_counts`). `keep`
/// is `FnMut` because the membership cache resolves lazily.
pub fn filtered_error_warning_counts(
&self,
mut keep: impl FnMut(&Path) -> bool,
) -> (usize, usize) {
// Dedup key mirrors `sort_and_dedup` in inspect/diagnostics_category.rs
// exactly (file, range, severity, message, source) so the bar and
// inspect collapse the same multi-server overlaps.
let mut seen: std::collections::HashSet<(
&Path,
u32,
u32,
u32,
u32,
&str,
&str,
Option<&str>,
)> = std::collections::HashSet::new();
let mut errors = 0usize;
let mut warnings = 0usize;
for ((_, file), entry) in &self.entries {
// All diagnostics in an entry share the entry's file, so the keep
// predicate (the cost center: tsconfig resolution) runs once per
// (server, file) entry, not once per diagnostic.
if !keep(file) {
continue;
}
for diagnostic in &entry.diagnostics {
let dedup_key = (
diagnostic.file.as_path(),
diagnostic.line,
diagnostic.column,
diagnostic.end_line,
diagnostic.end_column,
diagnostic.severity.as_str(),
diagnostic.message.as_str(),
diagnostic.source.as_deref(),
);
if !seen.insert(dedup_key) {
continue;
}
match diagnostic.severity {
DiagnosticSeverity::Error => errors += 1,
DiagnosticSeverity::Warning => warnings += 1,
_ => {}
}
}
}
(errors, warnings)
}
/// Drop all entries for a server kind (e.g., on server crash/restart).
/// Prefer `clear_for_server` for real manager cleanup so peer roots of the
/// same kind are not wiped.
pub fn clear_server(&mut self, server: ServerKind) {
self.entries
.retain(|(stored_key, _), _| stored_key.kind != server);
self.order
.retain(|(stored_key, _)| stored_key.kind != server);
self.last_publish_at_for_file
.retain(|(stored_key, _), _| stored_key.kind != server);
}
/// Drop one cached report for a specific server/file pair.
pub fn clear_for_server_file(&mut self, key: &ServerKey, file: &Path) {
let cache_key = (key.clone(), file.to_path_buf());
self.entries.remove(&cache_key);
self.order.retain(|entry_key| entry_key != &cache_key);
self.last_publish_at_for_file.remove(&cache_key);
}
/// Drop every cached report for a file across all servers. Used when a file
/// is deleted/renamed away — its diagnostics would otherwise linger in the
/// warm set forever (no server republishes for a path that no longer
/// exists), inflating the error/warning counts surfaced in the status bar
/// and `aft_inspect`. Returns true if any entry was removed.
pub fn clear_for_file(&mut self, file: &Path) -> bool {
let before = self.entries.len();
self.entries
.retain(|(_, stored_file), _| stored_file != file);
let removed = self.entries.len() != before;
if removed {
self.order.retain(|(_, stored_file)| stored_file != file);
self.last_publish_at_for_file
.retain(|(_, stored_file), _| stored_file != file);
}
removed
}
/// Drop all entries for a specific server instance.
pub fn clear_for_server(&mut self, key: &ServerKey) {
self.entries.retain(|(k, _), _| k != key);
self.order.retain(|(k, _)| k != key);
self.last_publish_at_for_file.retain(|(k, _), _| k != key);
}
/// Backward-compatible alias for tests/callers that already used the
/// instance-scoped name.
pub fn clear_server_instance(&mut self, key: &ServerKey) {
self.clear_for_server(key);
}
/// Remove the least-recently-used entry, returning its key for telemetry.
fn evict_lru(&mut self) -> Option<(ServerKey, PathBuf)> {
if self.order.is_empty() {
return None;
}
let evicted = self.order.remove(0);
self.entries.remove(&evicted);
self.last_publish_at_for_file.remove(&evicted);
Some(evicted)
}
fn touch_existing(&mut self, key: &(ServerKey, PathBuf)) {
if let Some(idx) = self.order.iter().position(|k| k == key) {
let removed = self.order.remove(idx);
self.order.push(removed);
}
}
}
impl Default for DiagnosticsStore {
fn default() -> Self {
Self::new()
}
}
/// Convert LSP diagnostics to our stored format.
/// LSP uses 0-based line/character; we convert to 1-based.
pub fn from_lsp_diagnostics(
file: PathBuf,
lsp_diagnostics: Vec<lsp_types::Diagnostic>,
) -> Vec<StoredDiagnostic> {
lsp_diagnostics
.into_iter()
.map(|diagnostic| StoredDiagnostic {
file: file.clone(),
line: diagnostic.range.start.line + 1,
column: diagnostic.range.start.character + 1,
end_line: diagnostic.range.end.line + 1,
end_column: diagnostic.range.end.character + 1,
severity: match diagnostic.severity {
Some(lsp_types::DiagnosticSeverity::ERROR) => DiagnosticSeverity::Error,
Some(lsp_types::DiagnosticSeverity::WARNING) => DiagnosticSeverity::Warning,
Some(lsp_types::DiagnosticSeverity::INFORMATION) => DiagnosticSeverity::Information,
Some(lsp_types::DiagnosticSeverity::HINT) => DiagnosticSeverity::Hint,
_ => DiagnosticSeverity::Warning,
},
message: diagnostic.message,
code: diagnostic.code.map(|code| match code {
lsp_types::NumberOrString::Number(value) => value.to_string(),
lsp_types::NumberOrString::String(value) => value,
}),
source: diagnostic.source,
})
.collect()
}
#[cfg(test)]
mod tests {
use std::path::{Path, PathBuf};
use lsp_types::{
Diagnostic, DiagnosticSeverity as LspDiagnosticSeverity, NumberOrString, Position, Range,
};
use super::{from_lsp_diagnostics, DiagnosticSeverity, DiagnosticsStore, StoredDiagnostic};
use crate::lsp::registry::ServerKind;
use crate::lsp::roots::ServerKey;
fn server_key(kind: ServerKind) -> ServerKey {
ServerKey {
kind,
root: PathBuf::from("/tmp/repo"),
}
}
fn diag(file: &str, line: u32, msg: &str, sev: DiagnosticSeverity) -> StoredDiagnostic {
StoredDiagnostic {
file: PathBuf::from(file),
line,
column: 1,
end_line: line,
end_column: 2,
severity: sev,
message: msg.into(),
code: None,
source: None,
}
}
#[test]
fn converts_lsp_positions_to_one_based() {
let file = PathBuf::from("/tmp/demo.rs");
let diagnostics = from_lsp_diagnostics(
file.clone(),
vec![Diagnostic {
range: Range::new(Position::new(0, 0), Position::new(1, 4)),
severity: Some(LspDiagnosticSeverity::ERROR),
code: Some(NumberOrString::String("E1".into())),
code_description: None,
source: Some("fake".into()),
message: "boom".into(),
related_information: None,
tags: None,
data: None,
}],
);
assert_eq!(diagnostics.len(), 1);
assert_eq!(diagnostics[0].file, file);
assert_eq!(diagnostics[0].line, 1);
assert_eq!(diagnostics[0].column, 1);
assert_eq!(diagnostics[0].end_line, 2);
assert_eq!(diagnostics[0].end_column, 5);
assert_eq!(diagnostics[0].severity, DiagnosticSeverity::Error);
assert_eq!(diagnostics[0].code.as_deref(), Some("E1"));
}
#[test]
fn publish_replaces_existing_file_diagnostics() {
let file = PathBuf::from("/tmp/demo.rs");
let mut store = DiagnosticsStore::new();
let key = server_key(ServerKind::Rust);
store.publish(
key.clone(),
file.clone(),
vec![diag(
"/tmp/demo.rs",
1,
"first",
DiagnosticSeverity::Warning,
)],
);
store.publish(
key.clone(),
file.clone(),
vec![diag("/tmp/demo.rs", 2, "second", DiagnosticSeverity::Error)],
);
let stored = store.for_file(&file);
assert_eq!(stored.len(), 1);
assert_eq!(stored[0].message, "second");
}
#[test]
fn empty_publish_is_preserved_as_checked_clean() {
// The whole point of the v0.16 audit fix: empty publish ≠ deletion.
// Agents need to be able to ask "has this file been checked yet?"
// and get a truthful answer.
let file = PathBuf::from("/tmp/clean.rs");
let mut store = DiagnosticsStore::new();
let key = server_key(ServerKind::Rust);
// First publish has an issue.
store.publish(
key.clone(),
file.clone(),
vec![diag(
"/tmp/clean.rs",
5,
"fix me",
DiagnosticSeverity::Warning,
)],
);
assert!(store.has_any_report_for_file(&file));
assert_eq!(store.for_file(&file).len(), 1);
// Second publish is empty (the fix worked). Entry is preserved as
// "checked clean" rather than deleted.
store.publish(key.clone(), file.clone(), Vec::new());
assert!(
store.has_any_report_for_file(&file),
"checked-clean must be distinguishable from never-checked"
);
assert_eq!(store.for_file(&file).len(), 0);
let entries = store.entries_for_file(&file);
assert_eq!(entries.len(), 1);
assert!(entries[0].1.epoch > 0);
}
#[test]
fn never_checked_returns_no_report() {
let store = DiagnosticsStore::new();
let file = PathBuf::from("/tmp/never.rs");
assert!(!store.has_any_report_for_file(&file));
assert!(store.for_file(&file).is_empty());
}
#[test]
fn per_server_state_is_tracked_independently() {
let file = PathBuf::from("/tmp/multi.py");
let mut store = DiagnosticsStore::new();
let pyright_key = server_key(ServerKind::Python);
let ty_key = server_key(ServerKind::Ty);
store.publish(
pyright_key,
file.clone(),
vec![diag(
"/tmp/multi.py",
1,
"pyright says X",
DiagnosticSeverity::Error,
)],
);
store.publish(
ty_key,
file.clone(),
vec![diag(
"/tmp/multi.py",
2,
"ty says Y",
DiagnosticSeverity::Warning,
)],
);
let messages: Vec<&str> = store
.for_file(&file)
.into_iter()
.map(|d| d.message.as_str())
.collect();
assert_eq!(messages.len(), 2, "both servers' reports preserved");
assert!(messages.iter().any(|m| m == &"pyright says X"));
assert!(messages.iter().any(|m| m == &"ty says Y"));
}
#[test]
fn clear_for_server_file_removes_only_exact_entry() {
let file_a = PathBuf::from("/tmp/a.rs");
let file_b = PathBuf::from("/tmp/b.rs");
let mut store = DiagnosticsStore::new();
let rust_key = server_key(ServerKind::Rust);
let py_key = server_key(ServerKind::Python);
store.publish(
rust_key.clone(),
file_a.clone(),
vec![diag("/tmp/a.rs", 1, "rust a", DiagnosticSeverity::Error)],
);
store.publish(
rust_key.clone(),
file_b.clone(),
vec![diag("/tmp/b.rs", 1, "rust b", DiagnosticSeverity::Warning)],
);
store.publish(
py_key.clone(),
file_a.clone(),
vec![diag("/tmp/a.rs", 2, "py a", DiagnosticSeverity::Warning)],
);
store.clear_for_server_file(&rust_key, &file_a);
assert!(!store.has_report_for_server_file(&rust_key, &file_a));
assert!(store.has_report_for_server_file(&rust_key, &file_b));
assert!(store.has_report_for_server_file(&py_key, &file_a));
}
#[test]
fn lru_evicts_oldest_when_capacity_exceeded() {
let mut store = DiagnosticsStore::with_capacity(2);
let key = server_key(ServerKind::Rust);
store.publish(
key.clone(),
PathBuf::from("/a.rs"),
vec![diag("/a.rs", 1, "a", DiagnosticSeverity::Warning)],
);
store.publish(
key.clone(),
PathBuf::from("/b.rs"),
vec![diag("/b.rs", 1, "b", DiagnosticSeverity::Warning)],
);
assert_eq!(store.len(), 2);
// Inserting a third entry should evict /a.rs (oldest).
store.publish(
key.clone(),
PathBuf::from("/c.rs"),
vec![diag("/c.rs", 1, "c", DiagnosticSeverity::Warning)],
);
assert_eq!(store.len(), 2);
assert!(!store.has_any_report_for_file(Path::new("/a.rs")));
assert!(store.has_any_report_for_file(Path::new("/b.rs")));
assert!(store.has_any_report_for_file(Path::new("/c.rs")));
}
#[test]
fn touching_existing_entry_moves_it_to_end_of_lru() {
let mut store = DiagnosticsStore::with_capacity(2);
let key = server_key(ServerKind::Rust);
store.publish(
key.clone(),
PathBuf::from("/a.rs"),
vec![diag("/a.rs", 1, "a", DiagnosticSeverity::Warning)],
);
store.publish(
key.clone(),
PathBuf::from("/b.rs"),
vec![diag("/b.rs", 1, "b", DiagnosticSeverity::Warning)],
);
// Re-publish /a.rs — this should refresh its LRU position so it's
// newer than /b.rs. Inserting /c.rs should now evict /b.rs.
store.publish(
key.clone(),
PathBuf::from("/a.rs"),
vec![diag("/a.rs", 1, "a2", DiagnosticSeverity::Error)],
);
store.publish(
key.clone(),
PathBuf::from("/c.rs"),
vec![diag("/c.rs", 1, "c", DiagnosticSeverity::Warning)],
);
assert!(store.has_any_report_for_file(Path::new("/a.rs")));
assert!(!store.has_any_report_for_file(Path::new("/b.rs")));
assert!(store.has_any_report_for_file(Path::new("/c.rs")));
}
#[test]
fn capacity_zero_disables_eviction() {
let mut store = DiagnosticsStore::with_capacity(0);
let key = server_key(ServerKind::Rust);
for i in 0..50 {
store.publish(
key.clone(),
PathBuf::from(format!("/f{i}.rs")),
vec![diag(
&format!("/f{i}.rs"),
1,
"x",
DiagnosticSeverity::Warning,
)],
);
}
assert_eq!(store.len(), 50);
}
#[test]
fn set_capacity_evicts_on_shrink() {
let mut store = DiagnosticsStore::with_capacity(0);
let key = server_key(ServerKind::Rust);
for i in 0..10 {
store.publish(
key.clone(),
PathBuf::from(format!("/f{i}.rs")),
vec![diag(
&format!("/f{i}.rs"),
1,
"x",
DiagnosticSeverity::Warning,
)],
);
}
assert_eq!(store.len(), 10);
store.set_capacity(3);
assert_eq!(store.len(), 3);
// Most recent 3 should remain (/f7.rs, /f8.rs, /f9.rs).
assert!(store.has_any_report_for_file(Path::new("/f9.rs")));
assert!(!store.has_any_report_for_file(Path::new("/f0.rs")));
}
#[test]
fn epoch_increments_monotonically() {
let mut store = DiagnosticsStore::new();
let key = server_key(ServerKind::Rust);
let file = PathBuf::from("/e.rs");
store.publish(key.clone(), file.clone(), Vec::new());
let e1 = store.entries_for_file(&file)[0].1.epoch;
store.publish(key.clone(), file.clone(), Vec::new());
let e2 = store.entries_for_file(&file)[0].1.epoch;
assert!(e2 > e1, "epoch must increase on republish");
}
#[test]
fn result_id_is_round_tripped() {
let mut store = DiagnosticsStore::new();
let key = server_key(ServerKind::Rust);
let file = PathBuf::from("/r.rs");
store.publish_with_result_id(
key.clone(),
file.clone(),
Vec::new(),
Some("rev-42".to_string()),
);
let entries = store.entries_for_file(&file);
assert_eq!(entries[0].1.result_id.as_deref(), Some("rev-42"));
}
#[test]
fn clear_server_drops_all_entries_for_kind() {
let mut store = DiagnosticsStore::new();
let py_key = server_key(ServerKind::Python);
let rust_key = server_key(ServerKind::Rust);
store.publish(
py_key.clone(),
PathBuf::from("/a.py"),
vec![diag("/a.py", 1, "x", DiagnosticSeverity::Error)],
);
store.publish(
rust_key.clone(),
PathBuf::from("/b.rs"),
vec![diag("/b.rs", 1, "y", DiagnosticSeverity::Error)],
);
store.clear_server(ServerKind::Python);
assert!(!store.has_any_report_for_file(Path::new("/a.py")));
assert!(store.has_any_report_for_file(Path::new("/b.rs")));
}
#[test]
fn clear_for_file_drops_every_server_entry_and_updates_counts() {
let mut store = DiagnosticsStore::new();
let py_key = server_key(ServerKind::Python);
let biome_key = server_key(ServerKind::Biome);
// Two servers both report for the SAME deleted file, plus an unrelated
// file that must survive.
store.publish(
py_key,
PathBuf::from("/gone.ts"),
vec![diag("/gone.ts", 4, "type error", DiagnosticSeverity::Error)],
);
store.publish(
biome_key,
PathBuf::from("/gone.ts"),
vec![diag(
"/gone.ts",
7,
"lint warning",
DiagnosticSeverity::Warning,
)],
);
store.publish(
server_key(ServerKind::Rust),
PathBuf::from("/keep.rs"),
vec![diag("/keep.rs", 1, "live error", DiagnosticSeverity::Error)],
);
assert_eq!(store.error_warning_counts(), (2, 1));
// Clearing the deleted file drops both server entries for it.
let removed = store.clear_for_file(Path::new("/gone.ts"));
assert!(removed);
assert!(!store.has_any_report_for_file(Path::new("/gone.ts")));
// The unrelated file's diagnostic is untouched.
assert!(store.has_any_report_for_file(Path::new("/keep.rs")));
assert_eq!(store.error_warning_counts(), (1, 0));
// Clearing again is a no-op (nothing left for that file).
assert!(!store.clear_for_file(Path::new("/gone.ts")));
}
#[test]
fn filtered_counts_apply_keep_predicate() {
let mut store = DiagnosticsStore::new();
store.publish(
server_key(ServerKind::TypeScript),
PathBuf::from("/repo/src/app.ts"),
vec![diag(
"/repo/src/app.ts",
1,
"in build",
DiagnosticSeverity::Error,
)],
);
store.publish(
server_key(ServerKind::TypeScript),
PathBuf::from("/repo/src/app.test.ts"),
vec![diag(
"/repo/src/app.test.ts",
1,
"excluded",
DiagnosticSeverity::Error,
)],
);
// Raw count sees both files.
assert_eq!(store.error_warning_counts(), (2, 0));
// Filtered count drops the build-excluded test file.
let counts = store.filtered_error_warning_counts(|file| !file.ends_with("app.test.ts"));
assert_eq!(counts, (1, 0));
}
#[test]
fn filtered_counts_dedup_across_servers() {
let mut store = DiagnosticsStore::new();
let file = "/repo/src/app.ts";
// Two different servers report the SAME diagnostic (same file/range/
// severity/message/source) for one file — e.g. tsserver + a linter that
// both surface an identical issue. Raw counting double-counts; the
// status-bar count must collapse to one (matching inspect sort_and_dedup).
store.publish(
server_key(ServerKind::TypeScript),
PathBuf::from(file),
vec![diag(file, 7, "dup", DiagnosticSeverity::Error)],
);
store.publish(
server_key(ServerKind::Biome),
PathBuf::from(file),
vec![diag(file, 7, "dup", DiagnosticSeverity::Error)],
);
assert_eq!(store.error_warning_counts(), (2, 0));
assert_eq!(store.filtered_error_warning_counts(|_| true), (1, 0));
}
#[test]
fn filtered_counts_keep_distinct_diagnostics_same_file() {
let mut store = DiagnosticsStore::new();
let file = "/repo/src/app.ts";
// Two servers, genuinely different diagnostics on the same file — both
// must be counted (dedup keys on location+message+source, not file).
store.publish(
server_key(ServerKind::TypeScript),
PathBuf::from(file),
vec![diag(file, 7, "type error", DiagnosticSeverity::Error)],
);
store.publish(
server_key(ServerKind::Biome),
PathBuf::from(file),
vec![diag(file, 12, "lint warn", DiagnosticSeverity::Warning)],
);
assert_eq!(store.filtered_error_warning_counts(|_| true), (1, 1));
}
}