aprender-orchestrate 0.29.0

Sovereign AI orchestration: autonomous agents, ML serving, code analysis, and transpilation pipelines
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
//! Section 9: Cross-Platform & API Completeness (CP-01 to CP-05)
//!
//! Portability and API coverage verification.
//!
//! # TPS Principles
//!
//! - **Portability**: Multi-platform support
//! - **API completeness**: NumPy/sklearn coverage

use super::types::{CheckItem, Evidence, EvidenceType, Severity};
use std::path::Path;
use std::time::Instant;

/// Evaluate all Cross-Platform & API checks.
pub fn evaluate_all(project_path: &Path) -> Vec<CheckItem> {
    vec![
        check_linux_compatibility(project_path),
        check_macos_windows_compatibility(project_path),
        check_wasm_browser_compatibility(project_path),
        check_numpy_api_coverage(project_path),
        check_sklearn_coverage(project_path),
    ]
}

/// CP-01: Linux Distribution Compatibility
pub fn check_linux_compatibility(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "CP-01",
        "Linux Distribution Compatibility",
        "Stack runs on major Linux distributions",
    )
    .with_severity(Severity::Major)
    .with_tps("Portability");

    let has_linux_ci = check_ci_for_pattern(project_path, &["ubuntu", "linux"]);
    let has_glibc_docs = check_for_pattern(project_path, &["glibc", "musl", "linux"]);

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!("Linux: ci={}, docs={}", has_linux_ci, has_glibc_docs),
        data: None,
        files: Vec::new(),
    });

    if has_linux_ci {
        item = item.pass();
    } else {
        item = item.partial("No Linux CI testing");
    }

    item.finish_timed(start)
}

/// CP-02: macOS/Windows Compatibility
pub fn check_macos_windows_compatibility(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item =
        CheckItem::new("CP-02", "macOS/Windows Compatibility", "Stack runs on macOS and Windows")
            .with_severity(Severity::Major)
            .with_tps("Portability");

    let has_macos_ci = check_ci_for_pattern(project_path, &["macos", "darwin"]);
    let has_windows_ci = check_ci_for_pattern(project_path, &["windows"]);
    let has_cross_platform_code =
        check_for_pattern(project_path, &["cfg(target_os", "cfg!(windows)", "cfg!(macos)"]);

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "Cross-platform: macos_ci={}, windows_ci={}, code={}",
            has_macos_ci, has_windows_ci, has_cross_platform_code
        ),
        data: None,
        files: Vec::new(),
    });

    if has_macos_ci && has_windows_ci {
        item = item.pass();
    } else if has_macos_ci || has_windows_ci {
        item = item.partial("Partial cross-platform CI");
    } else if has_cross_platform_code {
        item = item.partial("Cross-platform code (no CI)");
    } else {
        item = item.partial("Linux-only testing");
    }

    item.finish_timed(start)
}

/// CP-03: WASM Browser Compatibility
pub fn check_wasm_browser_compatibility(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item =
        CheckItem::new("CP-03", "WASM Browser Compatibility", "WASM build works in major browsers")
            .with_severity(Severity::Major)
            .with_tps("Edge deployment");

    let has_wasm_build = check_for_pattern(project_path, &["wasm32", "wasm-bindgen", "wasm-pack"]);
    let has_browser_tests = check_for_pattern(
        project_path,
        &["wasm-bindgen-test", "browser_test", "chrome", "firefox"],
    );

    // Check for WASM feature in Cargo.toml
    let cargo_toml = project_path.join("Cargo.toml");
    let has_wasm_feature = cargo_toml
        .exists()
        .then(|| std::fs::read_to_string(&cargo_toml).ok())
        .flatten()
        .map(|c| c.contains("wasm") || c.contains("wasm32"))
        .unwrap_or(false);

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "WASM: build={}, tests={}, feature={}",
            has_wasm_build, has_browser_tests, has_wasm_feature
        ),
        data: None,
        files: Vec::new(),
    });

    if has_wasm_build && has_browser_tests {
        item = item.pass();
    } else if has_wasm_build || has_wasm_feature {
        item = item.partial("WASM support (verify browser testing)");
    } else {
        item = item.partial("No WASM browser support");
    }

    item.finish_timed(start)
}

/// CP-04: NumPy API Coverage
pub fn check_numpy_api_coverage(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item =
        CheckItem::new("CP-04", "NumPy API Coverage", "Supports >90% of NumPy operations")
            .with_severity(Severity::Major)
            .with_tps("API completeness");

    // Check for array/tensor operations that mirror NumPy
    let numpy_ops = [
        "reshape",
        "transpose",
        "dot",
        "matmul",
        "sum",
        "mean",
        "std",
        "var",
        "min",
        "max",
        "argmin",
        "argmax",
        "zeros",
        "ones",
        "eye",
        "linspace",
        "concatenate",
        "stack",
        "split",
    ];

    let mut found_ops = 0;
    if let Ok(entries) = glob::glob(&format!("{}/src/**/*.rs", project_path.display())) {
        for entry in entries.flatten() {
            if let Ok(content) = std::fs::read_to_string(&entry) {
                for op in &numpy_ops {
                    if content.contains(op) {
                        found_ops += 1;
                    }
                }
            }
        }
    }

    let coverage = (found_ops as f64 / numpy_ops.len() as f64 * 100.0) as u32;

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!("NumPy coverage: ~{}% ({}/{})", coverage, found_ops, numpy_ops.len()),
        data: None,
        files: Vec::new(),
    });

    let is_numeric = check_for_pattern(project_path, &["ndarray", "tensor", "Array"]);
    if !is_numeric || found_ops >= numpy_ops.len() * 80 / 100 {
        item = item.pass();
    } else if found_ops >= numpy_ops.len() / 2 {
        item = item.partial(format!("Partial NumPy coverage (~{}%)", coverage));
    } else {
        item = item.partial("Limited NumPy-like API coverage");
    }

    item.finish_timed(start)
}

/// CP-05: sklearn Estimator Coverage
pub fn check_sklearn_coverage(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "CP-05",
        "sklearn Estimator Coverage",
        "Supports >80% of sklearn estimators",
    )
    .with_severity(Severity::Major)
    .with_tps("API completeness");

    // Check for common sklearn estimator equivalents
    let sklearn_estimators = [
        "LinearRegression",
        "LogisticRegression",
        "Ridge",
        "Lasso",
        "RandomForest",
        "GradientBoosting",
        "DecisionTree",
        "KMeans",
        "DBSCAN",
        "PCA",
        "StandardScaler",
        "SVM",
        "KNeighbors",
        "NaiveBayes",
    ];

    let found_estimators = sklearn_estimators
        .iter()
        .filter(|est| {
            super::helpers::source_contains_pattern(project_path, &[est])
                || super::helpers::files_contain_pattern_ci(project_path, &["src/**/*.rs"], &[est])
        })
        .count();

    let coverage = (found_estimators as f64 / sklearn_estimators.len() as f64 * 100.0) as u32;

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "sklearn coverage: ~{}% ({}/{})",
            coverage,
            found_estimators,
            sklearn_estimators.len()
        ),
        data: None,
        files: Vec::new(),
    });

    let is_ml = check_for_pattern(project_path, &["train", "fit", "predict", "classifier"]);
    if !is_ml || found_estimators >= sklearn_estimators.len() * 70 / 100 {
        item = item.pass();
    } else if found_estimators >= sklearn_estimators.len() / 3 {
        item = item.partial(format!("Partial sklearn coverage (~{}%)", coverage));
    } else {
        item = item.partial("Limited sklearn-like estimator coverage");
    }

    item.finish_timed(start)
}

fn check_for_pattern(project_path: &Path, patterns: &[&str]) -> bool {
    super::helpers::source_contains_pattern(project_path, patterns)
}

fn check_ci_for_pattern(project_path: &Path, patterns: &[&str]) -> bool {
    super::helpers::ci_contains_pattern(project_path, patterns)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::path::PathBuf;

    #[test]
    fn test_evaluate_all_returns_5_items() {
        let path = PathBuf::from(".");
        let items = evaluate_all(&path);
        assert_eq!(items.len(), 5);
    }

    #[test]
    fn test_all_items_have_tps_principle() {
        let path = PathBuf::from(".");
        for item in evaluate_all(&path) {
            assert!(!item.tps_principle.is_empty(), "Item {} missing TPS", item.id);
        }
    }

    #[test]
    fn test_all_items_have_evidence() {
        let path = PathBuf::from(".");
        for item in evaluate_all(&path) {
            assert!(!item.evidence.is_empty(), "Item {} missing evidence", item.id);
        }
    }

    // ========================================================================
    // Additional Coverage Tests
    // ========================================================================

    #[test]
    fn test_cp01_linux_compatibility_id() {
        let result = check_linux_compatibility(Path::new("."));
        assert_eq!(result.id, "CP-01");
        assert_eq!(result.severity, Severity::Major);
        assert_eq!(result.tps_principle, "Portability");
    }

    #[test]
    fn test_cp02_macos_windows_compatibility_id() {
        let result = check_macos_windows_compatibility(Path::new("."));
        assert_eq!(result.id, "CP-02");
        assert_eq!(result.severity, Severity::Major);
        assert_eq!(result.tps_principle, "Portability");
    }

    #[test]
    fn test_cp03_wasm_browser_compatibility_id() {
        let result = check_wasm_browser_compatibility(Path::new("."));
        assert_eq!(result.id, "CP-03");
        assert_eq!(result.severity, Severity::Major);
        assert_eq!(result.tps_principle, "Edge deployment");
    }

    #[test]
    fn test_cp04_numpy_api_coverage_id() {
        let result = check_numpy_api_coverage(Path::new("."));
        assert_eq!(result.id, "CP-04");
        assert_eq!(result.severity, Severity::Major);
        assert_eq!(result.tps_principle, "API completeness");
    }

    #[test]
    fn test_cp05_sklearn_coverage_id() {
        let result = check_sklearn_coverage(Path::new("."));
        assert_eq!(result.id, "CP-05");
        assert_eq!(result.severity, Severity::Major);
        assert_eq!(result.tps_principle, "API completeness");
    }

    #[test]
    fn test_cp_nonexistent_path() {
        let path = Path::new("/nonexistent/path/for/testing");
        let items = evaluate_all(path);
        // Should still return 5 items
        assert_eq!(items.len(), 5);
    }

    #[test]
    fn test_linux_compat_with_ci_dir() {
        let temp_dir = std::env::temp_dir().join("test_cp_linux");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(temp_dir.join(".github/workflows")).expect("mkdir failed");

        // Create workflow with ubuntu
        std::fs::write(temp_dir.join(".github/workflows/ci.yml"), "runs-on: ubuntu-latest")
            .expect("unexpected failure");

        let result = check_linux_compatibility(&temp_dir);
        assert_eq!(result.id, "CP-01");

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_macos_windows_compat_with_ci() {
        let temp_dir = std::env::temp_dir().join("test_cp_macos");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(temp_dir.join(".github/workflows")).expect("mkdir failed");

        // Create workflow with macos
        std::fs::write(temp_dir.join(".github/workflows/ci.yml"), "runs-on: macos-latest")
            .expect("unexpected failure");

        let result = check_macos_windows_compatibility(&temp_dir);
        assert_eq!(result.id, "CP-02");

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_wasm_compat_with_cargo_toml() {
        let temp_dir = std::env::temp_dir().join("test_cp_wasm");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).expect("mkdir failed");

        // Create Cargo.toml with wasm-bindgen
        std::fs::write(
            temp_dir.join("Cargo.toml"),
            r#"[package]
name = "test"
version = "0.1.0"

[dependencies]
wasm-bindgen = "0.2"
"#,
        )
        .expect("unexpected failure");

        let result = check_wasm_browser_compatibility(&temp_dir);
        assert_eq!(result.id, "CP-03");

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_numpy_coverage_with_converter() {
        let temp_dir = std::env::temp_dir().join("test_cp_numpy");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(temp_dir.join("src")).expect("mkdir failed");

        // Create file with numpy converter reference
        std::fs::write(
            temp_dir.join("src/converter.rs"),
            "// numpy converter using trueno operations",
        )
        .expect("unexpected failure");

        let result = check_numpy_api_coverage(&temp_dir);
        assert_eq!(result.id, "CP-04");

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_sklearn_coverage_with_converter() {
        let temp_dir = std::env::temp_dir().join("test_cp_sklearn");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(temp_dir.join("src")).expect("mkdir failed");

        // Create file with sklearn converter reference
        std::fs::write(
            temp_dir.join("src/sklearn_converter.rs"),
            "// sklearn to aprender conversion",
        )
        .expect("unexpected failure");

        let result = check_sklearn_coverage(&temp_dir);
        assert_eq!(result.id, "CP-05");

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_all_items_have_reasonable_duration() {
        let path = PathBuf::from(".");
        for item in evaluate_all(&path) {
            // Duration should be reasonable (less than 1 minute per check)
            assert!(
                item.duration_ms < 60_000,
                "Item {} took unreasonably long: {}ms",
                item.id,
                item.duration_ms
            );
        }
    }

    // =========================================================================
    // Coverage Gap: check_numpy_api_coverage partial/limited branches
    // =========================================================================

    #[test]
    fn test_numpy_coverage_partial_with_numeric_project() {
        // Create a project that has tensor/ndarray but only ~50% numpy ops
        let temp_dir = std::env::temp_dir().join("test_cp04_partial");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(temp_dir.join("src")).expect("mkdir failed");

        // Include ndarray reference (is_numeric=true) and ~10 numpy ops (above 50%)
        std::fs::write(
            temp_dir.join("src/ops.rs"),
            concat!(
                "use ndarray::Array;\n",
                "pub fn reshape() {}\n",
                "pub fn transpose() {}\n",
                "pub fn dot() {}\n",
                "pub fn matmul() {}\n",
                "pub fn sum() {}\n",
                "pub fn mean() {}\n",
                "pub fn std() {}\n",
                "pub fn var() {}\n",
                "pub fn min() {}\n",
                "pub fn max() {}\n",
            ),
        )
        .expect("unexpected failure");

        let result = check_numpy_api_coverage(&temp_dir);
        assert_eq!(result.id, "CP-04");
        // With is_numeric=true and ~10/18 ops (55%), should be partial
        assert_eq!(result.status, super::super::types::CheckStatus::Partial);
        assert!(result.rejection_reason.as_deref().unwrap_or("").contains("NumPy"));

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_numpy_coverage_limited_with_numeric_project() {
        // Create a project that has ndarray (is_numeric=true) but very few numpy ops (< 50%)
        let temp_dir = std::env::temp_dir().join("test_cp04_limited");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(temp_dir.join("src")).expect("mkdir failed");

        // Include ndarray reference for is_numeric=true, but only 2 numpy ops
        std::fs::write(
            temp_dir.join("src/lib.rs"),
            "use ndarray::Array2;\npub fn reshape() {}\npub fn dot() {}\n",
        )
        .expect("unexpected failure");

        let result = check_numpy_api_coverage(&temp_dir);
        assert_eq!(result.id, "CP-04");
        // With is_numeric=true and only ~2/18 ops (11%), should be partial "Limited"
        assert_eq!(result.status, super::super::types::CheckStatus::Partial);
        assert!(result.rejection_reason.as_deref().unwrap_or("").contains("Limited"));

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    // =========================================================================
    // Coverage Gap: check_sklearn_coverage partial/limited branches
    // =========================================================================

    #[test]
    fn test_sklearn_coverage_partial_with_ml_project() {
        // ML project with some sklearn estimators (>= 33%, < 70%)
        let temp_dir = std::env::temp_dir().join("test_cp05_partial");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(temp_dir.join("src")).expect("mkdir failed");

        // has train/fit/predict (is_ml=true) + ~6 estimators
        std::fs::write(
            temp_dir.join("src/ml.rs"),
            concat!(
                "pub fn train() {}\npub fn fit() {}\npub fn predict() {}\n",
                "pub struct LinearRegression;\n",
                "pub struct LogisticRegression;\n",
                "pub struct Ridge;\n",
                "pub struct Lasso;\n",
                "pub struct RandomForest;\n",
                "pub struct GradientBoosting;\n",
            ),
        )
        .expect("unexpected failure");

        let result = check_sklearn_coverage(&temp_dir);
        assert_eq!(result.id, "CP-05");
        // 6/14 ~= 42%, above 33% threshold, should be partial
        assert_eq!(result.status, super::super::types::CheckStatus::Partial);
        assert!(result.rejection_reason.as_deref().unwrap_or("").contains("sklearn"));

        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_sklearn_coverage_limited_with_ml_project() {
        // ML project with very few sklearn estimators (< 33%)
        let temp_dir = std::env::temp_dir().join("test_cp05_limited");
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(temp_dir.join("src")).expect("mkdir failed");

        // has train/fit (is_ml=true) but only 1 estimator
        std::fs::write(
            temp_dir.join("src/ml.rs"),
            "pub fn train() {}\npub fn fit() {}\npub fn classifier() {}\npub struct LinearRegression;\n",
        )
        .expect("unexpected failure");

        let result = check_sklearn_coverage(&temp_dir);
        assert_eq!(result.id, "CP-05");
        // 1/14 ~= 7%, below 33% threshold, should be partial "Limited"
        assert_eq!(result.status, super::super::types::CheckStatus::Partial);
        assert!(result.rejection_reason.as_deref().unwrap_or("").contains("Limited"));

        let _ = std::fs::remove_dir_all(&temp_dir);
    }
}