-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path{}.tmp
More file actions
3602 lines (3269 loc) · 137 KB
/
{}.tmp
File metadata and controls
3602 lines (3269 loc) · 137 KB
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
// Copyright © 2026 NexVigilant LLC. All Rights Reserved.
// Intellectual Property of Matthew Alexander Campion, PharmD
//! Error types for the phenotype system.
//!
//! ## Primitive Grounding: ∂ (Boundary) + Σ (Sum)
//!
//! Errors define boundaries between valid and invalid mutation states.
//! The error enum is a sum type (Σ) of all possible failure modes.
use nexcore_error::Error;
/// Phenotype system errors.
///
/// ## Tier: T2-P (∂ + Σ)
#[derive(Debug, Error)]
pub enum PhenotypeError {
/// Mutation could not be applied to the given schema.
#[error("mutation failed for {mutation}: {reason}")]
MutationFailed {
/// The mutation that failed.
mutation: String,
/// Why it failed.
reason: String,
},
/// Verification against ribosome failed.
#[error("verification error: {0}")]
VerificationError(String),
/// Invalid schema provided for mutation.
#[error("invalid schema: {0}")]
InvalidSchema(String),
}
/// Result type for phenotype operations.
pub type PhenotypeResult<T> = Result<T, PhenotypeError>;
//! # Harm Synthesis — PV-Domain Adversarial Test Generation
//!
//! Extends the phenotype mutation engine with pharmacovigilance-specific
//! harm scenarios. Generates adversarial test fixtures that simulate
//! real-world data integrity failures in drug safety records.
//!
//! ## Innovation Scan 001 — Goal 4 (Score: 7.85)
//!
//! ```text
//! HarmScenario → PvHarmMutation → Phenotype { data, expected_drifts }
//! ↓
//! pv_contracts::evaluate_drift → PvDriftAction
//! ```
//!
//! ## ToV Alignment: V4 Safety Manifold
//! d(s) > 0 — these mutations simulate the exact failure modes that
//! threaten patient safety, ensuring detection systems catch them.
//!
//! ## Tier: T2-C (∂ + μ + κ + N + →)
use nexcore_ribosome::DriftType;
use serde::{Deserialize, Serialize};
// ─── Harm Scenarios ──────────────────────────────────────────────────────────
/// PV-domain harm scenarios that map to real-world data integrity failures.
///
/// Each scenario represents a specific way drug safety data can be
/// corrupted, mislabeled, or manipulated — and what detection systems
/// should catch.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum HarmScenario {
/// Adverse event term replaced with a less severe synonym.
/// Example: "hepatotoxicity" → "nausea" (severity downgrade).
/// Impact: Underreporting of serious adverse events.
SeverityDowngrade,
/// Seriousness criteria fields removed or set to false.
/// Example: `is_serious: true` → field missing.
/// Impact: Serious cases not flagged for expedited reporting.
MissingSeriousness,
/// Drug name altered to a different substance.
/// Example: "warfarin" → "aspirin" (attribution error).
/// Impact: Signal attributed to wrong drug.
DrugMisattribution,
/// Case count artificially reduced.
/// Example: `case_count: 47` → `case_count: 3`.
/// Impact: PRR/ROR denominator manipulation, signal suppression.
CaseCountDeflation,
/// Duplicate records injected with slightly different keys.
/// Example: Same case, different `case_id` values.
/// Impact: Artificially inflated signal strength.
DuplicateInjection,
/// Narrative/description field truncated below useful length.
/// Example: 500-char narrative → 10-char stub.
/// Impact: Loss of clinical context for causality assessment.
NarrativeTruncation,
/// Reporting date shifted to avoid time-based signal windows.
/// Example: `report_date: 2025-01-15` → `report_date: 2023-01-15`.
/// Impact: Case excluded from temporal signal analysis.
TemporalShift,
/// Outcome field changed to mask fatal outcomes.
/// Example: `outcome: "death"` → `outcome: "recovered"`.
/// Impact: Fatal cases invisible in mortality signal detection.
OutcomeMasking,
}
impl HarmScenario {
/// All available harm scenarios.
pub const ALL: &[Self] = &[
Self::SeverityDowngrade,
Self::MissingSeriousness,
Self::DrugMisattribution,
Self::CaseCountDeflation,
Self::DuplicateInjection,
Self::NarrativeTruncation,
Self::TemporalShift,
Self::OutcomeMasking,
];
/// Which drift types this scenario should trigger in the ribosome.
#[must_use]
pub fn expected_drift_types(self) -> Vec<DriftType> {
match self {
Self::SeverityDowngrade
| Self::DrugMisattribution
| Self::TemporalShift
| Self::OutcomeMasking => vec![DriftType::TypeMismatch],
Self::MissingSeriousness => vec![DriftType::MissingField],
Self::CaseCountDeflation => vec![DriftType::RangeContraction],
Self::DuplicateInjection => vec![DriftType::ExtraField, DriftType::ArraySizeChange],
Self::NarrativeTruncation => vec![DriftType::LengthChange],
}
}
/// Patient safety impact level (1-5).
/// 5 = directly threatens patient life.
#[must_use]
pub const fn safety_impact(&self) -> u8 {
match self {
Self::OutcomeMasking => 5,
Self::SeverityDowngrade | Self::MissingSeriousness | Self::DrugMisattribution => 4,
Self::CaseCountDeflation | Self::TemporalShift => 3,
Self::DuplicateInjection | Self::NarrativeTruncation => 2,
}
}
/// Human-readable label.
#[must_use]
pub const fn label(&self) -> &'static str {
match self {
Self::SeverityDowngrade => "Severity Downgrade",
Self::MissingSeriousness => "Missing Seriousness",
Self::DrugMisattribution => "Drug Misattribution",
Self::CaseCountDeflation => "Case Count Deflation",
Self::DuplicateInjection => "Duplicate Injection",
Self::NarrativeTruncation => "Narrative Truncation",
Self::TemporalShift => "Temporal Shift",
Self::OutcomeMasking => "Outcome Masking",
}
}
}
impl std::fmt::Display for HarmScenario {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.label())
}
}
// ─── PV Harm Mutation ────────────────────────────────────────────────────────
/// A PV-domain mutation with full traceability.
///
/// Records exactly what was changed, why, and what the detection
/// system should flag.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PvHarmMutation {
/// Which harm scenario this mutation simulates.
pub scenario: HarmScenario,
/// Which field was targeted.
pub target_field: String,
/// Original value (before mutation).
pub original_value: serde_json::Value,
/// Mutated value (after mutation).
pub mutated_value: serde_json::Value,
/// Expected patient safety impact (1-5).
pub safety_impact: u8,
/// Expected drift types the ribosome should detect.
pub expected_drifts: Vec<DriftType>,
}
// ─── PV Harm Phenotype ───────────────────────────────────────────────────────
/// A PV-domain phenotype: mutated drug safety record with harm metadata.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PvHarmPhenotype {
/// The mutated FAERS-like record.
pub data: serde_json::Value,
/// All harm mutations applied.
pub mutations: Vec<PvHarmMutation>,
/// Aggregate safety impact (max of all mutations).
pub max_safety_impact: u8,
}
// ─── Baseline Record ─────────────────────────────────────────────────────────
/// Generate a baseline FAERS-like drug safety record.
///
/// This represents a "healthy" record with all fields present and valid.
/// Mutations are applied against this baseline.
#[must_use]
pub fn baseline_drug_record() -> serde_json::Value {
serde_json::json!({
"case_id": "CASE-2025-00001",
"report_date": "2025-06-15",
"drug_name": "warfarin",
"drug_role": "primary_suspect",
"indication": "atrial_fibrillation",
"adverse_event": "hepatotoxicity",
"adverse_event_code": "10019851",
"is_serious": true,
"seriousness_criteria": {
"death": false,
"life_threatening": true,
"hospitalization": true,
"disability": false,
"congenital_anomaly": false,
"other_medically_important": true
},
"outcome": "hospitalization",
"case_count": 47,
"reporter_type": "healthcare_professional",
"narrative": "A 67-year-old male patient on warfarin therapy for atrial fibrillation presented with elevated liver enzymes (ALT 5x ULN, AST 4x ULN) after 3 weeks of treatment. Warfarin was discontinued and liver function returned to normal within 2 weeks. Positive dechallenge supports causal relationship.",
"age": 67,
"sex": "male",
"weight_kg": 82.5
})
}
// ─── Harm Synthesis Engine ───────────────────────────────────────────────────
/// Apply a single harm scenario to a baseline record.
///
/// Returns a `PvHarmPhenotype` with the mutation applied and full
/// traceability metadata.
#[must_use]
pub fn synthesize_harm(baseline: &serde_json::Value, scenario: HarmScenario) -> PvHarmPhenotype {
let mut data = baseline.clone();
let mutation = apply_harm_mutation(&mut data, scenario);
let safety_impact = mutation.safety_impact;
PvHarmPhenotype {
data,
mutations: vec![mutation],
max_safety_impact: safety_impact,
}
}
/// Apply all harm scenarios to a baseline record, producing one phenotype each.
#[must_use]
pub fn synthesize_all_harms(baseline: &serde_json::Value) -> Vec<PvHarmPhenotype> {
HarmScenario::ALL
.iter()
.map(|s| synthesize_harm(baseline, *s))
.collect()
}
/// Apply multiple harm scenarios to a single record (compound mutation).
///
/// Produces a single record with multiple mutations — simulates
/// sophisticated data manipulation.
#[must_use]
pub fn synthesize_compound_harm(
baseline: &serde_json::Value,
scenarios: &[HarmScenario],
) -> PvHarmPhenotype {
let mut data = baseline.clone();
let mut mutations = Vec::with_capacity(scenarios.len());
let mut max_impact = 0u8;
for scenario in scenarios {
let mutation = apply_harm_mutation(&mut data, *scenario);
if mutation.safety_impact > max_impact {
max_impact = mutation.safety_impact;
}
mutations.push(mutation);
}
PvHarmPhenotype {
data,
mutations,
max_safety_impact: max_impact,
}
}
/// Core dispatch: apply a specific harm mutation to a mutable JSON value.
fn apply_harm_mutation(data: &mut serde_json::Value, scenario: HarmScenario) -> PvHarmMutation {
match scenario {
HarmScenario::SeverityDowngrade => severity_downgrade(data),
HarmScenario::MissingSeriousness => missing_seriousness(data),
HarmScenario::DrugMisattribution => drug_misattribution(data),
HarmScenario::CaseCountDeflation => case_count_deflation(data),
HarmScenario::DuplicateInjection => duplicate_injection(data),
HarmScenario::NarrativeTruncation => narrative_truncation(data),
HarmScenario::TemporalShift => temporal_shift(data),
HarmScenario::OutcomeMasking => outcome_masking(data),
}
}
// ─── Mutation Implementations ────────────────────────────────────────────────
fn severity_downgrade(data: &mut serde_json::Value) -> PvHarmMutation {
let original = data
.get("adverse_event")
.cloned()
.unwrap_or(serde_json::Value::Null);
// Replace serious AE term with a mild one
if let Some(obj) = data.as_object_mut() {
obj.insert("adverse_event".to_string(), serde_json::json!("nausea"));
obj.insert(
"adverse_event_code".to_string(),
serde_json::json!("10028813"),
);
}
PvHarmMutation {
scenario: HarmScenario::SeverityDowngrade,
target_field: "adverse_event".to_string(),
original_value: original,
mutated_value: serde_json::json!("nausea"),
safety_impact: HarmScenario::SeverityDowngrade.safety_impact(),
expected_drifts: HarmScenario::SeverityDowngrade.expected_drift_types(),
}
}
fn missing_seriousness(data: &mut serde_json::Value) -> PvHarmMutation {
let original = data
.get("is_serious")
.cloned()
.unwrap_or(serde_json::Value::Null);
// Remove seriousness-related fields
if let Some(obj) = data.as_object_mut() {
obj.remove("is_serious");
obj.remove("seriousness_criteria");
}
PvHarmMutation {
scenario: HarmScenario::MissingSeriousness,
target_field: "is_serious".to_string(),
original_value: original,
mutated_value: serde_json::Value::Null,
safety_impact: HarmScenario::MissingSeriousness.safety_impact(),
expected_drifts: HarmScenario::MissingSeriousness.expected_drift_types(),
}
}
fn drug_misattribution(data: &mut serde_json::Value) -> PvHarmMutation {
let original = data
.get("drug_name")
.cloned()
.unwrap_or(serde_json::Value::Null);
if let Some(obj) = data.as_object_mut() {
obj.insert("drug_name".to_string(), serde_json::json!("aspirin"));
}
PvHarmMutation {
scenario: HarmScenario::DrugMisattribution,
target_field: "drug_name".to_string(),
original_value: original,
mutated_value: serde_json::json!("aspirin"),
safety_impact: HarmScenario::DrugMisattribution.safety_impact(),
expected_drifts: HarmScenario::DrugMisattribution.expected_drift_types(),
}
}
fn case_count_deflation(data: &mut serde_json::Value) -> PvHarmMutation {
let original = data
.get("case_count")
.cloned()
.unwrap_or(serde_json::Value::Null);
if let Some(obj) = data.as_object_mut() {
obj.insert("case_count".to_string(), serde_json::json!(1));
}
PvHarmMutation {
scenario: HarmScenario::CaseCountDeflation,
target_field: "case_count".to_string(),
original_value: original,
mutated_value: serde_json::json!(1),
safety_impact: HarmScenario::CaseCountDeflation.safety_impact(),
expected_drifts: HarmScenario::CaseCountDeflation.expected_drift_types(),
}
}
fn duplicate_injection(data: &mut serde_json::Value) -> PvHarmMutation {
let original = data
.get("case_id")
.cloned()
.unwrap_or(serde_json::Value::Null);
// Add a duplicate_cases array to simulate injection
if let Some(obj) = data.as_object_mut() {
obj.insert(
"duplicate_cases".to_string(),
serde_json::json!([
"CASE-2025-00001-DUP1",
"CASE-2025-00001-DUP2",
"CASE-2025-00001-DUP3"
]),
);
obj.insert("_injected_flag".to_string(), serde_json::json!(true));
}
PvHarmMutation {
scenario: HarmScenario::DuplicateInjection,
target_field: "case_id".to_string(),
original_value: original,
mutated_value: serde_json::json!("CASE-2025-00001 + 3 duplicates"),
safety_impact: HarmScenario::DuplicateInjection.safety_impact(),
expected_drifts: HarmScenario::DuplicateInjection.expected_drift_types(),
}
}
fn narrative_truncation(data: &mut serde_json::Value) -> PvHarmMutation {
let original = data
.get("narrative")
.cloned()
.unwrap_or(serde_json::Value::Null);
if let Some(obj) = data.as_object_mut() {
obj.insert("narrative".to_string(), serde_json::json!("Truncated."));
}
PvHarmMutation {
scenario: HarmScenario::NarrativeTruncation,
target_field: "narrative".to_string(),
original_value: original,
mutated_value: serde_json::json!("Truncated."),
safety_impact: HarmScenario::NarrativeTruncation.safety_impact(),
expected_drifts: HarmScenario::NarrativeTruncation.expected_drift_types(),
}
}
fn temporal_shift(data: &mut serde_json::Value) -> PvHarmMutation {
let original = data
.get("report_date")
.cloned()
.unwrap_or(serde_json::Value::Null);
if let Some(obj) = data.as_object_mut() {
obj.insert("report_date".to_string(), serde_json::json!("2020-01-01"));
}
PvHarmMutation {
scenario: HarmScenario::TemporalShift,
target_field: "report_date".to_string(),
original_value: original,
mutated_value: serde_json::json!("2020-01-01"),
safety_impact: HarmScenario::TemporalShift.safety_impact(),
expected_drifts: HarmScenario::TemporalShift.expected_drift_types(),
}
}
fn outcome_masking(data: &mut serde_json::Value) -> PvHarmMutation {
let original = data
.get("outcome")
.cloned()
.unwrap_or(serde_json::Value::Null);
if let Some(obj) = data.as_object_mut() {
obj.insert("outcome".to_string(), serde_json::json!("recovered"));
}
PvHarmMutation {
scenario: HarmScenario::OutcomeMasking,
target_field: "outcome".to_string(),
original_value: original,
mutated_value: serde_json::json!("recovered"),
safety_impact: HarmScenario::OutcomeMasking.safety_impact(),
expected_drifts: HarmScenario::OutcomeMasking.expected_drift_types(),
}
}
// ─── Tests ───────────────────────────────────────────────────────────────────
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
fn baseline() -> serde_json::Value {
baseline_drug_record()
}
// ── Scenario coverage ─────────────────────────────────────────────────
#[test]
fn test_all_scenarios_count() {
assert_eq!(HarmScenario::ALL.len(), 8);
}
#[test]
fn test_all_scenarios_have_expected_drifts() {
for scenario in HarmScenario::ALL {
let drifts = scenario.expected_drift_types();
assert!(!drifts.is_empty(), "{scenario} has no expected drift types");
}
}
#[test]
fn test_all_scenarios_have_safety_impact() {
for scenario in HarmScenario::ALL {
let impact = scenario.safety_impact();
assert!(
(1..=5).contains(&impact),
"{scenario} has invalid safety impact: {impact}"
);
}
}
// ── Baseline record ───────────────────────────────────────────────────
#[test]
fn test_baseline_has_required_fields() {
let b = baseline();
assert!(b.get("case_id").is_some());
assert!(b.get("drug_name").is_some());
assert!(b.get("adverse_event").is_some());
assert!(b.get("is_serious").is_some());
assert!(b.get("outcome").is_some());
assert!(b.get("case_count").is_some());
assert!(b.get("narrative").is_some());
assert!(b.get("report_date").is_some());
}
#[test]
fn test_baseline_is_object() {
assert!(baseline().is_object());
}
// ── Individual mutations ──────────────────────────────────────────────
#[test]
fn test_severity_downgrade() {
let phenotype = synthesize_harm(&baseline(), HarmScenario::SeverityDowngrade);
assert_eq!(phenotype.data["adverse_event"], "nausea");
assert_eq!(phenotype.mutations[0].target_field, "adverse_event");
assert_eq!(phenotype.max_safety_impact, 4);
}
#[test]
fn test_missing_seriousness() {
let phenotype = synthesize_harm(&baseline(), HarmScenario::MissingSeriousness);
assert!(phenotype.data.get("is_serious").is_none());
assert!(phenotype.data.get("seriousness_criteria").is_none());
}
#[test]
fn test_drug_misattribution() {
let phenotype = synthesize_harm(&baseline(), HarmScenario::DrugMisattribution);
assert_eq!(phenotype.data["drug_name"], "aspirin");
assert_ne!(
phenotype.mutations[0].original_value,
phenotype.mutations[0].mutated_value
);
}
#[test]
fn test_case_count_deflation() {
let phenotype = synthesize_harm(&baseline(), HarmScenario::CaseCountDeflation);
assert_eq!(phenotype.data["case_count"], 1);
}
#[test]
fn test_duplicate_injection() {
let phenotype = synthesize_harm(&baseline(), HarmScenario::DuplicateInjection);
assert!(phenotype.data.get("duplicate_cases").is_some());
assert!(phenotype.data.get("_injected_flag").is_some());
}
#[test]
fn test_narrative_truncation() {
let phenotype = synthesize_harm(&baseline(), HarmScenario::NarrativeTruncation);
let narrative = phenotype.data["narrative"].as_str().unwrap_or("");
assert!(
narrative.len() < 20,
"Narrative should be truncated, got len={}",
narrative.len()
);
}
#[test]
fn test_temporal_shift() {
let phenotype = synthesize_harm(&baseline(), HarmScenario::TemporalShift);
assert_eq!(phenotype.data["report_date"], "2020-01-01");
}
#[test]
fn test_outcome_masking() {
let phenotype = synthesize_harm(&baseline(), HarmScenario::OutcomeMasking);
assert_eq!(phenotype.data["outcome"], "recovered");
assert_eq!(phenotype.max_safety_impact, 5);
}
// ── Batch operations ──────────────────────────────────────────────────
#[test]
fn test_synthesize_all_harms() {
let phenotypes = synthesize_all_harms(&baseline());
assert_eq!(phenotypes.len(), 8);
}
#[test]
fn test_compound_harm() {
let phenotype = synthesize_compound_harm(
&baseline(),
&[
HarmScenario::SeverityDowngrade,
HarmScenario::OutcomeMasking,
],
);
assert_eq!(phenotype.mutations.len(), 2);
assert_eq!(phenotype.max_safety_impact, 5); // OutcomeMasking is 5
assert_eq!(phenotype.data["adverse_event"], "nausea");
assert_eq!(phenotype.data["outcome"], "recovered");
}
#[test]
fn test_compound_harm_all_scenarios() {
let phenotype = synthesize_compound_harm(&baseline(), HarmScenario::ALL);
assert_eq!(phenotype.mutations.len(), 8);
assert_eq!(phenotype.max_safety_impact, 5);
}
// ── Traceability ──────────────────────────────────────────────────────
#[test]
fn test_mutation_records_original_value() {
let phenotype = synthesize_harm(&baseline(), HarmScenario::DrugMisattribution);
assert_eq!(phenotype.mutations[0].original_value, "warfarin");
}
#[test]
fn test_mutation_records_mutated_value() {
let phenotype = synthesize_harm(&baseline(), HarmScenario::DrugMisattribution);
assert_eq!(phenotype.mutations[0].mutated_value, "aspirin");
}
#[test]
fn test_mutation_records_scenario() {
let phenotype = synthesize_harm(&baseline(), HarmScenario::TemporalShift);
assert_eq!(phenotype.mutations[0].scenario, HarmScenario::TemporalShift);
}
// ── Display ───────────────────────────────────────────────────────────
#[test]
fn test_harm_scenario_display() {
assert_eq!(HarmScenario::OutcomeMasking.to_string(), "Outcome Masking");
assert_eq!(
HarmScenario::SeverityDowngrade.to_string(),
"Severity Downgrade"
);
}
// ── Safety impact ordering ────────────────────────────────────────────
#[test]
fn test_outcome_masking_is_highest_impact() {
let max_impact = HarmScenario::ALL
.iter()
.map(|s| s.safety_impact())
.max()
.unwrap_or(0);
assert_eq!(max_impact, 5);
assert_eq!(HarmScenario::OutcomeMasking.safety_impact(), max_impact);
}
#[test]
fn test_narrative_truncation_is_lower_impact() {
assert!(
HarmScenario::NarrativeTruncation.safety_impact()
< HarmScenario::OutcomeMasking.safety_impact()
);
}
}
//! # GroundsTo implementations for nexcore-phenotype types
//!
//! Connects adversarial test fixture generator types to the Lex Primitiva type system.
//!
//! ## Biological Analogy
//!
//! In biology, a phenotype is the observable expression of a genotype.
//! This crate mutates schemas (genotype) to produce observable drift (phenotype).
//!
//! ## Key Primitive Mapping
//!
//! - Mutation dispatch: partial (Boundary) -- conditional mutation selection
//! - Value generation: mu (Mapping) -- schema -> mutated value
//! - Type swap: kappa (Comparison) -- expected vs actual drift comparison
use nexcore_lex_primitiva::grounding::GroundsTo;
use nexcore_lex_primitiva::primitiva::{LexPrimitiva, PrimitiveComposition};
use crate::{Mutation, Phenotype};
// ---------------------------------------------------------------------------
// Mutation types -- Sigma (Sum) dominant
// ---------------------------------------------------------------------------
/// Mutation: T2-P (Sigma + partial), dominant Sigma
///
/// Seven-variant enum classifying mutation strategies.
/// Sum-dominant: the type IS a categorical alternation of mutation types.
/// Boundary is secondary (each mutation tests a different boundary).
impl GroundsTo for Mutation {
fn primitive_composition() -> PrimitiveComposition {
PrimitiveComposition::new(vec![
LexPrimitiva::Sum, // Sigma -- mutation type alternation
LexPrimitiva::Boundary, // partial -- boundary violation type
])
.with_dominant(LexPrimitiva::Sum, 0.85)
}
}
// ---------------------------------------------------------------------------
// Result types -- mu (Mapping) dominant
// ---------------------------------------------------------------------------
/// Phenotype: T2-C (mu + sigma + kappa + partial), dominant mu
///
/// A mutated JSON value with metadata about what was changed.
/// Mapping-dominant: it maps a schema + mutation to a mutated value.
/// Sequence is secondary (mutations_applied is ordered).
/// Comparison is tertiary (expected_drifts for verification).
/// Boundary is quaternary (each mutation violates a boundary).
impl GroundsTo for Phenotype {
fn primitive_composition() -> PrimitiveComposition {
PrimitiveComposition::new(vec![
LexPrimitiva::Mapping, // mu -- schema + mutation -> value
LexPrimitiva::Sequence, // sigma -- ordered mutations
LexPrimitiva::Comparison, // kappa -- drift verification
LexPrimitiva::Boundary, // partial -- boundary violations
])
.with_dominant(LexPrimitiva::Mapping, 0.80)
}
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use nexcore_lex_primitiva::tier::Tier;
#[test]
fn mutation_is_t2p() {
assert_eq!(Mutation::tier(), Tier::T2Primitive);
assert_eq!(Mutation::dominant_primitive(), Some(LexPrimitiva::Sum));
}
#[test]
fn phenotype_is_t2c() {
assert_eq!(Phenotype::tier(), Tier::T2Composite);
assert_eq!(Phenotype::dominant_primitive(), Some(LexPrimitiva::Mapping));
}
#[test]
fn phenotype_contains_boundary() {
let comp = Phenotype::primitive_composition();
assert!(comp.primitives.contains(&LexPrimitiva::Boundary));
}
#[test]
fn all_confidences_valid() {
let compositions = [
Mutation::primitive_composition(),
Phenotype::primitive_composition(),
];
for comp in &compositions {
assert!(comp.confidence >= 0.80);
assert!(comp.confidence <= 1.0);
}
}
}
//! # Trait Bridge
//!
//! Multi-system aggregation: Muscular + Skeletal + Nervous → Phenotype.
//!
//! Converts health metrics from three internal systems into observable
//! phenotypic traits — the outward expression of underlying system health.
//!
//! ```text
//! Muscular::MuscularHealth ─┐
//! Skeletal::SkeletalHealth ─┤──► PhenotypicProfile (observable fitness)
//! Nervous::NervousHealth ─┘
//! ```
//!
//! **Biological mapping**: A phenotype is the observable expression of
//! underlying genotype + environment. In the same way, this bridge
//! aggregates internal system health metrics into an observable profile
//! that represents how the organism *appears* from outside. A fatigued
//! muscular system, a weak skeleton, or a slow nervous system all
//! manifest as degraded phenotypic traits — visible to external
//! monitoring, adversarial probes, and drift detection.
use nexcore_muscular::MuscularHealth;
use nexcore_nervous::NervousHealth;
use nexcore_skeletal::SkeletalHealth;
/// Aggregated phenotypic profile derived from multiple system health metrics.
///
/// **Biological mapping**: The phenotype — what you can observe from outside.
/// Internal health scores from muscular (performance), skeletal (structure),
/// and nervous (responsiveness) systems combine into an overall fitness
/// profile with per-system trait scores.
#[derive(Debug, Clone, PartialEq)]
pub struct PhenotypicProfile {
/// Overall fitness score (0.0–1.0). Average of system trait scores.
pub fitness: f64,
/// Muscular trait: performance capacity (0.0–1.0).
pub performance: f64,
/// Skeletal trait: structural integrity (0.0–1.0).
pub integrity: f64,
/// Nervous trait: responsiveness / signal speed (0.0–1.0).
pub responsiveness: f64,
/// Number of systems contributing to this profile.
pub systems_assessed: usize,
/// Whether the phenotype is considered healthy (fitness >= 0.6).
pub healthy: bool,
}
/// Convert muscular health into a performance trait score (0.0–1.0).
///
/// **Biological mapping**: Muscular performance phenotype — grip strength,
/// endurance, coordination. Reflects whether the muscular system can
/// sustain work without excessive fatigue or imbalance.
pub fn muscular_to_trait(health: &MuscularHealth) -> f64 {
let mut score = 0.0;
if health.size_principle_compliant {
score += 0.25;
}
if health.antagonistic_pairs_defined {
score += 0.25;
}
if health.recruitment_balanced {
score += 0.20;
}
if health.cardiac_running {
score += 0.15;
}
// Fatigue reduces performance: 0.0 fatigue = +0.15, 1.0 fatigue = +0.0
score += 0.15 * (1.0 - health.fatigue_level.clamp(0.0, 1.0));
score
}
/// Convert skeletal health into a structural integrity trait score (0.0–1.0).
///
/// **Biological mapping**: Skeletal integrity phenotype — posture, bone
/// density, joint stability. Reflects whether the structural framework
/// supports the organism properly. Missing CLAUDE.md (skull) or inactive
/// Wolff's Law feedback weakens the phenotypic expression.
pub fn skeletal_to_trait(health: &SkeletalHealth) -> f64 {
let mut score = 0.0;
if health.claude_md_present {
score += 0.30;
}
if health.corrections_feeding_claude_md {
score += 0.25;
}
if health.settings_versioned {
score += 0.20;
}
if health.wolff_law_active {
score += 0.25;
}
score
}
/// Convert nervous health into a responsiveness trait score (0.0–1.0).
///
/// **Biological mapping**: Nervous responsiveness phenotype — reaction
/// time, reflex speed, sensory acuity. High myelination ratio and low
/// signal latency indicate a responsive nervous system that manifests
/// as quick, coordinated phenotypic behavior.
pub fn nervous_to_trait(health: &NervousHealth) -> f64 {
let mut score = 0.0;
// Myelination ratio contributes to signal speed
// Ratio of 1.0 = fully myelinated = fast, 0.0 = unmyelinated = slow
score += 0.30 * health.myelination_ratio.clamp(0.0, 1.0);
// Low latency is good. Assume <50ms is excellent, >500ms is poor.
let latency_factor = if health.avg_signal_latency_ms <= 0.0 {
1.0
} else {
(1.0 - (health.avg_signal_latency_ms / 500.0)).clamp(0.0, 1.0)
};
score += 0.25 * latency_factor;
// Sensory integration
if health.sensory_integration_ok {
score += 0.20;
}
// Active neurons and reflex arcs (capacity)
// More is better, but normalize: assume 10+ neurons = full score
let neuron_factor = (health.neuron_count as f64 / 10.0).min(1.0);
score += 0.15 * neuron_factor;
let reflex_factor = (health.reflex_arcs_active as f64 / 5.0).min(1.0);
score += 0.10 * reflex_factor;
score
}
/// Aggregate health metrics from all three systems into a phenotypic profile.
///
/// **Biological mapping**: Phenotypic expression — the integrated,
/// observable output of all underlying biological systems. Just as a
/// doctor assesses a patient's phenotype by observing strength (muscular),
/// posture (skeletal), and reflexes (nervous), this function combines
/// three health assessments into one observable profile.
pub fn aggregate_phenotype(
muscular: &MuscularHealth,
skeletal: &SkeletalHealth,
nervous: &NervousHealth,
) -> PhenotypicProfile {
let performance = muscular_to_trait(muscular);
let integrity = skeletal_to_trait(skeletal);
let responsiveness = nervous_to_trait(nervous);
let fitness = (performance + integrity + responsiveness) / 3.0;
PhenotypicProfile {
fitness,
performance,
integrity,
responsiveness,
systems_assessed: 3,
healthy: fitness >= 0.6,
}
}
/// Compute the throughput metric for phenotypic assessment.
///
/// Returns the number of healthy traits (score >= 0.5) out of the three
/// system assessments.
///
/// **Biological mapping**: Phenotypic vigor — how many observable traits
/// reach a healthy threshold. An organism with all three systems healthy
/// has high phenotypic throughput; one with degraded systems shows
/// reduced phenotypic expression.
pub fn phenotype_throughput(
muscular: &MuscularHealth,
skeletal: &SkeletalHealth,
nervous: &NervousHealth,
) -> usize {
let mut count = 0usize;
if muscular_to_trait(muscular) >= 0.5 {
count = count.saturating_add(1);
}
if skeletal_to_trait(skeletal) >= 0.5 {
count = count.saturating_add(1);
}
if nervous_to_trait(nervous) >= 0.5 {
count = count.saturating_add(1);
}
count
}
/// Identify which mutation types are most likely based on system health.
///
/// **Biological mapping**: Phenotype–genotype correlation — certain
/// phenotypic weaknesses predispose the organism to specific mutation
/// types. A structurally weak skeleton (missing CLAUDE.md) predisposes
/// to `StructureSwap` mutations. A fatigued muscular system predisposes
/// to `RangeExpand` (overextension) mutations.
pub fn health_to_mutation_risk(
muscular: &MuscularHealth,
skeletal: &SkeletalHealth,
nervous: &NervousHealth,
) -> Vec<crate::Mutation> {
let mut risks = Vec::new();
// Low muscular performance → risk of range expansion (overextension)
if muscular_to_trait(muscular) < 0.5 {
risks.push(crate::Mutation::RangeExpand);
}
// Weak skeletal integrity → risk of structural swap