antifragile 0.0.1

Antifragile is a Rust library implementing concepts from Nassim Nicholas Taleb's antifragility theory. The library provides a trait-based system for analyzing how systems respond to stress and volatility, classifying them into three categories: Fragile (harmed by volatility), Robust (unaffected), and Antifragile (benefits from volatility)
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
//! # Core types and traits for antifragility analysis
//!
//! This module provides the foundational types for analyzing system responses to stress.
//!
//! ## Example: Analyzing a Portfolio
//!
//! ```rust
//! use antifragile::{Antifragile, TriadAnalysis, Triad};
//!
//! struct OptionsPortfolio {
//!     // Long volatility position
//!     vega_exposure: f64,
//! }
//!
//! impl Antifragile for OptionsPortfolio {
//!     type Stressor = f64;  // Market volatility
//!     type Payoff = f64;    // Portfolio P&L
//!
//!     fn payoff(&self, volatility: f64) -> f64 {
//!         // Options gain from volatility (convex payoff)
//!         self.vega_exposure * volatility * volatility
//!     }
//! }
//!
//! let portfolio = OptionsPortfolio { vega_exposure: 1.0 };
//! assert!(portfolio.is_antifragile(0.2, 0.05));
//! ```

use core::cmp::Ordering;
use core::fmt::Display;
use core::ops::{Add, Sub};
use core::str::FromStr;

#[cfg(feature = "std")]
use std::error::Error;

#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Trait for systems that can be analyzed for fragility
///
/// Implement this trait to measure how your system responds to stress.
pub trait Antifragile {
    /// The type of stressor (e.g., volatility, load, perturbation)
    type Stressor: Copy + Add<Output = Self::Stressor> + Sub<Output = Self::Stressor>;

    /// The type of payoff/outcome (must be comparable and additive)
    type Payoff: Copy + Add<Output = Self::Payoff> + PartialOrd;

    /// The payoff function: what outcome does the system produce under given stress?
    ///
    /// The "payoff" is what you get back when the system experiences
    /// a certain level of stress/volatility.
    fn payoff(&self, stressor: Self::Stressor) -> Self::Payoff;

    /// Returns the payoff added to itself (r + r)
    ///
    /// Used for convexity test: f(x+Δ) + f(x-Δ) vs twin(f(x))
    ///
    /// Named "twin" because it produces the same value twice, added together.
    ///
    /// The default implementation returns `r + r`. Override if your `Payoff` type
    /// has a more efficient doubling operation.
    fn twin(r: Self::Payoff) -> Self::Payoff {
        r + r
    }
}

/// Triad: the three categories of response to volatility
///
/// Variants are ordered by desirability: Fragile < Robust < Antifragile.
/// This ordering is consistent with `Ord`, `rank()`, and numeric conversions.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[repr(u8)]
#[must_use]
pub enum Triad {
    /// Harmed by volatility (concave response) - least desirable
    Fragile,
    /// Unaffected by volatility (linear response) - neutral
    Robust,
    /// Benefits from volatility (convex response) - most desirable
    Antifragile,
}

impl Triad {
    /// All variants in desirability order: `[Fragile, Robust, Antifragile]`
    pub const ALL: [Self; 3] = [Self::Fragile, Self::Robust, Self::Antifragile];

    /// Returns an iterator over all variants in desirability order
    #[inline]
    pub fn iter() -> impl Iterator<Item = Self> {
        Self::ALL.into_iter()
    }

    /// Returns the desirability rank: Fragile=0, Robust=1, Antifragile=2
    ///
    /// Higher rank means more desirable. This is consistent with `Ord` ordering.
    #[inline]
    #[must_use]
    pub const fn rank(self) -> u8 {
        self as u8
    }

    /// Returns true if this is the best classification (Antifragile)
    #[inline]
    #[must_use]
    pub const fn is_antifragile(self) -> bool {
        matches!(self, Triad::Antifragile)
    }

    /// Returns true if this is the worst classification (Fragile)
    #[inline]
    #[must_use]
    pub const fn is_fragile(self) -> bool {
        matches!(self, Triad::Fragile)
    }

    /// Returns true if this is neutral (Robust)
    #[inline]
    #[must_use]
    pub const fn is_robust(self) -> bool {
        matches!(self, Triad::Robust)
    }

    /// Returns the opposite classification
    ///
    /// - `Antifragile` ↔ `Fragile`
    /// - `Robust` → `Robust` (self-opposite, as it's neutral)
    #[inline]
    pub const fn opposite(self) -> Self {
        match self {
            Self::Antifragile => Self::Fragile,
            Self::Fragile => Self::Antifragile,
            Self::Robust => Self::Robust,
        }
    }
}

impl PartialOrd for Triad {
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Triad {
    /// Orders by desirability: Fragile < Robust < Antifragile
    #[inline]
    fn cmp(&self, other: &Self) -> Ordering {
        self.rank().cmp(&other.rank())
    }
}

impl Default for Triad {
    /// Returns `Triad::Robust` as the neutral default
    #[inline]
    fn default() -> Self {
        Self::Robust
    }
}

impl From<Triad> for u8 {
    #[inline]
    fn from(triad: Triad) -> Self {
        triad.rank()
    }
}

impl From<Triad> for &'static str {
    #[inline]
    fn from(triad: Triad) -> Self {
        match triad {
            Triad::Antifragile => "antifragile",
            Triad::Fragile => "fragile",
            Triad::Robust => "robust",
        }
    }
}

impl Display for Triad {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        match self {
            Self::Antifragile => write!(f, "Antifragile (benefits from volatility)"),
            Self::Fragile => write!(f, "Fragile (harmed by volatility)"),
            Self::Robust => write!(f, "Robust (unaffected by volatility)"),
        }
    }
}

/// Error returned when converting an invalid value to [`Triad`]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct InvalidTriadValue(pub u8);

impl Display for InvalidTriadValue {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "invalid triad value: {} (expected 0, 1, or 2)", self.0)
    }
}

#[cfg(feature = "std")]
impl Error for InvalidTriadValue {}

impl TryFrom<u8> for Triad {
    type Error = InvalidTriadValue;

    #[inline]
    fn try_from(value: u8) -> Result<Self, Self::Error> {
        match value {
            0 => Ok(Self::Fragile),
            1 => Ok(Self::Robust),
            2 => Ok(Self::Antifragile),
            n => Err(InvalidTriadValue(n)),
        }
    }
}

/// Error returned when parsing a string into [`Triad`] fails
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseTriadError;

impl Display for ParseTriadError {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(
            f,
            "invalid triad string (expected \"antifragile\", \"fragile\", or \"robust\")"
        )
    }
}

#[cfg(feature = "std")]
impl Error for ParseTriadError {}

impl FromStr for Triad {
    type Err = ParseTriadError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.eq_ignore_ascii_case("antifragile") {
            Ok(Self::Antifragile)
        } else if s.eq_ignore_ascii_case("fragile") {
            Ok(Self::Fragile)
        } else if s.eq_ignore_ascii_case("robust") {
            Ok(Self::Robust)
        } else {
            Err(ParseTriadError)
        }
    }
}

/// Extension trait providing Triad classification methods
pub trait TriadAnalysis: Antifragile {
    /// Classify the system on Taleb's Triad at a specific operating point
    ///
    /// Uses Taleb's convexity test: f(x+Δ) + f(x-Δ) vs 2·f(x)
    /// - If sum > twin → Antifragile (convex payoff)
    /// - If sum < twin → Fragile (concave payoff)
    /// - If sum = twin → Robust (linear payoff)
    ///
    /// # Arguments
    /// * `at` - The operating point (stress level) to test
    /// * `delta` - The perturbation size for the convexity test
    ///
    /// # Note
    /// This uses exact comparison. For floating-point payoffs where exact
    /// equality is unlikely, use [`classify_with_tolerance`](Self::classify_with_tolerance).
    #[inline]
    fn classify(&self, at: Self::Stressor, delta: Self::Stressor) -> Triad
    where
        Self::Payoff: Sub<Output = Self::Payoff> + Default + PartialOrd,
    {
        let f_x = self.payoff(at);
        let f_x_plus = self.payoff(at + delta);
        let f_x_minus = self.payoff(at - delta);

        let sum = f_x_plus + f_x_minus;
        let twin_f_x = Self::twin(f_x);

        if sum > twin_f_x {
            Triad::Antifragile
        } else if sum < twin_f_x {
            Triad::Fragile
        } else {
            Triad::Robust
        }
    }

    /// Classify with numerical tolerance for floating-point payoffs
    ///
    /// Like [`classify`](Self::classify), but treats values within `epsilon` of
    /// each other as equal. This is useful for `f32`/`f64` payoffs where exact
    /// equality is rare due to floating-point precision.
    ///
    /// # Arguments
    /// * `at` - The operating point (stress level) to test
    /// * `delta` - The perturbation size for the convexity test
    /// * `epsilon` - Tolerance for considering values equal
    ///
    /// # Example
    ///
    /// ```
    /// use antifragile::{Antifragile, Triad, TriadAnalysis};
    ///
    /// struct NearlyLinear;
    /// impl Antifragile for NearlyLinear {
    ///     type Stressor = f64;
    ///     type Payoff = f64;
    ///     fn payoff(&self, x: Self::Stressor) -> Self::Payoff {
    ///         2.0 * x + 1e-10 * x * x  // Almost linear with tiny convexity
    ///     }
    /// }
    ///
    /// let system = NearlyLinear;
    /// // Exact classification sees the tiny convexity
    /// assert_eq!(system.classify(10.0, 1.0), Triad::Antifragile);
    /// // With tolerance, it's effectively Robust
    /// assert_eq!(system.classify_with_tolerance(10.0, 1.0, 1e-6), Triad::Robust);
    /// ```
    #[inline]
    fn classify_with_tolerance(
        &self,
        at: Self::Stressor,
        delta: Self::Stressor,
        epsilon: Self::Payoff,
    ) -> Triad
    where
        Self::Payoff: Sub<Output = Self::Payoff> + Default + PartialOrd,
    {
        let f_x = self.payoff(at);
        let f_x_plus = self.payoff(at + delta);
        let f_x_minus = self.payoff(at - delta);

        let sum = f_x_plus + f_x_minus;
        let twin_f_x = Self::twin(f_x);

        // Compute absolute difference: |sum - twin_f_x|
        let diff = if sum >= twin_f_x {
            sum - twin_f_x
        } else {
            twin_f_x - sum
        };

        if diff <= epsilon {
            Triad::Robust
        } else if sum > twin_f_x {
            Triad::Antifragile
        } else {
            Triad::Fragile
        }
    }

    /// Check if system is antifragile at a given point (convexity test)
    #[inline]
    #[must_use]
    fn is_antifragile(&self, at: Self::Stressor, delta: Self::Stressor) -> bool
    where
        Self::Payoff: Sub<Output = Self::Payoff> + Default + PartialOrd,
    {
        self.classify(at, delta) == Triad::Antifragile
    }

    /// Does the system gain from increased stress?
    ///
    /// A practical test: does higher stress lead to better payoff?
    /// Returns true if payoff(high) > payoff(low).
    ///
    /// This is useful for learning systems where payoff improves
    /// with exposure, even if mathematically concave.
    #[inline]
    #[must_use]
    fn gains_from_stress(&self, low: Self::Stressor, high: Self::Stressor) -> bool {
        self.payoff(high) > self.payoff(low)
    }

    /// Is the payoff stable across stress levels?
    ///
    /// Returns true if the absolute difference between `payoff(high)` and
    /// `payoff(low)` is less than or equal to `threshold`.
    ///
    /// This indicates robust behavior where the system's output doesn't
    /// vary significantly with changes in stress.
    ///
    /// # Example
    ///
    /// A system with constant payoff is perfectly stable:
    /// ```
    /// use antifragile::{Antifragile, TriadAnalysis};
    ///
    /// struct ConstantSystem;
    /// impl Antifragile for ConstantSystem {
    ///     type Stressor = f64;
    ///     type Payoff = f64;
    ///     fn payoff(&self, _: Self::Stressor) -> Self::Payoff { 10.0 }
    /// }
    ///
    /// let system = ConstantSystem;
    /// assert!(system.is_stable(1.0, 100.0, 0.001));
    /// ```
    #[inline]
    #[must_use]
    fn is_stable(&self, low: Self::Stressor, high: Self::Stressor, threshold: Self::Payoff) -> bool
    where
        Self::Payoff: Sub<Output = Self::Payoff>,
    {
        let payoff_low = self.payoff(low);
        let payoff_high = self.payoff(high);

        // Check |payoff_high - payoff_low| <= threshold
        if payoff_high >= payoff_low {
            payoff_high - payoff_low <= threshold
        } else {
            payoff_low - payoff_high <= threshold
        }
    }
}

// Blanket implementation for all Antifragile types
impl<T: Antifragile> TriadAnalysis for T {}

/// A wrapper that marks a system as verified on the Triad
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Verified<T> {
    inner: T,
    classification: Triad,
}

impl<T: Antifragile> Verified<T>
where
    T::Payoff: Sub<Output = T::Payoff> + Default + PartialOrd,
{
    /// Verify a system's Triad classification at a given operating point
    #[must_use]
    pub fn check(system: T, at: T::Stressor, delta: T::Stressor) -> Self {
        let classification = system.classify(at, delta);
        Self {
            inner: system,
            classification,
        }
    }

    /// Get the verified Triad classification
    #[inline]
    pub const fn classification(&self) -> Triad {
        self.classification
    }

    /// Get reference to inner system
    #[inline]
    #[must_use]
    pub const fn inner(&self) -> &T {
        &self.inner
    }

    /// Unwrap the verified system
    #[inline]
    #[must_use]
    pub fn into_inner(self) -> T {
        self.inner
    }

    /// Returns true if the system was classified as Antifragile
    #[inline]
    #[must_use]
    pub const fn is_antifragile(&self) -> bool {
        self.classification.is_antifragile()
    }

    /// Returns true if the system was classified as Fragile
    #[inline]
    #[must_use]
    pub const fn is_fragile(&self) -> bool {
        self.classification.is_fragile()
    }

    /// Returns true if the system was classified as Robust
    #[inline]
    #[must_use]
    pub const fn is_robust(&self) -> bool {
        self.classification.is_robust()
    }

    /// Re-verify classification at a new operating point
    ///
    /// Updates the stored classification by re-running the convexity test
    /// at the specified operating point and delta.
    #[inline]
    pub fn re_verify(&mut self, at: T::Stressor, delta: T::Stressor) {
        self.classification = self.inner.classify(at, delta);
    }

    /// Check if the classification still holds at a different operating point
    ///
    /// Returns `true` if classifying at the new point yields the same result
    /// as the stored classification.
    #[inline]
    #[must_use]
    pub fn still_holds(&self, at: T::Stressor, delta: T::Stressor) -> bool {
        self.inner.classify(at, delta) == self.classification
    }
}

impl<T> AsRef<T> for Verified<T> {
    #[inline]
    fn as_ref(&self) -> &T {
        &self.inner
    }
}

impl<T> core::ops::Deref for Verified<T> {
    type Target = T;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<T: Antifragile + Default> Default for Verified<T>
where
    T::Stressor: Default,
    T::Payoff: Sub<Output = T::Payoff> + Default + PartialOrd,
{
    /// Creates a verified system using `T::default()` classified at the default stressor
    fn default() -> Self {
        let system = T::default();
        let at = T::Stressor::default();
        Self::check(system, at, at)
    }
}

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

    // Test helpers - mathematical functions for verifying the convexity test
    struct ConvexFn; // f(x) = x²
    struct ConcaveFn; // f(x) = √x
    struct LinearFn {
        slope: f64,
        intercept: f64,
    }

    impl Antifragile for ConvexFn {
        type Stressor = f64;
        type Payoff = f64;
        fn payoff(&self, x: Self::Stressor) -> Self::Payoff {
            x * x
        }
    }

    impl Antifragile for ConcaveFn {
        type Stressor = f64;
        type Payoff = f64;
        fn payoff(&self, x: Self::Stressor) -> Self::Payoff {
            x.abs().sqrt()
        }
    }

    impl Antifragile for LinearFn {
        type Stressor = f64;
        type Payoff = f64;
        fn payoff(&self, x: Self::Stressor) -> Self::Payoff {
            self.slope * x + self.intercept
        }
    }

    #[test]
    fn test_convex_is_antifragile() {
        let system = ConvexFn;
        assert!(system.is_antifragile(10.0, 1.0));
        assert_eq!(system.classify(10.0, 1.0), Triad::Antifragile);
    }

    #[test]
    fn test_concave_is_fragile() {
        let system = ConcaveFn;
        assert_eq!(system.classify(10.0, 1.0), Triad::Fragile);
    }

    #[test]
    fn test_linear_is_robust() {
        let system = LinearFn {
            slope: 2.0,
            intercept: 5.0,
        };
        assert_eq!(system.classify(10.0, 1.0), Triad::Robust);
    }

    #[test]
    fn test_gains_from_stress() {
        let convex = ConvexFn;
        assert!(convex.gains_from_stress(1.0, 2.0)); // 1 < 4

        let concave = ConcaveFn;
        assert!(concave.gains_from_stress(1.0, 4.0)); // 1 < 2
    }

    #[test]
    fn test_verified_wrapper() {
        let system = ConvexFn;
        let verified = Verified::check(system, 10.0, 1.0);
        assert_eq!(verified.classification(), Triad::Antifragile);
    }

    #[test]
    fn test_triad_display() {
        assert_eq!(
            format!("{}", Triad::Antifragile),
            "Antifragile (benefits from volatility)"
        );
        assert_eq!(
            format!("{}", Triad::Fragile),
            "Fragile (harmed by volatility)"
        );
        assert_eq!(
            format!("{}", Triad::Robust),
            "Robust (unaffected by volatility)"
        );
    }

    #[test]
    fn test_triad_ordering() {
        // Ordering by desirability: Fragile < Robust < Antifragile
        assert!(Triad::Fragile < Triad::Robust);
        assert!(Triad::Robust < Triad::Antifragile);
        assert!(Triad::Fragile < Triad::Antifragile);

        // Test rank values (matches desirability order)
        assert_eq!(Triad::Fragile.rank(), 0);
        assert_eq!(Triad::Robust.rank(), 1);
        assert_eq!(Triad::Antifragile.rank(), 2);

        // Test sorting (sorts by desirability, worst to best)
        let mut triads = vec![Triad::Antifragile, Triad::Fragile, Triad::Robust];
        triads.sort();
        assert_eq!(
            triads,
            vec![Triad::Fragile, Triad::Robust, Triad::Antifragile]
        );
    }

    #[test]
    fn test_triad_predicates() {
        assert!(Triad::Antifragile.is_antifragile());
        assert!(!Triad::Antifragile.is_fragile());
        assert!(!Triad::Antifragile.is_robust());

        assert!(Triad::Fragile.is_fragile());
        assert!(!Triad::Fragile.is_antifragile());
        assert!(!Triad::Fragile.is_robust());

        assert!(Triad::Robust.is_robust());
        assert!(!Triad::Robust.is_antifragile());
        assert!(!Triad::Robust.is_fragile());
    }

    #[test]
    fn test_verified_predicates() {
        let system = ConvexFn;
        let verified = Verified::check(system, 10.0, 1.0);
        assert!(verified.is_antifragile());
        assert!(!verified.is_fragile());
        assert!(!verified.is_robust());
    }

    #[test]
    fn test_triad_default() {
        assert_eq!(Triad::default(), Triad::Robust);
    }

    #[test]
    fn test_triad_from_u8() {
        assert_eq!(Triad::try_from(0_u8), Ok(Triad::Fragile));
        assert_eq!(Triad::try_from(1_u8), Ok(Triad::Robust));
        assert_eq!(Triad::try_from(2_u8), Ok(Triad::Antifragile));
        assert_eq!(Triad::try_from(3_u8), Err(InvalidTriadValue(3)));
        assert_eq!(Triad::try_from(255_u8), Err(InvalidTriadValue(255)));
    }

    #[test]
    fn test_triad_into_u8() {
        assert_eq!(u8::from(Triad::Fragile), 0);
        assert_eq!(u8::from(Triad::Robust), 1);
        assert_eq!(u8::from(Triad::Antifragile), 2);
    }

    #[test]
    fn test_triad_into_str() {
        assert_eq!(<&str>::from(Triad::Antifragile), "antifragile");
        assert_eq!(<&str>::from(Triad::Fragile), "fragile");
        assert_eq!(<&str>::from(Triad::Robust), "robust");
    }

    #[test]
    fn test_verified_deref() {
        let system = ConvexFn;
        let verified = Verified::check(system, 10.0, 1.0);
        // Can call payoff through Deref
        assert!((verified.payoff(5.0) - 25.0).abs() < f64::EPSILON);
    }

    #[test]
    fn test_invalid_triad_value_display() {
        let err = InvalidTriadValue(42);
        assert_eq!(
            format!("{err}"),
            "invalid triad value: 42 (expected 0, 1, or 2)"
        );
    }

    #[test]
    fn test_triad_from_str() {
        // Case insensitive parsing
        assert_eq!("antifragile".parse::<Triad>(), Ok(Triad::Antifragile));
        assert_eq!("Antifragile".parse::<Triad>(), Ok(Triad::Antifragile));
        assert_eq!("ANTIFRAGILE".parse::<Triad>(), Ok(Triad::Antifragile));

        assert_eq!("fragile".parse::<Triad>(), Ok(Triad::Fragile));
        assert_eq!("Fragile".parse::<Triad>(), Ok(Triad::Fragile));

        assert_eq!("robust".parse::<Triad>(), Ok(Triad::Robust));
        assert_eq!("ROBUST".parse::<Triad>(), Ok(Triad::Robust));

        // Invalid strings
        assert_eq!("invalid".parse::<Triad>(), Err(ParseTriadError));
        assert_eq!("".parse::<Triad>(), Err(ParseTriadError));
    }

    #[test]
    fn test_parse_triad_error_display() {
        let err = ParseTriadError;
        assert_eq!(
            format!("{err}"),
            "invalid triad string (expected \"antifragile\", \"fragile\", or \"robust\")"
        );
    }

    #[test]
    fn test_classify_at_zero() {
        let system = ConvexFn;
        let _ = system.classify(0.0, 0.1);
    }

    #[test]
    fn test_classify_with_zero_delta() {
        let system = ConvexFn;
        assert_eq!(system.classify(10.0, 0.0), Triad::Robust);
    }

    #[test]
    fn test_classify_negative_stressor() {
        let system = ConvexFn;
        assert_eq!(system.classify(-10.0, 1.0), Triad::Antifragile);
    }

    #[test]
    fn test_triad_opposite() {
        assert_eq!(Triad::Antifragile.opposite(), Triad::Fragile);
        assert_eq!(Triad::Fragile.opposite(), Triad::Antifragile);
        assert_eq!(Triad::Robust.opposite(), Triad::Robust);
        assert_eq!(Triad::Antifragile.opposite().opposite(), Triad::Antifragile);
    }

    #[test]
    fn test_triad_iter() {
        let all: Vec<_> = Triad::iter().collect();
        assert_eq!(all, vec![Triad::Fragile, Triad::Robust, Triad::Antifragile]);
        assert_eq!(Triad::ALL.len(), 3);
    }

    #[test]
    fn test_classify_with_tolerance_returns_antifragile() {
        let system = ConvexFn;
        let result = system.classify_with_tolerance(10.0, 1.0, 1e-10);
        assert_eq!(result, Triad::Antifragile);
    }

    #[test]
    fn test_classify_with_tolerance_returns_fragile() {
        let system = ConcaveFn;
        let result = system.classify_with_tolerance(10.0, 1.0, 1e-10);
        assert_eq!(result, Triad::Fragile);
    }

    #[test]
    fn test_classify_with_tolerance_boundary() {
        // Create a system with known convexity
        let convex = ConvexFn;

        // At x=10, delta=1:
        // f(9) = 81, f(10) = 100, f(11) = 121
        // sum = 81 + 121 = 202
        // twin = 200
        // diff = 202 - 200 = 2

        // With epsilon = 1, diff (2) > epsilon, so Antifragile
        assert_eq!(
            convex.classify_with_tolerance(10.0, 1.0, 1.0),
            Triad::Antifragile
        );

        // With epsilon = 2, diff (2) <= epsilon, so Robust
        assert_eq!(
            convex.classify_with_tolerance(10.0, 1.0, 2.0),
            Triad::Robust
        );

        // With epsilon = 3, diff (2) <= epsilon, so Robust
        assert_eq!(
            convex.classify_with_tolerance(10.0, 1.0, 3.0),
            Triad::Robust
        );
    }

    #[test]
    fn test_classify_with_tolerance_fragile_boundary() {
        // Test that fragile systems are correctly identified with tolerance
        let concave = ConcaveFn;

        // With very small epsilon, should be Fragile
        assert_eq!(
            concave.classify_with_tolerance(10.0, 1.0, 1e-10),
            Triad::Fragile
        );

        // With large epsilon, should be Robust (within tolerance)
        assert_eq!(
            concave.classify_with_tolerance(10.0, 1.0, 10.0),
            Triad::Robust
        );
    }

    #[test]
    fn test_is_antifragile_returns_false() {
        let linear = LinearFn {
            slope: 1.0,
            intercept: 0.0,
        };
        assert!(!linear.is_antifragile(10.0, 1.0));

        let concave = ConcaveFn;
        assert!(!concave.is_antifragile(10.0, 1.0));
    }

    #[test]
    fn test_gains_from_stress_returns_false() {
        // Test a system where higher stress leads to LOWER payoff
        struct DecreasingSystem;
        impl Antifragile for DecreasingSystem {
            type Stressor = f64;
            type Payoff = f64;
            fn payoff(&self, x: Self::Stressor) -> Self::Payoff {
                -x // Decreasing function
            }
        }

        let system = DecreasingSystem;
        assert!(!system.gains_from_stress(1.0, 2.0)); // -1 > -2 is false
    }

    #[test]
    fn test_gains_from_stress_boundary() {
        // When payoffs are equal, should return false (not strictly gaining)
        struct ConstantSystem;
        impl Antifragile for ConstantSystem {
            type Stressor = f64;
            type Payoff = f64;
            fn payoff(&self, _x: Self::Stressor) -> Self::Payoff {
                5.0
            }
        }

        let system = ConstantSystem;
        assert!(!system.gains_from_stress(1.0, 2.0)); // 5 > 5 is false
    }

    #[test]
    fn test_is_stable_returns_false() {
        let convex = ConvexFn;
        // f(1) = 1, f(10) = 100, diff = 99 > threshold of 1
        assert!(!convex.is_stable(1.0, 10.0, 1.0));
    }

    #[test]
    fn test_is_stable_boundary_conditions() {
        struct KnownSystem;
        impl Antifragile for KnownSystem {
            type Stressor = f64;
            type Payoff = f64;
            fn payoff(&self, x: Self::Stressor) -> Self::Payoff {
                x * 2.0 // payoff(5) = 10, payoff(10) = 20
            }
        }

        let system = KnownSystem;

        // diff = |20 - 10| = 10
        // threshold = 10: diff <= threshold, so stable
        assert!(system.is_stable(5.0, 10.0, 10.0));

        // threshold = 9: diff > threshold, so not stable
        assert!(!system.is_stable(5.0, 10.0, 9.0));

        // Test with reversed order (low > high)
        // payoff(10) = 20, payoff(5) = 10, diff = |10 - 20| = 10
        assert!(system.is_stable(10.0, 5.0, 10.0));
        assert!(!system.is_stable(10.0, 5.0, 9.0));
    }

    #[test]
    fn test_verified_is_fragile_returns_true() {
        let concave = ConcaveFn;
        let verified = Verified::check(concave, 10.0, 1.0);
        assert!(verified.is_fragile());
        assert!(!verified.is_antifragile());
        assert!(!verified.is_robust());
    }

    #[test]
    fn test_verified_is_robust_returns_true() {
        let linear = LinearFn {
            slope: 2.0,
            intercept: 5.0,
        };
        let verified = Verified::check(linear, 10.0, 1.0);
        assert!(verified.is_robust());
        assert!(!verified.is_antifragile());
        assert!(!verified.is_fragile());
    }

    #[test]
    fn test_verified_is_antifragile_returns_false() {
        let concave = ConcaveFn;
        let verified = Verified::check(concave, 10.0, 1.0);
        assert!(!verified.is_antifragile());

        let linear = LinearFn {
            slope: 1.0,
            intercept: 0.0,
        };
        let verified = Verified::check(linear, 10.0, 1.0);
        assert!(!verified.is_antifragile());
    }

    #[test]
    fn test_verified_re_verify_changes_classification() {
        // System that changes classification based on operating point
        struct VariableSystem;
        impl Antifragile for VariableSystem {
            type Stressor = f64;
            type Payoff = f64;
            fn payoff(&self, x: Self::Stressor) -> Self::Payoff {
                if x > 0.0 {
                    x * x // Convex for positive x
                } else {
                    x.abs().sqrt() // Concave for negative x (using abs)
                }
            }
        }

        let system = VariableSystem;
        let mut verified = Verified::check(system, 10.0, 1.0);
        assert_eq!(verified.classification(), Triad::Antifragile);

        // Re-verify at a point where it's robust (zero delta)
        verified.re_verify(10.0, 0.0);
        assert_eq!(verified.classification(), Triad::Robust);
    }

    #[test]
    fn test_verified_still_holds_returns_false() {
        let convex = ConvexFn;
        let verified = Verified::check(convex, 10.0, 1.0);
        assert_eq!(verified.classification(), Triad::Antifragile);

        // At delta = 0, classification changes to Robust
        assert!(!verified.still_holds(10.0, 0.0));
    }

    #[test]
    fn test_verified_still_holds_returns_true() {
        let convex = ConvexFn;
        let verified = Verified::check(convex, 10.0, 1.0);

        // At a different point with same delta, should still be Antifragile
        assert!(verified.still_holds(5.0, 1.0));
        assert!(verified.still_holds(20.0, 2.0));
    }

    #[test]
    fn test_classify_with_tolerance_exact_boundary() {
        // When sum == twin_f_x exactly (linear function) and epsilon < 0,
        // the diff (0) > epsilon check passes, so we reach the sum > twin_f_x check.
        // A linear function should return Fragile (since sum is not > twin),
        // not Antifragile (which the >= mutation would cause).
        let linear = LinearFn {
            slope: 2.0,
            intercept: 5.0,
        };

        // For linear: f(x-d) + f(x+d) = 2*f(x) exactly, so sum == twin_f_x
        // With negative epsilon, diff (0) <= epsilon (-1) is false
        // So we reach: if sum > twin_f_x (false for linear) -> else Fragile
        // Mutation would make it: if sum >= twin_f_x (true) -> Antifragile (wrong!)
        let result = linear.classify_with_tolerance(10.0, 1.0, -1.0);
        assert_eq!(result, Triad::Fragile);
    }
}