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
#![cfg(feature = "demo")]
#![cfg(feature = "demo")]

use pmat::demo::server::EnhancedHotspot;
use pmat::demo::{DemoContent, LocalDemoServer};
use std::collections::HashMap;
use std::time::Duration;
use tokio::time::timeout;

fn create_test_demo_content() -> DemoContent {
    DemoContent {
        mermaid_diagram: "graph TD\n  A --> B".to_string(),
        system_diagram: None,
        files_analyzed: 10,
        functions_analyzed: 5,
        avg_complexity: 5.5,
        p90_complexity: 15,
        hotspot_functions: 2,
        quality_score: 0.85,
        tech_debt_hours: 20,
        hotspots: vec![],
        language_stats: HashMap::new(),
        ast_time_ms: 100,
        complexity_time_ms: 150,
        churn_time_ms: 200,
        dag_time_ms: 250,
        recommendations: vec![],
        polyglot_analysis: None,
    }
}

#[tokio::test]
async fn test_demo_server_startup_and_shutdown() {
    // Create test content
    let content = create_test_demo_content();

    // Start server
    let (server, port) = LocalDemoServer::spawn(content.clone()).await.unwrap();
    assert!(port > 0);

    // Verify server is running
    let client = reqwest::Client::new();
    let response = client
        .get(format!("http://127.0.0.1:{port}/"))
        .send()
        .await
        .unwrap();
    assert_eq!(response.status(), 200);

    // Shutdown server
    server.shutdown();

    // Verify server has stopped (with timeout)
    let result = timeout(Duration::from_secs(2), async {
        loop {
            if client
                .get(format!("http://127.0.0.1:{port}/"))
                .send()
                .await
                .is_err()
            {
                break;
            }
            tokio::time::sleep(Duration::from_millis(100)).await;
        }
    })
    .await;

    assert!(result.is_ok(), "Server did not shut down in time");
}

#[tokio::test]
async fn test_demo_server_api_endpoints() {
    // Create test content with hotspots
    let mut content = create_test_demo_content();
    content.mermaid_diagram = "graph TD\n  A[Main] --> B[Utils]\n  A --> C[Helpers]".to_string();
    content.files_analyzed = 25;
    content.avg_complexity = 8.3;
    content.tech_debt_hours = 45;
    content.hotspots = vec![
        EnhancedHotspot {
            function: "complex_algorithm".to_string(),
            file: "src/complex.rs".to_string(),
            path: "src/complex.rs".to_string(),
            complexity: 15,
            loc: 80,
            language: "rust".to_string(),
            churn_score: 80,
            refactor_suggestion: "Consider breaking down this function".to_string(),
        },
        EnhancedHotspot {
            function: "utility_helper".to_string(),
            file: "src/utils.rs".to_string(),
            path: "src/utils.rs".to_string(),
            complexity: 12,
            loc: 60,
            language: "rust".to_string(),
            churn_score: 60,
            refactor_suggestion: "Extract common patterns".to_string(),
        },
    ];
    content.ast_time_ms = 120;
    content.complexity_time_ms = 180;
    content.churn_time_ms = 240;
    content.dag_time_ms = 300;

    let (server, port) = LocalDemoServer::spawn(content).await.unwrap();
    let client = reqwest::Client::new();
    let base_url = format!("http://127.0.0.1:{port}");

    // Test root endpoint (HTML dashboard)
    let response = client.get(&base_url).send().await.unwrap();
    assert_eq!(response.status(), 200);
    let html = response.text().await.unwrap();
    assert!(html.contains("<!DOCTYPE html>"));
    assert!(html.contains("PAIML MCP Agent Toolkit Demo"));
    assert!(html.contains("25")); // files_analyzed
    assert!(html.contains("8.3")); // avg_complexity

    // Test summary API endpoint
    let response = client
        .get(format!("{base_url}/api/summary"))
        .send()
        .await
        .unwrap();
    assert_eq!(response.status(), 200);
    let summary: serde_json::Value = response.json().await.unwrap();
    assert_eq!(summary["files_analyzed"], 25);
    assert_eq!(summary["avg_complexity"], 8.3);
    assert_eq!(summary["tech_debt_hours"], 45);
    assert_eq!(summary["time_context"], 100);

    // Test metrics API endpoint
    let response = client
        .get(format!("{base_url}/api/metrics"))
        .send()
        .await
        .unwrap();
    assert_eq!(response.status(), 200);
    let metrics: serde_json::Value = response.json().await.unwrap();
    assert_eq!(metrics["files_analyzed"], 25);

    // Test hotspots API endpoint
    let response = client
        .get(format!("{base_url}/api/hotspots"))
        .send()
        .await
        .unwrap();
    assert_eq!(response.status(), 200);
    let hotspots: Vec<serde_json::Value> = response.json().await.unwrap();
    // Returns fallback hotspots since complexity analysis is empty
    assert_eq!(hotspots.len(), 5);

    // Test DAG API endpoint
    let response = client
        .get(format!("{base_url}/api/dag"))
        .send()
        .await
        .unwrap();
    assert_eq!(response.status(), 200);
    let dag = response.text().await.unwrap();
    assert!(dag.contains("graph TD"));

    // Test 404 handling
    let response = client
        .get(format!("{base_url}/nonexistent"))
        .send()
        .await
        .unwrap();
    assert_eq!(response.status(), 404);

    server.shutdown();
}

#[tokio::test]
async fn test_demo_server_static_assets() {
    let mut content = create_test_demo_content();
    content.mermaid_diagram = "graph TD".to_string();
    content.files_analyzed = 1;
    content.avg_complexity = 1.0;
    content.tech_debt_hours = 0;

    let (server, port) = LocalDemoServer::spawn(content).await.unwrap();
    let client = reqwest::Client::new();
    let base_url = format!("http://127.0.0.1:{port}");

    // Test vendor assets (if they exist)
    let vendor_paths = vec!["/vendor/gridjs.min.js", "/vendor/gridjs-mermaid.min.css"];

    for path in vendor_paths {
        let response = client
            .get(format!("{base_url}{path}"))
            .send()
            .await
            .unwrap();
        // Assets might not exist during tests, so we accept either 200 or 404
        assert!(
            response.status() == 200 || response.status() == 404,
            "Unexpected status for {}: {}",
            path,
            response.status()
        );
    }

    server.shutdown();
}

#[tokio::test]
async fn test_demo_server_concurrent_requests() {
    let mut content = create_test_demo_content();
    content.mermaid_diagram = "graph TD\n  A --> B".to_string();
    content.files_analyzed = 100;
    content.avg_complexity = std::f64::consts::PI;
    content.tech_debt_hours = 8;

    let (server, port) = LocalDemoServer::spawn(content).await.unwrap();
    let base_url = format!("http://127.0.0.1:{port}");

    // Spawn multiple concurrent requests
    let mut handles = vec![];
    for i in 0..10 {
        let url = base_url.clone();
        let handle = tokio::spawn(async move {
            let client = reqwest::Client::new();
            let endpoint = match i % 4 {
                0 => "/",
                1 => "/api/summary",
                2 => "/api/metrics",
                _ => "/api/dag",
            };
            let response = client.get(format!("{url}{endpoint}")).send().await.unwrap();
            assert_eq!(response.status(), 200);
        });
        handles.push(handle);
    }

    // Wait for all requests to complete
    for handle in handles {
        handle.await.unwrap();
    }

    server.shutdown();
}

#[tokio::test]
async fn test_demo_server_response_headers() {
    let mut content = create_test_demo_content();
    content.mermaid_diagram = "graph TD".to_string();
    content.files_analyzed = 1;
    content.avg_complexity = 1.0;
    content.tech_debt_hours = 0;

    let (server, port) = LocalDemoServer::spawn(content).await.unwrap();
    let client = reqwest::Client::new();
    let base_url = format!("http://127.0.0.1:{port}");

    // Test HTML response headers
    let response = client.get(&base_url).send().await.unwrap();
    assert_eq!(
        response.headers().get("content-type").unwrap(),
        "text/html; charset=utf-8"
    );
    assert_eq!(response.headers().get("cache-control").unwrap(), "no-cache");

    // Test JSON response headers
    let response = client
        .get(format!("{base_url}/api/summary"))
        .send()
        .await
        .unwrap();
    assert_eq!(
        response.headers().get("content-type").unwrap(),
        "application/json"
    );

    // Test DAG response headers
    let response = client
        .get(format!("{base_url}/api/dag"))
        .send()
        .await
        .unwrap();
    assert_eq!(
        response.headers().get("content-type").unwrap(),
        "text/plain"
    );

    server.shutdown();
}

#[tokio::test]
async fn test_demo_content_rendering() {
    // Test with specific values to ensure proper rendering
    let mut content = create_test_demo_content();
    content.mermaid_diagram =
        "graph TD\n  API[API Server] --> DB[Database]\n  API --> Cache[Redis Cache]".to_string();
    content.files_analyzed = 42;
    content.avg_complexity = 6.78;
    content.tech_debt_hours = 123;
    content.hotspots = vec![
        EnhancedHotspot {
            function: "main".to_string(),
            file: "src/main.rs".to_string(),
            path: "src/main.rs".to_string(),
            complexity: 25,
            loc: 150,
            language: "rust".to_string(),
            churn_score: 95,
            refactor_suggestion: "High complexity function needs refactoring".to_string(),
        },
        EnhancedHotspot {
            function: "handle_api".to_string(),
            file: "src/handlers/api.rs".to_string(),
            path: "src/handlers/api.rs".to_string(),
            complexity: 18,
            loc: 120,
            language: "rust".to_string(),
            churn_score: 70,
            refactor_suggestion: "Consider breaking into smaller functions".to_string(),
        },
        EnhancedHotspot {
            function: "database_query".to_string(),
            file: "src/services/database.rs".to_string(),
            path: "src/services/database.rs".to_string(),
            complexity: 15,
            loc: 100,
            language: "rust".to_string(),
            churn_score: 50,
            refactor_suggestion: "Extract query builder patterns".to_string(),
        },
    ];

    let (server, port) = LocalDemoServer::spawn(content).await.unwrap();
    let client = reqwest::Client::new();

    // Check that the HTML contains our specific values
    let response = client
        .get(format!("http://127.0.0.1:{port}/"))
        .send()
        .await
        .unwrap();
    let html = response.text().await.unwrap();

    // Verify specific content is rendered
    assert!(html.contains("42")); // files_analyzed
    assert!(html.contains("6.78")); // avg_complexity formatted
                                    // Note: tech_debt_hours is not currently displayed in the HTML template

    // Verify timing values
    assert!(html.contains("100")); // time_context
    assert!(html.contains("150")); // time_complexity
    assert!(html.contains("200")); // time_dag
    assert!(html.contains("250")); // time_churn

    server.shutdown();
}

// Legacy test compatibility
#[cfg(test)]
mod demo_web_tests {
    use super::*;
    use pmat::models::dag::{DependencyGraph, NodeInfo, NodeType};

    #[tokio::test]
    async fn test_demo_server_starts() {
        let mut content = create_test_demo_content();
        content.mermaid_diagram = String::from("graph TD\n    A[Test] --> B[Demo]");
        content.files_analyzed = 10;
        content.avg_complexity = 5.5;
        content.tech_debt_hours = 12;
        content.hotspots = vec![EnhancedHotspot {
            function: "test_function".to_string(),
            file: String::from("test.rs"),
            path: String::from("test.rs"),
            complexity: 15,
            loc: 80,
            language: "rust".to_string(),
            churn_score: 80,
            refactor_suggestion: "Test function needs optimization".to_string(),
        }];

        // Start the server
        let (server, port) = LocalDemoServer::spawn(content)
            .await
            .expect("Failed to start demo server");

        // Verify we got a port
        assert!(port > 0);
        assert_eq!(server.port(), port);

        // Server will shut down when dropped
    }

    #[test]
    fn test_demo_content_from_analysis() {
        let mut graph = DependencyGraph::new();
        graph.add_node(NodeInfo {
            id: "test".to_string(),
            label: "Test Node".to_string(),
            node_type: NodeType::Function,
            file_path: String::new(),
            line_number: 0,
            complexity: 5,
            metadata: rustc_hash::FxHashMap::default(),
        });

        let content =
            DemoContent::from_analysis_results(&graph, 10, 5.5, 12, vec![], 100, 150, 200, 250);

        assert_eq!(content.files_analyzed, 10);
        assert_eq!(content.avg_complexity, 5.5);
        assert_eq!(content.tech_debt_hours, 12);
        assert!(content.mermaid_diagram.contains("graph TD"));
        assert!(content.mermaid_diagram.contains("test[Test Node]"));
    }
}