coverage-mcp 0.15.3

Local-first coverage time-series dashboard and MCP server
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
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};
use serde_json::Value;

/// Returns a ratio or null when the denominator is empty.
pub fn rate(covered: i64, total: i64) -> Option<f64> {
    (total > 0).then_some(covered as f64 / total as f64)
}

/// Normalizes a report path to the repository-relative spelling used by queries.
pub fn normalize_report_path(path: &str, repo_path: Option<&str>) -> String {
    let raw = PathBuf::from(path);
    if let Some(repo_path) = repo_path {
        if raw.is_absolute() {
            if let (Ok(file), Ok(repo)) = (raw.canonicalize(), Path::new(repo_path).canonicalize())
            {
                if let Ok(relative) = file.strip_prefix(repo) {
                    return relative.to_string_lossy().replace('\\', "/");
                }
            }
        }
    }
    raw.to_string_lossy().replace('\\', "/")
}

/// One normalized source-line measurement.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct LineCoverage {
    /// Repository-relative path.
    pub file_path: String,
    /// One-based line number.
    pub line_number: i64,
    /// Execution count.
    pub hits: i64,
    /// Whether the line is covered.
    pub covered: bool,
    /// Whether this row contributes to line totals.
    pub count_line: bool,
    /// Branch outcomes attached to the line.
    pub total_branches: i64,
    /// Covered branch outcomes attached to the line.
    pub covered_branches: i64,
    /// Functions attached to the line.
    pub total_functions: i64,
    /// Covered functions attached to the line.
    pub covered_functions: i64,
    /// Parser-specific detail.
    pub details: Value,
}

impl LineCoverage {
    /// Merges duplicate records emitted by a coverage format.
    pub fn merge(&mut self, other: &Self) {
        if other.count_line {
            self.hits = self.hits.max(other.hits);
            self.covered |= other.covered;
        }
        self.count_line |= other.count_line;
        self.total_branches += other.total_branches;
        self.covered_branches += other.covered_branches;
        self.total_functions += other.total_functions;
        self.covered_functions += other.covered_functions;
        if let (Value::Object(current), Value::Object(extra)) = (&mut self.details, &other.details)
        {
            for (key, value) in extra {
                current.insert(key.clone(), value.clone());
            }
        }
    }
}

/// Per-file coverage totals.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct FileCoverage {
    /// Repository-relative path.
    pub file_path: String,
    /// Instrumented lines.
    pub total_lines: i64,
    /// Covered lines.
    pub covered_lines: i64,
    /// Instrumented branches.
    pub total_branches: i64,
    /// Covered branches.
    pub covered_branches: i64,
    /// Instrumented functions.
    pub total_functions: i64,
    /// Covered functions.
    pub covered_functions: i64,
    /// Instrumented regions.
    pub total_regions: i64,
    /// Covered regions.
    pub covered_regions: i64,
    /// Format-specific raw metrics.
    pub raw_metrics: Value,
}

/// One covered region attributed to a named test by the source coverage artifact.
///
/// The observation is deliberately independent of execution hit counts. Duplicate
/// detection compares the complete set of these normalized observations for each
/// test, so a different branch or function identity is not collapsed into a line
/// match. The parser only populates this field when the artifact names tests.
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize, Deserialize)]
pub struct TestCoverageObservation {
    /// Test name as reported by the coverage artifact.
    pub test_name: String,
    /// Observation kind, currently `line`, `branch`, or `function` for LCOV.
    pub kind: String,
    /// Repository-relative source path.
    pub file_path: String,
    /// One-based source line associated with the observation.
    pub line_number: i64,
    /// Exact kind-specific identity, such as an LCOV branch or function name.
    pub region_key: String,
}

impl FileCoverage {
    /// Line rate.
    pub fn line_rate(&self) -> Option<f64> {
        rate(self.covered_lines, self.total_lines)
    }
    /// Branch rate.
    pub fn branch_rate(&self) -> Option<f64> {
        rate(self.covered_branches, self.total_branches)
    }
    /// Function rate.
    pub fn function_rate(&self) -> Option<f64> {
        rate(self.covered_functions, self.total_functions)
    }
    /// Region rate.
    pub fn region_rate(&self) -> Option<f64> {
        rate(self.covered_regions, self.total_regions)
    }
}

/// A normalized coverage report before it is persisted as a snapshot.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct CoverageReport {
    /// Canonical parser format.
    pub format: String,
    /// Source artifact path.
    pub report_path: String,
    /// Normalized file rows.
    pub files: Vec<FileCoverage>,
    /// Normalized line rows.
    pub lines: Vec<LineCoverage>,
    /// Distinct non-blank test names reported by the coverage artifact.
    pub test_names: Vec<String>,
    /// Covered line, branch, and function observations attributed to named tests.
    pub test_coverage: Vec<TestCoverageObservation>,
    /// Parser warnings.
    pub warnings: Vec<String>,
    /// Parser metadata.
    pub metadata: Value,
}

impl CoverageReport {
    /// Total lines.
    pub fn total_lines(&self) -> i64 {
        self.files.iter().map(|file| file.total_lines).sum()
    }
    /// Covered lines.
    pub fn covered_lines(&self) -> i64 {
        self.files.iter().map(|file| file.covered_lines).sum()
    }
    /// Total branches.
    pub fn total_branches(&self) -> i64 {
        self.files.iter().map(|file| file.total_branches).sum()
    }
    /// Covered branches.
    pub fn covered_branches(&self) -> i64 {
        self.files.iter().map(|file| file.covered_branches).sum()
    }
    /// Total functions.
    pub fn total_functions(&self) -> i64 {
        self.files.iter().map(|file| file.total_functions).sum()
    }
    /// Covered functions.
    pub fn covered_functions(&self) -> i64 {
        self.files.iter().map(|file| file.covered_functions).sum()
    }
    /// Total regions.
    pub fn total_regions(&self) -> i64 {
        self.files.iter().map(|file| file.total_regions).sum()
    }
    /// Covered regions.
    pub fn covered_regions(&self) -> i64 {
        self.files.iter().map(|file| file.covered_regions).sum()
    }
    /// Line rate.
    pub fn line_rate(&self) -> Option<f64> {
        rate(self.covered_lines(), self.total_lines())
    }
    /// Branch rate.
    pub fn branch_rate(&self) -> Option<f64> {
        rate(self.covered_branches(), self.total_branches())
    }
    /// Function rate.
    pub fn function_rate(&self) -> Option<f64> {
        rate(self.covered_functions(), self.total_functions())
    }
    /// Region rate.
    pub fn region_rate(&self) -> Option<f64> {
        rate(self.covered_regions(), self.total_regions())
    }
}

/// Accumulates format records into deterministic file and line rows.
#[derive(Debug)]
pub struct CoverageBuilder {
    repo_path: Option<String>,
    lines: BTreeMap<(String, i64), LineCoverage>,
    test_names: BTreeSet<String>,
    test_coverage: BTreeSet<(String, String, String, i64, String)>,
    file_metrics: BTreeMap<String, serde_json::Map<String, Value>>,
    normalized_paths: BTreeMap<String, String>,
}

impl CoverageBuilder {
    /// Creates a builder relative to an optional repository root.
    pub fn new(repo_path: Option<&str>) -> Self {
        Self {
            repo_path: repo_path.map(str::to_owned),
            lines: BTreeMap::new(),
            test_names: BTreeSet::new(),
            test_coverage: BTreeSet::new(),
            file_metrics: BTreeMap::new(),
            normalized_paths: BTreeMap::new(),
        }
    }

    /// Adds one line, branch, or function observation.
    #[allow(clippy::too_many_arguments)]
    pub fn add_line(
        &mut self,
        file_path: &str,
        line_number: i64,
        hits: i64,
        covered: Option<bool>,
        count_line: bool,
        total_branches: i64,
        covered_branches: i64,
        total_functions: i64,
        covered_functions: i64,
        details: Value,
    ) {
        if line_number <= 0 {
            return;
        }
        let normalized = self
            .normalized_paths
            .entry(file_path.to_owned())
            .or_insert_with(|| normalize_report_path(file_path, self.repo_path.as_deref()))
            .clone();
        let line_hits = if count_line { hits.max(0) } else { 0 };
        let is_covered = if count_line {
            covered.unwrap_or(line_hits > 0)
        } else {
            false
        };
        let row = LineCoverage {
            file_path: normalized.clone(),
            line_number,
            hits: line_hits,
            covered: is_covered,
            count_line,
            total_branches: total_branches.max(0),
            covered_branches: covered_branches.max(0),
            total_functions: total_functions.max(0),
            covered_functions: covered_functions.max(0),
            details,
        };
        if let Some(existing) = self.lines.get_mut(&(normalized, line_number)) {
            existing.merge(&row);
        } else {
            self.lines.insert((row.file_path.clone(), line_number), row);
        }
    }

    /// Adds format-specific file metrics.
    pub fn add_file_metrics(&mut self, file_path: &str, metrics: serde_json::Map<String, Value>) {
        let normalized = self
            .normalized_paths
            .entry(file_path.to_owned())
            .or_insert_with(|| normalize_report_path(file_path, self.repo_path.as_deref()))
            .clone();
        self.file_metrics
            .entry(normalized)
            .or_default()
            .extend(metrics);
    }

    /// Records a named test even when it has no covered observations.
    pub fn add_test_name(&mut self, test_name: &str) {
        let test_name = test_name.trim();
        if !test_name.is_empty() {
            self.test_names.insert(test_name.to_owned());
        }
    }

    /// Adds one covered, kind-specific observation for a named test.
    pub fn add_test_observation(
        &mut self,
        test_name: &str,
        kind: &str,
        file_path: &str,
        line_number: i64,
        region_key: &str,
    ) {
        let test_name = test_name.trim();
        let kind = kind.trim();
        if test_name.is_empty() || kind.is_empty() || line_number <= 0 {
            return;
        }
        self.add_test_name(test_name);
        let normalized = self
            .normalized_paths
            .entry(file_path.to_owned())
            .or_insert_with(|| normalize_report_path(file_path, self.repo_path.as_deref()))
            .clone();
        self.test_coverage.insert((
            test_name.to_owned(),
            kind.to_owned(),
            normalized,
            line_number,
            region_key.to_owned(),
        ));
    }

    /// Finalizes deterministic file totals and a report.
    pub fn build(
        mut self,
        format: &str,
        report_path: &str,
        warnings: Vec<String>,
        metadata: Value,
    ) -> CoverageReport {
        let lines: Vec<LineCoverage> = self.lines.into_values().collect();
        let test_names = self.test_names.into_iter().collect();
        let test_coverage = self
            .test_coverage
            .into_iter()
            .map(
                |(test_name, kind, file_path, line_number, region_key)| TestCoverageObservation {
                    test_name,
                    kind,
                    file_path,
                    line_number,
                    region_key,
                },
            )
            .collect();
        let mut by_file: BTreeMap<String, Vec<LineCoverage>> = BTreeMap::new();
        for line in &lines {
            by_file
                .entry(line.file_path.clone())
                .or_default()
                .push(line.clone());
        }
        let mut files = Vec::new();
        let mut paths: std::collections::BTreeSet<String> = by_file.keys().cloned().collect();
        paths.extend(self.file_metrics.keys().cloned());
        for file_path in paths {
            let file_lines = by_file.get(&file_path).cloned().unwrap_or_default();
            let mut metrics = self.file_metrics.remove(&file_path).unwrap_or_default();
            let total_lines = metric_i64(
                &mut metrics,
                "total_lines",
                file_lines.iter().filter(|line| line.count_line).count() as i64,
            );
            let covered_lines = metric_i64(
                &mut metrics,
                "covered_lines",
                file_lines
                    .iter()
                    .filter(|line| line.count_line && line.covered)
                    .count() as i64,
            );
            let total_branches = metric_i64(
                &mut metrics,
                "total_branches",
                file_lines.iter().map(|line| line.total_branches).sum(),
            );
            let covered_branches = metric_i64(
                &mut metrics,
                "covered_branches",
                file_lines.iter().map(|line| line.covered_branches).sum(),
            );
            let total_functions = metric_i64(
                &mut metrics,
                "total_functions",
                file_lines.iter().map(|line| line.total_functions).sum(),
            );
            let covered_functions = metric_i64(
                &mut metrics,
                "covered_functions",
                file_lines.iter().map(|line| line.covered_functions).sum(),
            );
            let total_regions = metric_i64(&mut metrics, "total_regions", 0);
            let covered_regions = metric_i64(&mut metrics, "covered_regions", 0);
            files.push(FileCoverage {
                file_path,
                total_lines,
                covered_lines,
                total_branches,
                covered_branches,
                total_functions,
                covered_functions,
                total_regions,
                covered_regions,
                raw_metrics: Value::Object(metrics),
            });
        }
        CoverageReport {
            format: format.to_owned(),
            report_path: report_path.to_owned(),
            files,
            lines,
            test_names,
            test_coverage,
            warnings,
            metadata,
        }
    }
}

fn metric_i64(metrics: &mut serde_json::Map<String, Value>, key: &str, fallback: i64) -> i64 {
    metrics
        .remove(key)
        .and_then(|value| value.as_i64())
        .unwrap_or(fallback)
        .max(0)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn named_observation_inputs_reject_invalid_records() {
        let mut builder = CoverageBuilder::new(Some("/repo"));
        builder.add_test_name(" ");
        builder.add_test_observation("", "line", "src/a.rs", 1, "line");
        builder.add_test_observation("test-a", "", "src/a.rs", 1, "line");
        builder.add_test_observation("test-a", "line", "src/a.rs", 0, "line");
        builder.add_test_observation(" test-a ", " line ", "src/a.rs", 1, "line");

        let report = builder.build("lcov", "coverage.lcov", Vec::new(), Value::Null);
        assert_eq!(report.test_names, vec!["test-a"]);
        assert_eq!(report.test_coverage.len(), 1);
        assert_eq!(report.test_coverage[0].file_path, "src/a.rs");
        assert_eq!(report.test_coverage[0].kind, "line");
    }
}