pmat 3.11.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
#![cfg_attr(coverage_nightly, coverage(off))]
//! AGENTS.md Generator
//!
//! Generates AGENTS.md files from PMAT analysis and project structure.

use super::{AgentsMdDocument, Command, Path, PathBuf, QualityRules, Section};
use anyhow::{Context, Result};
use std::collections::HashMap;
use std::fmt::Write;

/// AGENTS.md generator with templates
pub struct AgentsMdGenerator {
    /// Templates for different project types
    templates: HashMap<ProjectType, Template>,

    /// Configuration
    config: GeneratorConfig,
}

/// Generator configuration
#[derive(Debug, Clone)]
pub struct GeneratorConfig {
    /// Include quality rules section
    pub include_quality: bool,

    /// Include security guidelines
    pub include_security: bool,

    /// Include PR guidelines
    pub include_pr_guidelines: bool,

    /// Maximum commands to include
    pub max_commands: usize,

    /// Include examples
    pub include_examples: bool,
}

impl Default for GeneratorConfig {
    fn default() -> Self {
        Self {
            include_quality: true,
            include_security: true,
            include_pr_guidelines: true,
            max_commands: 20,
            include_examples: true,
        }
    }
}

/// Project types for templates
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum ProjectType {
    Rust,
    JavaScript,
    Python,
    Go,
    Java,
    Generic,
}

/// Template for generating AGENTS.md
#[derive(Debug, Clone)]
pub struct Template {
    /// Template sections
    pub sections: Vec<TemplateSection>,

    /// Default commands
    pub default_commands: Vec<Command>,
}

/// Template section
#[derive(Debug, Clone)]
pub struct TemplateSection {
    /// Section title
    pub title: String,

    /// Section content template
    pub content: String,

    /// Variables to replace
    pub variables: Vec<String>,
}

/// PMAT analysis for generation
pub struct PmatAnalysis {
    /// Project name
    pub project_name: String,

    /// Project description
    pub description: String,

    /// Project type
    pub project_type: ProjectType,

    /// Detected commands
    pub commands: Vec<Command>,

    /// Quality metrics
    pub quality_metrics: QualityMetrics,

    /// Dependencies
    pub dependencies: Vec<String>,
}

/// Quality metrics from analysis
#[derive(Debug, Clone)]
pub struct QualityMetrics {
    /// Average complexity
    pub avg_complexity: f64,

    /// Test coverage
    pub test_coverage: f64,

    /// SATD count
    pub satd_count: usize,

    /// Code quality grade
    pub grade: String,
}

/// Project info for generation
pub struct ProjectInfo {
    /// Root directory
    pub root: PathBuf,

    /// Project name
    pub name: String,

    /// Version
    pub version: String,

    /// Description
    pub description: String,

    /// README content if exists
    pub readme: Option<String>,
}

/// Updates to apply to existing AGENTS.md
pub struct Updates {
    /// New commands to add
    pub new_commands: Vec<Command>,

    /// Updated quality rules
    pub quality_rules: Option<QualityRules>,

    /// New sections to add
    pub new_sections: Vec<Section>,
}

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

impl AgentsMdGenerator {
    /// Create new generator
    #[must_use]
    pub fn new() -> Self {
        let mut generator = Self {
            templates: HashMap::new(),
            config: GeneratorConfig::default(),
        };

        generator.load_default_templates();
        generator
    }

    /// Create with custom config
    #[must_use]
    pub fn with_config(config: GeneratorConfig) -> Self {
        let mut generator = Self {
            templates: HashMap::new(),
            config,
        };

        generator.load_default_templates();
        generator
    }

    /// Load default templates
    fn load_default_templates(&mut self) {
        // Rust template
        self.templates.insert(ProjectType::Rust, Template {
            sections: vec![
                TemplateSection {
                    title: "Project Overview".to_string(),
                    content: "{project_name}\n{description}".to_string(),
                    variables: vec!["project_name".to_string(), "description".to_string()],
                },
                TemplateSection {
                    title: "Development Setup".to_string(),
                    content: "```bash\n# Install dependencies\ncargo build --all\n\n# Run tests\ncargo test --all\n```".to_string(),
                    variables: vec![],
                },
            ],
            default_commands: vec![
                Command {
                    name: "Build".to_string(),
                    command: "cargo build --all".to_string(),
                    working_dir: None,
                    env: vec![],
                    timeout: Some(60),
                    safe: true,
                },
                Command {
                    name: "Test".to_string(),
                    command: "cargo test --all".to_string(),
                    working_dir: None,
                    env: vec![],
                    timeout: Some(120),
                    safe: true,
                },
            ],
        });

        // Add other language templates
        self.templates.insert(
            ProjectType::Generic,
            Template {
                sections: vec![TemplateSection {
                    title: "Project Overview".to_string(),
                    content: "{project_name}\n{description}".to_string(),
                    variables: vec!["project_name".to_string(), "description".to_string()],
                }],
                default_commands: vec![],
            },
        );
    }

    /// Generate from PMAT analysis
    pub fn generate_from_analysis(&self, analysis: &PmatAnalysis) -> Result<String> {
        let _template = self
            .templates
            .get(&analysis.project_type)
            .or_else(|| self.templates.get(&ProjectType::Generic))
            .context("No template found")?;

        let mut output = String::new();
        writeln!(output, "# AGENTS.md")?;
        writeln!(output)?;

        // Generate overview
        writeln!(output, "## Project Overview")?;
        writeln!(
            output,
            "{}\n{}",
            analysis.project_name, analysis.description
        )?;
        writeln!(output)?;

        // Generate development setup
        self.generate_dev_setup(&mut output, analysis)?;

        // Generate testing section
        self.generate_testing(&mut output, analysis)?;

        // Generate code style
        if self.config.include_quality {
            self.generate_code_style(&mut output, analysis)?;
        }

        // Generate PR guidelines
        if self.config.include_pr_guidelines {
            self.generate_pr_guidelines(&mut output)?;
        }

        // Generate security
        if self.config.include_security {
            self.generate_security(&mut output)?;
        }

        Ok(output)
    }

    /// Generate from project structure
    pub fn generate_from_project(&self, project: &ProjectInfo) -> Result<String> {
        // Create basic analysis from project info
        let analysis = PmatAnalysis {
            project_name: project.name.clone(),
            description: project.description.clone(),
            project_type: self.detect_project_type(&project.root)?,
            commands: self.detect_commands(&project.root)?,
            quality_metrics: QualityMetrics {
                avg_complexity: 10.0,
                test_coverage: 80.0,
                satd_count: 0,
                grade: "A".to_string(),
            },
            dependencies: vec![],
        };

        self.generate_from_analysis(&analysis)
    }

    /// Update existing AGENTS.md
    pub fn update_existing(&self, current: &str, updates: Updates) -> Result<String> {
        let parser = super::parser::AgentsMdParser::new();
        let mut doc = parser.parse(current)?;

        // Add new commands
        for cmd in updates.new_commands {
            if !doc.commands.iter().any(|c| c.name == cmd.name) {
                doc.commands.push(cmd);
            }
        }

        // Update quality rules
        if let Some(rules) = updates.quality_rules {
            doc.quality_rules = Some(rules);
        }

        // Add new sections
        for section in updates.new_sections {
            if !doc.sections.iter().any(|s| s.title == section.title) {
                doc.sections.push(section);
            }
        }

        // Regenerate document
        self.format_document(&doc)
    }

    /// Format document back to markdown
    fn format_document(&self, doc: &AgentsMdDocument) -> Result<String> {
        let mut output = String::new();
        writeln!(output, "# AGENTS.md")?;
        writeln!(output)?;

        for section in &doc.sections {
            self.format_section(&mut output, section, 2)?;
        }

        Ok(output)
    }

    /// Format a section
    #[allow(clippy::only_used_in_recursion)]
    fn format_section(&self, output: &mut String, section: &Section, level: usize) -> Result<()> {
        let heading = "#".repeat(level);
        writeln!(output, "{} {}", heading, section.title)?;
        writeln!(output, "{}", section.content)?;
        writeln!(output)?;

        for subsection in &section.subsections {
            self.format_section(output, subsection, level + 1)?;
        }

        Ok(())
    }

    /// Generate development setup section
    fn generate_dev_setup(&self, output: &mut String, analysis: &PmatAnalysis) -> Result<()> {
        writeln!(output, "## Development Setup")?;
        writeln!(output, "```bash")?;

        let commands = &analysis.commands[..analysis.commands.len().min(5)];
        for cmd in commands {
            writeln!(output, "# {}", cmd.name)?;
            writeln!(output, "{}", cmd.command)?;
            writeln!(output)?;
        }

        writeln!(output, "```")?;
        writeln!(output)?;
        Ok(())
    }

    /// Generate testing section
    fn generate_testing(&self, output: &mut String, analysis: &PmatAnalysis) -> Result<()> {
        writeln!(output, "## Testing Instructions")?;
        writeln!(output, "- Run tests before committing")?;
        writeln!(
            output,
            "- Ensure {}%+ coverage maintained",
            analysis.quality_metrics.test_coverage as u32
        )?;
        writeln!(output, "- All functions must have complexity ≤{}", 10)?;
        writeln!(output)?;
        Ok(())
    }

    /// Generate code style section
    fn generate_code_style(&self, output: &mut String, analysis: &PmatAnalysis) -> Result<()> {
        writeln!(output, "## Code Style")?;
        writeln!(output, "- Follow project coding standards")?;
        writeln!(
            output,
            "- Current quality grade: {}",
            analysis.quality_metrics.grade
        )?;
        writeln!(output, "- Zero SATD tolerance")?;
        writeln!(output)?;
        Ok(())
    }

    /// Generate PR guidelines
    fn generate_pr_guidelines(&self, output: &mut String) -> Result<()> {
        writeln!(output, "## PR Guidelines")?;
        writeln!(output, "- Squash commits with conventional format")?;
        writeln!(output, "- Must pass all quality gates")?;
        writeln!(output, "- Include tests for new features")?;
        writeln!(output)?;
        Ok(())
    }

    /// Generate security section
    fn generate_security(&self, output: &mut String) -> Result<()> {
        writeln!(output, "## Security Considerations")?;
        writeln!(output, "- No secrets in code")?;
        writeln!(output, "- Validate all external input")?;
        writeln!(output, "- Use secure defaults")?;
        writeln!(output)?;
        Ok(())
    }

    /// Detect project type from directory
    fn detect_project_type(&self, path: &Path) -> Result<ProjectType> {
        if path.join("Cargo.toml").exists() {
            Ok(ProjectType::Rust)
        } else if path.join("package.json").exists() {
            Ok(ProjectType::JavaScript)
        } else if path.join("setup.py").exists() || path.join("pyproject.toml").exists() {
            Ok(ProjectType::Python)
        } else if path.join("go.mod").exists() {
            Ok(ProjectType::Go)
        } else if path.join("pom.xml").exists() || path.join("build.gradle").exists() {
            Ok(ProjectType::Java)
        } else {
            Ok(ProjectType::Generic)
        }
    }

    /// Detect available commands
    fn detect_commands(&self, path: &Path) -> Result<Vec<Command>> {
        let mut commands = Vec::new();

        // Check for Makefile
        if path.join("Makefile").exists() {
            commands.push(Command {
                name: "Build".to_string(),
                command: "make build".to_string(),
                working_dir: None,
                env: vec![],
                timeout: Some(60),
                safe: true,
            });
            commands.push(Command {
                name: "Test".to_string(),
                command: "make test".to_string(),
                working_dir: None,
                env: vec![],
                timeout: Some(120),
                safe: true,
            });
        }

        // Check for package.json scripts
        if path.join("package.json").exists() {
            commands.push(Command {
                name: "Install".to_string(),
                command: "npm install".to_string(),
                working_dir: None,
                env: vec![],
                timeout: Some(300),
                safe: true,
            });
        }

        Ok(commands)
    }
}

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