pmat 2.93.1

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
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
//! AGENTS.md Parser Implementation
//!
//! Parses markdown files following the AGENTS.md specification with quality validation.

use super::{SectionType, AgentsMdDocument, DocumentMetadata, PathBuf, Section, Command, Guideline, Priority, QualityRules};
use anyhow::Result;
use pulldown_cmark::{Event, HeadingLevel, Parser as MarkdownParser, Tag, TagEnd};
use regex::Regex;
use std::collections::HashMap;

/// Parser for AGENTS.md documents
pub struct AgentsMdParser {
    /// Validation rules
    validation_rules: ValidationRules,

    /// Command patterns
    command_patterns: Vec<Regex>,
}

/// Validation rules for parsing
#[derive(Debug, Clone)]
pub struct ValidationRules {
    /// Require project overview section
    pub require_overview: bool,

    /// Require testing instructions
    pub require_testing: bool,

    /// Maximum document size in bytes
    pub max_size: usize,

    /// Allowed section types
    pub allowed_sections: Vec<SectionType>,
}

impl Default for ValidationRules {
    fn default() -> Self {
        Self {
            require_overview: false,
            require_testing: false,
            max_size: 1024 * 1024, // 1MB
            allowed_sections: vec![
                SectionType::Overview,
                SectionType::DevEnvironment,
                SectionType::Testing,
                SectionType::CodeStyle,
                SectionType::PRGuidelines,
                SectionType::Security,
            ],
        }
    }
}

/// Validation report
#[derive(Debug, Clone)]
pub struct ValidationReport {
    /// Whether validation passed
    pub valid: bool,

    /// Validation errors
    pub errors: Vec<ValidationError>,

    /// Validation warnings
    pub warnings: Vec<ValidationWarning>,
}

/// Validation error
#[derive(Debug, Clone)]
pub struct ValidationError {
    /// Error message
    pub message: String,

    /// Line number if applicable
    pub line: Option<usize>,

    /// Section where error occurred
    pub section: Option<String>,
}

/// Validation warning
#[derive(Debug, Clone)]
pub struct ValidationWarning {
    /// Warning message
    pub message: String,

    /// Severity level
    pub severity: WarningSeverity,
}

/// Warning severity levels
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WarningSeverity {
    Low,
    Medium,
    High,
}

impl Default for AgentsMdParser {
    fn default() -> Self {
        Self::new()
    }
}

impl AgentsMdParser {
    /// Create new parser with default rules
    #[must_use] 
    pub fn new() -> Self {
        Self::with_rules(ValidationRules::default())
    }

    /// Create parser with custom rules
    #[must_use] 
    pub fn with_rules(rules: ValidationRules) -> Self {
        Self {
            validation_rules: rules,
            command_patterns: Self::init_command_patterns(),
        }
    }

    /// Initialize command detection patterns
    fn init_command_patterns() -> Vec<Regex> {
        vec![
            Regex::new(r"^```(?:bash|sh|shell)\n(.*?)\n```").unwrap(),
            Regex::new(r"^\$ (.+)$").unwrap(),
            Regex::new(r"^> (.+)$").unwrap(),
        ]
    }

    /// Parse AGENTS.md content
    pub fn parse(&self, content: &str) -> Result<AgentsMdDocument> {
        // Check size limit
        if content.len() > self.validation_rules.max_size {
            return Err(anyhow::anyhow!(
                "Document exceeds maximum size of {} bytes",
                self.validation_rules.max_size
            ));
        }

        let mut document = AgentsMdDocument {
            metadata: DocumentMetadata {
                path: PathBuf::new(),
                modified: std::time::SystemTime::now(),
                version: None,
                project: None,
            },
            sections: Vec::new(),
            commands: Vec::new(),
            guidelines: Vec::new(),
            quality_rules: None,
        };

        // Parse markdown
        let parser = MarkdownParser::new(content);
        let mut current_section: Option<Section> = None;
        let mut current_heading_level = 0;
        let mut in_code_block = false;
        let mut code_block_content = String::new();
        let mut code_block_lang = String::new();
        let mut in_list = false;
        let mut list_item_content = String::new();

        for event in parser {
            match event {
                Event::Start(Tag::Heading { level, .. }) => {
                    current_heading_level = match level {
                        HeadingLevel::H1 => 1,
                        HeadingLevel::H2 => 2,
                        HeadingLevel::H3 => 3,
                        HeadingLevel::H4 => 4,
                        HeadingLevel::H5 => 5,
                        HeadingLevel::H6 => 6,
                    };
                }
                Event::Text(text) => {
                    if in_code_block {
                        code_block_content.push_str(&text);
                    } else if in_list {
                        // Capture list item text
                        list_item_content.push_str(&text);
                    } else if current_heading_level > 0 {
                        // Start new section
                        if let Some(section) = current_section.take() {
                            document.sections.push(section);
                        }

                        let section_type = Self::detect_section_type(&text);
                        current_section = Some(Section {
                            section_type,
                            title: text.to_string(),
                            content: String::new(),
                            subsections: Vec::new(),
                        });
                        current_heading_level = 0;
                    } else if let Some(ref mut section) = current_section {
                        section.content.push_str(&text);
                        section.content.push('\n');

                        // Extract commands from content
                        self.extract_commands(&text, &mut document.commands);

                        // Extract guidelines
                        self.extract_guidelines(
                            &text,
                            &section.section_type,
                            &mut document.guidelines,
                        );
                    }
                }
                Event::Start(Tag::CodeBlock(kind)) => {
                    in_code_block = true;
                    if let pulldown_cmark::CodeBlockKind::Fenced(lang) = kind {
                        code_block_lang = lang.to_string();
                    }
                }
                Event::End(TagEnd::CodeBlock) => {
                    if in_code_block {
                        if code_block_lang == "bash"
                            || code_block_lang == "sh"
                            || code_block_lang == "shell"
                        {
                            // Extract command from code block
                            for line in code_block_content.lines() {
                                if !line.trim().is_empty() && !line.trim().starts_with('#') {
                                    document.commands.push(Command {
                                        name: format!(
                                            "Command from {}",
                                            current_section
                                                .as_ref()
                                                .map_or(&"Unknown".to_string(), |s| &s.title)
                                        ),
                                        command: line.trim().to_string(),
                                        working_dir: None,
                                        env: Vec::new(),
                                        timeout: Some(60),
                                        safe: self.is_command_safe(line),
                                    });
                                }
                            }
                        }

                        // Add code block to current section content
                        if let Some(ref mut section) = current_section {
                            section.content.push_str(&format!(
                                "```{code_block_lang}\n{code_block_content}\n```\n"
                            ));
                        }

                        in_code_block = false;
                        code_block_content.clear();
                        code_block_lang.clear();
                    }
                }
                Event::Start(Tag::List(_)) => {
                    in_list = true;
                }
                Event::End(TagEnd::List(_)) => {
                    in_list = false;
                }
                Event::Start(Tag::Item) => {
                    list_item_content.clear();
                }
                Event::End(TagEnd::Item) => {
                    if let Some(ref mut section) = current_section {
                        // Add list item with bullet point prefix
                        section.content.push_str("- ");
                        section.content.push_str(&list_item_content);
                        section.content.push('\n');
                    }
                    list_item_content.clear();
                }
                _ => {}
            }
        }

        // Add final section
        if let Some(section) = current_section {
            document.sections.push(section);
        }

        // Extract guidelines from all sections
        for section in &document.sections {
            self.extract_guidelines(&section.content, &section.section_type, &mut document.guidelines);
        }

        // Extract quality rules
        document.quality_rules = self.extract_quality_rules(&document.sections);

        // Extract metadata
        self.extract_metadata(&document.sections, &mut document.metadata);

        Ok(document)
    }

    /// Validate parsed document
    pub fn validate(&self, doc: &AgentsMdDocument) -> Result<ValidationReport> {
        let mut report = ValidationReport {
            valid: true,
            errors: Vec::new(),
            warnings: Vec::new(),
        };

        // Check required sections
        if self.validation_rules.require_overview
            && !doc
                .sections
                .iter()
                .any(|s| matches!(s.section_type, SectionType::Overview))
            {
                report.errors.push(ValidationError {
                    message: "Missing required Overview section".to_string(),
                    line: None,
                    section: None,
                });
                report.valid = false;
            }

        if self.validation_rules.require_testing
            && !doc
                .sections
                .iter()
                .any(|s| matches!(s.section_type, SectionType::Testing))
            {
                report.errors.push(ValidationError {
                    message: "Missing required Testing section".to_string(),
                    line: None,
                    section: None,
                });
                report.valid = false;
            }

        // Check for unsafe commands
        for command in &doc.commands {
            if !command.safe {
                report.warnings.push(ValidationWarning {
                    message: format!("Potentially unsafe command: {}", command.command),
                    severity: WarningSeverity::High,
                });
            }
        }

        // Check quality rules consistency
        if let Some(ref rules) = doc.quality_rules {
            if let Some(coverage) = rules.min_coverage {
                if !(0.0..=100.0).contains(&coverage) {
                    report.errors.push(ValidationError {
                        message: format!("Invalid coverage requirement: {coverage}%"),
                        line: None,
                        section: Some("Quality Rules".to_string()),
                    });
                    report.valid = false;
                }
            }
        }

        Ok(report)
    }

    /// Extract sections by type
    #[must_use] 
    pub fn extract_sections(&self, doc: &AgentsMdDocument) -> HashMap<SectionType, Section> {
        let mut map = HashMap::new();
        for section in &doc.sections {
            map.insert(section.section_type.clone(), section.clone());
        }
        map
    }

    /// Detect section type from title
    fn detect_section_type(title: &str) -> SectionType {
        let lower = title.to_lowercase();

        if lower.contains("overview") || lower.contains("introduction") || lower.contains("about") {
            SectionType::Overview
        } else if lower.contains("dev") || lower.contains("environment") || lower.contains("setup")
        {
            SectionType::DevEnvironment
        } else if lower.contains("test") {
            SectionType::Testing
        } else if lower.contains("style") || lower.contains("format") || lower.contains("lint") {
            SectionType::CodeStyle
        } else if lower.contains("pr") || lower.contains("pull request") || lower.contains("commit")
        {
            SectionType::PRGuidelines
        } else if lower.contains("security") || lower.contains("safety") {
            SectionType::Security
        } else {
            SectionType::Custom(title.to_string())
        }
    }

    /// Extract commands from text
    fn extract_commands(&self, text: &str, commands: &mut Vec<Command>) {
        for pattern in &self.command_patterns {
            if let Some(captures) = pattern.captures(text) {
                if let Some(cmd) = captures.get(1) {
                    commands.push(Command {
                        name: "Extracted command".to_string(),
                        command: cmd.as_str().to_string(),
                        working_dir: None,
                        env: Vec::new(),
                        timeout: Some(60),
                        safe: self.is_command_safe(cmd.as_str()),
                    });
                }
            }
        }
    }

    /// Extract guidelines from text
    fn extract_guidelines(
        &self,
        text: &str,
        section_type: &SectionType,
        guidelines: &mut Vec<Guideline>,
    ) {
        // Simple extraction: lines starting with - or *
        for line in text.lines() {
            let trimmed = line.trim();
            if trimmed.starts_with("- ") || trimmed.starts_with("* ") {
                let content = &trimmed[2..];
                let priority = self.detect_priority(content);

                guidelines.push(Guideline {
                    category: format!("{section_type:?}"),
                    text: content.to_string(),
                    priority,
                });
            }
        }
    }

    /// Detect priority from guideline text
    fn detect_priority(&self, text: &str) -> Priority {
        let lower = text.to_lowercase();

        if lower.contains("must") || lower.contains("critical") || lower.contains("required") {
            Priority::Critical
        } else if lower.contains("should") || lower.contains("important") {
            Priority::High
        } else if lower.contains("recommend") || lower.contains("prefer") {
            Priority::Medium
        } else {
            Priority::Low
        }
    }

    /// Check if command is safe to execute
    fn is_command_safe(&self, command: &str) -> bool {
        let dangerous_patterns = [
            "rm -rf",
            "sudo",
            "chmod 777",
            "eval",
            "exec",
            "> /dev/",
            "dd if=",
        ];

        let lower = command.to_lowercase();
        !dangerous_patterns
            .iter()
            .any(|pattern| lower.contains(pattern))
    }

    /// Extract quality rules from sections
    fn extract_quality_rules(&self, sections: &[Section]) -> Option<QualityRules> {
        let mut rules = QualityRules {
            max_complexity: None,
            min_coverage: None,
            satd_allowed: false,
            custom_checks: Vec::new(),
        };

        let mut found_rules = false;

        // Compile regex patterns once before the loop
        let complexity_regex = Regex::new(r"complexity.*?(\d+)").unwrap();
        let coverage_regex = Regex::new(r"coverage.*?(\d+)").unwrap();

        for section in sections {
            let content = &section.content.to_lowercase();

            // Look for complexity limits
            if content.contains("complexity") {
                if let Some(captures) = complexity_regex.captures(content)
                {
                    if let Some(num) = captures.get(1) {
                        rules.max_complexity = num.as_str().parse().ok();
                        found_rules = true;
                    }
                }
            }

            // Look for coverage requirements
            if content.contains("coverage") {
                if let Some(captures) = coverage_regex.captures(content) {
                    if let Some(num) = captures.get(1) {
                        rules.min_coverage = num.as_str().parse::<f64>().ok();
                        found_rules = true;
                    }
                }
            }

            // Check SATD policy
            if content.contains("satd") || content.contains("technical debt") {
                // Check if it's explicitly allowed (but not "not allowed" or "disallowed")
                rules.satd_allowed = (content.contains("allow") || content.contains("permitted")) 
                    && !content.contains("not allow") 
                    && !content.contains("disallow")
                    && !content.contains("is not");
                found_rules = true;
            }
        }

        if found_rules {
            Some(rules)
        } else {
            None
        }
    }

    /// Extract metadata from document
    fn extract_metadata(&self, sections: &[Section], metadata: &mut DocumentMetadata) {
        // Look for project name in overview
        for section in sections {
            if matches!(section.section_type, SectionType::Overview) {
                // Simple extraction: first line often contains project name
                if let Some(first_line) = section.content.lines().next() {
                    metadata.project = Some(first_line.trim().to_string());
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_empty_document() {
        let parser = AgentsMdParser::new();
        let result = parser.parse("");
        assert!(result.is_ok());
        let doc = result.unwrap();
        assert!(doc.sections.is_empty());
        assert!(doc.commands.is_empty());
    }

    #[test]
    fn test_parse_basic_sections() {
        let content = r#"
# AGENTS.md

## Project Overview
This is a test project.

## Testing Instructions
Run `cargo test` to execute tests.

## Code Style
- Use rustfmt
- Follow clippy suggestions
"#;

        let parser = AgentsMdParser::new();
        let result = parser.parse(content);
        assert!(result.is_ok());

        let doc = result.unwrap();
        assert_eq!(doc.sections.len(), 4); // Including the AGENTS.md header section

        // Check section types
        assert!(doc
            .sections
            .iter()
            .any(|s| matches!(s.section_type, SectionType::Overview)));
        assert!(doc
            .sections
            .iter()
            .any(|s| matches!(s.section_type, SectionType::Testing)));
        assert!(doc
            .sections
            .iter()
            .any(|s| matches!(s.section_type, SectionType::CodeStyle)));
    }

    #[test]
    fn test_extract_commands() {
        let content = r#"
## Dev Setup

Install dependencies:
```bash
cargo build --all
cargo test
```

Run the application:
```sh
cargo run --release
```
"#;

        let parser = AgentsMdParser::new();
        let result = parser.parse(content);
        assert!(result.is_ok());

        let doc = result.unwrap();
        assert_eq!(doc.commands.len(), 3);
        assert_eq!(doc.commands[0].command, "cargo build --all");
        assert_eq!(doc.commands[1].command, "cargo test");
        assert_eq!(doc.commands[2].command, "cargo run --release");
    }

    #[test]
    fn test_extract_guidelines() {
        let content = r#"
## Code Style

- Must use rustfmt for formatting
- Should follow clippy recommendations
- Prefer explicit types over inference
* Document all public APIs
"#;

        let parser = AgentsMdParser::new();
        let result = parser.parse(content);
        assert!(result.is_ok());

        let doc = result.unwrap();
        assert_eq!(doc.guidelines.len(), 4);

        // Check priorities
        assert_eq!(doc.guidelines[0].priority, Priority::Critical); // "Must"
        assert_eq!(doc.guidelines[1].priority, Priority::High); // "Should"
        assert_eq!(doc.guidelines[2].priority, Priority::Medium); // "Prefer"
    }

    #[test]
    fn test_detect_unsafe_commands() {
        let parser = AgentsMdParser::new();

        assert!(!parser.is_command_safe("rm -rf /"));
        assert!(!parser.is_command_safe("sudo rm -rf /"));
        assert!(!parser.is_command_safe("chmod 777 /etc/passwd"));
        assert!(!parser.is_command_safe("eval $USER_INPUT"));

        assert!(parser.is_command_safe("cargo build"));
        assert!(parser.is_command_safe("npm test"));
        assert!(parser.is_command_safe("make clean"));
    }

    #[test]
    fn test_extract_quality_rules() {
        let content = r#"
## Quality Requirements

All functions must have complexity less than 10.
Maintain test coverage above 80%.
Technical debt is not allowed in production code.
"#;

        let parser = AgentsMdParser::new();
        let result = parser.parse(content);
        assert!(result.is_ok());

        let doc = result.unwrap();
        assert!(doc.quality_rules.is_some());

        let rules = doc.quality_rules.unwrap();
        assert_eq!(rules.max_complexity, Some(10));
        assert_eq!(rules.min_coverage, Some(80.0));
        assert!(!rules.satd_allowed);
    }

    #[test]
    fn test_validation_required_sections() {
        let parser = AgentsMdParser::with_rules(ValidationRules {
            require_overview: true,
            require_testing: true,
            ..Default::default()
        });

        let content = "## Code Style\nUse rustfmt";
        let doc = parser.parse(content).unwrap();
        let report = parser.validate(&doc).unwrap();

        assert!(!report.valid);
        assert_eq!(report.errors.len(), 2);
        assert!(report.errors.iter().any(|e| e.message.contains("Overview")));
        assert!(report.errors.iter().any(|e| e.message.contains("Testing")));
    }

    #[test]
    fn test_size_limit() {
        let parser = AgentsMdParser::with_rules(ValidationRules {
            max_size: 10,
            ..Default::default()
        });

        let content = "This content is too long for the limit";
        let result = parser.parse(content);

        assert!(result.is_err());
        assert!(result
            .unwrap_err()
            .to_string()
            .contains("exceeds maximum size"));
    }

    #[test]
    fn test_section_type_detection() {
        let _parser = AgentsMdParser::new();

        assert_eq!(
            AgentsMdParser::detect_section_type("Project Overview"),
            SectionType::Overview
        );
        assert_eq!(
            AgentsMdParser::detect_section_type("Development Environment"),
            SectionType::DevEnvironment
        );
        assert_eq!(
            AgentsMdParser::detect_section_type("Testing Instructions"),
            SectionType::Testing
        );
        assert_eq!(
            AgentsMdParser::detect_section_type("PR Guidelines"),
            SectionType::PRGuidelines
        );
        assert_eq!(
            AgentsMdParser::detect_section_type("Security Considerations"),
            SectionType::Security
        );
        assert_eq!(
            AgentsMdParser::detect_section_type("Custom Section"),
            SectionType::Custom("Custom Section".to_string())
        );
    }
}