pmat 3.30.1

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP)
Documentation
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
// --- Churn analysis ---

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn analyze_churn(path: &std::path::Path, days: u32) -> anyhow::Result<CodeChurnAnalysis> {
    use crate::services::git_analysis::GitAnalysisService;
    use std::time::{Duration, Instant};

    info!("Starting churn analysis for path: {:?}", path);
    let start = Instant::now();

    // Smart bounds: timeout after 3 seconds for churn analysis
    let timeout = Duration::from_secs(3);

    match tokio::time::timeout(timeout, async {
        GitAnalysisService::analyze_code_churn(path, days)
            .map_err(|e| anyhow::anyhow!("Failed to analyze code churn: {e}"))
    })
    .await
    {
        Ok(result) => {
            info!("Churn analysis completed in {:?}", start.elapsed());
            result
        }
        Err(_) => {
            warn!("Churn analysis timed out after {:?}", timeout);
            // Return empty churn analysis instead of failing
            use crate::models::churn::ChurnSummary;
            use chrono::Utc;

            Ok(CodeChurnAnalysis {
                generated_at: Utc::now(),
                period_days: days,
                repository_root: path.to_path_buf(),
                files: Vec::new(),
                summary: ChurnSummary {
                    total_commits: 0,
                    total_files_changed: 0,
                    hotspot_files: Vec::new(),
                    stable_files: Vec::new(),
                    author_contributions: std::collections::HashMap::new(),
                    mean_churn_score: 0.0,
                    variance_churn_score: 0.0,
                    stddev_churn_score: 0.0,
                },
            })
        }
    }
}
// --- Duplicate code analysis ---

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn analyze_duplicate_code(
    path: &std::path::Path,
) -> anyhow::Result<crate::services::duplicate_detector::CloneReport> {
    use crate::services::duplicate_detector::DuplicateDetectionEngine;

    let all_files = discover_project_files(path)?;
    let files_for_analysis = filter_and_categorize_files_for_duplicates(all_files)?;
    let engine = DuplicateDetectionEngine::default();
    engine.detect_duplicates(&files_for_analysis)
}

fn discover_project_files(path: &std::path::Path) -> anyhow::Result<Vec<std::path::PathBuf>> {
    use crate::services::file_discovery::ProjectFileDiscovery;
    let discovery_service = ProjectFileDiscovery::new(path.to_path_buf());
    let files = discovery_service.discover_files()?;
    // Skip test files — they add noise to duplicate/clone detection
    Ok(files
        .into_iter()
        .filter(|f| !crate::services::deep_context::is_test_file(f))
        .collect())
}

fn filter_and_categorize_files_for_duplicates(
    all_files: Vec<std::path::PathBuf>,
) -> anyhow::Result<
    Vec<(
        std::path::PathBuf,
        String,
        crate::services::duplicate_detector::Language,
    )>,
> {
    let mut files_for_analysis = Vec::new();
    for file_path in all_files {
        if let Some((file, content, lang)) = process_file_for_duplicate_detection(&file_path)? {
            files_for_analysis.push((file, content, lang));
        }
    }
    Ok(files_for_analysis)
}

fn process_file_for_duplicate_detection(
    file_path: &std::path::Path,
) -> anyhow::Result<
    Option<(
        std::path::PathBuf,
        String,
        crate::services::duplicate_detector::Language,
    )>,
> {
    let ext = match file_path.extension().and_then(|e| e.to_str()) {
        Some(e) => e,
        None => return Ok(None),
    };

    let language = match_extension_to_language(ext)?;
    if language.is_none() {
        return Ok(None);
    }

    let content = match std::fs::read_to_string(file_path) {
        Ok(c) if c.lines().count() >= 10 => c,
        _ => return Ok(None),
    };

    Ok(Some((
        file_path.to_path_buf(),
        content,
        language.expect("internal error"),
    )))
}

fn match_extension_to_language(
    ext: &str,
) -> anyhow::Result<Option<crate::services::duplicate_detector::Language>> {
    use crate::services::duplicate_detector::Language;

    Ok(match ext {
        "rs" => Some(Language::Rust),
        "ts" | "tsx" => Some(Language::TypeScript),
        "js" | "jsx" => Some(Language::JavaScript),
        "py" => Some(Language::Python),
        "c" | "h" => Some(Language::C),
        "cpp" | "cc" | "cxx" | "hpp" | "hxx" | "cu" | "cuh" => Some(Language::Cpp),
        "kt" | "kts" => Some(Language::Kotlin),
        _ => None,
    })
}

// --- SATD analysis ---

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn analyze_satd(path: &std::path::Path) -> anyhow::Result<SATDAnalysisResult> {
    use crate::services::satd_detector::SATDDetector;

    let detector = SATDDetector::new();
    let result = detector.analyze_project(path, false).await?;

    Ok(result)
}

// --- Provability analysis ---

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn analyze_provability(
    path: &std::path::Path,
) -> anyhow::Result<Vec<crate::services::lightweight_provability_analyzer::ProofSummary>> {
    analyze_provability_with_cache(path, None).await
}

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn analyze_provability_with_cache(
    path: &std::path::Path,
    cache_manager: Option<std::sync::Arc<crate::services::cache::SessionCacheManager>>,
) -> anyhow::Result<Vec<crate::services::lightweight_provability_analyzer::ProofSummary>> {
    analyze_provability_with_context(path, cache_manager, None).await
}

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn analyze_provability_with_context(
    path: &std::path::Path,
    cache_manager: Option<std::sync::Arc<crate::services::cache::SessionCacheManager>>,
    prebuilt_context: Option<std::sync::Arc<crate::services::context::ProjectContext>>,
) -> anyhow::Result<Vec<crate::services::lightweight_provability_analyzer::ProofSummary>> {
    use crate::services::context::AstItem;
    use crate::services::lightweight_provability_analyzer::{
        FunctionId, LightweightProvabilityAnalyzer,
    };
    use std::time::Instant;

    info!("Starting provability analysis for path: {:?}", path);

    let analyzer = LightweightProvabilityAnalyzer::new();

    // No timeouts - use proper concurrency instead
    let start = Instant::now();

    // Reuse pre-built ProjectContext from AST phase if available (saves ~1 GB syn parsing)
    // Use owned context only when we need to call analyze_project_with_cache;
    // otherwise borrow from Arc to avoid cloning the entire ProjectContext.
    let owned_context;
    let project_context: &crate::services::context::ProjectContext = if let Some(ref ctx) = prebuilt_context {
        ctx.as_ref()
    } else {
        use crate::services::context::analyze_project_with_cache;
        let language = detect_project_language(path);
        match analyze_project_with_cache(path, language, cache_manager).await {
            Ok(context) => {
                owned_context = context;
                &owned_context
            }
            Err(e) => {
                warn!("AST analysis failed for provability: {:?}", e);
                return Ok(vec![]);
            }
        }
    };

    let mut function_ids = Vec::new();

    // Smart bounds: limit to 50 functions to prevent timeouts
    let mut function_count = 0;
    const MAX_FUNCTIONS: usize = 50;

    for file in &project_context.files {
        for item in &file.items {
            if let AstItem::Function { name, line, .. } = item {
                if function_count < MAX_FUNCTIONS {
                    function_ids.push(FunctionId {
                        file_path: file.path.clone(),
                        function_name: name.clone(),
                        line_number: *line,
                    });
                    function_count += 1;
                } else {
                    break;
                }
            }
        }
        if function_count >= MAX_FUNCTIONS {
            break;
        }
    }

    // If no functions found, add a mock one
    if function_ids.is_empty() {
        function_ids.push(FunctionId {
            file_path: format!("{}/src/main.rs", path.display()),
            function_name: "main".to_string(),
            line_number: 1,
        });
    }

    // Analyze all functions with proper parallel processing
    let summaries = analyzer.analyze_incrementally(&function_ids).await;

    info!(
        "Provability analysis completed for {} functions in {:?}",
        summaries.len(),
        start.elapsed()
    );
    Ok(summaries)
}

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
/// Detect project language.
pub fn detect_project_language(path: &std::path::Path) -> &'static str {
    use crate::services::file_discovery::ProjectFileDiscovery;
    let discovery = ProjectFileDiscovery::new(path.to_path_buf());
    let files = discovery.discover_files().unwrap_or_default();

    let mut counts = [0; 5]; // rust, python, ruby, ts, js
    for file in &files {
        if let Some(ext) = file.extension().and_then(|e| e.to_str()) {
            match ext {
                "rs" => counts[0] += 1,
                "py" => counts[1] += 1,
                "rb" => counts[2] += 1,
                "ts" | "tsx" => counts[3] += 1,
                "js" | "jsx" => counts[4] += 1,
                _ => {}
            }
        }
    }

    let (max_idx, _) = counts
        .iter()
        .enumerate()
        .max_by_key(|(_, &count)| count)
        .unwrap_or((0, &0));
    match max_idx {
        0 => "rust",
        1 => "python",
        2 => "ruby",
        3 => "typescript",
        _ => "javascript",
    }
}

// --- DAG analysis ---

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn analyze_dag(
    path: &std::path::Path,
    dag_type: DagType,
) -> anyhow::Result<DependencyGraph> {
    analyze_dag_with_cache(path, dag_type, None).await
}

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn analyze_dag_with_cache(
    path: &std::path::Path,
    dag_type: DagType,
    cache_manager: Option<std::sync::Arc<crate::services::cache::SessionCacheManager>>,
) -> anyhow::Result<DependencyGraph> {
    analyze_dag_with_context(path, dag_type, cache_manager, None).await
}

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn analyze_dag_with_context(
    path: &std::path::Path,
    dag_type: DagType,
    cache_manager: Option<std::sync::Arc<crate::services::cache::SessionCacheManager>>,
    prebuilt_context: Option<std::sync::Arc<crate::services::context::ProjectContext>>,
) -> anyhow::Result<DependencyGraph> {
    use crate::services::dag_builder::{
        filter_call_edges, filter_import_edges, filter_inheritance_edges, DagBuilder,
    };
    use std::time::Instant;

    info!("Starting DAG analysis for path: {:?}", path);
    let _start = Instant::now();

    // Reuse pre-built ProjectContext from AST phase if available (saves ~1 GB syn parsing)
    // Borrow from Arc to avoid cloning the entire ProjectContext.
    let owned_context;
    let project_context: &crate::services::context::ProjectContext = if let Some(ref ctx) = prebuilt_context {
        ctx.as_ref()
    } else {
        use crate::services::context::analyze_project_with_cache;
        let language = detect_project_language(path);
        owned_context = analyze_project_with_cache(path, language, cache_manager)
            .await
            .map_err(|e| {
                warn!("AST analysis failed for DAG: {:?}", e);
                anyhow::anyhow!("AST analysis failed: {}", e)
            })?;
        &owned_context
    };

    // Smart bounds: limit graph size to 200 nodes (was 400)
    let mut graph = DagBuilder::build_from_project_with_limit(project_context, 200);

    // #653 was only ever fixed on the CLI path. `DagBuilder` derives edges from
    // `use`/`impl` items, so it emits no `EdgeType::Calls` edge at all and
    // `filter_call_edges` below then deleted the entire graph: the MCP
    // `analyze_dag` tool answered "DAG analysis completed (0 nodes, 0 edges)"
    // for the very tree over which `pmat analyze dag --dag-type call-graph`
    // drew 24 call edges. An empty graph reported as a completed analysis is a
    // silent wrong answer, so the call-edge enrichment lives here, where both
    // surfaces reach it.
    crate::services::dag_call_edges::add_call_edges(&mut graph, path);

    // Apply filters based on DAG type
    let filtered_graph = match dag_type {
        DagType::CallGraph => filter_call_edges(graph),
        DagType::ImportGraph => filter_import_edges(graph),
        DagType::Inheritance => filter_inheritance_edges(graph),
        DagType::FullDependency => graph,
    };

    Ok(filtered_graph)
}

// --- Big-O analysis ---

#[provable_contracts_macros::contract("pmat-core.yaml", equation = "path_exists")]
pub async fn analyze_big_o(
    path: &std::path::Path,
) -> anyhow::Result<crate::services::big_o_analyzer::BigOAnalysisReport> {
    use crate::services::big_o_analyzer::{BigOAnalysisConfig, BigOAnalyzer};

    let analyzer = BigOAnalyzer::new();
    let config = BigOAnalysisConfig {
        project_path: path.to_path_buf(),
        include_patterns: vec![
            "**/*.rs".to_string(),
            "**/*.ts".to_string(),
            "**/*.py".to_string(),
        ],
        exclude_patterns: vec!["**/target/**".to_string(), "**/node_modules/**".to_string()],
        confidence_threshold: 50,
        analyze_space_complexity: false,
    };

    analyzer.analyze(config).await
}

#[cfg_attr(coverage_nightly, coverage(off))]
#[cfg(test)]
mod dag_service_tests {
    use super::*;

    /// The MCP `analyze_dag` tool goes through `analyze_dag_with_context`, not
    /// through the CLI handler, and only the CLI handler added call edges — so
    /// the tool reported "0 nodes, 0 edges" for a tree the CLI drew 24 edges
    /// over. A call graph with no edges over real Rust sources is a wrong
    /// answer, not an empty project.
    #[tokio::test]
    async fn call_graph_from_the_service_path_has_call_edges() {
        let dir = tempfile::tempdir().expect("tempdir");
        std::fs::write(
            dir.path().join("main.rs"),
            "mod helper;\nfn main() { helper_one(); }\nfn helper_one() { helper_two(); }\nfn helper_two() {}\n",
        )
        .expect("write main.rs");

        let graph = analyze_dag(dir.path(), DagType::CallGraph)
            .await
            .expect("call-graph analysis must succeed");

        assert!(
            !graph.edges.is_empty(),
            "call graph over Rust sources must contain Calls edges, got {} nodes / {} edges",
            graph.nodes.len(),
            graph.edges.len()
        );
        assert!(
            !graph.nodes.is_empty(),
            "edges without nodes would be a filtered-away graph again"
        );
    }
}