pmat 3.11.0

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
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
// dependency_checks_analysis.rs — included by dependency_checks.rs
// CB-081 violation detection, scoring, Cargo.toml analysis, trend tracking

/// Build a CB-081-A threshold violation if dependency counts exceed the given
/// thresholds.  Returns `None` when both `direct` and `transitive` are within
/// limits.  The description lists failing metrics first, with passing metrics
/// shown in parentheses as context.
fn build_threshold_violation(
    cargo_toml: &str,
    direct: usize,
    transitive: usize,
    direct_max: usize,
    trans_max: usize,
    severity: Severity,
) -> Option<CbPatternViolation> {
    if direct <= direct_max && transitive <= trans_max {
        return None;
    }

    let mut parts = Vec::new();
    let mut ok_parts = Vec::new();

    if direct > direct_max {
        parts.push(if matches!(severity, Severity::Error) {
            format!("{} direct deps exceed max {}", direct, direct_max)
        } else {
            format!("{} direct deps (threshold {})", direct, direct_max)
        });
    } else {
        ok_parts.push(format!("{} direct OK", direct));
    }

    if transitive > trans_max {
        parts.push(if matches!(severity, Severity::Error) {
            format!(
                "{} prod transitive deps exceed max {}",
                transitive, trans_max
            )
        } else {
            format!(
                "{} prod transitive deps (threshold {})",
                transitive, trans_max
            )
        });
    } else {
        ok_parts.push(format!("{} transitive OK", transitive));
    }

    let description = if ok_parts.is_empty() {
        parts.join(", ")
    } else {
        format!("{} ({})", parts.join(", "), ok_parts.join(", "))
    };

    Some(CbPatternViolation {
        pattern_id: "CB-081-A".to_string(),
        file: cargo_toml.to_string(),
        line: 0,
        description,
        severity,
    })
}

/// Generate all CB-081 violations (A through E) from pre-computed metrics.
#[allow(clippy::too_many_arguments)]
fn check_dependency_count_violations(
    cargo_toml: &str,
    cargo_lock: &str,
    direct: usize,
    effective_transitive: usize,
    feature_gated_pct: f64,
    duplicate_crates: &[DuplicateCrate],
    trend: &Option<DependencyTrend>,
    transitive_count: usize,
    sovereign_count: usize,
) -> Vec<CbPatternViolation> {
    let mut violations = Vec::new();

    // CB-081-A: Count thresholds -- sovereign stack adjustment
    let sovereign_allowance = sovereign_count.min(3) * 50;
    let trans_error_max = 250 + sovereign_allowance;
    let trans_warn_max = 200 + sovereign_allowance;

    if let Some(v) = build_threshold_violation(
        cargo_toml,
        direct,
        effective_transitive,
        50,
        trans_error_max,
        Severity::Error,
    ) {
        violations.push(v);
    } else if let Some(v) = build_threshold_violation(
        cargo_toml,
        direct,
        effective_transitive,
        40,
        trans_warn_max,
        Severity::Warning,
    ) {
        violations.push(v);
    }

    // CB-081-B: Duplicate crates
    check_duplicate_crates_violation(cargo_lock, duplicate_crates, &mut violations);

    // CB-081-C: Low feature gating (only warn if deps exceed excellent tier threshold)
    if direct > 20 && feature_gated_pct < 30.0 {
        violations.push(CbPatternViolation {
            pattern_id: "CB-081-C".to_string(),
            file: cargo_toml.to_string(),
            line: 0,
            description: format!(
                "Only {:.0}% deps use default-features=false. Consider disabling unused features",
                feature_gated_pct
            ),
            severity: Severity::Info,
        });
    }

    // CB-081-E: Trend regression
    check_trend_regression_violation(cargo_toml, trend, transitive_count, &mut violations);

    violations
}

/// CB-081-B: Generate a violation for duplicate crates if any exist.
fn check_duplicate_crates_violation(
    cargo_lock: &str,
    duplicate_crates: &[DuplicateCrate],
    violations: &mut Vec<CbPatternViolation>,
) {
    if !duplicate_crates.is_empty() {
        let dup_names: Vec<_> = duplicate_crates.iter().map(|d| d.name.as_str()).collect();
        violations.push(CbPatternViolation {
            pattern_id: "CB-081-B".to_string(),
            file: cargo_lock.to_string(),
            line: 0,
            description: format!(
                "{} duplicate crates: {}. Run 'cargo tree --duplicates'",
                duplicate_crates.len(),
                dup_names.join(", ")
            ),
            severity: Severity::Warning,
        });
    }
}

/// CB-081-E: Generate a violation if transitive dependency count increased >10%.
fn check_trend_regression_violation(
    cargo_toml: &str,
    trend: &Option<DependencyTrend>,
    transitive_count: usize,
    violations: &mut Vec<CbPatternViolation>,
) {
    if let Some(ref t) = trend {
        let pct_increase = if t.transitive_delta > 0 {
            (t.transitive_delta as f64 / (transitive_count as i32 - t.transitive_delta) as f64)
                * 100.0
        } else {
            0.0
        };
        if pct_increase > 10.0 {
            violations.push(CbPatternViolation {
                pattern_id: "CB-081-E".to_string(),
                file: cargo_toml.to_string(),
                line: 0,
                description: format!(
                    "Dependency creep: +{} transitive deps ({:.0}% increase) since {}",
                    t.transitive_delta, pct_increase, t.previous_timestamp
                ),
                severity: Severity::Warning,
            });
        }
    }
}

/// CB-081: Detect excessive dependency counts (enhanced)
/// Thresholds from rust-project-score-v1.1-update.md:
/// - 5 points: <=20 direct, <=100 transitive
/// - 4 points: <=30 direct, <=150 transitive
/// - 3 points: <=40 direct, <=200 transitive
/// - 2 points: <=50 direct, <=250 transitive
/// - 0 points: >50 direct or >250 transitive
pub fn detect_cb081_dependency_count(project_path: &Path) -> DependencyCountReport {
    let cargo_toml_path = project_path.join("Cargo.toml");
    let cargo_lock_path = project_path.join("Cargo.lock");

    // CB-081-A: Count direct dependencies from Cargo.toml
    let (direct_count, feature_gated_count, sovereign_crates) =
        analyze_cargo_toml(&cargo_toml_path);

    // CB-081-A & CB-081-B: Use O(1) cached analysis (issue #148 fix)
    let (transitive_count, prod_transitive_count, duplicate_crates) =
        get_cached_dependency_analysis(project_path, &cargo_lock_path);

    // Use production-only count for scoring (excludes dev-dep transitive)
    // Fall back to total Cargo.lock count if cargo tree is unavailable
    let effective_transitive = prod_transitive_count.unwrap_or(transitive_count);

    // CB-081-C: Calculate feature gating percentage
    let feature_gated_pct = if direct_count > 0 {
        (feature_gated_count as f64 / direct_count as f64) * 100.0
    } else {
        0.0
    };

    // CB-081-D: Calculate sovereign bonus (max +3)
    let sovereign_bonus = std::cmp::min(sovereign_crates.len() as u8, 3);

    // CB-081-E: Load trend data
    let trend = load_dependency_trend(project_path);

    // Calculate base score using production-only transitive count (sovereign-adjusted)
    let mut score =
        calculate_dependency_score(direct_count, effective_transitive, sovereign_crates.len());

    // Apply bonuses (capped at 5 total)
    if feature_gated_pct >= 50.0 && score < 5 {
        score = std::cmp::min(score + 1, 5);
    }

    // Generate all violations
    let violations = check_dependency_count_violations(
        &cargo_toml_path.display().to_string(),
        &cargo_lock_path.display().to_string(),
        direct_count,
        effective_transitive,
        feature_gated_pct,
        &duplicate_crates,
        &trend,
        transitive_count,
        sovereign_crates.len(),
    );

    // Save current metrics for future trend tracking (use effective count)
    let _ = save_dependency_metrics(project_path, direct_count, effective_transitive);

    DependencyCountReport {
        direct_count,
        transitive_count,
        prod_transitive_count,
        score,
        duplicate_crates,
        feature_gated_count,
        feature_gated_pct,
        sovereign_crates,
        sovereign_bonus,
        trend,
        violations,
    }
}

/// Parse a TOML section header to determine which dependency section we're in.
/// Returns (in_dependencies, in_dev_dependencies, in_build_dependencies).
fn is_dependency_section(trimmed: &str) -> (bool, bool, bool) {
    let in_dependencies = trimmed == "[dependencies]"
        || trimmed.starts_with("[dependencies.")
        || trimmed.starts_with("[target.");
    let in_dev_dependencies =
        trimmed == "[dev-dependencies]" || trimmed.starts_with("[dev-dependencies.");
    let in_build_dependencies =
        trimmed == "[build-dependencies]" || trimmed.starts_with("[build-dependencies.");
    (in_dependencies, in_dev_dependencies, in_build_dependencies)
}

/// Return true when the line is a scoreable (non-dev, non-build) dependency.
/// The line must be inside a `[dependencies]` section (not `[dev-dependencies]`
/// or `[build-dependencies]`), contain `=`, and not be a comment.
fn is_scoreable_dependency(in_deps: bool, in_dev: bool, in_build: bool, trimmed: &str) -> bool {
    in_deps && !in_dev && !in_build && trimmed.contains('=') && !trimmed.starts_with('#')
}

/// Process a single dependency line to determine if it is a direct (non-optional)
/// dependency and whether it uses feature gating (`default-features = false`).
/// Also checks for sovereign crates, appending any found to `sovereign_found`.
/// Returns (is_direct, is_feature_gated).
fn process_dependency_line(trimmed: &str, sovereign_found: &mut Vec<String>) -> (bool, bool) {
    let is_optional = trimmed.contains("optional") && trimmed.contains("true");
    let is_direct = !is_optional;

    let is_feature_gated = trimmed.contains("default-features") && trimmed.contains("false");

    for crate_name in SOVEREIGN_CRATES {
        if trimmed.starts_with(crate_name)
            && (trimmed.chars().nth(crate_name.len()) == Some(' ')
                || trimmed.chars().nth(crate_name.len()) == Some('='))
        {
            sovereign_found.push(crate_name.to_string());
        }
    }

    (is_direct, is_feature_gated)
}

/// Analyze Cargo.toml for dependencies, feature gating, and sovereign crates
pub(super) fn analyze_cargo_toml(cargo_toml_path: &Path) -> (usize, usize, Vec<String>) {
    let content = match fs::read_to_string(cargo_toml_path) {
        Ok(c) => c,
        Err(_) => return (0, 0, Vec::new()),
    };

    let mut direct_count = 0;
    let mut feature_gated_count = 0;
    let mut sovereign_found = Vec::new();
    let mut in_dependencies = false;
    let mut in_dev_dependencies = false;
    let mut in_build_dependencies = false;

    for line in content.lines() {
        let trimmed = line.trim();

        // Track section headers
        if trimmed.starts_with('[') {
            (in_dependencies, in_dev_dependencies, in_build_dependencies) =
                is_dependency_section(trimmed);
            continue;
        }

        // Count dependencies (excluding dev, build, and optional deps for scoring)
        if is_scoreable_dependency(
            in_dependencies,
            in_dev_dependencies,
            in_build_dependencies,
            trimmed,
        ) {
            let (is_direct, is_feature_gated) =
                process_dependency_line(trimmed, &mut sovereign_found);
            if is_direct {
                direct_count += 1;
            }
            if is_feature_gated {
                feature_gated_count += 1;
            }
        }
    }

    (direct_count, feature_gated_count, sovereign_found)
}

/// Calculate dependency health score (0-5 points)
/// Sovereign stack projects get adjusted thresholds (each sovereign crate brings
/// its own ecosystem, e.g. trueno-graph -> arrow/wgpu, trueno-rag -> vector search).
pub(super) fn calculate_dependency_score(
    direct: usize,
    transitive: usize,
    sovereign_count: usize,
) -> u8 {
    let bonus = sovereign_count.min(3) * 50;
    if direct <= 20 && transitive <= 100 + bonus {
        5
    } else if direct <= 30 && transitive <= 150 + bonus {
        4
    } else if direct <= 40 && transitive <= 200 + bonus {
        3
    } else if direct <= 50 && transitive <= 250 + bonus {
        2
    } else {
        0
    }
}

/// CB-081-E: Load previous dependency metrics for trend tracking
pub(super) fn load_dependency_trend(project_path: &Path) -> Option<DependencyTrend> {
    let metrics_path = project_path
        .join(".pmat")
        .join("metrics")
        .join("dependencies.json");

    let content = fs::read_to_string(&metrics_path).ok()?;

    #[derive(serde::Deserialize)]
    #[allow(dead_code)] // Fields used for JSON deserialization structure matching
    struct PreviousMetrics {
        direct_count: usize,
        transitive_count: usize,
        timestamp: String,
    }

    let prev: PreviousMetrics = serde_json::from_str(&content).ok()?;

    // Return trend with previous timestamp - deltas calculated elsewhere
    Some(DependencyTrend {
        direct_delta: 0,
        transitive_delta: 0,
        previous_timestamp: prev.timestamp,
    })
}

/// CB-081-E: Save current dependency metrics for future trend tracking
pub(super) fn save_dependency_metrics(
    project_path: &Path,
    direct: usize,
    transitive: usize,
) -> std::io::Result<()> {
    let metrics_dir = project_path.join(".pmat").join("metrics");
    fs::create_dir_all(&metrics_dir)?;

    let metrics_path = metrics_dir.join("dependencies.json");

    // Load previous metrics to calculate deltas
    let previous = if metrics_path.exists() {
        fs::read_to_string(&metrics_path)
            .ok()
            .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok())
    } else {
        None
    };

    let timestamp = chrono::Utc::now().to_rfc3339();

    let metrics = serde_json::json!({
        "direct_count": direct,
        "transitive_count": transitive,
        "timestamp": timestamp,
        "previous": previous,
    });

    fs::write(&metrics_path, serde_json::to_string_pretty(&metrics)?)
}

/// Recalculate trend deltas with current counts
#[allow(dead_code)] // Reserved for future trend comparison feature
pub(super) fn calculate_trend_deltas(
    project_path: &Path,
    current_direct: usize,
    current_transitive: usize,
) -> Option<DependencyTrend> {
    let metrics_path = project_path
        .join(".pmat")
        .join("metrics")
        .join("dependencies.json");

    let content = fs::read_to_string(&metrics_path).ok()?;
    let prev: serde_json::Value = serde_json::from_str(&content).ok()?;

    let prev_direct = prev.get("previous")?.get("direct_count")?.as_u64()? as usize;
    let prev_transitive = prev.get("previous")?.get("transitive_count")?.as_u64()? as usize;
    let prev_timestamp = prev.get("previous")?.get("timestamp")?.as_str()?;

    Some(DependencyTrend {
        direct_delta: current_direct as i32 - prev_direct as i32,
        transitive_delta: current_transitive as i32 - prev_transitive as i32,
        previous_timestamp: prev_timestamp.to_string(),
    })
}