pmat 3.16.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
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
#![cfg_attr(coverage_nightly, coverage(off))]
//! TDG baseline management: create, compare, list, update baselines
//!
//! Sprint 66 Phase 1: Baseline CRUD operations for quality tracking.

use super::display::{display_baseline_table, display_grade_distribution};
use super::is_analyzable_file;
use crate::cli::colors as c;
use crate::tdg::TdgAnalyzer;
use anyhow::Result;
use std::path::{Path, PathBuf};

/// Handle TDG baseline subcommand (Sprint 66 Phase 1)
pub(super) async fn handle_baseline_command(
    command: crate::cli::commands::BaselineCommand,
    _analyzer: &TdgAnalyzer,
    _config: &super::TdgCommandConfig,
) -> Result<()> {
    use crate::cli::commands::BaselineCommand;

    match command {
        BaselineCommand::Create {
            path,
            output,
            with_git_context,
            name: _name,
        } => create_baseline(_analyzer, &path, &output, with_git_context).await,

        BaselineCommand::Compare {
            baseline,
            path,
            format,
            fail_on_regression,
        } => compare_baseline(_analyzer, &baseline, &path, format, fail_on_regression).await,

        BaselineCommand::List { path, format } => list_baselines(&path, format).await,

        BaselineCommand::Update {
            baseline,
            path,
            with_git_context,
        } => update_baseline(_analyzer, &baseline, &path, with_git_context).await,
    }
}

/// Extract git context for baseline creation
fn extract_git_context(
    path: &Path,
    with_git_context: bool,
) -> Option<crate::models::git_context::GitContext> {
    if !with_git_context {
        return None;
    }
    match crate::models::git_context::GitContext::try_from_current_dir(path) {
        Some(ctx) => {
            println!(
                "   {} {} on {}",
                c::label("Git:"),
                c::number(&ctx.commit_sha_short),
                c::path(&ctx.branch)
            );
            Some(ctx)
        }
        None => {
            println!(
                "   {}",
                c::warn("Not in a git repository, git context unavailable")
            );
            None
        }
    }
}

/// Create a new TDG baseline for the project (Sprint 66 Phase 1)
pub(super) async fn create_baseline(
    analyzer: &TdgAnalyzer,
    path: &Path,
    output: &Path,
    with_git_context: bool,
) -> Result<()> {
    use crate::tdg::TdgBaseline;

    println!("{}", c::header("Creating TDG baseline..."));
    println!(
        "   {} {}",
        c::label("Path:"),
        c::path(&path.display().to_string())
    );
    println!(
        "   {} {}",
        c::label("Output:"),
        c::path(&output.display().to_string())
    );
    println!(
        "   {} {}",
        c::label("Git context:"),
        if with_git_context { "yes" } else { "no" }
    );

    let git_context = extract_git_context(path, with_git_context);
    let mut baseline = TdgBaseline::new(git_context);
    let (files_analyzed, files_skipped) =
        analyze_baseline_files(analyzer, path, &mut baseline).await?;

    println!();
    println!("\n{}", c::pass("Analysis complete:"));
    println!(
        "   {} {}",
        c::label("Files analyzed:"),
        c::number(&format!("{}", files_analyzed))
    );
    println!(
        "   {} {}",
        c::label("Files skipped:"),
        c::number(&format!("{}", files_skipped))
    );
    println!(
        "   {} {}",
        c::label("Average score:"),
        c::number(&format!("{:.1}", baseline.summary.avg_score))
    );

    display_grade_distribution(&baseline);

    baseline.save(output)?;
    println!(
        "\n{}",
        c::pass(&format!(
            "Baseline saved to: {}",
            c::path(&output.display().to_string())
        ))
    );

    Ok(())
}

/// Analyze files and populate the baseline
async fn analyze_baseline_files(
    analyzer: &TdgAnalyzer,
    path: &Path,
    baseline: &mut crate::tdg::TdgBaseline,
) -> Result<(usize, usize)> {
    use crate::tdg::BaselineEntry;
    use std::fs;
    use walkdir::WalkDir;

    let mut files_analyzed = 0;
    let mut files_skipped = 0;

    println!("\n{}", c::dim("Analyzing files..."));

    for entry in WalkDir::new(path)
        .follow_links(false)
        .into_iter()
        .filter_entry(|e| {
            // Never filter out the root entry (depth 0) — fixes `--path .`
            if e.depth() == 0 {
                return true;
            }
            let name = e.file_name().to_string_lossy();
            !name.starts_with('.')
                && !matches!(name.as_ref(), "target" | "node_modules" | "dist" | "build")
        })
    {
        let entry = entry?;
        if !entry.file_type().is_file() || !is_analyzable_file(entry.path()) {
            continue;
        }

        let file_path = entry.path();
        // Skip include!() fragment files — they aren't standalone Rust modules
        // and tree-sitter can't parse them, resulting in false F-grade scores
        if crate::cli::language_analyzer::is_include_fragment(file_path) {
            files_skipped += 1;
            continue;
        }
        match analyzer.analyze_file(file_path).await {
            Ok(score) => {
                let content = fs::read(file_path)?;
                let entry = BaselineEntry {
                    content_hash: blake3::hash(&content),
                    score: score.clone(),
                    components: crate::tdg::storage::ComponentScores::default(),
                    git_context: None,
                };
                baseline.add_entry(file_path.to_path_buf(), entry);
                files_analyzed += 1;
                if files_analyzed % 10 == 0 {
                    print!(".");
                    use std::io::Write;
                    std::io::stdout().flush().ok();
                }
            }
            Err(e) => {
                files_skipped += 1;
                if files_skipped <= 5 {
                    println!(
                        "   {}",
                        c::warn(&format!(
                            "Skipped {}: {}",
                            c::path(&file_path.display().to_string()),
                            e
                        ))
                    );
                }
            }
        }
    }

    Ok((files_analyzed, files_skipped))
}

/// Compare current state against a baseline (Sprint 66 Phase 1)
pub(super) async fn compare_baseline(
    analyzer: &TdgAnalyzer,
    baseline_path: &Path,
    current_path: &Path,
    format: crate::cli::TdgOutputFormat,
    fail_on_regression: bool,
) -> Result<()> {
    use crate::tdg::TdgBaseline;

    println!("{}", c::header("Comparing against baseline..."));
    println!(
        "   {} {}",
        c::label("Baseline:"),
        c::path(&baseline_path.display().to_string())
    );
    println!(
        "   {} {}",
        c::label("Current path:"),
        c::path(&current_path.display().to_string())
    );

    // Load baseline
    let old_baseline = TdgBaseline::load(baseline_path)?;
    println!(
        "   {} {} files, avg score {}",
        c::label("Loaded baseline:"),
        c::number(&format!("{}", old_baseline.summary.total_files)),
        c::number(&format!("{:.1}", old_baseline.summary.avg_score))
    );

    // Create new baseline for current state
    println!("\n{}", c::dim("Analyzing current state..."));
    let temp_output = std::env::temp_dir().join("pmat-current-baseline.json");
    create_baseline(analyzer, current_path, &temp_output, false).await?;
    let new_baseline = TdgBaseline::load(&temp_output)?;

    // Clean up ephemeral baseline file
    std::fs::remove_file(&temp_output).ok();

    // Compare
    println!("\n{}", c::dim("Computing comparison..."));
    let comparison = old_baseline.compare(&new_baseline);

    // Format output
    let output_str = match format {
        crate::cli::TdgOutputFormat::Table | crate::cli::TdgOutputFormat::Markdown => {
            comparison.format_text()
        }
        crate::cli::TdgOutputFormat::Json => serde_json::to_string_pretty(&comparison)?,
        crate::cli::TdgOutputFormat::Sarif => {
            // SARIF not implemented yet, use text
            comparison.format_text()
        }
    };

    println!("\n{}", output_str);

    // Check for regressions
    if fail_on_regression && comparison.has_regressions() {
        return Err(anyhow::anyhow!(
            "Quality regression detected: {} file(s) regressed",
            comparison.regressed.len()
        ));
    }

    Ok(())
}

/// Find all baseline files in a directory
fn find_baseline_files(path: &Path) -> Vec<(PathBuf, crate::tdg::TdgBaseline)> {
    use crate::tdg::TdgBaseline;
    use walkdir::WalkDir;

    WalkDir::new(path)
        .max_depth(3)
        .follow_links(false)
        .into_iter()
        .filter_map(|e| e.ok())
        .filter(|e| e.file_type().is_file())
        .filter_map(|entry| {
            let name = entry.file_name().to_str()?;
            if name.ends_with("-baseline.json") || name == ".pmat-baseline.json" {
                TdgBaseline::load(entry.path())
                    .ok()
                    .map(|b| (entry.path().to_path_buf(), b))
            } else {
                None
            }
        })
        .collect()
}

/// List all baselines in a directory (Sprint 66 Phase 1)
async fn list_baselines(path: &Path, format: crate::cli::TdgOutputFormat) -> Result<()> {
    println!(
        "{} {}",
        c::header("Listing baselines in:"),
        c::path(&path.display().to_string())
    );

    let baselines = find_baseline_files(path);

    if baselines.is_empty() {
        println!("   {}", c::dim("No baselines found"));
        return Ok(());
    }

    println!(
        "\n{} {}:\n",
        c::label("Found"),
        c::number(&format!("{} baseline(s)", baselines.len()))
    );

    match format {
        crate::cli::TdgOutputFormat::Table | crate::cli::TdgOutputFormat::Markdown => {
            for (path, baseline) in &baselines {
                display_baseline_table(path, baseline);
            }
        }
        crate::cli::TdgOutputFormat::Json => {
            let output: Vec<_> = baselines
                .iter()
                .map(|(path, baseline)| {
                    serde_json::json!({
                        "path": path.display().to_string(),
                        "version": baseline.version,
                        "created_at": baseline.created_at,
                        "total_files": baseline.summary.total_files,
                        "avg_score": baseline.summary.avg_score,
                        "git_context": baseline.git_context
                    })
                })
                .collect();
            println!("{}", serde_json::to_string_pretty(&output)?);
        }
        crate::cli::TdgOutputFormat::Sarif => {
            for (path, baseline) in &baselines {
                println!("{}", c::path(&path.display().to_string()));
                println!(
                    "   {} {} | {} {}",
                    c::label("Files:"),
                    c::number(&format!("{}", baseline.summary.total_files)),
                    c::label("Avg:"),
                    c::number(&format!("{:.1}", baseline.summary.avg_score))
                );
            }
        }
    }

    Ok(())
}

/// Update an existing baseline (Sprint 66 Phase 1)
async fn update_baseline(
    analyzer: &TdgAnalyzer,
    baseline_path: &Path,
    project_path: &Path,
    with_git_context: bool,
) -> Result<()> {
    println!("{}", c::header("Updating baseline..."));
    println!(
        "   {} {}",
        c::label("Baseline:"),
        c::path(&baseline_path.display().to_string())
    );
    println!(
        "   {} {}",
        c::label("Path:"),
        c::path(&project_path.display().to_string())
    );

    // Simply re-create the baseline (overwrites the file)
    create_baseline(analyzer, project_path, baseline_path, with_git_context).await?;

    println!("\n{}", c::pass("Baseline updated successfully"));

    Ok(())
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod baseline_tests {
    use super::*;
    use crate::tdg::TdgBaseline;

    /// extract_git_context returns None immediately when with_git_context=false,
    /// skipping the GitContext::try_from_current_dir path.
    #[test]
    fn test_extract_git_context_disabled_returns_none() {
        let tmp = tempfile::tempdir().unwrap();
        let result = extract_git_context(tmp.path(), false);
        assert!(result.is_none());
    }

    /// extract_git_context on a non-git directory hits the None arm
    /// of try_from_current_dir (logs "Not in a git repository").
    #[test]
    fn test_extract_git_context_non_git_dir_returns_none() {
        let tmp = tempfile::tempdir().unwrap();
        // Tempdir is not a git repo → try_from_current_dir returns None →
        // the warning-log arm fires and returns None.
        let result = extract_git_context(tmp.path(), true);
        assert!(result.is_none());
    }

    /// find_baseline_files returns empty for a dir with no baseline files.
    #[test]
    fn test_find_baseline_files_empty_dir() {
        let tmp = tempfile::tempdir().unwrap();
        let out = find_baseline_files(tmp.path());
        assert!(out.is_empty());
    }

    /// find_baseline_files picks up a real baseline file written with the
    /// canonical `-baseline.json` suffix at the project root.
    #[test]
    fn test_find_baseline_files_matches_suffix() {
        let tmp = tempfile::tempdir().unwrap();
        let baseline = TdgBaseline::new(None);
        let out_path = tmp.path().join("my-baseline.json");
        baseline.save(&out_path).unwrap();

        let found = find_baseline_files(tmp.path());
        assert_eq!(found.len(), 1, "must find the -baseline.json file");
        assert_eq!(found[0].0, out_path);
    }

    /// find_baseline_files picks up the canonical `.pmat-baseline.json` dotfile
    /// name (second name arm of the `||` match).
    #[test]
    fn test_find_baseline_files_matches_pmat_dotfile_name() {
        let tmp = tempfile::tempdir().unwrap();
        let baseline = TdgBaseline::new(None);
        let out_path = tmp.path().join(".pmat-baseline.json");
        baseline.save(&out_path).unwrap();

        let found = find_baseline_files(tmp.path());
        assert_eq!(found.len(), 1, "must find .pmat-baseline.json");
        assert_eq!(found[0].0, out_path);
    }

    /// find_baseline_files ignores files that don't match either naming rule.
    #[test]
    fn test_find_baseline_files_ignores_unrelated_files() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("unrelated.json"), "{}").unwrap();
        std::fs::write(tmp.path().join("baseline.json"), "{}").unwrap(); // no `-` prefix
        std::fs::write(tmp.path().join("notes.txt"), "hi").unwrap();

        let found = find_baseline_files(tmp.path());
        assert!(found.is_empty(), "must not pick up non-matching names");
    }

    /// find_baseline_files gracefully skips baseline files that fail to load
    /// (invalid JSON content) — the `TdgBaseline::load(...).ok().map(...)`
    /// returns None and filter_map drops the entry.
    #[test]
    fn test_find_baseline_files_skips_unreadable_baseline() {
        let tmp = tempfile::tempdir().unwrap();
        // Matching name but invalid JSON → load returns Err, filter_map drops.
        std::fs::write(tmp.path().join("bad-baseline.json"), "not json").unwrap();

        let found = find_baseline_files(tmp.path());
        assert!(found.is_empty(), "invalid content must be dropped");
    }
}