pmat 3.15.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
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
    async fn test_handle_spec_create_with_epic() {
        let temp_dir = TempDir::new().unwrap();
        let output_path = temp_dir.path();

        let result =
            handle_spec_create("Epic Feature", None, Some("EPIC-001"), Some(output_path)).await;

        assert!(result.is_ok());

        let expected_file = output_path.join("epic-feature.md");
        let content = fs::read_to_string(&expected_file).unwrap();
        assert!(content.contains("EPIC-001"));
    }

    #[tokio::test]
    async fn test_handle_spec_create_slug_conversion() {
        let temp_dir = TempDir::new().unwrap();
        let output_path = temp_dir.path();

        let result = handle_spec_create(
            "Complex Feature Name With Spaces",
            None,
            None,
            Some(output_path),
        )
        .await;

        assert!(result.is_ok());

        let expected_file = output_path.join("complex-feature-name-with-spaces.md");
        assert!(expected_file.exists());
    }

    #[tokio::test]
    async fn test_handle_spec_create_template_structure() {
        let temp_dir = TempDir::new().unwrap();
        let output_path = temp_dir.path();

        let result =
            handle_spec_create("Template Test", None, None, Some(output_path)).await;

        assert!(result.is_ok());

        let expected_file = output_path.join("template-test.md");
        let content = fs::read_to_string(&expected_file).unwrap();

        // Check template has all required sections
        assert!(content.contains("---")); // YAML frontmatter
        assert!(content.contains("## Executive Summary"));
        assert!(content.contains("## Scientific Foundation"));
        assert!(content.contains("## Requirements"));
        assert!(content.contains("### Functional Requirements"));
        assert!(content.contains("### Non-Functional Requirements"));
        assert!(content.contains("## Acceptance Criteria"));
        assert!(content.contains("## Code Examples"));
        assert!(content.contains("## Testing Strategy"));
        assert!(content.contains("## References"));
    }

    #[tokio::test]
    async fn test_handle_spec_create_creates_directory() {
        let temp_dir = TempDir::new().unwrap();
        let nested_path = temp_dir.path().join("nested").join("specs");

        let result =
            handle_spec_create("Nested Spec", None, None, Some(&nested_path)).await;

        assert!(result.is_ok());
        assert!(nested_path.exists());
    }

    // ============================================================================
    // Tests for handle_spec_comply (async)
    // ============================================================================

    #[tokio::test]
    async fn test_handle_spec_comply_compliant_spec() {
        let temp_dir = TempDir::new().unwrap();
        let spec_path = temp_dir.path().join("compliant.md");

        // Create a compliant spec with all requirements met
        let content = create_compliant_spec_content();
        fs::write(&spec_path, content).unwrap();

        let result =
            handle_spec_comply(&spec_path, true, SpecOutputFormat::Text).await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_handle_spec_comply_missing_issue_refs() {
        let temp_dir = TempDir::new().unwrap();
        let spec_path = temp_dir.path().join("no-issues.md");

        let content = r#"---
title: No Issues Spec
---
# No Issues Spec

## Requirements
- [ ] AC-001: First
"#;
        fs::write(&spec_path, content).unwrap();

        // The function should succeed but report the missing issue refs
        let result =
            handle_spec_comply(&spec_path, true, SpecOutputFormat::Text).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_handle_spec_comply_missing_code_examples() {
        let temp_dir = TempDir::new().unwrap();
        let spec_path = temp_dir.path().join("no-code.md");

        let content = r##"---
title: No Code Spec
issue_refs: ["#123"]
---
# No Code Spec

## Requirements
- [ ] AC-001: First
"##;
        fs::write(&spec_path, content).unwrap();

        let result =
            handle_spec_comply(&spec_path, true, SpecOutputFormat::Text).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_handle_spec_comply_dry_run_no_changes() {
        let temp_dir = TempDir::new().unwrap();
        let spec_path = temp_dir.path().join("dryrun.md");

        let content = r#"---
title: Dry Run Spec
---
# Dry Run Spec
"#;
        fs::write(&spec_path, content).unwrap();

        let original_content = fs::read_to_string(&spec_path).unwrap();

        let result =
            handle_spec_comply(&spec_path, true, SpecOutputFormat::Text).await;
        assert!(result.is_ok());

        // Content should be unchanged in dry run
        let final_content = fs::read_to_string(&spec_path).unwrap();
        assert_eq!(original_content, final_content);
    }

    #[tokio::test]
    async fn test_handle_spec_comply_file_not_found() {
        let result = handle_spec_comply(
            Path::new("/nonexistent/path/spec.md"),
            true,
            SpecOutputFormat::Text,
        )
        .await;

        assert!(result.is_err());
    }

    // ============================================================================
    // Tests for handle_spec_list (async)
    // ============================================================================

    #[tokio::test]
    async fn test_handle_spec_list_empty_directory() {
        let temp_dir = TempDir::new().unwrap();

        let result = handle_spec_list(
            temp_dir.path(),
            None,
            false,
            SpecOutputFormat::Text,
        )
        .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_handle_spec_list_with_specs() {
        let temp_dir = TempDir::new().unwrap();

        // Create a few spec files
        let spec1 = temp_dir.path().join("spec1.md");
        let spec2 = temp_dir.path().join("spec2.md");

        fs::write(&spec1, create_compliant_spec_content()).unwrap();
        fs::write(&spec2, "# Simple Spec\n").unwrap();

        let result = handle_spec_list(
            temp_dir.path(),
            None,
            false,
            SpecOutputFormat::Text,
        )
        .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_handle_spec_list_min_score_filter() {
        let temp_dir = TempDir::new().unwrap();

        let spec1 = temp_dir.path().join("high-score.md");
        let spec2 = temp_dir.path().join("low-score.md");

        fs::write(&spec1, create_compliant_spec_content()).unwrap();
        fs::write(&spec2, "# Low Score\n").unwrap();

        let result = handle_spec_list(
            temp_dir.path(),
            Some(50), // Only specs with score >= 50
            false,
            SpecOutputFormat::Text,
        )
        .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_handle_spec_list_failing_only() {
        let temp_dir = TempDir::new().unwrap();

        let spec1 = temp_dir.path().join("failing.md");
        fs::write(&spec1, "# Failing Spec\n").unwrap();

        let result = handle_spec_list(
            temp_dir.path(),
            None,
            true, // failing_only
            SpecOutputFormat::Text,
        )
        .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_handle_spec_list_json_format() {
        let temp_dir = TempDir::new().unwrap();

        let spec1 = temp_dir.path().join("spec.md");
        fs::write(&spec1, create_compliant_spec_content()).unwrap();

        let result = handle_spec_list(
            temp_dir.path(),
            None,
            false,
            SpecOutputFormat::Json,
        )
        .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_handle_spec_list_markdown_format() {
        let temp_dir = TempDir::new().unwrap();

        let spec1 = temp_dir.path().join("spec.md");
        fs::write(&spec1, create_compliant_spec_content()).unwrap();

        let result = handle_spec_list(
            temp_dir.path(),
            None,
            false,
            SpecOutputFormat::Markdown,
        )
        .await;

        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_handle_spec_list_single_file() {
        let temp_dir = TempDir::new().unwrap();
        let spec_path = temp_dir.path().join("single.md");

        fs::write(&spec_path, create_compliant_spec_content()).unwrap();

        // Pass a file path instead of directory
        let result = handle_spec_list(
            &spec_path,
            None,
            false,
            SpecOutputFormat::Text,
        )
        .await;

        assert!(result.is_ok());
    }

    // ============================================================================
    // Edge case tests
    // ============================================================================

    #[test]
    fn test_calculate_spec_score_boundary_at_95() {
        // Test score exactly at passing threshold
        let mut spec = create_empty_spec();
        spec.title = "Test".to_string(); // 5 pts
        spec.issue_refs = vec!["#1".to_string()]; // 10 pts
        spec.code_examples = (0..5)
            .map(|i| CodeExample {
                language: "rust".to_string(),
                code: format!("fn f{}() {{}}", i),
                line: i,
                executable: true,
            })
            .collect(); // 20 pts
        spec.acceptance_criteria = (0..10)
            .map(|i| AcceptanceCriterion {
                text: format!("AC-{}", i),
                complete: false,
                line: i,
            })
            .collect(); // 30 pts
        spec.claims = (0..20)
            .map(|i| ValidationClaim {
                id: format!("C-{}", i),
                text: format!("Claim {}", i),
                line: i,
                category: ClaimCategory::Implementation,
                automatable: false,
                validation_cmd: None,
                expected_pattern: None,
            })
            .collect(); // 20 pts
        spec.test_requirements = (0..5)
            .map(|i| TestRequirement {
                text: format!("Test {}", i),
                test_type: "unit".to_string(),
                code_path: None,
            })
            .collect(); // 15 pts

        let score = calculate_spec_score(&spec);
        // Total should be exactly 100
        assert_eq!(score, 100.0);
        assert!(score >= 95.0);
    }

    #[test]
    fn test_calculate_spec_score_just_below_95() {
        let mut spec = create_empty_spec();
        spec.title = "Test".to_string(); // 5 pts
        spec.issue_refs = vec!["#1".to_string()]; // 10 pts
        spec.code_examples = (0..5)
            .map(|i| CodeExample {
                language: "rust".to_string(),
                code: format!("fn f{}() {{}}", i),
                line: i,
                executable: true,
            })
            .collect(); // 20 pts
        spec.acceptance_criteria = (0..10)
            .map(|i| AcceptanceCriterion {
                text: format!("AC-{}", i),
                complete: false,
                line: i,
            })
            .collect(); // 30 pts
        spec.claims = (0..19)
            .map(|i| ValidationClaim {
                id: format!("C-{}", i),
                text: format!("Claim {}", i),
                line: i,
                category: ClaimCategory::Implementation,
                automatable: false,
                validation_cmd: None,
                expected_pattern: None,
            })
            .collect(); // 19 pts (one less)
        spec.test_requirements = (0..5)
            .map(|i| TestRequirement {
                text: format!("Test {}", i),
                test_type: "unit".to_string(),
                code_path: None,
            })
            .collect(); // 15 pts

        let score = calculate_spec_score(&spec);
        // Total should be 99 (just under max, but tests boundary logic)
        assert_eq!(score, 99.0);
    }

    #[test]
    fn test_format_outputs_consistency() {
        // Ensure all format functions handle the same spec consistently
        let spec = create_full_spec();
        let score = calculate_spec_score(&spec);

        let text = format_spec_score_text(&spec, score, false);
        let json_result = format_spec_score_json(&spec, score);
        let markdown = format_spec_score_markdown(&spec, score);

        // All should succeed
        assert!(!text.is_empty());
        assert!(json_result.is_ok());
        assert!(!markdown.is_empty());

        // All should indicate passing for a full spec
        assert!(text.contains("PASS"));
        let json: serde_json::Value = serde_json::from_str(&json_result.unwrap()).unwrap();
        assert_eq!(json["passing"], true);
        assert!(markdown.contains("PASS"));
    }

    #[test]
    fn test_format_outputs_failing_consistency() {
        let spec = create_empty_spec();
        let score = calculate_spec_score(&spec);

        let text = format_spec_score_text(&spec, score, false);
        let json_result = format_spec_score_json(&spec, score);
        let markdown = format_spec_score_markdown(&spec, score);

        // All should indicate failing for an empty spec
        assert!(text.contains("FAIL"));
        let json: serde_json::Value = serde_json::from_str(&json_result.unwrap()).unwrap();
        assert_eq!(json["passing"], false);
        assert!(markdown.contains("FAIL"));
    }

    // ============================================================================
    // Helper function to create a compliant spec content
    // ============================================================================

    fn create_compliant_spec_content() -> String {
        r##"---
title: Compliant Specification
status: Active
issue_refs: ["#123", "#456"]
---

# Compliant Specification

## Executive Summary

This is a compliant spec with [citation1] and [citation2].

## Scientific Foundation

1. Author et al., 2024. Paper Title. [citation3]
2. Another et al., 2024. Another Paper. [citation4]
3. Third et al., 2024. Third Paper. [citation5]

## Requirements

### Functional Requirements

The system MUST provide functionality.
The system SHOULD handle errors gracefully.
The system SHALL be backwards compatible.

### Non-Functional Requirements

Performance MUST be within acceptable limits.

## Acceptance Criteria

### Core Criteria

- [ ] AC-001: First criterion
- [ ] AC-002: Second criterion
- [ ] AC-003: Third criterion
- [ ] AC-004: Fourth criterion
- [ ] AC-005: Fifth criterion
- [ ] AC-006: Sixth criterion
- [ ] AC-007: Seventh criterion
- [ ] AC-008: Eighth criterion
- [ ] AC-009: Ninth criterion
- [ ] AC-010: Tenth criterion

## Code Examples

### Example 1

```rust
fn example_one() {
    println!("Example 1");
}
```

### Example 2

```rust
fn example_two() {
    println!("Example 2");
}
```

### Example 3

```rust
fn example_three() {
    println!("Example 3");
}
```

### Example 4

```rust
fn example_four() {
    println!("Example 4");
}
```

### Example 5

```rust
fn example_five() {
    println!("Example 5");
}
```

## Testing Strategy

Unit tests must cover 95% of the codebase.
Integration tests must validate all endpoints.
Property tests should verify invariants.
E2e tests should test the full workflow.
Mutation tests should validate test quality.

## References

[citation1] Reference 1
[citation2] Reference 2
[citation3] Reference 3
[citation4] Reference 4
[citation5] Reference 5
"##
        .to_string()
    }
}