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
// model_quality_checks.rs — CB-1000 series detection functions.
// Included by model_quality.rs; shares its module scope.

// =============================================================================
// CB-1000: Missing Model Card
// =============================================================================

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
/// Detect cb1000 missing model card.
pub fn detect_cb1000_missing_model_card(project_path: &Path) -> Vec<CbPatternViolation> {
    let model_files = walkdir_model_files(project_path);
    let mut violations = Vec::new();

    // Group model files by directory
    let mut dirs_with_models: HashMap<PathBuf, Vec<PathBuf>> = HashMap::new();
    for f in &model_files {
        if let Some(parent) = f.parent() {
            dirs_with_models
                .entry(parent.to_path_buf())
                .or_default()
                .push(f.clone());
        }
    }

    for (dir, files) in &dirs_with_models {
        let has_readme = dir.join("README.md").exists()
            || dir.join("readme.md").exists()
            || dir.join("model_card.md").exists()
            || dir.join("MODEL_CARD.md").exists();

        if !has_readme {
            let rel = dir
                .strip_prefix(project_path)
                .unwrap_or(dir)
                .display()
                .to_string();
            let model_names: Vec<String> = files
                .iter()
                .filter_map(|f| f.file_name().map(|n| n.to_string_lossy().to_string()))
                .collect();

            violations.push(CbPatternViolation {
                pattern_id: "CB-1000".to_string(),
                file: rel,
                line: 0,
                description: format!(
                    "Model directory has {} model file(s) but no model card (README.md): {}",
                    model_names.len(),
                    model_names.join(", ")
                ),
                severity: Severity::Warning,
            });
        }
    }

    violations
}

// =============================================================================
// CB-1001: Oversized Tensor Count
// =============================================================================

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
/// Detect cb1001 oversized tensor count.
pub fn detect_cb1001_oversized_tensor_count(project_path: &Path) -> Vec<CbPatternViolation> {
    let model_files = walkdir_model_files(project_path);
    let mut violations = Vec::new();

    for file_path in &model_files {
        let metadata = match parse_model_header(file_path) {
            Some(m) => m,
            None => continue,
        };
        let rel = file_path
            .strip_prefix(project_path)
            .unwrap_or(file_path)
            .display()
            .to_string();

        if let Some(count) = metadata.tensor_count {
            if count > MAX_TENSOR_COUNT {
                violations.push(CbPatternViolation {
                    pattern_id: "CB-1001".to_string(),
                    file: rel,
                    line: 0,
                    description: format!(
                        "{} file has {} tensors (limit: {}) — likely corrupt header (BUG-GGUF-001)",
                        metadata.format.name(),
                        count,
                        MAX_TENSOR_COUNT
                    ),
                    severity: Severity::Error,
                });
            }
        }
    }

    violations
}

// =============================================================================
// CB-1002: Missing Tokenizer
// =============================================================================

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
/// Detect cb1002 missing tokenizer.
pub fn detect_cb1002_missing_tokenizer(project_path: &Path) -> Vec<CbPatternViolation> {
    let model_files = walkdir_model_files(project_path);
    let mut violations = Vec::new();

    // Group by directory
    let mut dirs_with_models: HashMap<PathBuf, Vec<PathBuf>> = HashMap::new();
    for f in &model_files {
        if let Some(parent) = f.parent() {
            dirs_with_models
                .entry(parent.to_path_buf())
                .or_default()
                .push(f.clone());
        }
    }

    for (dir, files) in &dirs_with_models {
        // Check for any language model (heuristic: GGUF files are typically LLMs)
        let has_llm = files.iter().any(|f| {
            f.extension()
                .and_then(|e| e.to_str())
                .map(|e| e == "gguf")
                .unwrap_or(false)
        });

        if !has_llm {
            continue;
        }

        let has_tokenizer = dir.join("tokenizer.json").exists()
            || dir.join("tokenizer.model").exists()
            || dir.join("vocab.json").exists();

        if !has_tokenizer {
            let rel = dir
                .strip_prefix(project_path)
                .unwrap_or(dir)
                .display()
                .to_string();

            violations.push(CbPatternViolation {
                pattern_id: "CB-1002".to_string(),
                file: rel,
                line: 0,
                description:
                    "GGUF model directory missing tokenizer (tokenizer.json/tokenizer.model)"
                        .to_string(),
                severity: Severity::Warning,
            });
        }
    }

    violations
}

// =============================================================================
// CB-1006: Sharded SafeTensors Without Index
// =============================================================================

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
/// Detect cb1006 sharded without index.
pub fn detect_cb1006_sharded_without_index(project_path: &Path) -> Vec<CbPatternViolation> {
    let model_files = walkdir_model_files(project_path);
    let mut violations = Vec::new();

    // Group by directory
    let mut dirs_with_models: HashMap<PathBuf, Vec<PathBuf>> = HashMap::new();
    for f in &model_files {
        if let Some(parent) = f.parent() {
            dirs_with_models
                .entry(parent.to_path_buf())
                .or_default()
                .push(f.clone());
        }
    }

    for (dir, files) in &dirs_with_models {
        // Detect sharded pattern: model-00001-of-00003.safetensors
        let sharded_files: Vec<&PathBuf> = files
            .iter()
            .filter(|f| {
                let name = f.file_name().and_then(|n| n.to_str()).unwrap_or("");
                name.contains("-of-") && name.ends_with(".safetensors")
            })
            .collect();

        if sharded_files.len() > 1 {
            let has_index = dir.join("model.safetensors.index.json").exists();
            if !has_index {
                let rel = dir
                    .strip_prefix(project_path)
                    .unwrap_or(dir)
                    .display()
                    .to_string();

                violations.push(CbPatternViolation {
                    pattern_id: "CB-1006".to_string(),
                    file: rel,
                    line: 0,
                    description: format!(
                        "{} sharded SafeTensors files without model.safetensors.index.json (BUG-212)",
                        sharded_files.len()
                    ),
                    severity: Severity::Error,
                });
            }
        }
    }

    violations
}

// =============================================================================
// CB-1007: Excessive File Size
// =============================================================================

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
/// Detect cb1007 excessive file size.
pub fn detect_cb1007_excessive_file_size(project_path: &Path) -> Vec<CbPatternViolation> {
    let model_files = walkdir_model_files(project_path);
    let mut violations = Vec::new();

    for file_path in &model_files {
        let file_size = match fs::metadata(file_path) {
            Ok(m) => m.len(),
            Err(_) => continue,
        };

        if file_size > LARGE_MODEL_THRESHOLD {
            let rel = file_path
                .strip_prefix(project_path)
                .unwrap_or(file_path)
                .display()
                .to_string();
            let size_gb = file_size as f64 / (1024.0 * 1024.0 * 1024.0);

            violations.push(CbPatternViolation {
                pattern_id: "CB-1007".to_string(),
                file: rel,
                line: 0,
                description: format!(
                    "Model file is {:.1} GB — consider quantization or sharding",
                    size_gb
                ),
                severity: Severity::Info,
            });
        }
    }

    violations
}

// =============================================================================
// CB-1004: Missing Architecture (GGUF)
// =============================================================================

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
/// Detect cb1004 missing architecture.
pub fn detect_cb1004_missing_architecture(project_path: &Path) -> Vec<CbPatternViolation> {
    let model_files = walkdir_model_files(project_path);
    let mut violations = Vec::new();

    for file_path in &model_files {
        if file_path.extension().and_then(|e| e.to_str()) != Some("gguf") {
            continue;
        }

        // Read enough header to check for architecture KV
        let content = match fs::read(file_path) {
            Ok(c) => c,
            Err(_) => continue,
        };

        // GGUF files should contain "general.architecture" key in metadata
        // Simple byte scan — GGUF metadata keys are stored as strings
        let needle = b"general.architecture";
        let has_arch = content.windows(needle.len()).any(|w| w == needle);

        if !has_arch && content.len() > 100 {
            let rel = file_path
                .strip_prefix(project_path)
                .unwrap_or(file_path)
                .display()
                .to_string();

            violations.push(CbPatternViolation {
                pattern_id: "CB-1004".to_string(),
                file: rel,
                line: 0,
                description:
                    "GGUF file missing `general.architecture` metadata key (BUG-EXPORT-004)"
                        .to_string(),
                severity: Severity::Warning,
            });
        }
    }

    violations
}

// =============================================================================
// CB-1005: Quantization Mismatch
// =============================================================================

/// Common quantization names that appear in filenames.
const QUANT_NAMES: &[&str] = &[
    "q2_k", "q3_k", "q4_k", "q4_0", "q4_1", "q5_k", "q5_0", "q5_1", "q6_k", "q8_0", "q8_1", "f16",
    "f32", "bf16", "q4_k_m", "q4_k_s", "q5_k_m", "q5_k_s", "q3_k_m", "q3_k_s", "q3_k_l", "q6_k_l",
    "q2_k_s", "iq4_xs", "iq4_nl",
];

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
/// Detect cb1005 quantization mismatch.
pub fn detect_cb1005_quantization_mismatch(project_path: &Path) -> Vec<CbPatternViolation> {
    let model_files = walkdir_model_files(project_path);
    let mut violations = Vec::new();

    for file_path in &model_files {
        if file_path.extension().and_then(|e| e.to_str()) != Some("gguf") {
            continue;
        }

        let filename = file_path
            .file_name()
            .and_then(|n| n.to_str())
            .unwrap_or("")
            .to_lowercase();

        // Check if filename claims a quantization type
        let claimed_quant = QUANT_NAMES.iter().find(|q| filename.contains(*q));

        if let Some(quant) = claimed_quant {
            // For F32 claims, check file size ratio
            // F32 models are ~4x larger than Q4 models
            if *quant == "f32" {
                let file_size = fs::metadata(file_path).map(|m| m.len()).unwrap_or(0);
                // A small F32 GGUF (< 100KB) with "f32" in name is suspicious
                if file_size < 100_000 && file_size > 0 {
                    let rel = file_path
                        .strip_prefix(project_path)
                        .unwrap_or(file_path)
                        .display()
                        .to_string();

                    violations.push(CbPatternViolation {
                        pattern_id: "CB-1005".to_string(),
                        file: rel,
                        line: 0,
                        description: format!(
                            "Filename claims {} quantization but file is suspiciously small ({} bytes) (BUG-1)",
                            quant.to_uppercase(),
                            file_size
                        ),
                        severity: Severity::Warning,
                    });
                }
            }
        }
    }

    violations
}

// =============================================================================
// CB-1008: APR Missing CRC
// =============================================================================

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
/// Detect cb1008 apr missing crc.
pub fn detect_cb1008_apr_missing_crc(project_path: &Path) -> Vec<CbPatternViolation> {
    let model_files = walkdir_model_files(project_path);
    let mut violations = Vec::new();

    for file_path in &model_files {
        if file_path.extension().and_then(|e| e.to_str()) != Some("apr") {
            continue;
        }

        let metadata = match parse_model_header(file_path) {
            Some(m) => m,
            None => continue,
        };

        if !metadata.has_crc {
            let rel = file_path
                .strip_prefix(project_path)
                .unwrap_or(file_path)
                .display()
                .to_string();

            violations.push(CbPatternViolation {
                pattern_id: "CB-1008".to_string(),
                file: rel,
                line: 0,
                description: "APR file missing CRC32 footer checksum".to_string(),
                severity: Severity::Warning,
            });
        }
    }

    violations
}