aprender-orchestrate 0.31.2

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
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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
//! Section 1: Sovereign Data Governance (SDG-01 to SDG-15)
//!
//! Implements the Five Pillars verification: Data Residency, Privacy, Legal Controls.
//!
//! # TPS Principles
//!
//! - **Jidoka**: Automatic boundary violation detection
//! - **Poka-Yoke**: Classification-based routing, privacy by design
//! - **Muda**: Data inventory hygiene, prevent hoarding liability
//! - **Genchi Genbutsu**: Verify physical data locations

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

/// Evaluate all Sovereign Data Governance checks.
pub fn evaluate_all(project_path: &Path) -> Vec<CheckItem> {
    vec![
        check_data_residency_boundary(project_path),
        check_data_inventory_completeness(project_path),
        check_privacy_preserving_computation(project_path),
        check_federated_learning_isolation(project_path),
        check_supply_chain_provenance(project_path),
        check_vpc_isolation(project_path),
        check_data_classification_enforcement(project_path),
        check_consent_purpose_limitation(project_path),
        check_rtbf_compliance(project_path),
        check_cross_border_logging(project_path),
        check_model_weight_sovereignty(project_path),
        check_inference_classification(project_path),
        check_audit_log_immutability(project_path),
        check_third_party_isolation(project_path),
        check_secure_computation(project_path),
    ]
}

/// SDG-01: Data Residency Boundary Enforcement
///
/// **Claim:** Sovereign-critical data never crosses defined geographic boundaries.
///
/// **Rejection Criteria (Critical):**
/// - Any network call to non-compliant regions during Sovereign-tier operations
pub fn check_data_residency_boundary(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "SDG-01",
        "Data Residency Boundary Enforcement",
        "Sovereign-critical data never crosses geographic boundaries",
    )
    .with_severity(Severity::Critical)
    .with_tps("Jidoka — automatic boundary violation detection");

    // Check for residency configuration
    let config_files = [
        project_path.join("config/residency.yaml"),
        project_path.join("config/residency.toml"),
        project_path.join(".sovereignty/residency.yaml"),
    ];

    let has_residency_config = config_files.iter().any(|p| p.exists());

    // Check for VPC/network isolation configuration
    let infra_files = [
        project_path.join("infrastructure/vpc.tf"),
        project_path.join("terraform/vpc.tf"),
        project_path.join("infra/network.yaml"),
    ];

    let has_network_isolation = infra_files.iter().any(|p| p.exists());

    // Check for residency-aware code patterns
    let has_residency_checks = check_for_pattern(
        project_path,
        &["residency", "region_check", "boundary_enforce", "geo_fence"],
    );

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "Residency: config={}, network_isolation={}, code_checks={}",
            has_residency_config, has_network_isolation, has_residency_checks
        ),
        data: None,
        files: Vec::new(),
    });

    let is_cli_only = !has_network_code(project_path);
    item = apply_check_outcome(
        item,
        &[
            (has_residency_config && has_network_isolation, None),
            (
                has_residency_config || has_residency_checks,
                Some("Partial residency enforcement (missing network isolation)"),
            ),
            (is_cli_only, None),
            (true, Some("No explicit residency configuration")),
        ],
    );

    item.finish_timed(start)
}

/// SDG-02: Data Inventory Completeness
///
/// **Claim:** All ingested data has documented purpose, classification, and lifecycle policy.
///
/// **Rejection Criteria (Major):**
/// - Any data asset without classification tag or lifecycle policy
pub fn check_data_inventory_completeness(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "SDG-02",
        "Data Inventory Completeness",
        "All data has documented purpose, classification, and lifecycle",
    )
    .with_severity(Severity::Major)
    .with_tps("Muda (Inventory waste) — prevent data hoarding");

    // Check for data catalog/inventory
    let inventory_files = [
        project_path.join("data/inventory.yaml"),
        project_path.join("docs/data-catalog.md"),
        project_path.join(".datasheets/"),
        project_path.join("data/schema/"),
    ];

    let has_inventory = inventory_files.iter().any(|p| p.exists());

    // Check for data classification schema
    let has_classification = check_for_pattern(
        project_path,
        &["DataClassification", "data_class", "classification_level"],
    );

    // Check for lifecycle policies
    let has_lifecycle = check_for_pattern(
        project_path,
        &["lifecycle_policy", "retention_days", "data_ttl", "expiration"],
    );

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "Data inventory: catalog={}, classification={}, lifecycle={}",
            has_inventory, has_classification, has_lifecycle
        ),
        data: None,
        files: Vec::new(),
    });

    let handles_data = check_for_pattern(project_path, &["DataFrame", "Dataset", "DataLoader"]);
    item = apply_check_outcome(
        item,
        &[
            (has_inventory && has_classification && has_lifecycle, None),
            (
                has_inventory || has_classification,
                Some("Partial data inventory (missing lifecycle or classification)"),
            ),
            (!handles_data, None),
            (true, Some("No data inventory documentation")),
        ],
    );

    item.finish_timed(start)
}

/// SDG-03: Privacy-Preserving Computation
///
/// **Claim:** Differential privacy correctly implemented where specified.
///
/// **Rejection Criteria (Major):**
/// - ε-δ guarantees not met, composition budget exceeded
pub fn check_privacy_preserving_computation(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "SDG-03",
        "Privacy-Preserving Computation",
        "Differential privacy correctly implemented",
    )
    .with_severity(Severity::Major)
    .with_tps("Poka-Yoke — privacy by design");

    // Check for differential privacy implementation
    let has_dp = check_for_pattern(
        project_path,
        &[
            "differential_privacy",
            "epsilon",
            "privacy_budget",
            "laplace_noise",
            "gaussian_mechanism",
        ],
    );

    // Check for privacy budget tracking
    let has_budget_tracking =
        check_for_pattern(project_path, &["privacy_accountant", "budget_consumed", "composition"]);

    // Check for privacy tests
    let has_privacy_tests = check_for_test_pattern(project_path, &["privacy", "dp_test"]);

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "Privacy: dp_impl={}, budget_tracking={}, tests={}",
            has_dp, has_budget_tracking, has_privacy_tests
        ),
        data: None,
        files: Vec::new(),
    });

    let needs_privacy = check_for_pattern(project_path, &["pii", "personal_data", "gdpr"]);
    item = apply_check_outcome(
        item,
        &[
            (has_dp && has_budget_tracking && has_privacy_tests, None),
            (has_dp, Some("DP implemented but missing budget tracking or tests")),
            (!needs_privacy, None),
            (true, Some("PII handling without differential privacy")),
        ],
    );

    item.finish_timed(start)
}

/// SDG-04: Federated Learning Client Isolation
///
/// **Claim:** Federated learning clients send only model updates, never raw data.
///
/// **Rejection Criteria (Critical):**
/// - Any payload containing raw training samples in network trace
pub fn check_federated_learning_isolation(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "SDG-04",
        "Federated Learning Client Isolation",
        "FL clients send only model updates, never raw data",
    )
    .with_severity(Severity::Critical)
    .with_tps("Jidoka — client-side enforcement");

    // Check for federated learning implementation
    let has_fl = check_for_pattern(
        project_path,
        &["federated", "FederatedClient", "model_update", "gradient_only"],
    );

    // Check for secure aggregation
    let has_secure_agg = check_for_pattern(
        project_path,
        &["secure_aggregation", "SecureAggregator", "encrypted_gradient"],
    );

    // Check for data isolation tests
    let has_isolation_tests =
        check_for_test_pattern(project_path, &["client_isolation", "no_raw_data"]);

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "FL isolation: fl_impl={}, secure_agg={}, tests={}",
            has_fl, has_secure_agg, has_isolation_tests
        ),
        data: None,
        files: Vec::new(),
    });

    item = apply_check_outcome(
        item,
        &[
            (!has_fl, None),
            (has_fl && has_secure_agg && has_isolation_tests, None),
            (
                has_fl && has_secure_agg,
                Some("FL with secure aggregation (missing isolation tests)"),
            ),
            (true, Some("FL without secure aggregation")),
        ],
    );

    item.finish_timed(start)
}

/// SDG-05: Supply Chain Provenance (AI BOM)
///
/// **Claim:** All model weights and training data have verified provenance.
///
/// **Rejection Criteria (Critical):**
/// - Pre-trained weight without signature, training data without chain-of-custody
pub fn check_supply_chain_provenance(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "SDG-05",
        "Supply Chain Provenance (AI BOM)",
        "All model weights and data have verified provenance",
    )
    .with_severity(Severity::Critical)
    .with_tps("Jidoka — supply chain circuit breaker");

    // Check for AI BOM / SBOM
    let bom_files = [
        project_path.join("ai-bom.json"),
        project_path.join("sbom.json"),
        project_path.join("bom.xml"),
        project_path.join(".sbom/"),
    ];

    let has_bom = bom_files.iter().any(|p| p.exists());

    // Check for cargo-audit / cargo-deny
    let cargo_toml = project_path.join("Cargo.toml");
    let has_audit = cargo_toml
        .exists()
        .then(|| std::fs::read_to_string(&cargo_toml).ok())
        .flatten()
        .map(|c| c.contains("cargo-deny") || c.contains("cargo-audit"))
        .unwrap_or(false);

    // Check deny.toml for license/source policies
    let deny_toml = project_path.join("deny.toml");
    let has_deny_config = deny_toml.exists();

    // Check for signature verification
    let has_signature_check = check_for_pattern(
        project_path,
        &["verify_signature", "Ed25519", "sign_model", "provenance"],
    );

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "Supply chain: bom={}, audit={}, deny={}, signatures={}",
            has_bom, has_audit, has_deny_config, has_signature_check
        ),
        data: None,
        files: Vec::new(),
    });

    item = apply_check_outcome(
        item,
        &[
            (has_deny_config && (has_bom || has_signature_check), None),
            (has_deny_config || has_audit, Some("Dependency audit configured (missing AI BOM)")),
            (true, Some("No supply chain verification configured")),
        ],
    );

    item.finish_timed(start)
}

/// SDG-06: VPC Isolation Verification
///
/// **Claim:** Compute resources spin up only in compliant sovereign regions.
///
/// **Rejection Criteria (Major):**
/// - Any resource in non-approved region
pub fn check_vpc_isolation(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "SDG-06",
        "VPC Isolation Verification",
        "Compute only in compliant sovereign regions",
    )
    .with_severity(Severity::Major)
    .with_tps("Genchi Genbutsu — verify physical location");

    // Check for IaC with region constraints
    let iac_files = [
        project_path.join("terraform/"),
        project_path.join("infrastructure/"),
        project_path.join("pulumi/"),
        project_path.join("cloudformation/"),
    ];

    let has_iac = iac_files.iter().any(|p| p.exists());

    // Check for region policy
    let has_region_policy = check_for_pattern(
        project_path,
        &["allowed_regions", "region_whitelist", "sovereign_region"],
    );

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!("VPC: iac={}, region_policy={}", has_iac, has_region_policy),
        data: None,
        files: Vec::new(),
    });

    item = apply_check_outcome(
        item,
        &[
            (!has_iac, None),
            (has_iac && has_region_policy, None),
            (true, Some("IaC without explicit region constraints")),
        ],
    );

    item.finish_timed(start)
}

/// SDG-07: Data Classification Enforcement
///
/// **Claim:** Code paths enforce data classification levels.
///
/// **Rejection Criteria (Major):**
/// - Sovereign-classified data processed by Public-tier code path
pub fn check_data_classification_enforcement(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "SDG-07",
        "Data Classification Enforcement",
        "Code paths enforce data classification levels",
    )
    .with_severity(Severity::Major)
    .with_tps("Poka-Yoke — classification-based routing");

    // Check for type-level classification
    let has_type_classification = check_for_pattern(
        project_path,
        &["Classification", "DataTier", "SecurityLevel", "Sovereign<", "Confidential<"],
    );

    // Check for runtime enforcement
    let has_runtime_check = check_for_pattern(
        project_path,
        &["check_classification", "enforce_tier", "validate_access_level"],
    );

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "Classification: type_level={}, runtime={}",
            has_type_classification, has_runtime_check
        ),
        data: None,
        files: Vec::new(),
    });

    let handles_classified =
        check_for_pattern(project_path, &["sovereign", "confidential", "restricted"]);
    item = apply_check_outcome(
        item,
        &[
            (has_type_classification && has_runtime_check, None),
            (
                has_type_classification || has_runtime_check,
                Some("Partial classification enforcement"),
            ),
            (!handles_classified, None),
            (true, Some("Classified data without enforcement")),
        ],
    );

    item.finish_timed(start)
}

/// SDG-08: Consent and Purpose Limitation
///
/// **Claim:** Data usage matches documented consent scope.
///
/// **Rejection Criteria (Major):**
/// - Any data processing without matching consent record
pub fn check_consent_purpose_limitation(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "SDG-08",
        "Consent and Purpose Limitation",
        "Data usage matches documented consent scope",
    )
    .with_severity(Severity::Major)
    .with_tps("Legal controls pillar");

    // Check for consent management
    let has_consent =
        check_for_pattern(project_path, &["consent", "purpose_limitation", "data_usage_agreement"]);

    // Check for purpose binding
    let has_purpose_binding =
        check_for_pattern(project_path, &["purpose_id", "usage_scope", "consent_scope"]);

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "Consent: management={}, purpose_binding={}",
            has_consent, has_purpose_binding
        ),
        data: None,
        files: Vec::new(),
    });

    let handles_user_data = check_for_pattern(project_path, &["user_data", "personal", "pii"]);
    item = apply_check_outcome(
        item,
        &[
            (!handles_user_data, None),
            (has_consent && has_purpose_binding, None),
            (has_consent, Some("Consent tracking without purpose binding")),
            (true, Some("User data handling without consent management")),
        ],
    );

    item.finish_timed(start)
}

/// SDG-09: Right to Erasure (RTBF) Compliance
///
/// **Claim:** Data deletion requests fully propagate through all storage.
///
/// **Rejection Criteria (Major):**
/// - Any trace of erased identity in storage or model
pub fn check_rtbf_compliance(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "SDG-09",
        "Right to Erasure (RTBF) Compliance",
        "Deletion requests propagate through all storage",
    )
    .with_severity(Severity::Major)
    .with_tps("Muda — data inventory hygiene");

    // Check for deletion cascade
    let has_deletion = check_for_pattern(
        project_path,
        &["delete_user", "erasure", "rtbf", "forget_user", "cascade_delete"],
    );

    // Check for model unlearning
    let has_unlearning =
        check_for_pattern(project_path, &["unlearn", "model_forget", "data_removal"]);

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "RTBF: deletion_cascade={}, model_unlearning={}",
            has_deletion, has_unlearning
        ),
        data: None,
        files: Vec::new(),
    });

    let stores_user_data = check_for_pattern(project_path, &["user_store", "persist_user", "save"]);
    item = apply_check_outcome(
        item,
        &[
            (!stores_user_data, None),
            (has_deletion && has_unlearning, None),
            (has_deletion, Some("Deletion without model unlearning")),
            (true, Some("Data persistence without erasure mechanism")),
        ],
    );

    item.finish_timed(start)
}

/// SDG-10: Cross-Border Transfer Logging
///
/// **Claim:** All cross-border data transfers are logged and justified.
///
/// **Rejection Criteria (Major):**
/// - Any cross-border transfer without audit log entry
pub fn check_cross_border_logging(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "SDG-10",
        "Cross-Border Transfer Logging",
        "All cross-border transfers logged and justified",
    )
    .with_severity(Severity::Major)
    .with_tps("Auditability requirement");

    // Check for transfer logging
    let has_transfer_log = check_for_pattern(
        project_path,
        &["transfer_log", "cross_border", "data_export", "international_transfer"],
    );

    // Check for legal basis documentation
    let has_legal_basis = check_for_pattern(
        project_path,
        &["legal_basis", "transfer_agreement", "adequacy_decision"],
    );

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "Cross-border: logging={}, legal_basis={}",
            has_transfer_log, has_legal_basis
        ),
        data: None,
        files: Vec::new(),
    });

    let does_transfers = has_network_code(project_path);
    item = apply_check_outcome(
        item,
        &[
            (!does_transfers, None),
            (has_transfer_log && has_legal_basis, None),
            (has_transfer_log, Some("Transfer logging without legal basis")),
            (true, Some("Network operations without transfer logging")),
        ],
    );

    item.finish_timed(start)
}

/// SDG-11: Model Weight Sovereignty
///
/// **Claim:** Model weights trained on sovereign data remain under sovereign control.
///
/// **Rejection Criteria (Critical):**
/// - Model weights accessible from non-sovereign context
pub fn check_model_weight_sovereignty(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "SDG-11",
        "Model Weight Sovereignty",
        "Weights from sovereign data remain under sovereign control",
    )
    .with_severity(Severity::Critical)
    .with_tps("Jidoka — weight exfiltration prevention");

    // Check for weight access control
    let has_access_control = check_for_pattern(
        project_path,
        &["weight_access", "model_acl", "sovereign_model", "protected_weights"],
    );

    // Check for encryption
    let has_encryption =
        check_for_pattern(project_path, &["encrypt_weights", "sealed_model", "encrypted_model"]);

    // Check for key management
    let has_key_mgmt = check_for_pattern(project_path, &["key_management", "kms", "key_rotation"]);

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "Weight sovereignty: access_control={}, encryption={}, key_mgmt={}",
            has_access_control, has_encryption, has_key_mgmt
        ),
        data: None,
        files: Vec::new(),
    });

    let handles_weights =
        check_for_pattern(project_path, &["model_weights", "load_model", "save_model"]);
    item = apply_check_outcome(
        item,
        &[
            (!handles_weights, None),
            (has_access_control && has_encryption, None),
            (has_access_control || has_encryption, Some("Partial weight protection")),
            (true, Some("Model weights without sovereignty controls")),
        ],
    );

    item.finish_timed(start)
}

/// SDG-12: Inference Result Classification
///
/// **Claim:** Inference outputs inherit classification from input data.
///
/// **Rejection Criteria (Major):**
/// - Sovereign input produces unclassified output
pub fn check_inference_classification(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "SDG-12",
        "Inference Result Classification",
        "Outputs inherit classification from inputs",
    )
    .with_severity(Severity::Major)
    .with_tps("Poka-Yoke — automatic classification propagation");

    // Check for classification inheritance
    let has_inheritance = check_for_pattern(
        project_path,
        &["inherit_classification", "propagate_tier", "output_classification"],
    );

    // Check for output tagging
    let has_output_tagging =
        check_for_pattern(project_path, &["tag_output", "classify_result", "result_tier"]);

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "Inference classification: inheritance={}, tagging={}",
            has_inheritance, has_output_tagging
        ),
        data: None,
        files: Vec::new(),
    });

    let does_inference = check_for_pattern(project_path, &["inference", "predict", "infer"]);
    item = apply_check_outcome(
        item,
        &[
            (!does_inference, None),
            (has_inheritance && has_output_tagging, None),
            (has_inheritance || has_output_tagging, Some("Partial classification propagation")),
            (true, Some("Inference without classification propagation")),
        ],
    );

    item.finish_timed(start)
}

/// SDG-13: Audit Log Immutability
///
/// **Claim:** Audit logs cannot be modified or deleted.
///
/// **Rejection Criteria (Critical):**
/// - Any successful modification of historical log entry
pub fn check_audit_log_immutability(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "SDG-13",
        "Audit Log Immutability",
        "Audit logs cannot be modified or deleted",
    )
    .with_severity(Severity::Critical)
    .with_tps("Governance layer integrity");

    // Check for append-only logging
    let has_append_only =
        check_for_pattern(project_path, &["append_only", "immutable_log", "write_once"]);

    // Check for cryptographic chaining
    let has_chaining = check_for_pattern(
        project_path,
        &["merkle", "hash_chain", "log_signature", "tamper_evident"],
    );

    // Check for audit trail implementation
    let has_audit_trail =
        check_for_pattern(project_path, &["audit_trail", "audit_log", "AuditEntry"]);

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "Audit immutability: append_only={}, chaining={}, trail={}",
            has_append_only, has_chaining, has_audit_trail
        ),
        data: None,
        files: Vec::new(),
    });

    item = apply_check_outcome(
        item,
        &[
            (has_audit_trail && has_chaining, None),
            (has_audit_trail, Some("Audit trail without cryptographic verification")),
            (true, Some("No immutable audit logging")),
        ],
    );

    item.finish_timed(start)
}

/// SDG-14: Third-Party API Isolation
///
/// **Claim:** No third-party API calls during sovereign-tier operations.
///
/// **Rejection Criteria (Critical):**
/// - Any outbound call to non-sovereign endpoint
pub fn check_third_party_isolation(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "SDG-14",
        "Third-Party API Isolation",
        "No third-party API calls during sovereign operations",
    )
    .with_severity(Severity::Critical)
    .with_tps("Jidoka — network isolation");

    // Check for network allowlist
    let has_allowlist = check_for_pattern(
        project_path,
        &["allowlist", "whitelist", "approved_endpoints", "sovereign_endpoints"],
    );

    // Check for offline mode
    let has_offline_mode =
        check_for_pattern(project_path, &["offline_mode", "airgap", "no_network", "local_only"]);

    // Check for network guards
    let has_network_guard =
        check_for_pattern(project_path, &["network_guard", "egress_filter", "outbound_check"]);

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "Third-party isolation: allowlist={}, offline={}, guard={}",
            has_allowlist, has_offline_mode, has_network_guard
        ),
        data: None,
        files: Vec::new(),
    });

    let does_network = has_network_code(project_path);
    item = apply_check_outcome(
        item,
        &[
            (!does_network || has_offline_mode, None),
            (has_allowlist && has_network_guard, None),
            (has_allowlist, Some("Allowlist without runtime guard")),
            (true, Some("Network operations without isolation controls")),
        ],
    );

    item.finish_timed(start)
}

/// SDG-15: Homomorphic/Secure Computation Verification
///
/// **Claim:** Secure computation primitives correctly implemented.
///
/// **Rejection Criteria (Major):**
/// - Any information leakage beyond specified bounds
pub fn check_secure_computation(project_path: &Path) -> CheckItem {
    let start = Instant::now();
    let mut item = CheckItem::new(
        "SDG-15",
        "Secure Computation Verification",
        "Cryptographic primitives correctly implemented",
    )
    .with_severity(Severity::Major)
    .with_tps("Formal verification requirement");

    // Check for homomorphic encryption
    let has_he = check_for_pattern(project_path, &["homomorphic", "fhe", "seal", "paillier"]);

    // Check for MPC
    let has_mpc = check_for_pattern(project_path, &["mpc", "secure_multiparty", "secret_sharing"]);

    // Check for TEE
    let has_tee = check_for_pattern(project_path, &["sgx", "enclave", "trusted_execution", "tee"]);

    // Check for crypto tests
    let has_crypto_tests =
        check_for_test_pattern(project_path, &["crypto", "encryption", "secure_compute"]);

    item = item.with_evidence(Evidence {
        evidence_type: EvidenceType::StaticAnalysis,
        description: format!(
            "Secure compute: he={}, mpc={}, tee={}, tests={}",
            has_he, has_mpc, has_tee, has_crypto_tests
        ),
        data: None,
        files: Vec::new(),
    });

    let needs_secure_compute = has_he || has_mpc || has_tee;
    item = apply_check_outcome(
        item,
        &[
            (!needs_secure_compute, None),
            (needs_secure_compute && has_crypto_tests, None),
            (true, Some("Secure computation without comprehensive tests")),
        ],
    );

    item.finish_timed(start)
}

// ============================================================================
// Helper Functions
// ============================================================================

/// Apply the first matching outcome to a CheckItem.
///
/// Each entry is `(condition, outcome)` where `None` means pass and
/// `Some(msg)` means partial with that message.  The first `true` condition
/// wins; if nothing matches the item is returned unchanged.
fn apply_check_outcome(item: CheckItem, checks: &[(bool, Option<&str>)]) -> CheckItem {
    for &(condition, msg) in checks {
        if condition {
            return match msg {
                Some(m) => item.partial(m),
                None => item.pass(),
            };
        }
    }
    item
}

/// Check if any Rust source or config file contains any of the given patterns.
fn check_for_pattern(project_path: &Path, patterns: &[&str]) -> bool {
    super::helpers::source_or_config_contains_pattern(project_path, patterns)
}

/// Check if any test file contains any of the given patterns.
fn check_for_test_pattern(project_path: &Path, patterns: &[&str]) -> bool {
    super::helpers::test_contains_pattern(project_path, patterns)
}

/// Check if project has network code (HTTP, gRPC, etc.).
fn has_network_code(project_path: &Path) -> bool {
    check_for_pattern(
        project_path,
        &["reqwest", "hyper", "tonic", "TcpStream", "HttpClient", "fetch", "grpc"],
    )
}

// ============================================================================
// Tests
// ============================================================================

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

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

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

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

    #[test]
    fn test_sdg_01_data_residency() {
        let path = PathBuf::from(".");
        let item = check_data_residency_boundary(&path);
        assert_eq!(item.id, "SDG-01");
        assert_eq!(item.severity, Severity::Critical);
    }

    #[test]
    fn test_sdg_05_supply_chain() {
        let path = PathBuf::from(".");
        let item = check_supply_chain_provenance(&path);
        assert_eq!(item.id, "SDG-05");
        assert_eq!(item.severity, Severity::Critical);
    }

    #[test]
    fn test_sdg_13_audit_log() {
        let path = PathBuf::from(".");
        let item = check_audit_log_immutability(&path);
        assert_eq!(item.id, "SDG-13");
        assert_eq!(item.severity, Severity::Critical);
    }

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

    #[test]
    fn test_sdg_02_data_inventory() {
        let path = PathBuf::from(".");
        let item = check_data_inventory_completeness(&path);
        assert_eq!(item.id, "SDG-02");
    }

    #[test]
    fn test_sdg_03_privacy_preserving() {
        let path = PathBuf::from(".");
        let item = check_privacy_preserving_computation(&path);
        assert_eq!(item.id, "SDG-03");
    }

    #[test]
    fn test_sdg_04_federated_learning() {
        let path = PathBuf::from(".");
        let item = check_federated_learning_isolation(&path);
        assert_eq!(item.id, "SDG-04");
    }

    #[test]
    fn test_sdg_06_vpc_isolation() {
        let path = PathBuf::from(".");
        let item = check_vpc_isolation(&path);
        assert_eq!(item.id, "SDG-06");
    }

    #[test]
    fn test_sdg_07_data_classification() {
        let path = PathBuf::from(".");
        let item = check_data_classification_enforcement(&path);
        assert_eq!(item.id, "SDG-07");
    }

    #[test]
    fn test_sdg_08_consent_purpose() {
        let path = PathBuf::from(".");
        let item = check_consent_purpose_limitation(&path);
        assert_eq!(item.id, "SDG-08");
    }

    #[test]
    fn test_sdg_09_rtbf_compliance() {
        let path = PathBuf::from(".");
        let item = check_rtbf_compliance(&path);
        assert_eq!(item.id, "SDG-09");
    }

    #[test]
    fn test_sdg_10_cross_border() {
        let path = PathBuf::from(".");
        let item = check_cross_border_logging(&path);
        assert_eq!(item.id, "SDG-10");
    }

    #[test]
    fn test_sdg_11_model_weight() {
        let path = PathBuf::from(".");
        let item = check_model_weight_sovereignty(&path);
        assert_eq!(item.id, "SDG-11");
    }

    #[test]
    fn test_sdg_12_inference_classification() {
        let path = PathBuf::from(".");
        let item = check_inference_classification(&path);
        assert_eq!(item.id, "SDG-12");
    }

    #[test]
    fn test_sdg_14_third_party() {
        let path = PathBuf::from(".");
        let item = check_third_party_isolation(&path);
        assert_eq!(item.id, "SDG-14");
    }

    #[test]
    fn test_sdg_15_secure_computation() {
        let path = PathBuf::from(".");
        let item = check_secure_computation(&path);
        assert_eq!(item.id, "SDG-15");
    }

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

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

        std::fs::write(
            temp_dir.join("Cargo.toml"),
            r#"
[package]
name = "test"
version = "0.1.0"

[dependencies]
differential-privacy = "0.1"
"#,
        )
        .expect("unexpected failure");

        let item = check_privacy_preserving_computation(&temp_dir);
        assert_eq!(item.id, "SDG-03");

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

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

        std::fs::write(
            temp_dir.join("src/lib.rs"),
            r#"
pub struct DataInventory {
    pub pii: bool,
    pub classification: String,
}
"#,
        )
        .expect("unexpected failure");

        let item = check_data_inventory_completeness(&temp_dir);
        assert_eq!(item.id, "SDG-02");

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

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

        std::fs::write(
            temp_dir.join("src/lib.rs"),
            r#"
pub struct AuditLog {
    pub append_only: bool,
    pub immutable: bool,
}
"#,
        )
        .expect("unexpected failure");

        let item = check_audit_log_immutability(&temp_dir);
        assert_eq!(item.id, "SDG-13");

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

    #[test]
    fn test_all_have_severity() {
        let path = PathBuf::from(".");
        let items = evaluate_all(&path);
        for item in items {
            // All should have a severity set
            assert!(
                item.severity == Severity::Critical
                    || item.severity == Severity::Major
                    || item.severity == Severity::Minor
            );
        }
    }
}