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
#![cfg_attr(coverage_nightly, coverage(off))]
//! CB-900 Series: Markdown Best Practices Detection
//!
//! Pattern-based Markdown quality detection for `pmat comply check`.
//! Focuses on documentation quality: heading structure, link validation,
//! and readability.

use super::types::*;
use ignore::WalkBuilder;
use std::fs;
use std::path::{Path, PathBuf};

/// Directories to skip when walking for Markdown files.
///
/// These are additional hard-coded skips layered on top of `.gitignore`,
/// `.pmatignore`, and `.paimlignore` (honored via `ignore::WalkBuilder`).
/// They catch build artifacts and vendored directories that may not be
/// listed in an ignore file.
const SKIP_DIRS: &[&str] = &[
    ".git",
    ".claude",
    "node_modules",
    "target",
    ".pmat",
    "vendor",
    "build",
    "dist",
    "__pycache__",
    ".venv",
    "site-packages",
];

// =============================================================================
// File walking
// =============================================================================

/// Walk directory recursively for `.md`/`.mdx` files.
///
/// Honors `.gitignore`, `.pmatignore`, and `.paimlignore` plus exclude
/// patterns from `.pmat-gates.toml [exclude] paths` and `.pmat.yaml
/// comply.thresholds.file_health_exclude` (GH-278).
#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub fn walkdir_markdown_files(dir: &Path) -> Vec<PathBuf> {
    let excludes = load_markdown_excludes(dir);
    walkdir_markdown_files_with_excludes(dir, &excludes)
}

/// Walk for Markdown files applying explicit glob excludes in addition to
/// the ignore-file rules baked into [`WalkBuilder`].
pub fn walkdir_markdown_files_with_excludes(dir: &Path, excludes: &[String]) -> Vec<PathBuf> {
    let mut files = Vec::new();

    let walker = WalkBuilder::new(dir)
        .hidden(false)
        .git_ignore(true)
        .git_exclude(true)
        .add_custom_ignore_filename(".pmatignore")
        .add_custom_ignore_filename(".paimlignore")
        .filter_entry(|entry| {
            let name = entry
                .path()
                .file_name()
                .and_then(|n| n.to_str())
                .unwrap_or("");
            !SKIP_DIRS.contains(&name)
        })
        .build();

    for entry in walker.flatten() {
        let path = entry.path();
        if !path.is_file() {
            continue;
        }
        let is_md = path
            .extension()
            .and_then(|e| e.to_str())
            .map(|e| matches!(e, "md" | "mdx" | "markdown"))
            .unwrap_or(false);
        if !is_md {
            continue;
        }
        if path_matches_any_exclude(path, dir, excludes) {
            continue;
        }
        files.push(path.to_path_buf());
    }

    files
}

/// Load exclude patterns applied to CB-9xx Markdown checks. Merges entries
/// from `.pmat-gates.toml [exclude] paths`, `.pmat-gates.toml [file_health]
/// exclude`, and `.pmat.yaml comply.thresholds.file_health_exclude`.
fn load_markdown_excludes(dir: &Path) -> Vec<String> {
    let mut out: Vec<String> = Vec::new();

    let gates = dir.join(".pmat-gates.toml");
    if let Ok(content) = fs::read_to_string(&gates) {
        if let Ok(table) = content.parse::<toml::Table>() {
            push_str_array(&mut out, table.get("exclude").and_then(|e| e.get("paths")));
            push_str_array(
                &mut out,
                table.get("file_health").and_then(|fh| fh.get("exclude")),
            );
        }
    }

    if let Ok(cfg) = crate::models::comply_config::PmatYamlConfig::load(dir) {
        for pat in &cfg.comply.thresholds.file_health_exclude {
            if !out.iter().any(|p| p == pat) {
                out.push(pat.clone());
            }
        }
    }

    out
}

fn push_str_array(out: &mut Vec<String>, v: Option<&toml::Value>) {
    let Some(arr) = v.and_then(|x| x.as_array()) else {
        return;
    };
    for item in arr {
        if let Some(s) = item.as_str() {
            let s = s.to_string();
            if !out.iter().any(|p| p == &s) {
                out.push(s);
            }
        }
    }
}

fn path_matches_any_exclude(path: &Path, root: &Path, patterns: &[String]) -> bool {
    if patterns.is_empty() {
        return false;
    }
    let rel = path.strip_prefix(root).unwrap_or(path);
    let rel_str = rel.to_string_lossy();
    let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
    for pattern in patterns {
        if glob_like_match(&rel_str, file_name, pattern) {
            return true;
        }
    }
    false
}

fn glob_like_match(path_str: &str, file_name: &str, pattern: &str) -> bool {
    if let Some(suffix) = pattern.strip_prefix("**/") {
        if suffix.ends_with("/**") {
            let segment = suffix.trim_end_matches("/**");
            return path_str.contains(segment);
        }
        if suffix.contains('*') {
            return glob::Pattern::new(suffix)
                .map(|p| p.matches(file_name))
                .unwrap_or(false);
        }
        return file_name == suffix || path_str.contains(suffix);
    }
    if let Some(prefix) = pattern.strip_suffix("/**") {
        return path_str.starts_with(prefix) || path_str.contains(&format!("/{prefix}/"));
    }
    if pattern.contains('/') {
        return path_str.contains(pattern);
    }
    if pattern.contains('*') {
        return glob::Pattern::new(pattern)
            .map(|p| p.matches(file_name))
            .unwrap_or(false);
    }
    file_name == pattern
}

// =============================================================================
// CB-900: Internal link validation
// =============================================================================

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
/// Detect cb900 broken internal link.
pub fn detect_cb900_broken_internal_link(project_path: &Path) -> Vec<CbPatternViolation> {
    let files = walkdir_markdown_files(project_path);
    let mut violations = Vec::new();

    for file_path in &files {
        let content = match fs::read_to_string(file_path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let rel = file_path
            .strip_prefix(project_path)
            .unwrap_or(file_path)
            .display()
            .to_string();
        let file_dir = file_path.parent().unwrap_or(project_path);

        for (i, line) in content.lines().enumerate() {
            // Skip code blocks
            if line.trim().starts_with("```") {
                continue;
            }

            // Find markdown links: [text](path)
            let mut search_pos = 0;
            while let Some(start) = line[search_pos..].find("](") {
                let abs_start = search_pos + start + 2;
                if let Some(end) = line[abs_start..].find(')') {
                    let link_target = &line[abs_start..abs_start + end];

                    // Only check internal links (not http/https/mailto/#anchors)
                    if !link_target.starts_with("http")
                        && !link_target.starts_with("mailto:")
                        && !link_target.starts_with('#')
                        && !link_target.is_empty()
                    {
                        // Strip anchor from link
                        let file_part = link_target.split('#').next().unwrap_or(link_target);
                        if !file_part.is_empty() {
                            let target_path = file_dir.join(file_part);
                            if !target_path.exists() {
                                violations.push(CbPatternViolation {
                                    pattern_id: "CB-900".to_string(),
                                    file: rel.clone(),
                                    line: i + 1,
                                    description: format!(
                                        "Broken internal link `{}` — target does not exist",
                                        link_target
                                    ),
                                    severity: Severity::Warning,
                                });
                            }
                        }
                    }

                    search_pos = abs_start + end + 1;
                } else {
                    break;
                }
            }
        }
    }

    violations
}

// =============================================================================
// CB-901: Heading Hierarchy Skip
// =============================================================================

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
/// Detect cb901 heading hierarchy skip.
pub fn detect_cb901_heading_hierarchy_skip(project_path: &Path) -> Vec<CbPatternViolation> {
    let files = walkdir_markdown_files(project_path);
    let mut violations = Vec::new();

    for file_path in &files {
        let content = match fs::read_to_string(file_path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let rel = file_path
            .strip_prefix(project_path)
            .unwrap_or(file_path)
            .display()
            .to_string();

        let mut last_level: usize = 0;
        let mut in_code_block = false;

        for (i, line) in content.lines().enumerate() {
            let trimmed = line.trim();

            // Track code blocks
            if trimmed.starts_with("```") {
                in_code_block = !in_code_block;
                continue;
            }
            if in_code_block {
                continue;
            }

            // Count heading level
            if trimmed.starts_with('#') {
                let level = trimmed.chars().take_while(|c| *c == '#').count();
                if (1..=6).contains(&level) {
                    // Check for skip: e.g., h1 -> h3 (skip h2)
                    if last_level > 0 && level > last_level + 1 {
                        violations.push(CbPatternViolation {
                            pattern_id: "CB-901".to_string(),
                            file: rel.clone(),
                            line: i + 1,
                            description: format!(
                                "Heading hierarchy skip: h{} to h{} — missing h{}",
                                last_level,
                                level,
                                last_level + 1
                            ),
                            severity: Severity::Info,
                        });
                    }
                    last_level = level;
                }
            }
        }
    }

    violations
}

// =============================================================================
// CB-902: Missing Alt Text on Images
// =============================================================================

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
/// Detect cb902 missing alt text.
pub fn detect_cb902_missing_alt_text(project_path: &Path) -> Vec<CbPatternViolation> {
    let files = walkdir_markdown_files(project_path);
    let mut violations = Vec::new();

    for file_path in &files {
        let content = match fs::read_to_string(file_path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let rel = file_path
            .strip_prefix(project_path)
            .unwrap_or(file_path)
            .display()
            .to_string();

        let mut in_code_block = false;

        for (i, line) in content.lines().enumerate() {
            let trimmed = line.trim();
            if trimmed.starts_with("```") {
                in_code_block = !in_code_block;
                continue;
            }
            if in_code_block {
                continue;
            }

            // Find ![](url) pattern — missing alt text
            if line.contains("![]") {
                violations.push(CbPatternViolation {
                    pattern_id: "CB-902".to_string(),
                    file: rel.clone(),
                    line: i + 1,
                    description:
                        "Image missing alt text — add descriptive text in `![alt text](url)`"
                            .to_string(),
                    severity: Severity::Info,
                });
            }
        }
    }

    violations
}

// =============================================================================
// CB-903: Bare URL
// =============================================================================

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
/// Detect cb903 bare url.
pub fn detect_cb903_bare_url(project_path: &Path) -> Vec<CbPatternViolation> {
    let files = walkdir_markdown_files(project_path);
    let mut violations = Vec::new();

    for file_path in &files {
        let content = match fs::read_to_string(file_path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let rel = file_path
            .strip_prefix(project_path)
            .unwrap_or(file_path)
            .display()
            .to_string();

        let mut in_code_block = false;

        for (i, line) in content.lines().enumerate() {
            let trimmed = line.trim();
            if trimmed.starts_with("```") {
                in_code_block = !in_code_block;
                continue;
            }
            if in_code_block {
                continue;
            }

            // Find bare URLs (http/https not wrapped in markdown link or angle brackets)
            if let Some(http_pos) = line.find("http://").or_else(|| line.find("https://")) {
                // Check if it's already in a markdown link or angle brackets
                if http_pos > 0 {
                    let before = line.as_bytes()[http_pos - 1];
                    if before == b'(' || before == b'<' || before == b'"' || before == b'\'' {
                        continue;
                    }
                }
                // Check if line is a markdown link definition or image
                if trimmed.starts_with('[') || trimmed.starts_with("![") {
                    continue;
                }
                // Check if the URL is the only thing on the line (common in link lists)
                if trimmed.starts_with("http://") || trimmed.starts_with("https://") {
                    violations.push(CbPatternViolation {
                        pattern_id: "CB-903".to_string(),
                        file: rel.clone(),
                        line: i + 1,
                        description: "Bare URL — wrap in markdown link `[text](url)` or angle brackets `<url>`"
                            .to_string(),
                        severity: Severity::Info,
                    });
                }
            }
        }
    }

    violations
}

// =============================================================================
// CB-904: Long Line
// =============================================================================

/// Default line length threshold for markdown files.
const MD_LINE_LENGTH_THRESHOLD: usize = 120;

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
/// Detect cb904 long line.
pub fn detect_cb904_long_line(project_path: &Path) -> Vec<CbPatternViolation> {
    let files = walkdir_markdown_files(project_path);
    let mut violations = Vec::new();

    for file_path in &files {
        let content = match fs::read_to_string(file_path) {
            Ok(c) => c,
            Err(_) => continue,
        };
        let rel = file_path
            .strip_prefix(project_path)
            .unwrap_or(file_path)
            .display()
            .to_string();

        let mut in_code_block = false;

        for (i, line) in content.lines().enumerate() {
            let trimmed = line.trim();
            if trimmed.starts_with("```") {
                in_code_block = !in_code_block;
                continue;
            }
            // Skip code blocks (long lines are expected in code examples)
            if in_code_block {
                continue;
            }
            // Skip tables (lines with pipes)
            if trimmed.starts_with('|') {
                continue;
            }
            // Skip lines that are mostly URLs
            if trimmed.contains("http://") || trimmed.contains("https://") {
                continue;
            }

            if line.len() > MD_LINE_LENGTH_THRESHOLD {
                violations.push(CbPatternViolation {
                    pattern_id: "CB-904".to_string(),
                    file: rel.clone(),
                    line: i + 1,
                    description: format!(
                        "Line length {} exceeds {} characters",
                        line.len(),
                        MD_LINE_LENGTH_THRESHOLD
                    ),
                    severity: Severity::Info,
                });
            }
        }
    }

    violations
}