pmat 3.31.0

PMAT - Zero-config AI context generation and code quality toolkit (CLI, MCP, HTTP)
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
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
//! E2E Demo Server Integration Tests
//!
//! Spawns demo binary as subprocess, parses ephemeral port from stdout,
//! executes HTTP assertions against live server.
//!
//! These tests are skipped in CI due to timing issues with subprocess spawning.
//!
//! NOTE (PMAT-COVERAGE-004): All tests in this file are marked #[ignore] because:
//! - Spawn subprocesses (incompatible with coverage instrumentation)
//! - Take 60+ seconds each
//! - Cause "Broken pipe" errors in coverage runs
//! - Should be run manually: cargo test --test demo_e2e_integration -- --ignored

// Helper macro to skip tests in CI
macro_rules! skip_in_ci {
    () => {
        if std::env::var("SKIP_SLOW_TESTS").is_ok() || std::env::var("CI").is_ok() {
            eprintln!("Skipping demo e2e test in CI environment");
            return Ok(());
        }
    };
}

use anyhow::Result;
use regex::Regex;
use reqwest::Client;
use serde_json::Value;
use serial_test::serial;
use std::process::{Child, Command, Stdio};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tempfile::TempDir;
use tokio::time::sleep;

/// Shared HTTP client for all tests
static HTTP_CLIENT: std::sync::LazyLock<Client> = std::sync::LazyLock::new(|| {
    Client::builder()
        .timeout(Duration::from_secs(30))
        .build()
        .expect("Failed to create HTTP client")
});

/// Regex for parsing port from demo server output
static PORT_REGEX: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
    Regex::new(r"http://127\.0\.0\.1:(\d+)").expect("Failed to compile port regex")
});

/// Test repository fixture for consistent analysis results
static TEST_REPO: std::sync::LazyLock<Arc<TempDir>> = std::sync::LazyLock::new(|| {
    Arc::new(create_test_repository().expect("Failed to create test repository"))
});

/// Demo server process with automatic cleanup
struct DemoServer {
    process: Child,
    #[allow(dead_code)]
    port: u16,
    base_url: String,
}

impl DemoServer {
    /// Spawn demo server subprocess and wait for startup
    async fn spawn(repo_path: &str) -> Result<Self> {
        // Skip demo tests in CI environment if binary not available
        if std::env::var("CI").is_ok() && std::env::var("CARGO_BIN_EXE_pmat").is_err() {
            // In CI, check for the built binary
            let ci_binary = "target/release/pmat";
            if !std::path::Path::new(ci_binary).exists() {
                eprintln!(
                    "[TEST] Skipping demo test - binary not found at {}",
                    ci_binary
                );
                anyhow::bail!("Demo binary not available in CI");
            }
        }

        // Use cargo's TARGET_DIR or fallback to workspace target directory
        let binary_path = std::env::var("CARGO_BIN_EXE_pmat").unwrap_or_else(|_| {
            // In CI, we build to target/release/pmat from workspace root
            let workspace_release = "target/release/pmat";
            let workspace_debug = "target/debug/pmat";

            if std::path::Path::new(workspace_release).exists() {
                workspace_release.to_string()
            } else if std::path::Path::new(workspace_debug).exists() {
                workspace_debug.to_string()
            } else if std::path::Path::new("../target/release/pmat").exists() {
                // Fallback for running from server directory
                "../target/release/pmat".to_string()
            } else if std::path::Path::new("../target/debug/pmat").exists() {
                // Use debug build if release not available
                "../target/debug/pmat".to_string()
            } else {
                // Final fallback
                panic!("Could not find pmat binary. Please run 'cargo build' or 'cargo build --release' from workspace root.")
            }
        });

        eprintln!("[TEST] Spawning demo server with binary: {}", binary_path);
        eprintln!("[TEST] Demo path: {}", repo_path);

        let mut process = Command::new(&binary_path)
            .args(["demo", "--path", repo_path, "--no-browser"])
            .stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .spawn()
            .map_err(|e| {
                anyhow::anyhow!("Failed to spawn demo server at {}: {}", binary_path, e)
            })?;

        // Read stdout until we find the server URL
        let stdout = process.stdout.take().expect("Failed to capture stdout");
        let stderr = process.stderr.take().expect("Failed to capture stderr");

        // Start monitoring stderr in background
        tokio::spawn(async move {
            use tokio::io::{AsyncBufReadExt, BufReader};
            let reader = BufReader::new(tokio::process::ChildStderr::from_std(stderr).unwrap());
            let mut lines = reader.lines();
            while let Ok(Some(line)) = lines.next_line().await {
                eprintln!("[DEMO STDERR] {}", line);
            }
        });

        let port = Self::parse_port_from_output(stdout).await?;

        let base_url = format!("http://127.0.0.1:{port}");

        // Wait for server to be ready
        Self::wait_for_server_ready(&base_url).await?;

        Ok(Self {
            process,
            port,
            base_url,
        })
    }

    async fn parse_port_from_output(stdout: std::process::ChildStdout) -> Result<u16> {
        // Spawn blocking task to handle stdout reading
        tokio::task::spawn_blocking(move || {
            use std::io::Read;

            let mut stdout = stdout;
            let timeout = Duration::from_secs(60); // Increased timeout for demo server startup
            let start = Instant::now();
            let mut buffer = Vec::new();

            while start.elapsed() < timeout {
                let mut temp_buffer = [0u8; 1024];
                match stdout.read(&mut temp_buffer) {
                    Ok(bytes_read) if bytes_read > 0 => {
                        buffer.extend_from_slice(&temp_buffer[..bytes_read]);
                        let output = String::from_utf8_lossy(&buffer);

                        // Print output for debugging
                        if !output.trim().is_empty() {
                            eprintln!("[DEMO STDOUT] {}", output.trim());
                        }

                        if let Some(captures) = PORT_REGEX.captures(&output) {
                            if let Some(port_str) = captures.get(1) {
                                eprintln!("[TEST] Found port: {}", port_str.as_str());
                                return Ok(port_str.as_str().parse().unwrap());
                            }
                        }
                    }
                    _ => {
                        std::thread::sleep(Duration::from_millis(100));
                    }
                }
            }

            let final_output = String::from_utf8_lossy(&buffer);
            eprintln!("[TEST] Final output from demo server:\n{}", final_output);
            Err(anyhow::anyhow!(
                "Failed to parse port from demo server output within timeout. Output: {}",
                final_output
            ))
        })
        .await?
    }

    async fn wait_for_server_ready(base_url: &str) -> Result<()> {
        let client = &*HTTP_CLIENT;
        let timeout = Duration::from_secs(60); // Increased timeout for slower systems
        let start = Instant::now();
        let mut last_error = None;

        while start.elapsed() < timeout {
            match client
                .get(base_url)
                .timeout(Duration::from_secs(5))
                .send()
                .await
            {
                Ok(response) if response.status().is_success() => {
                    // Give the server a bit more time to stabilize
                    sleep(Duration::from_millis(500)).await;
                    return Ok(());
                }
                Ok(response) => {
                    last_error = Some(format!("Server returned status: {}", response.status()));
                }
                Err(e) => {
                    last_error = Some(format!("Connection error: {}", e));
                }
            }
            sleep(Duration::from_millis(200)).await;
        }

        anyhow::bail!(
            "Server did not become ready within timeout. Last error: {}",
            last_error.unwrap_or_else(|| "Unknown".to_string())
        )
    }

    fn url(&self, path: &str) -> String {
        format!("{}{}", self.base_url, path)
    }
}

impl Drop for DemoServer {
    fn drop(&mut self) {
        // Gracefully terminate the demo server
        let _ = self.process.kill();
        let _ = self.process.wait();
    }
}

/// Create a minimal test repository with known structure
fn create_test_repository() -> Result<TempDir> {
    let temp_dir = tempfile::tempdir()?;
    let repo_path = temp_dir.path();

    // Create a simple Rust project structure
    std::fs::create_dir_all(repo_path.join("src"))?;

    // Cargo.toml
    std::fs::write(
        repo_path.join("Cargo.toml"),
        r#"[package]
name = "test-repo"
version = "0.1.0"
edition = "2021"

[dependencies]
serde = "1.0"
"#,
    )?;

    // Main.rs with known complexity
    std::fs::write(
        repo_path.join("src/main.rs"),
        r#"use serde::Serialize;

#[derive(Serialize)]
struct TestStruct {
    field1: String,
    field2: i32,
}

fn main() {
    let test = TestStruct {
        field1: "hello".to_string(),
        field2: 42,
    };
    println!("{:?}", test);
}

// High complexity function for testing
fn complex_function(x: i32, y: i32, z: i32) -> i32 {
    if x > 0 {
        if y > 0 {
            if z > 0 {
                if x > y {
                    if y > z {
                        return x + y + z;
                    } else if z > x {
                        return z - x;
                    } else {
                        return y * z;
                    }
                } else if y > z {
                    return y - z;
                } else {
                    return x * y;
                }
            } else {
                return x - y;
            }
        } else {
            return x + z;
        }
    } else {
        return y + z;
    }
}

fn simple_function(a: i32, b: i32) -> i32 {
    a + b
}
"#,
    )?;

    // Lib.rs with additional complexity
    std::fs::write(
        repo_path.join("src/lib.rs"),
        r#"pub mod utils;

pub fn library_function() -> String {
    "library".to_string()
}

pub fn another_complex_function(input: Vec<i32>) -> Vec<i32> {
    let mut result = Vec::new();
    for item in input {
        if item % 2 == 0 {
            if item > 10 {
                result.push(item * 2);
            } else {
                result.push(item + 1);
            }
        } else {
            if item > 5 {
                result.push(item - 1);
            } else {
                result.push(item * 3);
            }
        }
    }
    result
}
"#,
    )?;

    // Utils module
    std::fs::write(
        repo_path.join("src/utils.rs"),
        r#"pub fn utility_function(x: f64) -> f64 {
    if x < 0.0 {
        -x
    } else {
        x
    }
}

pub fn format_number(n: i32) -> String {
    format!("Number: {}", n)
}
"#,
    )?;

    // Initialize git repository for churn analysis
    Command::new("git")
        .args(["init"])
        .current_dir(repo_path)
        .output()?;

    Command::new("git")
        .args(["config", "user.name", "Test User"])
        .current_dir(repo_path)
        .output()?;

    Command::new("git")
        .args(["config", "user.email", "test@example.com"])
        .current_dir(repo_path)
        .output()?;

    Command::new("git")
        .args(["add", "."])
        .current_dir(repo_path)
        .output()?;

    Command::new("git")
        .args(["commit", "-m", "Initial commit"])
        .current_dir(repo_path)
        .output()?;

    Ok(temp_dir)
}

#[tokio::test]
#[ignore] // E2E test spawns subprocess (PMAT-COVERAGE-004)
async fn test_demo_server_happy_path() -> Result<()> {
    skip_in_ci!();

    let repo_path = TEST_REPO.path().to_str().unwrap();
    let server = DemoServer::spawn(repo_path).await?;

    // Test dashboard loads
    let response = HTTP_CLIENT.get(server.url("/")).send().await?;
    assert!(response.status().is_success());

    let html_content = response.text().await?;
    assert!(html_content.contains("PAIML MCP Agent Toolkit"));
    assert!(html_content.len() > 100); // Basic sanity check that we got content

    // Verify HTML structure with string matching (replaces scraper dependency)
    assert!(
        html_content.contains("stats-grid"),
        "Missing stats-grid class"
    );
    assert!(
        html_content.contains("stat-card"),
        "Missing stat-card class"
    );

    // Count stat-card occurrences (should have at least 4)
    let stat_card_count = html_content.matches("stat-card").count();
    assert!(
        stat_card_count >= 4,
        "Should have at least 4 stat cards, found {}",
        stat_card_count
    );

    Ok(())
}

#[tokio::test]
#[ignore] // E2E test spawns subprocess (PMAT-COVERAGE-004)
async fn test_api_contract_compliance() -> Result<()> {
    skip_in_ci!();

    let repo_path = TEST_REPO.path().to_str().unwrap();
    let server = DemoServer::spawn(repo_path).await?;

    // Test /api/summary endpoint
    let summary_response = HTTP_CLIENT.get(server.url("/api/summary")).send().await?;
    assert!(summary_response.status().is_success());

    let summary_json: Value = summary_response.json().await?;
    assert!(summary_json.get("files_analyzed").is_some());
    assert!(summary_json.get("avg_complexity").is_some());
    assert!(summary_json.get("tech_debt_hours").is_some());

    // Test /api/hotspots endpoint
    let hotspots_response = HTTP_CLIENT.get(server.url("/api/hotspots")).send().await?;
    assert!(hotspots_response.status().is_success());

    let hotspots_json: Value = hotspots_response.json().await?;
    assert!(hotspots_json.as_array().is_some());

    // Verify hotspot structure
    if let Some(hotspots) = hotspots_json.as_array() {
        if !hotspots.is_empty() {
            let first_hotspot = &hotspots[0];
            assert!(first_hotspot.get("function").is_some());
            assert!(first_hotspot.get("complexity").is_some());
            assert!(first_hotspot.get("loc").is_some());
            assert!(first_hotspot.get("path").is_some());
        }
    }

    // Test /api/dag endpoint
    let dag_response = HTTP_CLIENT.get(server.url("/api/dag")).send().await?;
    assert!(dag_response.status().is_success());

    let dag_text = dag_response.text().await?;
    assert!(dag_text.contains("graph TD") || dag_text.contains("flowchart"));

    // Test /api/system-diagram endpoint
    let system_response = HTTP_CLIENT
        .get(server.url("/api/system-diagram"))
        .send()
        .await?;
    assert!(system_response.status().is_success());

    let system_text = system_response.text().await?;
    assert!(system_text.contains("graph TD") || system_text.contains("flowchart"));

    // Test enhanced API endpoints
    let stats_response = HTTP_CLIENT
        .get(server.url("/api/v1/analysis/statistics"))
        .send()
        .await?;
    assert!(stats_response.status().is_success());

    let stats_json: Value = stats_response.json().await?;
    assert!(stats_json.get("structural_metrics").is_some());
    assert!(stats_json.get("code_metrics").is_some());

    Ok(())
}

#[tokio::test]
#[ignore] // E2E test spawns subprocess (PMAT-COVERAGE-004)
async fn test_concurrent_requests() -> Result<()> {
    skip_in_ci!();

    let repo_path = TEST_REPO.path().to_str().unwrap();
    let server = DemoServer::spawn(repo_path).await?;

    // Create 50 concurrent requests to different endpoints
    let mut handles = Vec::new();

    for i in 0..50 {
        let base_url = server.base_url.clone();
        let client = HTTP_CLIENT.clone();

        let handle = tokio::spawn(async move {
            let endpoint = match i % 4 {
                0 => "/",
                1 => "/api/summary",
                2 => "/api/hotspots",
                _ => "/api/dag",
            };

            let response = client.get(format!("{base_url}{endpoint}")).send().await?;
            assert!(response.status().is_success());
            Ok::<_, anyhow::Error>(())
        });

        handles.push(handle);
    }

    // Wait for all requests to complete
    for handle in handles {
        handle.await??;
    }

    Ok(())
}

#[tokio::test]
#[ignore] // E2E test spawns subprocess (PMAT-COVERAGE-004)
#[serial]
async fn test_performance_assertions() -> Result<()> {
    skip_in_ci!();

    let repo_path = TEST_REPO.path().to_str().unwrap();

    // Measure startup time
    let startup_start = Instant::now();
    let server = DemoServer::spawn(repo_path).await?;
    let startup_time = startup_start.elapsed();

    // Startup should be reasonable (analysis time is separate)
    // Allow more time on slower systems or under load
    assert!(
        startup_time < Duration::from_secs(90),
        "Startup took too long: {startup_time:?}"
    );

    // Test response latency
    let mut response_times = Vec::new();

    for i in 0..20 {
        let start = Instant::now();
        let response = HTTP_CLIENT.get(server.url("/api/summary")).send().await?;
        let elapsed = start.elapsed();

        assert!(response.status().is_success());
        response_times.push(elapsed);

        // Small delay between requests to avoid overwhelming the server
        if i < 19 {
            sleep(Duration::from_millis(50)).await;
        }
    }

    // Calculate p99 latency
    response_times.sort();
    let p99_index = (response_times.len() as f64 * 0.99) as usize;
    let p99_latency = response_times[p99_index.min(response_times.len() - 1)];

    // Allow higher latency on slower systems or under load
    assert!(
        p99_latency < Duration::from_millis(2000),
        "P99 latency too high: {p99_latency:?}"
    );

    Ok(())
}

#[tokio::test]
#[ignore] // E2E test spawns subprocess (PMAT-COVERAGE-004)
#[serial]
async fn test_error_handling() -> Result<()> {
    skip_in_ci!();

    let repo_path = TEST_REPO.path().to_str().unwrap();
    let server = DemoServer::spawn(repo_path).await?;

    // Test 404 for invalid paths
    let response = HTTP_CLIENT.get(server.url("/invalid/path")).send().await?;
    assert_eq!(response.status(), 404);

    // Test additional 404 cases
    let response = HTTP_CLIENT
        .get(server.url("/nonexistent/endpoint"))
        .send()
        .await?;
    assert_eq!(response.status(), 404);

    let response = HTTP_CLIENT
        .get(server.url("/api/nonexistent"))
        .send()
        .await?;
    assert_eq!(response.status(), 404);

    Ok(())
}

#[tokio::test]
#[ignore] // E2E test spawns subprocess (PMAT-COVERAGE-004)
async fn test_analysis_pipeline_integrity() -> Result<()> {
    skip_in_ci!();

    let repo_path = TEST_REPO.path().to_str().unwrap();

    // Capture process output to verify analysis steps
    let binary_path = std::env::var("CARGO_BIN_EXE_pmat").unwrap_or_else(|_| {
        // Try different locations for the binary
        let paths = [
            "target/release/pmat",
            "target/debug/pmat",
            "../target/release/pmat",
            "../target/debug/pmat",
        ];
        for path in &paths {
            if std::path::Path::new(path).exists() {
                return path.to_string();
            }
        }

        panic!("Could not find pmat binary. Please run 'cargo build' or 'cargo build --release' from workspace root.")
    });

    let mut process = Command::new(&binary_path)
        .args(["demo", "--path", repo_path, "--no-browser"])
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()?;

    // Read output until server starts
    let stdout = process.stdout.take().unwrap();
    let mut output = String::new();

    use std::io::Read;
    let mut reader = std::io::BufReader::new(stdout);
    let mut buffer = [0; 1024];

    let timeout = Duration::from_secs(60);
    let start = Instant::now();

    while start.elapsed() < timeout {
        if let Ok(bytes_read) = reader.read(&mut buffer) {
            if bytes_read > 0 {
                output.push_str(&String::from_utf8_lossy(&buffer[..bytes_read]));

                // Check if server has started
                if output.contains("Demo server running at:") {
                    break;
                }
            }
        }
        tokio::time::sleep(Duration::from_millis(100)).await;
    }

    // Verify all 7 analysis steps completed
    let expected_steps = [
        "Generating AST Context",
        "Analyzing Code Complexity",
        "Generating Dependency Graph",
        "Analyzing Code Churn",
        "Analyzing System Architecture",
        "Analyzing Defect Probability",
        "Generating Template",
    ];

    for step in &expected_steps {
        assert!(output.contains(step), "Missing analysis step: {step}");
    }

    // Verify completion markers
    for i in 1..=7 {
        let marker = format!("{i}️⃣");
        assert!(output.contains(&marker), "Missing step marker: {marker}");
    }

    // Clean up process
    let _ = process.kill();
    let _ = process.wait();

    Ok(())
}

#[tokio::test]
#[ignore] // E2E test spawns subprocess (PMAT-COVERAGE-004)
async fn test_data_source_indicators() -> Result<()> {
    skip_in_ci!();

    let repo_path = TEST_REPO.path().to_str().unwrap();
    let server = DemoServer::spawn(repo_path).await?;

    // Get dashboard HTML
    let response = HTTP_CLIENT.get(server.url("/")).send().await?;
    let html_content = response.text().await?;

    // Check for data source indicators with string matching (replaces scraper)
    assert!(
        html_content.contains("data-indicator") && html_content.contains("dynamic"),
        "Should have dynamic data indicators"
    );

    // Verify Performance Breakdown section exists
    assert!(
        html_content.contains("Performance Breakdown"),
        "Performance section should exist"
    );

    Ok(())
}

#[tokio::test]
#[ignore] // E2E test spawns subprocess (PMAT-COVERAGE-004)
async fn test_mermaid_diagram_rendering() -> Result<()> {
    skip_in_ci!();

    let repo_path = TEST_REPO.path().to_str().unwrap();
    let server = DemoServer::spawn(repo_path).await?;

    // Test DAG diagram endpoint
    let dag_response = HTTP_CLIENT.get(server.url("/api/dag")).send().await?;
    assert!(dag_response.status().is_success());

    let dag_content = dag_response.text().await?;

    // Verify it's valid Mermaid syntax
    assert!(
        dag_content.starts_with("graph TD")
            || dag_content.starts_with("flowchart")
            || dag_content.contains("graph TD"),
        "DAG should contain valid Mermaid syntax"
    );

    // Test system diagram endpoint
    let system_response = HTTP_CLIENT
        .get(server.url("/api/system-diagram"))
        .send()
        .await?;
    assert!(system_response.status().is_success());

    let system_content = system_response.text().await?;
    assert!(
        system_content.starts_with("graph TD")
            || system_content.starts_with("flowchart")
            || system_content.contains("graph TD"),
        "System diagram should contain valid Mermaid syntax"
    );

    // Verify diagrams are not empty
    assert!(
        dag_content.len() > 20,
        "DAG diagram should have substantial content"
    );
    assert!(
        system_content.len() > 20,
        "System diagram should have substantial content"
    );

    Ok(())
}