pmat 3.30.1

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP)
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
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
948
949
950
951
952
953
954
955
//! QDD (Quality-Driven Development) CLI handlers
//! Toyota Way: Single Responsibility and DRY principles

#![cfg_attr(coverage_nightly, coverage(off))]
use crate::cli::colors as c;
use crate::cli::commands::{QddCodeType, QddCommands, QddOutputFormat, QddQualityProfile};
use crate::qdd::{
    CodeType, CreateSpec, Parameter, QddOperation, QddResult, QddTool, QualityProfile, RefactorSpec,
};
use anyhow::{Context, Result};
use std::path::{Path, PathBuf};

/// Handle QDD CLI commands
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "check_compliance")]
pub async fn handle_qdd_command(command: QddCommands) -> Result<()> {
    match command {
        QddCommands::Create {
            code_type,
            name,
            purpose,
            profile,
            input,
            output,
            output_file,
        } => {
            handle_qdd_create(
                code_type,
                name,
                purpose,
                profile,
                input,
                output,
                output_file,
            )
            .await
        }

        QddCommands::Refactor {
            file,
            function,
            profile,
            max_complexity,
            min_coverage,
            output,
            dry_run,
        } => {
            handle_qdd_refactor(
                file,
                function,
                profile,
                max_complexity,
                min_coverage,
                output,
                dry_run,
            )
            .await
        }

        QddCommands::Validate {
            path,
            profile,
            format,
            output,
            strict,
        } => handle_qdd_validate(path, profile, format, output, strict).await,
    }
}

/// Handle QDD create command
async fn handle_qdd_create(
    code_type: QddCodeType,
    name: String,
    purpose: String,
    profile: QddQualityProfile,
    inputs: Vec<(String, String)>,
    output_type: String,
    output_file: Option<PathBuf>,
) -> Result<()> {
    let qdd_code_type = convert_code_type(code_type);
    let quality_profile = convert_quality_profile(profile);
    let parameters = convert_parameters(inputs);
    let create_spec = build_create_spec(qdd_code_type, name, purpose, parameters, output_type);

    let result = execute_create_operation(quality_profile, create_spec).await?;
    display_create_results(profile, &result);
    output_generated_code(output_file, &result)?;

    Ok(())
}

/// Convert CLI code type to QDD code type
fn convert_code_type(code_type: QddCodeType) -> CodeType {
    match code_type {
        QddCodeType::Function => CodeType::Function,
        QddCodeType::Module => CodeType::Module,
        QddCodeType::Service => CodeType::Service,
        QddCodeType::Test => CodeType::Test,
    }
}

/// Convert CLI quality profile to QDD quality profile
fn convert_quality_profile(profile: QddQualityProfile) -> QualityProfile {
    match profile {
        QddQualityProfile::Extreme => QualityProfile::extreme(),
        QddQualityProfile::Standard => QualityProfile::standard(),
        QddQualityProfile::Relaxed => QualityProfile::relaxed(),
    }
}

/// Convert input parameters to QDD parameters
fn convert_parameters(inputs: Vec<(String, String)>) -> Vec<Parameter> {
    inputs
        .into_iter()
        .map(|(param_type, param_name)| Parameter {
            name: param_name,
            param_type,
            description: None,
        })
        .collect()
}

/// Build create specification
fn build_create_spec(
    code_type: CodeType,
    name: String,
    purpose: String,
    inputs: Vec<Parameter>,
    output_type: String,
) -> CreateSpec {
    CreateSpec {
        code_type,
        name,
        purpose,
        inputs,
        outputs: Parameter {
            name: "result".to_string(),
            param_type: output_type,
            description: Some("Function output".to_string()),
        },
    }
}

/// Execute create operation
async fn execute_create_operation(
    quality_profile: QualityProfile,
    create_spec: CreateSpec,
) -> Result<QddResult> {
    let qdd_tool = QddTool::with_profile(quality_profile);
    let operation = QddOperation::Create(create_spec);
    qdd_tool.execute(operation).await
}

/// Display creation results
///
/// The four numbers here used to be printed as measurements: "Quality Score: 98.0,
/// Complexity: 1, Coverage: 100.0%, TDG Score: 1" — identical for `add two numbers`
/// and for `a distributed consensus engine with retries and backoff`, over a body
/// that is `todo!("Implementation needed")`. Coverage is a literal 100 that no test
/// run ever produced and TDG is a constant, so they are reported as not measured;
/// the complexity/quality figures are labelled as the template estimates they are.
fn display_create_results(profile: QddQualityProfile, result: &QddResult) {
    println!("{}", c::header("QDD Template Generated"));
    println!("{}", c::pass(&format!("Quality Profile: {profile:?}")));

    let is_stub = result.code.contains("todo!");
    if is_stub {
        println!(
            "  {}",
            c::warn("Template only: the generated body is `todo!()` — nothing is implemented yet")
        );
    }

    println!(
        "  {} {} {}",
        c::label("Template complexity (estimated):"),
        c::number(&format!("{}", result.quality_score.complexity)),
        c::dim("(keyword heuristic over the template)")
    );
    println!(
        "  {} {} {}",
        c::label("Template quality score (estimated):"),
        c::number(&format!("{:.1}", result.quality_score.overall)),
        c::dim("(derived from the estimate above, not an analysis of your code)")
    );
    println!(
        "  {} {}",
        c::label("Coverage:"),
        c::dim("not measured (no tests were executed)")
    );
    println!("  {} {}", c::label("TDG Score:"), c::dim("not measured"));
    println!();
}

/// Output generated code to file or stdout
fn output_generated_code(output_file: Option<PathBuf>, result: &QddResult) -> Result<()> {
    if let Some(output_path) = output_file {
        // The documentation is Markdown. It used to be concatenated onto the end of
        // the same file as the code and the tests, so `-o add.rs` produced a file
        // that carried "# add_two", "## Returns" and a ```rust fence after
        // `mod tests` — the emitted .rs could not parse. Rust goes in the source
        // file; the prose goes in a sibling .md.
        let source = format!("{}\n\n{}\n", result.code, result.tests);
        std::fs::write(&output_path, source)?;
        println!(
            "{}",
            c::pass(&format!(
                "Generated code written to: {}",
                c::path(&output_path.display().to_string())
            ))
        );

        if !result.documentation.trim().is_empty() {
            let mut doc_path = output_path.with_extension("md");
            if doc_path == output_path {
                doc_path = output_path.with_extension("doc.md");
            }
            std::fs::write(&doc_path, format!("{}\n", result.documentation))?;
            println!(
                "{}",
                c::pass(&format!(
                    "Generated documentation written to: {}",
                    c::path(&doc_path.display().to_string())
                ))
            );
        }
    } else {
        println!("{}", c::subheader("Generated Code:"));
        println!("{}", result.code);
        println!("\n{}", c::subheader("Generated Tests:"));
        println!("{}", result.tests);
        println!("\n{}", c::subheader("Generated Documentation:"));
        println!("{}", result.documentation);
    }
    Ok(())
}

/// Handle QDD refactor command
async fn handle_qdd_refactor(
    file: PathBuf,
    function: Option<String>,
    profile: QddQualityProfile,
    max_complexity: Option<u32>,
    min_coverage: Option<u32>,
    output: Option<PathBuf>,
    dry_run: bool,
) -> Result<()> {
    validate_file_exists(&file)?;

    let quality_profile = create_quality_profile(profile, max_complexity, min_coverage);
    let refactor_spec = create_refactor_spec(&file, function.clone(), &quality_profile);

    if dry_run {
        return handle_dry_run(&file, &function, profile, &quality_profile);
    }

    let result = execute_refactoring(quality_profile, refactor_spec).await?;
    display_refactor_results(&file, function, profile, &result);
    save_refactored_code(&output.unwrap_or(file), &result.code)?;
    display_rollback_info(&result);

    Ok(())
}

/// Validate that the target file exists
fn validate_file_exists(file: &Path) -> Result<()> {
    if !file.exists() {
        return Err(anyhow::anyhow!("File does not exist: {}", file.display()));
    }
    Ok(())
}

/// Create quality profile with optional overrides
fn create_quality_profile(
    profile: QddQualityProfile,
    max_complexity: Option<u32>,
    min_coverage: Option<u32>,
) -> QualityProfile {
    let mut quality_profile = match profile {
        QddQualityProfile::Extreme => QualityProfile::extreme(),
        QddQualityProfile::Standard => QualityProfile::standard(),
        QddQualityProfile::Relaxed => QualityProfile::relaxed(),
    };

    if let Some(complexity) = max_complexity {
        quality_profile.thresholds.max_complexity = complexity;
    }
    if let Some(coverage) = min_coverage {
        quality_profile.thresholds.min_coverage = coverage;
    }

    quality_profile
}

/// Create refactor specification
fn create_refactor_spec(
    file: &Path,
    function: Option<String>,
    quality_profile: &QualityProfile,
) -> RefactorSpec {
    RefactorSpec {
        file_path: file.to_path_buf(),
        function_name: function,
        target_metrics: quality_profile.thresholds.clone(),
    }
}

/// Handle dry run mode
fn handle_dry_run(
    file: &Path,
    function: &Option<String>,
    profile: QddQualityProfile,
    quality_profile: &QualityProfile,
) -> Result<()> {
    println!(
        "{}",
        c::dim(&format!(
            "DRY RUN: Would refactor file: {}",
            c::path(&file.display().to_string())
        ))
    );
    if let Some(func) = function {
        println!("  {} {}", c::label("Target function:"), func);
    }
    println!("  {} {profile:?}", c::label("Quality profile:"));
    println!(
        "  {} {}",
        c::label("Max complexity:"),
        c::number(&format!("{}", quality_profile.thresholds.max_complexity))
    );
    println!(
        "  {} {}",
        c::label("Min coverage:"),
        c::pct(quality_profile.thresholds.min_coverage as f64, 80.0, 60.0)
    );
    println!(
        "{}",
        c::warn("Use without --dry-run to execute refactoring")
    );
    Ok(())
}

/// Execute the refactoring operation
async fn execute_refactoring(
    quality_profile: QualityProfile,
    refactor_spec: RefactorSpec,
) -> Result<QddResult> {
    let qdd_tool = QddTool::with_profile(quality_profile);
    let operation = QddOperation::Refactor(refactor_spec);
    qdd_tool.execute(operation).await
}

/// Display refactoring results
///
/// Same defect as [`display_create_results`], one command over: "Coverage: 80.0%"
/// came from `CodeAnalyzer::estimate_coverage`, which is `count("#[test]") * 10 /
/// line_count` — no test was compiled, let alone run — and "TDG Score: 0" is a
/// count of the literals `todo!` and `unwrap` in the text, not a TDG score. Both
/// are reported as not measured; the two figures that ARE derived from the code
/// (a keyword count of branching constructs, and the score computed from it) are
/// labelled as the estimates they are. The estimates still drive the refactoring
/// loop's stopping condition — they are just no longer printed as measurements.
fn display_refactor_results(
    file: &Path,
    function: Option<String>,
    profile: QddQualityProfile,
    result: &QddResult,
) {
    print!(
        "{}",
        format_refactor_results(file, function, profile, result)
    );
}

/// The text [`display_refactor_results`] prints, as a string so it can be
/// asserted on.
fn format_refactor_results(
    file: &Path,
    function: Option<String>,
    profile: QddQualityProfile,
    result: &QddResult,
) -> String {
    let mut out = String::new();
    out.push_str(&format!("{}\n", c::header("QDD Refactoring Successful!")));
    out.push_str(&format!(
        "  {} {}\n",
        c::label("File:"),
        c::path(&file.display().to_string())
    ));
    if let Some(func) = function {
        out.push_str(&format!("  {} {}\n", c::label("Function:"), func));
    }
    out.push_str(&format!(
        "{}\n",
        c::pass(&format!("Quality Profile: {profile:?}"))
    ));
    out.push_str(&format!(
        "  {} {} {}\n",
        c::label("Quality score (estimated):"),
        c::number(&format!("{:.1}", result.quality_score.overall)),
        c::dim("(derived from the estimates below, not an analysis run)")
    ));
    out.push_str(&format!(
        "  {} {} {}\n",
        c::label("Complexity (estimated):"),
        c::number(&format!("{}", result.quality_score.complexity)),
        c::dim("(keyword heuristic over the refactored text)")
    ));
    out.push_str(&format!(
        "  {} {}\n",
        c::label("Coverage:"),
        c::dim("not measured (no tests were executed)")
    ));
    out.push_str(&format!(
        "  {} {}\n\n",
        c::label("TDG Score:"),
        c::dim("not measured")
    ));
    out
}

/// Save refactored code to file
fn save_refactored_code(output_path: &Path, code: &str) -> Result<()> {
    std::fs::write(output_path, code)?;
    println!(
        "{}",
        c::pass(&format!(
            "Refactored code written to: {}",
            c::path(&output_path.display().to_string())
        ))
    );
    Ok(())
}

/// Display rollback information if available
fn display_rollback_info(result: &QddResult) {
    if !result.rollback_plan.checkpoints.is_empty() {
        println!(
            "  {} {} rollback checkpoints available",
            c::label("Rollback:"),
            c::number(&format!("{}", result.rollback_plan.checkpoints.len()))
        );
    }
}

/// Handle QDD validate command
async fn handle_qdd_validate(
    path: PathBuf,
    profile: QddQualityProfile,
    format: QddOutputFormat,
    output: Option<PathBuf>,
    strict: bool,
) -> Result<()> {
    // `qdd validate -p /does/not/exist.rs` printed "✓ PASSED" and exited 0.
    crate::cli::ensure_analysis_path_exists(&path)?;

    let quality_profile = match profile {
        QddQualityProfile::Extreme => QualityProfile::extreme(),
        QddQualityProfile::Standard => QualityProfile::standard(),
        QddQualityProfile::Relaxed => QualityProfile::relaxed(),
    };
    let is_json = matches!(format, QddOutputFormat::Json);

    // JSON mode must keep stdout pure (jq-parseable): header goes to humans only
    if !is_json {
        print_validation_header(&path, profile, &quality_profile);
    }

    // This used to be `let validation_passed = true; // Would implement actual
    // validation`, and the Detailed arm printed four hardcoded PASSED lines with
    // no check behind any of them — so every input passed, including a path that
    // did not exist and this repository, whose own printed thresholds
    // ("Max Complexity: 10, Zero SATD: true") it violates. The verdict is now
    // derived from checks that actually run, and the two thresholds this command
    // cannot measure say so instead of passing.
    let outcome = run_validation_checks(&path, &quality_profile).await;
    let validation_passed = outcome.passed();

    match format {
        QddOutputFormat::Summary => {
            println!("\n{}", c::subheader("Validation Summary:"));
            println!("{}", render_status(&outcome));
            for (name, check) in &outcome.checks {
                println!("  {} {}", c::label(&format!("{name}:")), check.describe());
            }
        }
        QddOutputFormat::Detailed => {
            println!("\n{}", c::subheader("Detailed Validation Results:"));
            for (name, check) in &outcome.checks {
                println!("{}", check.render(name));
            }
            println!("{}", render_status(&outcome));
        }
        QddOutputFormat::Json => {
            let json_result = build_validation_json(&outcome, profile, &path);
            println!("{}", serde_json::to_string_pretty(&json_result)?);
        }
        QddOutputFormat::Markdown => {
            println!("# QDD Validation Report");
            println!();
            println!("**Status:** {}", markdown_status(&outcome));
            println!("**Profile:** {profile:?}");
            println!("**Path:** {}", path.display());
            println!(
                "**Date:** {}",
                chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC")
            );
            println!();
            for (name, check) in &outcome.checks {
                println!("- **{name}:** {}", check.describe());
            }
        }
    }

    if let Some(output_path) = output {
        // Write the report before claiming it was written
        let report =
            serde_json::to_string_pretty(&build_validation_json(&outcome, profile, &path))?;
        std::fs::write(&output_path, report)
            .with_context(|| format!("Failed to write report: {}", output_path.display()))?;
        let message = c::pass(&format!(
            "Validation report written to: {}",
            c::path(&output_path.display().to_string())
        ));
        if is_json {
            eprintln!("{message}");
        } else {
            println!("\n{message}");
        }
    }

    if strict && !validation_passed {
        return Err(anyhow::anyhow!(
            "Quality validation did not pass (strict mode): {}",
            outcome.strict_reason()
        ));
    }

    Ok(())
}

/// The result of one threshold this command claims to enforce.
#[derive(Debug, Clone, PartialEq, Eq)]
enum CheckOutcome {
    Passed(String),
    Failed(String),
    /// The threshold is printed by the header but nothing here measures it.
    /// An unmeasured check is never a pass — see the `cuda-tdg` "not measured"
    /// reports for the same rule.
    NotMeasured(String),
}

impl CheckOutcome {
    fn describe(&self) -> String {
        match self {
            Self::Passed(detail) | Self::Failed(detail) | Self::NotMeasured(detail) => {
                detail.clone()
            }
        }
    }

    fn verdict(&self) -> &'static str {
        match self {
            Self::Passed(_) => "passed",
            Self::Failed(_) => "failed",
            Self::NotMeasured(_) => "not measured",
        }
    }

    fn render(&self, name: &str) -> String {
        let line = format!(
            "{name}: {} ({})",
            self.verdict().to_uppercase(),
            self.describe()
        );
        match self {
            Self::Passed(_) => c::pass(&line),
            Self::Failed(_) => c::fail(&line),
            Self::NotMeasured(_) => c::warn(&line),
        }
    }
}

/// Every check this run performed, in the order the header prints them.
struct ValidationOutcome {
    checks: Vec<(&'static str, CheckOutcome)>,
}

impl ValidationOutcome {
    /// `failed` beats `incomplete` beats `passed`: a run that could not measure
    /// a threshold it prints must not report a pass.
    fn status(&self) -> &'static str {
        if self.has(|c| matches!(c, CheckOutcome::Failed(_))) {
            "failed"
        } else if self.has(|c| matches!(c, CheckOutcome::NotMeasured(_))) {
            "incomplete"
        } else {
            "passed"
        }
    }

    fn has(&self, pred: impl Fn(&CheckOutcome) -> bool) -> bool {
        self.checks.iter().any(|(_, c)| pred(c))
    }

    fn passed(&self) -> bool {
        self.status() == "passed"
    }

    fn strict_reason(&self) -> String {
        self.checks
            .iter()
            .filter(|(_, c)| !matches!(c, CheckOutcome::Passed(_)))
            .map(|(name, c)| format!("{name} {}: {}", c.verdict(), c.describe()))
            .collect::<Vec<_>>()
            .join("; ")
    }

    fn violations(&self) -> Vec<serde_json::Value> {
        self.checks
            .iter()
            .filter(|(_, c)| matches!(c, CheckOutcome::Failed(_)))
            .map(|(name, c)| serde_json::json!({ "check": name, "detail": c.describe() }))
            .collect()
    }

    fn unmeasured(&self) -> Vec<serde_json::Value> {
        self.checks
            .iter()
            .filter(|(_, c)| matches!(c, CheckOutcome::NotMeasured(_)))
            .map(|(name, c)| serde_json::json!({ "check": name, "reason": c.describe() }))
            .collect()
    }
}

fn render_status(outcome: &ValidationOutcome) -> String {
    match outcome.status() {
        "passed" => c::pass("PASSED"),
        "failed" => c::fail("FAILED"),
        other => c::warn(&other.to_uppercase()),
    }
}

fn markdown_status(outcome: &ValidationOutcome) -> &'static str {
    match outcome.status() {
        "passed" => "✅ PASSED",
        "failed" => "❌ FAILED",
        _ => "⚠️ INCOMPLETE (some thresholds were not measured)",
    }
}

/// Run the checks behind the thresholds the header prints.
async fn run_validation_checks(path: &Path, profile: &QualityProfile) -> ValidationOutcome {
    let thresholds = &profile.thresholds;
    ValidationOutcome {
        checks: vec![
            ("complexity", check_complexity(path, thresholds.max_complexity).await),
            ("technical debt", check_satd(path, thresholds.zero_satd).await),
            (
                "coverage",
                CheckOutcome::NotMeasured(format!(
                    "min {}% required; coverage needs an instrumented test run (cargo llvm-cov), which this command does not perform",
                    thresholds.min_coverage
                )),
            ),
            (
                "tdg",
                CheckOutcome::NotMeasured(format!(
                    "max {} allowed; run `pmat tdg` — this command does not compute TDG",
                    thresholds.max_tdg
                )),
            ),
        ],
    }
}

/// Source files this command can analyse under `path`.
fn collect_analysable_files(path: &Path) -> Vec<PathBuf> {
    use crate::cli::language_analyzer::Language;

    let candidates = if path.is_file() {
        vec![path.to_path_buf()]
    } else {
        crate::services::file_discovery::ProjectFileDiscovery::new(path.to_path_buf())
            .discover_files()
            .unwrap_or_default()
    };

    candidates
        .into_iter()
        .filter(|p| {
            !matches!(
                Language::from_path(p),
                Language::Unknown | Language::Markdown | Language::Yaml
            )
        })
        .collect()
}

/// Worst cyclomatic complexity under `path` against the profile threshold.
async fn check_complexity(path: &Path, max_complexity: u32) -> CheckOutcome {
    let files = collect_analysable_files(path);
    let mut worst: Option<(String, u16)> = None;
    let mut analyzed = 0usize;

    for file in &files {
        let Ok(metrics) =
            crate::services::complexity::analyze_file_complexity_uncached(file, None).await
        else {
            continue;
        };
        analyzed += 1;
        for func in &metrics.functions {
            if worst
                .as_ref()
                .is_none_or(|(_, c)| func.metrics.cyclomatic > *c)
            {
                worst = Some((
                    format!("{}::{}", metrics.path, func.name),
                    func.metrics.cyclomatic,
                ));
            }
        }
    }

    match worst {
        // Nothing read means nothing measured; a clean pass over zero files is
        // the fabrication this whole command was guilty of.
        None => CheckOutcome::NotMeasured(format!(
            "no functions were read under {} ({analyzed} file(s) analysed)",
            path.display()
        )),
        Some((name, cyclomatic)) if u32::from(cyclomatic) > max_complexity => CheckOutcome::Failed(
            format!("{name} has cyclomatic complexity {cyclomatic}, over the limit of {max_complexity} ({analyzed} file(s) analysed)"),
        ),
        Some((name, cyclomatic)) => CheckOutcome::Passed(format!(
            "worst function {name} at cyclomatic {cyclomatic}, within {max_complexity} ({analyzed} file(s) analysed)"
        )),
    }
}

/// Self-admitted technical debt against the profile's `zero_satd` threshold.
async fn check_satd(path: &Path, zero_satd: bool) -> CheckOutcome {
    use crate::services::satd_detector::SATDDetector;

    if !zero_satd {
        return CheckOutcome::Passed("this profile does not require zero SATD".to_string());
    }

    let detector = SATDDetector::new();
    let debts = if path.is_file() {
        match std::fs::read_to_string(path) {
            Ok(content) => detector.extract_from_content(&content, path).ok(),
            Err(_) => None,
        }
    } else {
        detector.analyze_directory(path).await.ok()
    };

    match debts {
        None => CheckOutcome::NotMeasured(format!("could not scan {} for SATD", path.display())),
        Some(debts) if debts.is_empty() => {
            CheckOutcome::Passed("no self-admitted technical debt found".to_string())
        }
        Some(debts) => {
            let first = debts
                .first()
                .map(|d| format!("{}:{}", d.file.display(), d.line))
                .unwrap_or_default();
            CheckOutcome::Failed(format!(
                "{} self-admitted debt marker(s), first at {first}",
                debts.len()
            ))
        }
    }
}

/// Print the validation header and thresholds (human formats only)
fn print_validation_header(
    path: &Path,
    profile: QddQualityProfile,
    quality_profile: &QualityProfile,
) {
    println!("{}", c::header("QDD Quality Validation"));
    println!(
        "  {} {}",
        c::label("Path:"),
        c::path(&path.display().to_string())
    );
    println!("{}", c::pass(&format!("Quality Profile: {profile:?}")));
    println!("{}", c::subheader("Thresholds:"));
    println!(
        "  {} {}",
        c::label("Max Complexity:"),
        c::number(&format!("{}", quality_profile.thresholds.max_complexity))
    );
    println!(
        "  {} {}",
        c::label("Min Coverage:"),
        c::pct(quality_profile.thresholds.min_coverage as f64, 80.0, 60.0)
    );
    println!(
        "  {} {}",
        c::label("Max TDG:"),
        c::number(&format!("{}", quality_profile.thresholds.max_tdg))
    );
    println!(
        "  {} {}",
        c::label("Zero SATD:"),
        c::number(&format!("{}", quality_profile.thresholds.zero_satd))
    );
}

/// Build the JSON payload for validation results (stdout in JSON mode is this payload only)
///
/// The payload used to be `{status, profile, path, validation_time}` with no
/// field able to carry a violation — status was always "passed" and there was
/// nowhere for a failure to appear even if one had been found. `checks`,
/// `violations` and `not_measured` make the verdict auditable.
fn build_validation_json(
    outcome: &ValidationOutcome,
    profile: QddQualityProfile,
    path: &Path,
) -> serde_json::Value {
    serde_json::json!({
        "status": outcome.status(),
        "profile": format!("{profile:?}").to_lowercase(),
        "path": path.display().to_string(),
        "checks": outcome.checks.iter().map(|(name, check)| serde_json::json!({
            "check": name,
            "result": check.verdict(),
            "detail": check.describe(),
        })).collect::<Vec<_>>(),
        "violations": outcome.violations(),
        "not_measured": outcome.unmeasured(),
        "validation_time": chrono::Utc::now().to_rfc3339()
    })
}

// Tests extracted to qdd_handlers_tests.rs for file health (CB-040).
include!("qdd_handlers_tests.rs");

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod qdd_output_tests {
    use super::*;
    use crate::qdd::{QualityMetrics, QualityScore, RollbackPlan};

    fn sample_result() -> QddResult {
        QddResult {
            code:
                "pub fn add_two(a: i32, b: i32) -> i32 {\n    todo!(\"Implementation needed\")\n}\n"
                    .to_string(),
            tests: "#[cfg(test)]\nmod tests {\n    use super::*;\n}\n".to_string(),
            documentation:
                "# add_two\n\nadd two numbers\n\n## Returns\n\n```rust\nlet x = 1;\n```\n"
                    .to_string(),
            quality_score: QualityScore {
                overall: 98.0,
                complexity: 1,
                coverage: 100.0,
                tdg: 1,
            },
            metrics: QualityMetrics::default(),
            rollback_plan: RollbackPlan {
                original: String::new(),
                checkpoints: vec![],
            },
        }
    }

    /// Strip ANSI SGR sequences so assertions see the words, not the colours.
    fn plain(s: &str) -> String {
        let mut out = String::new();
        let mut chars = s.chars();
        while let Some(ch) = chars.next() {
            if ch == '\u{1b}' {
                for c in chars.by_ref() {
                    if c == 'm' {
                        break;
                    }
                }
            } else {
                out.push(ch);
            }
        }
        out
    }

    /// `pmat qdd refactor` printed "Coverage: 80.0%" and "TDG Score: 0" for
    /// every run: coverage came from `#[test]` occurrences x 10 / line count
    /// (no test was ever executed) and "TDG" was a count of the literals
    /// `todo!` and `unwrap`. Neither may be printed as a measurement.
    #[test]
    fn refactor_results_do_not_print_a_coverage_measurement() {
        let mut result = sample_result();
        result.quality_score.coverage = 80.0;
        result.quality_score.tdg = 0;

        let text = plain(&format_refactor_results(
            Path::new("src/lib.rs"),
            None,
            QddQualityProfile::Standard,
            &result,
        ));

        assert!(
            text.contains("Coverage: not measured"),
            "coverage must be reported as not measured, got:\n{text}"
        );
        assert!(
            text.contains("TDG Score: not measured"),
            "TDG must be reported as not measured, got:\n{text}"
        );
        assert!(
            !text.contains("80.0%"),
            "the coverage guess must not be printed as a percentage:\n{text}"
        );
        // The figures that ARE derived from the code stay, labelled as estimates.
        assert!(
            text.contains("Complexity (estimated):"),
            "the complexity estimate must say it is an estimate:\n{text}"
        );
    }

    /// The Markdown documentation used to be appended to the generated .rs, leaving
    /// a source file that cannot parse. The .rs must contain Rust only.
    #[test]
    fn test_documentation_is_not_appended_to_the_rust_file() {
        let tmp = tempfile::TempDir::new().unwrap();
        let rs_path = tmp.path().join("add.rs");

        output_generated_code(Some(rs_path.clone()), &sample_result()).unwrap();

        let source = std::fs::read_to_string(&rs_path).unwrap();
        assert!(source.contains("pub fn add_two"), "code missing: {source}");
        assert!(source.contains("mod tests"), "tests missing: {source}");
        assert!(
            !source.contains("# add_two"),
            "markdown heading leaked into the .rs: {source}"
        );
        assert!(
            !source.contains("## Returns"),
            "markdown heading leaked into the .rs: {source}"
        );
        assert!(
            !source.contains("```"),
            "markdown fence leaked into the .rs: {source}"
        );
        // The .rs must be parseable Rust.
        syn::parse_file(&source).expect("generated .rs must parse as Rust");

        let doc = std::fs::read_to_string(tmp.path().join("add.md")).unwrap();
        assert!(doc.contains("## Returns"), "docs missing: {doc}");
    }
}