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
/// Handle spec score command (S-001)
/// Validates specification with 100-point Popperian score
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn handle_spec_score(
    spec_path: &Path,
    format: SpecOutputFormat,
    output: Option<&Path>,
    verbose: bool,
) -> anyhow::Result<()> {
    let parser = SpecParser::new();
    let spec = parser.parse_file(spec_path)?;

    // Simple score calculation (will be enhanced with full validation)
    let score = calculate_spec_score(&spec);

    let output_text = match format {
        SpecOutputFormat::Text => format_spec_score_text(&spec, score, verbose),
        SpecOutputFormat::Json => format_spec_score_json(&spec, score)?,
        SpecOutputFormat::Markdown => format_spec_score_markdown(&spec, score),
    };

    if let Some(output_path) = output {
        use crate::cli::colors as c;
        fs::write(output_path, &output_text)?;
        println!("{}", c::pass(&format!("Spec score written to {}", c::path(&output_path.display().to_string()))));
    } else {
        println!("{}", output_text);
    }

    // Fail if below 95 threshold (S-002)
    if score < 95.0 {
        use crate::cli::colors as c;
        println!(
            "\n{}",
            c::warn(&format!(
                "Spec score {:.1} is below 95 threshold. Run `pmat spec comply` to fix.",
                score
            ))
        );
        std::process::exit(1);
    }

    Ok(())
}

/// Handle spec comply command (S-003)
/// Auto-fixes spec issues to meet 95-point threshold
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn handle_spec_comply(
    spec_path: &Path,
    dry_run: bool,
    _format: SpecOutputFormat,
) -> anyhow::Result<()> {
    let parser = SpecParser::new();
    let spec = parser.parse_file(spec_path)?;

    let mut fixes: Vec<String> = Vec::new();

    // Check minimum requirements and suggest fixes
    if spec.issue_refs.is_empty() {
        fixes.push(
            "- Add issue_refs in YAML frontmatter (e.g., issue_refs: [\"#123\"])".to_string(),
        );
    }

    if spec.code_examples.len() < 5 {
        fixes.push(format!(
            "- Add {} more code examples (minimum 5 required)",
            5 - spec.code_examples.len()
        ));
    }

    if spec.acceptance_criteria.len() < 10 {
        fixes.push(format!(
            "- Add {} more acceptance criteria (minimum 10 required)",
            10 - spec.acceptance_criteria.len()
        ));
    }

    // Count unique citations [1], [2], etc. from full spec content
    let citation_count = {
        let mut seen = std::collections::HashSet::new();
        let re = regex::Regex::new(r"\[(\d+)\]").expect("internal error");
        for caps in re.captures_iter(&spec.raw_content) {
            if let Some(m) = caps.get(1) {
                seen.insert(m.as_str().to_string());
            }
        }
        seen.len()
    };
    if citation_count < 5 {
        fixes.push(format!(
            "- Add {} more peer-reviewed citations (found {}, minimum 5 required)",
            5 - citation_count,
            citation_count
        ));
    }

    if fixes.is_empty() {
        use crate::cli::colors as c;
        println!("{}", c::pass("Spec already meets all requirements!"));
        return Ok(());
    }

    {
        use crate::cli::colors as c;
        println!("{}\n", c::header("Spec Compliance Issues Found:"));
        for fix in &fixes {
            println!("{}", fix);
        }

        if dry_run {
            println!("\n{}", c::dim("(Dry run - no changes made)"));
        } else {
            println!("\n{}", c::warn("Auto-fix not yet implemented. Please apply fixes manually."));
        }
    }

    Ok(())
}

/// Handle spec create command
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn handle_spec_create(
    name: &str,
    issue: Option<&str>,
    epic: Option<&str>,
    output: Option<&Path>,
) -> anyhow::Result<()> {
    let slug = name.to_lowercase().replace(' ', "-");
    let output_dir = output
        .map(|p| p.to_path_buf())
        .unwrap_or_else(|| Path::new("docs/specifications").to_path_buf());

    let file_path = output_dir.join(format!("{}.md", slug));

    let issue_ref = issue.unwrap_or("#TODO");
    let epic_name = epic.unwrap_or("PMAT-TODO");
    let date = chrono::Local::now().format("%Y-%m-%d");

    let template = format!(
        r#"---
title: "{name}"
version: "1.0.0"
status: "Draft"
created: "{date}"
updated: "{date}"
issue_refs: ["{issue_ref}"]
epic: "{epic_name}"
---

# {name}

## Executive Summary

[Brief description of what this specification defines]

## Scientific Foundation

[Cite minimum 5 peer-reviewed sources]

1. [Author et al., Year. Title. Journal/Conference.]
2. [...]

## Requirements

### Functional Requirements

- [ ] FR-001: [Requirement description]
- [ ] FR-002: [Requirement description]

### Non-Functional Requirements

- [ ] NFR-001: [Performance requirement]
- [ ] NFR-002: [Security requirement]

## Acceptance Criteria

### Category 1 (AC-001 to AC-005)

- [ ] AC-001: [Testable criterion]
- [ ] AC-002: [Testable criterion]
- [ ] AC-003: [Testable criterion]
- [ ] AC-004: [Testable criterion]
- [ ] AC-005: [Testable criterion]

### Category 2 (AC-006 to AC-010)

- [ ] AC-006: [Testable criterion]
- [ ] AC-007: [Testable criterion]
- [ ] AC-008: [Testable criterion]
- [ ] AC-009: [Testable criterion]
- [ ] AC-010: [Testable criterion]

## Code Examples

### Example 1: Basic Usage

```rust
// Example code here
```

### Example 2: Advanced Usage

```rust
// Example code here
```

### Example 3: Error Handling

```rust
// Example code here
```

### Example 4: Integration

```rust
// Example code here
```

### Example 5: Performance

```rust
// Example code here
```

## Testing Strategy

- Unit tests: [Coverage target]
- Integration tests: [Scope]
- Property tests: [Properties to verify]

## References

[1] [Citation]
[2] [Citation]
[3] [Citation]
[4] [Citation]
[5] [Citation]
"#
    );

    // Create directory if needed
    if let Some(parent) = file_path.parent() {
        fs::create_dir_all(parent)?;
    }

    fs::write(&file_path, template)?;
    {
        use crate::cli::colors as c;
        println!("{}", c::pass(&format!("Created specification: {}", c::path(&file_path.display().to_string()))));
        println!("\n{}", c::label("Next steps:"));
        println!("  1. Edit the specification with your requirements");
        println!(
            "  2. Run `{}` to validate",
            c::label(&format!("pmat spec score {}", file_path.display()))
        );
        println!(
            "  3. Run `{}` to fix issues",
            c::label(&format!("pmat spec comply {}", file_path.display()))
        );
    }

    Ok(())
}

/// Handle spec list command
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn handle_spec_list(
    path: &Path,
    min_score: Option<u8>,
    failing_only: bool,
    format: SpecOutputFormat,
) -> anyhow::Result<()> {
    let parser = SpecParser::new();
    let specs = parser.find_specs(path)?;

    let mut results = Vec::new();

    for spec_path in specs {
        if let Ok(spec) = parser.parse_file(&spec_path) {
            let score = calculate_spec_score(&spec);
            let passing = score >= 95.0;

            if let Some(min) = min_score {
                if score < f64::from(min) {
                    continue;
                }
            }

            if failing_only && passing {
                continue;
            }

            results.push((spec_path, spec.title.clone(), score, passing));
        }
    }

    print_spec_list(&results, path, format)?;

    Ok(())
}

fn spec_display_name<'a>(path: &'a Path, title: &'a str) -> &'a str {
    if title.is_empty() {
        path.file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("unknown")
    } else {
        title
    }
}

fn print_spec_list(
    results: &[(std::path::PathBuf, String, f64, bool)],
    dir: &Path,
    format: SpecOutputFormat,
) -> anyhow::Result<()> {
    match format {
        SpecOutputFormat::Text => {
            use crate::cli::colors as c;
            println!("{}\n", c::header(&format!("Specifications in {}", c::path(&dir.display().to_string()))));
            println!(
                "{}{:<50}{} {:>8} {:>8}",
                c::BOLD, "SPECIFICATION", c::RESET, "SCORE", "STATUS"
            );
            println!("{}", c::separator());
            for (path, title, score, passing) in results {
                let status = if *passing {
                    c::pass("PASS")
                } else {
                    c::fail("FAIL")
                };
                let score_str = c::pct(*score, 95.0, 80.0);
                println!("{:<50} {:>15} {}", spec_display_name(path, title), score_str, status);
            }
            println!(
                "\n{} {} specs, {} passing",
                c::label("Total:"),
                c::number(&results.len().to_string()),
                c::number(&results.iter().filter(|(_, _, _, p)| *p).count().to_string())
            );
        }
        SpecOutputFormat::Json => {
            let json_results: Vec<_> = results
                .iter()
                .map(|(path, title, score, passing)| {
                    serde_json::json!({
                        "path": path.display().to_string(),
                        "title": title,
                        "score": score,
                        "passing": passing,
                    })
                })
                .collect();
            println!("{}", serde_json::to_string_pretty(&json_results)?);
        }
        SpecOutputFormat::Markdown => {
            println!("# Specification Status Report\n");
            println!("| Specification | Score | Status |");
            println!("|---------------|-------|--------|");
            for (path, title, score, passing) in results {
                let status = if *passing { "✅ PASS" } else { "❌ FAIL" };
                println!("| {} | {:.1} | {} |", spec_display_name(path, title), score, status);
            }
        }
    }
    Ok(())
}

#[cfg(test)]
mod spec_handlers_commands_tests {
    //! Covers spec_display_name + print_spec_list dispatcher in
    //! spec_handlers_commands.rs (49 uncov on broad, 0% cov).
    use super::*;
    use std::path::PathBuf;

    // ── spec_display_name: title vs path-stem fallback ──

    #[test]
    fn test_spec_display_name_uses_title_when_present() {
        let path = std::path::Path::new("docs/some-spec.md");
        assert_eq!(spec_display_name(path, "My Spec Title"), "My Spec Title");
    }

    #[test]
    fn test_spec_display_name_falls_back_to_file_stem_when_title_empty() {
        let path = std::path::Path::new("docs/some-spec.md");
        assert_eq!(spec_display_name(path, ""), "some-spec");
    }

    #[test]
    fn test_spec_display_name_unknown_when_no_stem_no_title() {
        let path = std::path::Path::new("");
        // Empty path → no stem → "unknown".
        assert_eq!(spec_display_name(path, ""), "unknown");
    }

    // ── print_spec_list: dispatch all 3 formats ──

    fn sample_results() -> Vec<(PathBuf, String, f64, bool)> {
        vec![
            (PathBuf::from("docs/spec-1.md"), "Spec 1".into(), 96.0, true),
            (PathBuf::from("docs/spec-2.md"), "Spec 2".into(), 60.0, false),
            (PathBuf::from("docs/spec-3.md"), String::new(), 95.0, true),
        ]
    }

    #[test]
    fn test_print_spec_list_text_format_no_panic() {
        let results = sample_results();
        let dir = std::path::Path::new("docs");
        print_spec_list(&results, dir, SpecOutputFormat::Text).unwrap();
    }

    #[test]
    fn test_print_spec_list_json_format_no_panic() {
        let results = sample_results();
        let dir = std::path::Path::new("docs");
        print_spec_list(&results, dir, SpecOutputFormat::Json).unwrap();
    }

    #[test]
    fn test_print_spec_list_markdown_format_no_panic() {
        let results = sample_results();
        let dir = std::path::Path::new("docs");
        print_spec_list(&results, dir, SpecOutputFormat::Markdown).unwrap();
    }

    #[test]
    fn test_print_spec_list_empty_results_text_no_panic() {
        let dir = std::path::Path::new("docs");
        print_spec_list(&[], dir, SpecOutputFormat::Text).unwrap();
    }

    #[test]
    fn test_print_spec_list_empty_results_json_emits_empty_array() {
        let dir = std::path::Path::new("docs");
        // Json branch runs serde_json::to_string_pretty over [] without panic.
        print_spec_list(&[], dir, SpecOutputFormat::Json).unwrap();
    }

    #[test]
    fn test_print_spec_list_empty_results_markdown_no_panic() {
        let dir = std::path::Path::new("docs");
        print_spec_list(&[], dir, SpecOutputFormat::Markdown).unwrap();
    }
}