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
#![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 std::fs;
use std::path::{Path, PathBuf};
/// Directories to skip when walking for Markdown files.
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.
pub fn walkdir_markdown_files(dir: &Path) -> Vec<PathBuf> {
let mut files = Vec::new();
walk_md_recursive(dir, &mut files);
files
}
fn walk_md_recursive(dir: &Path, files: &mut Vec<PathBuf>) {
let entries = match fs::read_dir(dir) {
Ok(e) => e,
Err(_) => return,
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
let dir_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");
if !SKIP_DIRS.contains(&dir_name) {
walk_md_recursive(&path, files);
}
} else if path
.extension()
.and_then(|e| e.to_str())
.map(|e| matches!(e, "md" | "mdx" | "markdown"))
.unwrap_or(false)
{
files.push(path);
}
}
}
// =============================================================================
// CB-900: Internal link validation
// =============================================================================
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
// =============================================================================
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
// =============================================================================
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  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 ``"
.to_string(),
severity: Severity::Info,
});
}
}
}
violations
}
// =============================================================================
// CB-903: 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("` 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;
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
}