elicitation 0.8.0

Conversational elicitation of strongly-typed Rust values via MCP
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
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
//! Formal verification framework for tool chains.
//!
//! Provides a generic `Contract` trait that can be implemented by multiple
//! verification tools (Kani, Creusot, Prusti, Verus, etc).
//!
//! # Quick Start
//!
//! ```rust,ignore
//! use elicitation::verification::{
//!     contracts::StringNonEmpty,
//!     WithContract,
//! };
//!
//! // Use with_contract() to verify elicited values
//! let value = String::with_contract(StringNonEmpty)
//!     .elicit(peer)
//!     .await?;
//! // value is guaranteed to be non-empty
//! ```
//!
//! # Architecture
//!
//! - **Core**: `Contract` trait - tool-agnostic interface
//! - **Adapters**: Tool-specific implementations (feature-gated)
//! - **Registry**: Unified interface for swapping verifiers at runtime
//! - **Composition**: Combine contracts with AND/OR/NOT logic
//! - **Examples**: Demonstration of verification with different tools
//!
//! # Feature Flags
//!
//! - `verification` - Core trait only (Kani contracts by default)
//! - `verify-kani` - Kani model checker support (default for verification)
//! - `verify-creusot` - Creusot deductive verifier
//! - `verify-prusti` - Prusti separation logic
//! - `verify-verus` - Verus SMT-based verifier
//!
//! # Contract Swapping
//!
//! ## Compile-Time (via features)
//!
//! Choose your verifier backend at compile-time:
//!
//! ```bash
//! # Use Kani (default)
//! cargo build --features verification
//!
//! # Use Creusot
//! cargo build --features verify-creusot
//!
//! # Use Prusti
//! cargo build --features verify-prusti
//!
//! # Use Verus
//! cargo build --features verify-verus
//! ```
//!
//! Then use default contracts in your code:
//!
//! ```rust,ignore
//! use elicitation::verification::DEFAULT_STRING_CONTRACT;
//!
//! let value = String::with_contract(DEFAULT_STRING_CONTRACT)
//!     .elicit(peer)
//!     .await?;
//! ```
//!
//! ## Runtime (via VerifierBackend)
//!
//! Swap verifiers dynamically at runtime:
//!
//! ```rust,ignore
//! use elicitation::verification::{VerifierBackend, contracts::*};
//!
//! // Choose backend at runtime
//! let verifier = VerifierBackend::Kani(Box::new(StringNonEmpty));
//! assert!(verifier.check_precondition(&String::from("hello")));
//!
//! // Verify a transformation
//! let result = verifier.verify(input, |x| x.to_uppercase())?;
//! ```
//!
//! # Contract Composition
//!
//! Combine contracts using boolean logic:
//!
//! ```rust,ignore
//! use elicitation::verification::{compose, contracts::*};
//!
//! // Non-empty string with max 100 characters
//! let contract = compose::and(
//!     StringNonEmpty,
//!     StringMaxLength::<100>
//! );
//!
//! // Positive OR non-negative (basically >= 0)
//! let contract = compose::or(I32Positive, I32NonNegative);
//!
//! // NOT positive (basically <= 0)
//! let contract = compose::not(I32Positive);
//!
//! // Complex nested composition
//! let contract = compose::or(
//!     compose::and(I32Positive, I32NonNegative),
//!     compose::not(I32Positive)
//! );
//! ```
//!
//! # Creating Custom Contracts
//!
//! Implement the `Contract` trait for your own types:
//!
//! ```rust,ignore
//! use elicitation::verification::Contract;
//!
//! struct ValidEmail;
//!
//! impl Contract for ValidEmail {
//!     type Input = String;
//!     type Output = String;
//!     
//!     fn requires(input: &String) -> bool {
//!         input.contains('@') && input.contains('.')
//!     }
//!     
//!     fn ensures(_input: &String, output: &String) -> bool {
//!         output.contains('@') && output.contains('.')
//!     }
//! }
//!
//! // Use with elicitation
//! let email = String::with_contract(ValidEmail)
//!     .elicit(peer)
//!     .await?;
//! ```
//!
//! # Formal Verification
//!
//! ## Kani (Model Checking)
//!
//! Kani contracts work out-of-the-box. Write harnesses in your tests:
//!
//! ```rust,ignore
//! #[cfg(kani)]
//! #[kani::proof]
//! fn verify_string_non_empty() {
//!     let inputs = ["hello", "world", "test"];
//!     for input in inputs {
//!         assert!(StringNonEmpty::requires(&input.to_string()));
//!     }
//! }
//! ```
//!
//! Run with: `cargo kani`
//!
//! ## Creusot (Deductive Verification)
//!
//! Creusot requires annotated source code:
//!
//! ```rust,ignore
//! #[requires(input.len() > 0)]
//! #[ensures(result.len() > 0)]
//! fn process(input: String) -> String {
//!     input
//! }
//! ```
//!
//! Our runtime contracts provide fallback checking.
//!
//! ## Prusti (Separation Logic)
//!
//! Prusti uses `prusti-contracts`:
//!
//! ```rust,ignore
//! #[requires(input > 0)]
//! #[ensures(result > 0)]
//! fn increment(input: i32) -> i32 {
//!     input + 1
//! }
//! ```
//!
//! ## Verus (SMT-Based)
//!
//! Verus uses modes and proof blocks:
//!
//! ```rust,ignore
//! fn process(input: i32) -> (result: i32)
//!     requires input > 0,
//!     ensures result > 0,
//! {
//!     input + 1
//! }
//! ```
//!
//! # Example
//!
//! See `examples/verification_demo.rs` for a complete demonstration:
//!
//! ```bash
//! cargo run --example verification_demo --features verification
//! ```

use crate::ElicitResult;
use crate::traits::Elicitation;
use std::fmt::Debug;

// ============================================================================
// Default Contract Selection (Feature-gated)
// ============================================================================

/// Default contract instances for primitives, selected at compile-time based on features.
///
/// When verification features are enabled, these constants resolve to the appropriate
/// verifier-specific contract:
/// - `verify-kani` → Kani contracts (default)
/// - `verify-creusot` → Creusot contracts
/// - `verify-prusti` → Prusti contracts
/// - `verify-verus` → Verus contracts
///
/// Usage:
/// ```rust,ignore
/// use elicitation::verification::DEFAULT_STRING_CONTRACT;
///
/// let value = String::with_contract(DEFAULT_STRING_CONTRACT)
///     .elicit(peer)
///     .await?;
/// ```
// String contracts
/// Default String contract (Kani unless overridden by feature).
#[cfg(all(
    feature = "verification",
    not(any(
        feature = "verify-creusot",
        feature = "verify-prusti",
        feature = "verify-verus"
    ))
))]
pub const DEFAULT_STRING_CONTRACT: contracts::StringNonEmpty = contracts::StringNonEmpty;

/// Default String contract (Creusot - priority 1).
#[cfg(feature = "verify-creusot")]
pub const DEFAULT_STRING_CONTRACT: contracts::creusot::CreusotStringNonEmpty =
    contracts::creusot::CreusotStringNonEmpty;

/// Default String contract (Prusti - priority 2).
#[cfg(all(feature = "verify-prusti", not(feature = "verify-creusot")))]
pub const DEFAULT_STRING_CONTRACT: contracts::prusti::PrustiStringNonEmpty =
    contracts::prusti::PrustiStringNonEmpty;

/// Default String contract (Verus - priority 3).
#[cfg(all(
    feature = "verify-verus",
    not(any(feature = "verify-creusot", feature = "verify-prusti"))
))]
pub const DEFAULT_STRING_CONTRACT: contracts::verus::VerusStringNonEmpty =
    contracts::verus::VerusStringNonEmpty;

// i32 contracts
/// Default i32 contract (Kani unless overridden by feature).
#[cfg(all(
    feature = "verification",
    not(any(
        feature = "verify-creusot",
        feature = "verify-prusti",
        feature = "verify-verus"
    ))
))]
pub const DEFAULT_I32_CONTRACT: contracts::I32Positive = contracts::I32Positive;

/// Default i32 contract (Creusot - priority 1).
#[cfg(feature = "verify-creusot")]
pub const DEFAULT_I32_CONTRACT: contracts::creusot::CreusotI32Positive =
    contracts::creusot::CreusotI32Positive;

/// Default i32 contract (Prusti - priority 2).
#[cfg(all(feature = "verify-prusti", not(feature = "verify-creusot")))]
pub const DEFAULT_I32_CONTRACT: contracts::prusti::PrustiI32Positive =
    contracts::prusti::PrustiI32Positive;

/// Default i32 contract (Verus - priority 3).
#[cfg(all(
    feature = "verify-verus",
    not(any(feature = "verify-creusot", feature = "verify-prusti"))
))]
pub const DEFAULT_I32_CONTRACT: contracts::verus::VerusI32Positive =
    contracts::verus::VerusI32Positive;

// bool contracts
/// Default bool contract (Kani unless overridden by feature).
#[cfg(all(
    feature = "verification",
    not(any(
        feature = "verify-creusot",
        feature = "verify-prusti",
        feature = "verify-verus"
    ))
))]
pub const DEFAULT_BOOL_CONTRACT: contracts::BoolValid = contracts::BoolValid;

/// Default bool contract (Creusot - priority 1).
#[cfg(feature = "verify-creusot")]
pub const DEFAULT_BOOL_CONTRACT: contracts::creusot::CreusotBoolValid =
    contracts::creusot::CreusotBoolValid;

/// Default bool contract (Prusti - priority 2).
#[cfg(all(feature = "verify-prusti", not(feature = "verify-creusot")))]
pub const DEFAULT_BOOL_CONTRACT: contracts::prusti::PrustiBoolValid =
    contracts::prusti::PrustiBoolValid;

/// Default bool contract (Verus).
#[cfg(all(
    feature = "verify-verus",
    not(any(feature = "verify-creusot", feature = "verify-prusti"))
))]
pub const DEFAULT_BOOL_CONTRACT: contracts::verus::VerusBoolValid =
    contracts::verus::VerusBoolValid;

// ============================================================================
// Contract Trait
// ============================================================================

/// Generic contract for formal verification.
///
/// This trait defines the interface for specifying contracts that can be
/// verified by various formal verification tools (Kani, Creusot, etc).
///
/// # Contract Semantics
///
/// - **Precondition** (`requires`): Must hold before execution
/// - **Postcondition** (`ensures`): Must hold after execution
/// - **Invariant**: Must hold throughout execution
///
/// # Tool Integration
///
/// Verification tools provide their own extensions:
/// - Kani: `#[kani::proof]` harnesses
/// - Creusot: Prophecy annotations
/// - Prusti: Separation logic specs
/// - Verus: Mode-based specifications
///
/// # Design Philosophy
///
/// 1. Tool-agnostic core trait
/// 2. Tool-specific adapters (feature-gated)
/// 3. Composable contracts
/// 4. Elicitation-compatible types
pub trait Contract {
    /// Input type (must be elicitable).
    type Input: Elicitation + Clone + std::fmt::Debug + Send;

    /// Output type (must be elicitable).
    type Output: Elicitation + Clone + std::fmt::Debug + Send;

    /// Precondition: What the tool requires to execute safely.
    ///
    /// This predicate must be **decidable** (finite execution) and **pure**
    /// (no side effects).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// fn requires(input: &String) -> bool {
    ///     !input.is_empty() && input.len() < 1000
    /// }
    /// ```
    fn requires(input: &Self::Input) -> bool;

    /// Postcondition: What the tool guarantees after execution.
    ///
    /// This predicate relates input to output, expressing the functional
    /// correctness property.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// fn ensures(input: &String, output: &Email) -> bool {
    ///     output.to_string() == *input && output.is_valid()
    /// }
    /// ```
    fn ensures(input: &Self::Input, output: &Self::Output) -> bool;

    /// Invariant: What remains true throughout execution.
    ///
    /// Default implementation allows all states. Override for stateful tools.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// fn invariant(&self) -> bool {
    ///     self.connection.is_alive()
    /// }
    /// ```
    fn invariant(&self) -> bool {
        true
    }
}

// ============================================================================
// Contract Composition
// ============================================================================

/// Combines two contracts with AND logic (both must pass).
///
/// # Example
///
/// ```rust,ignore
/// use elicitation::verification::{contracts::*, AndContract};
///
/// // Both contracts must be satisfied
/// let contract = AndContract::new(StringNonEmpty, StringMaxLength(100));
/// assert!(contract.requires(&String::from("hello")));
/// assert!(!contract.requires(&String::new())); // Fails StringNonEmpty
/// ```
#[derive(Debug, Clone)]
pub struct AndContract<C1, C2> {
    /// First contract.
    pub first: C1,
    /// Second contract.
    pub second: C2,
}

impl<C1, C2> AndContract<C1, C2> {
    /// Create new AND contract combining two contracts.
    #[tracing::instrument(level = "trace", skip(first, second))]
    pub fn new(first: C1, second: C2) -> Self {
        Self { first, second }
    }
}

impl<C1, C2, I, O> Contract for AndContract<C1, C2>
where
    C1: Contract<Input = I, Output = O>,
    C2: Contract<Input = I, Output = O>,
    I: Elicitation + Clone + Debug + Send,
    O: Elicitation + Clone + Debug + Send,
{
    type Input = I;
    type Output = O;

    fn requires(input: &Self::Input) -> bool {
        C1::requires(input) && C2::requires(input)
    }

    fn ensures(input: &Self::Input, output: &Self::Output) -> bool {
        C1::ensures(input, output) && C2::ensures(input, output)
    }

    fn invariant(&self) -> bool {
        self.first.invariant() && self.second.invariant()
    }
}

/// Combines two contracts with OR logic (either can pass).
///
/// # Example
///
/// ```rust,ignore
/// use elicitation::verification::{contracts::*, OrContract};
///
/// // Either contract can be satisfied
/// let contract = OrContract::new(I32Positive, I32Zero);
/// assert!(contract.requires(&42));   // Satisfies I32Positive
/// assert!(contract.requires(&0));    // Satisfies I32Zero
/// assert!(!contract.requires(&-1));  // Satisfies neither
/// ```
#[derive(Debug, Clone)]
pub struct OrContract<C1, C2> {
    /// First contract.
    pub first: C1,
    /// Second contract.
    pub second: C2,
}

impl<C1, C2> OrContract<C1, C2> {
    /// Create new OR contract combining two contracts.
    #[tracing::instrument(level = "trace", skip(first, second))]
    pub fn new(first: C1, second: C2) -> Self {
        Self { first, second }
    }
}

impl<C1, C2, I, O> Contract for OrContract<C1, C2>
where
    C1: Contract<Input = I, Output = O>,
    C2: Contract<Input = I, Output = O>,
    I: Elicitation + Clone + Debug + Send,
    O: Elicitation + Clone + Debug + Send,
{
    type Input = I;
    type Output = O;

    fn requires(input: &Self::Input) -> bool {
        C1::requires(input) || C2::requires(input)
    }

    fn ensures(input: &Self::Input, output: &Self::Output) -> bool {
        C1::ensures(input, output) || C2::ensures(input, output)
    }

    fn invariant(&self) -> bool {
        self.first.invariant() || self.second.invariant()
    }
}

/// Negates a contract (logical NOT).
///
/// # Example
///
/// ```rust,ignore
/// use elicitation::verification::{contracts::*, NotContract};
///
/// // Inverts the contract logic
/// let contract = NotContract::new(StringNonEmpty);
/// assert!(!contract.requires(&String::from("hello"))); // Was true, now false
/// assert!(contract.requires(&String::new()));          // Was false, now true
/// ```
#[derive(Debug, Clone)]
pub struct NotContract<C> {
    /// Inner contract to negate.
    pub inner: C,
}

impl<C> NotContract<C> {
    /// Create new NOT contract negating inner contract.
    #[tracing::instrument(level = "trace", skip(inner))]
    pub fn new(inner: C) -> Self {
        Self { inner }
    }
}

impl<C, I, O> Contract for NotContract<C>
where
    C: Contract<Input = I, Output = O>,
    I: Elicitation + Clone + Debug + Send,
    O: Elicitation + Clone + Debug + Send,
{
    type Input = I;
    type Output = O;

    fn requires(input: &Self::Input) -> bool {
        !C::requires(input)
    }

    fn ensures(input: &Self::Input, output: &Self::Output) -> bool {
        !C::ensures(input, output)
    }

    fn invariant(&self) -> bool {
        !self.inner.invariant()
    }
}

/// Helper functions for contract composition.
pub mod compose {
    use super::*;

    /// Create AND contract from two contracts.
    #[tracing::instrument(level = "trace", skip(first, second))]
    pub fn and<C1, C2>(first: C1, second: C2) -> AndContract<C1, C2> {
        AndContract::new(first, second)
    }

    /// Create OR contract from two contracts.
    #[tracing::instrument(level = "trace", skip(first, second))]
    pub fn or<C1, C2>(first: C1, second: C2) -> OrContract<C1, C2> {
        OrContract::new(first, second)
    }

    /// Create NOT contract from a contract.
    #[tracing::instrument(level = "trace", skip(inner))]
    pub fn not<C>(inner: C) -> NotContract<C> {
        NotContract::new(inner)
    }
}

// ============================================================================
// Verifier Backend Registry
// ============================================================================

/// Runtime-friendly contract wrapper for dynamic dispatch.
///
/// Since `Contract` has static methods, we need a trait object compatible version.
pub trait DynContract<I, O>: Send + Sync
where
    I: Elicitation + Clone + Debug + Send,
    O: Elicitation + Clone + Debug + Send,
{
    /// Check precondition.
    fn check_requires(&self, input: &I) -> bool;

    /// Check postcondition.
    fn check_ensures(&self, input: &I, output: &O) -> bool;

    /// Check invariant.
    fn check_invariant(&self) -> bool;
}

/// Blanket implementation to convert any Contract into DynContract.
impl<T, I, O> DynContract<I, O> for T
where
    T: Contract<Input = I, Output = O> + Send + Sync,
    I: Elicitation + Clone + Debug + Send,
    O: Elicitation + Clone + Debug + Send,
{
    fn check_requires(&self, input: &I) -> bool {
        Self::requires(input)
    }

    fn check_ensures(&self, input: &I, output: &O) -> bool {
        Self::ensures(input, output)
    }

    fn check_invariant(&self) -> bool {
        self.invariant()
    }
}

/// Unified interface for swapping verification backends at runtime.
///
/// This enum allows users to choose different verifiers for different types
/// or situations, supporting the refinement workflow.
///
/// # Example
///
/// ```rust,ignore
/// use elicitation::verification::{VerifierBackend, contracts::*};
///
/// // Start with Kani for quick checks
/// let verifier = VerifierBackend::Kani(Box::new(StringNonEmpty));
///
/// // Refine to Creusot for stronger guarantees
/// let verifier = VerifierBackend::Creusot(Box::new(
///     contracts::creusot::CreusotStringNonEmpty
/// ));
/// ```
pub enum VerifierBackend<I, O>
where
    I: Elicitation + Clone + Debug + Send,
    O: Elicitation + Clone + Debug + Send,
{
    /// Kani model checker (bounded verification)
    Kani(Box<dyn DynContract<I, O>>),

    /// Creusot deductive verifier (unbounded proofs)
    #[cfg(feature = "verify-creusot")]
    Creusot(Box<dyn DynContract<I, O>>),

    /// Prusti separation logic verifier
    #[cfg(feature = "verify-prusti")]
    Prusti(Box<dyn DynContract<I, O>>),

    /// Verus SMT-based verifier
    #[cfg(feature = "verify-verus")]
    Verus(Box<dyn DynContract<I, O>>),
}

impl<I, O> VerifierBackend<I, O>
where
    I: Elicitation + Clone + Debug + Send,
    O: Elicitation + Clone + Debug + Send,
{
    /// Check if precondition holds for input.
    pub fn check_precondition(&self, input: &I) -> bool {
        match self {
            Self::Kani(contract) => contract.check_requires(input),

            #[cfg(feature = "verify-creusot")]
            Self::Creusot(contract) => contract.check_requires(input),

            #[cfg(feature = "verify-prusti")]
            Self::Prusti(contract) => contract.check_requires(input),

            #[cfg(feature = "verify-verus")]
            Self::Verus(contract) => contract.check_requires(input),
        }
    }

    /// Check if postcondition holds for input/output pair.
    pub fn check_postcondition(&self, input: &I, output: &O) -> bool {
        match self {
            Self::Kani(contract) => contract.check_ensures(input, output),

            #[cfg(feature = "verify-creusot")]
            Self::Creusot(contract) => contract.check_ensures(input, output),

            #[cfg(feature = "verify-prusti")]
            Self::Prusti(contract) => contract.check_ensures(input, output),

            #[cfg(feature = "verify-verus")]
            Self::Verus(contract) => contract.check_ensures(input, output),
        }
    }

    /// Check if invariant holds.
    pub fn check_invariant(&self) -> bool {
        match self {
            Self::Kani(contract) => contract.check_invariant(),

            #[cfg(feature = "verify-creusot")]
            Self::Creusot(contract) => contract.check_invariant(),

            #[cfg(feature = "verify-prusti")]
            Self::Prusti(contract) => contract.check_invariant(),

            #[cfg(feature = "verify-verus")]
            Self::Verus(contract) => contract.check_invariant(),
        }
    }

    /// Verify a transformation: check precondition, apply function, check postcondition.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let verifier = VerifierBackend::Kani(Box::new(I32Positive));
    /// let result = verifier.verify(42, |x| x)?;
    /// assert_eq!(result, 42);
    /// ```
    pub fn verify<F>(&self, input: I, f: F) -> Result<O, String>
    where
        F: FnOnce(I) -> O,
    {
        // Check precondition
        if !self.check_precondition(&input) {
            return Err("Precondition failed".to_string());
        }

        // Check invariant before
        if !self.check_invariant() {
            return Err("Invariant failed before execution".to_string());
        }

        // Execute transformation
        let output = f(input.clone());

        // Check postcondition
        if !self.check_postcondition(&input, &output) {
            return Err("Postcondition failed".to_string());
        }

        // Check invariant after
        if !self.check_invariant() {
            return Err("Invariant failed after execution".to_string());
        }

        Ok(output)
    }
}

// ============================================================================
// Contract Integration with Elicitation
// ============================================================================

/// Builder for elicitation with contract verification.
///
/// Enables ergonomic syntax: `String::with_contract(StringNonEmpty).elicit(&peer).await?`
pub struct ContractedElicitation<T, C>
where
    T: Elicitation,
    C: Contract<Input = T, Output = T>,
{
    contract: C,
    _phantom: std::marker::PhantomData<T>,
}

impl<T, C> ContractedElicitation<T, C>
where
    T: Elicitation + Clone + Debug + Send,
    C: Contract<Input = T, Output = T> + Send + Sync + 'static,
{
    /// Create a new contracted elicitation builder.
    pub fn new(contract: C) -> Self {
        Self {
            contract,
            _phantom: std::marker::PhantomData,
        }
    }

    /// Elicit the value and verify contracts.
    ///
    /// This method:
    /// 1. Elicits the value using standard elicitation
    /// 2. Treats elicited value as both input and output (identity transformation)
    /// 3. Verifies precondition on elicited value
    /// 4. Verifies postcondition (since input == output for elicitation)
    /// 5. Returns value if contracts hold
    ///
    /// # Arguments
    ///
    /// * `peer` - The RMCP peer to use for interaction
    ///
    /// # Returns
    ///
    /// Returns the elicited value if contracts are satisfied.
    ///
    /// # Errors
    ///
    /// - Contract violation: Precondition or postcondition failed
    /// - Elicitation error: Standard elicitation failures
    pub async fn elicit(
        self,
        peer: std::sync::Arc<crate::rmcp::Peer<crate::rmcp::RoleClient>>,
    ) -> ElicitResult<T> {
        use tracing::{debug, error};

        // Elicit the value
        let client = crate::ElicitClient::new(peer);
        let value = T::elicit(&client).await?;

        debug!(
            value = ?value,
            "Value elicited, checking contracts"
        );

        // Check precondition (value must satisfy entry condition)
        if !C::requires(&value) {
            error!("Contract precondition failed");
            return Err(crate::ElicitError::new(
                crate::ElicitErrorKind::InvalidFormat {
                    expected: "Value satisfying contract precondition".to_string(),
                    received: format!("{:?}", value),
                },
            ));
        }

        // For elicitation, input == output (identity)
        // Check postcondition
        if !C::ensures(&value, &value) {
            error!("Contract postcondition failed");
            return Err(crate::ElicitError::new(
                crate::ElicitErrorKind::InvalidFormat {
                    expected: "Value satisfying contract postcondition".to_string(),
                    received: format!("{:?}", value),
                },
            ));
        }

        // Check invariant
        if !self.contract.invariant() {
            error!("Contract invariant failed");
            return Err(crate::ElicitError::new(
                crate::ElicitErrorKind::InvalidFormat {
                    expected: "Contract invariant to hold".to_string(),
                    received: "Invariant violated".to_string(),
                },
            ));
        }

        debug!("All contracts satisfied");
        Ok(value)
    }
}

/// Extension trait for adding contract verification to elicitation.
///
/// This trait is automatically implemented for all types that implement
/// `Elicitation`, allowing contract-verified elicitation.
///
/// # Example
///
/// ```rust,ignore
/// use elicitation::verification::{WithContract, contracts::StringNonEmpty};
///
/// // Elicit with contract verification
/// let value = String::with_contract(StringNonEmpty)
///     .elicit(&peer)
///     .await?;
///
/// // Value is guaranteed to satisfy StringNonEmpty contract
/// assert!(!value.is_empty());
/// ```
pub trait WithContract: Elicitation + Clone + Debug + Send {
    /// Attach a contract to this type's elicitation.
    ///
    /// Returns a builder that will verify the contract after elicitation.
    ///
    /// # Arguments
    ///
    /// * `contract` - The contract to verify
    ///
    /// # Returns
    ///
    /// A builder that can elicit and verify the value.
    fn with_contract<C>(contract: C) -> ContractedElicitation<Self, C>
    where
        C: Contract<Input = Self, Output = Self> + Send + Sync + 'static,
    {
        ContractedElicitation::new(contract)
    }
}

// Blanket implementation for all Elicitation types
impl<T> WithContract for T where T: Elicitation + Clone + Debug + Send {}

// ============================================================================
// Submodules
// ============================================================================

// Default contract implementations for primitive types
pub mod contracts;

// Mechanism-level contracts (Survey, Affirm, Text, etc)
pub mod mechanisms;

// Contract types for trenchcoat pattern (boundary validation)
pub mod types;

// CLI runner for proof orchestration
#[cfg(feature = "cli")]
pub mod runner;

// Tool-specific adapters (feature-gated)
#[cfg(feature = "verify-kani")]
pub mod kani;

#[cfg(feature = "verify-creusot")]
pub mod creusot;
#[cfg(feature = "cli")]
pub mod prusti_runner;

// TODO: Phase 2 - These will be top-level modules when we add Tool trait impls
// For now, verifier-specific contracts are in contracts/ submodules
// #[cfg(feature = "verify-prusti")]
// pub mod prusti;

// #[cfg(feature = "verify-verus")]
// pub mod verus;

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

#[cfg(test)]
mod tests {
    use super::*;
    use crate::verification::contracts::{BoolValid, I32Positive, StringNonEmpty};

    #[test]
    fn test_verifier_backend_string_kani() {
        let verifier = VerifierBackend::Kani(Box::new(StringNonEmpty));
        let input = String::from("hello");

        assert!(verifier.check_precondition(&input));
        assert!(verifier.check_postcondition(&input, &input));
        assert!(verifier.check_invariant());

        let result = verifier.verify(input.clone(), |x| x);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "hello");
    }

    #[test]
    fn test_verifier_backend_i32_kani() {
        let verifier = VerifierBackend::Kani(Box::new(I32Positive));
        let input = 42i32;

        assert!(verifier.check_precondition(&input));
        assert!(verifier.check_postcondition(&input, &input));
        assert!(verifier.check_invariant());

        let result = verifier.verify(input, |x| x);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), 42);
    }

    #[test]
    fn test_verifier_backend_bool_kani() {
        let verifier = VerifierBackend::Kani(Box::new(BoolValid));
        let input = true;

        assert!(verifier.check_precondition(&input));
        assert!(verifier.check_postcondition(&input, &input));
        assert!(verifier.check_invariant());

        let result = verifier.verify(input, |x| x);
        assert!(result.is_ok());
        assert!(result.unwrap());
    }

    #[test]
    fn test_verifier_backend_precondition_failure() {
        let verifier = VerifierBackend::Kani(Box::new(StringNonEmpty));
        let input = String::new(); // Empty string violates precondition

        assert!(!verifier.check_precondition(&input));

        let result = verifier.verify(input, |x| x);
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "Precondition failed");
    }

    #[test]
    fn test_verifier_backend_postcondition_failure() {
        let verifier = VerifierBackend::Kani(Box::new(I32Positive));
        let input = 42i32;

        // Transform that violates postcondition
        let result = verifier.verify(input, |_x| -1); // Returns negative
        assert!(result.is_err());
        assert_eq!(result.unwrap_err(), "Postcondition failed");
    }

    #[test]
    fn test_with_contract_creates_contracted_elicitation() {
        // Test that with_contract() creates a ContractedElicitation
        let contracted = String::with_contract(StringNonEmpty);

        // Verify the type is correct (compile-time check)
        let _: ContractedElicitation<String, StringNonEmpty> = contracted;
    }

    #[test]
    fn test_contracted_elicitation_builder_pattern() {
        // Test builder pattern construction
        let _contracted = ContractedElicitation {
            _phantom: std::marker::PhantomData::<i32>,
            contract: I32Positive,
        };

        // Verify contract is stored correctly
        assert!(I32Positive::requires(&42));
        assert!(!I32Positive::requires(&-1));
    }

    #[test]
    fn test_with_contract_works_for_all_elicitation_types() {
        // Test that with_contract() is available for all types that impl Elicitation
        let _string_contracted = String::with_contract(StringNonEmpty);
        let _i32_contracted = i32::with_contract(I32Positive);
        let _bool_contracted = bool::with_contract(BoolValid);
    }

    #[test]
    #[cfg(feature = "verification")]
    fn test_default_contracts_available() {
        // Test that default contract constants are available when verification feature enabled
        use super::{DEFAULT_BOOL_CONTRACT, DEFAULT_I32_CONTRACT, DEFAULT_STRING_CONTRACT};

        // Compile-time check that these constants exist and are the expected types
        fn check_string_contract<T: Contract<Input = String, Output = String>>(_: T) {}
        fn check_i32_contract<T: Contract<Input = i32, Output = i32>>(_: T) {}
        fn check_bool_contract<T: Contract<Input = bool, Output = bool>>(_: T) {}

        check_string_contract(DEFAULT_STRING_CONTRACT);
        check_i32_contract(DEFAULT_I32_CONTRACT);
        check_bool_contract(DEFAULT_BOOL_CONTRACT);
    }

    #[test]
    #[cfg(feature = "verification")]
    fn test_default_contracts_usable_with_with_contract() {
        // Test that default contracts work with with_contract()
        use super::{DEFAULT_BOOL_CONTRACT, DEFAULT_I32_CONTRACT, DEFAULT_STRING_CONTRACT};

        // These contracts are zero-sized unit structs
        let _string_contracted = String::with_contract(DEFAULT_STRING_CONTRACT);
        let _i32_contracted = i32::with_contract(DEFAULT_I32_CONTRACT);
        let _bool_contracted = bool::with_contract(DEFAULT_BOOL_CONTRACT);
    }

    // ========================================================================
    // Contract Composition Tests
    // ========================================================================

    #[test]
    fn test_and_contract_both_pass() {
        use super::AndContract;
        use super::contracts::{I32NonNegative, I32Positive};

        // 42 is both positive and non-negative
        AndContract::new(I32Positive, I32NonNegative);
        assert!(AndContract::<I32Positive, I32NonNegative>::requires(&42));
        assert!(AndContract::<I32Positive, I32NonNegative>::ensures(
            &42, &42
        ));
    }

    #[test]
    fn test_and_contract_one_fails() {
        use super::AndContract;
        use super::contracts::{I32NonNegative, I32Positive};

        // 0 is non-negative but not positive
        assert!(!AndContract::<I32Positive, I32NonNegative>::requires(&0));

        // -1 fails both
        assert!(!AndContract::<I32Positive, I32NonNegative>::requires(&-1));
    }

    #[test]
    fn test_or_contract_either_passes() {
        use super::OrContract;
        use super::contracts::{I32NonNegative, I32Positive};

        // 42 satisfies both (either is enough)
        assert!(OrContract::<I32Positive, I32NonNegative>::requires(&42));

        // 0 satisfies NonNegative only (still passes)
        assert!(OrContract::<I32Positive, I32NonNegative>::requires(&0));

        // -1 satisfies neither (fails)
        assert!(!OrContract::<I32Positive, I32NonNegative>::requires(&-1));
    }

    #[test]
    fn test_not_contract_inverts_logic() {
        use super::NotContract;
        use super::contracts::I32Positive;

        // Original: 42 is positive
        assert!(I32Positive::requires(&42));

        // Negated: 42 is NOT positive (false)
        assert!(!NotContract::<I32Positive>::requires(&42));

        // Original: -1 is not positive (false)
        assert!(!I32Positive::requires(&-1));

        // Negated: -1 is NOT positive (true)
        assert!(NotContract::<I32Positive>::requires(&-1));
    }

    #[test]
    fn test_string_composition_bounded_non_empty() {
        use super::AndContract;
        use super::contracts::{StringMaxLength, StringNonEmpty};

        // Create contract: non-empty AND max 10 chars
        AndContract::new(StringNonEmpty, StringMaxLength::<10>);

        // "hello" passes (non-empty, 5 chars)
        assert!(AndContract::<StringNonEmpty, StringMaxLength<10>>::requires(&"hello".to_string()));

        // "" fails (empty)
        assert!(!AndContract::<StringNonEmpty, StringMaxLength<10>>::requires(&"".to_string()));

        // "12345678901" fails (too long)
        assert!(
            !AndContract::<StringNonEmpty, StringMaxLength<10>>::requires(
                &"12345678901".to_string()
            )
        );
    }

    #[test]
    fn test_compose_helpers() {
        use super::compose;
        use super::contracts::{I32NonNegative, I32Positive};

        // Test helper functions
        let and_contract = compose::and(I32Positive, I32NonNegative);
        assert!(AndContract::<I32Positive, I32NonNegative>::requires(&42));

        let or_contract = compose::or(I32Positive, I32NonNegative);
        assert!(OrContract::<I32Positive, I32NonNegative>::requires(&0));

        let not_contract = compose::not(I32Positive);
        assert!(NotContract::<I32Positive>::requires(&-1));

        // Verify contracts are constructed correctly
        let _: AndContract<I32Positive, I32NonNegative> = and_contract;
        let _: OrContract<I32Positive, I32NonNegative> = or_contract;
        let _: NotContract<I32Positive> = not_contract;
    }

    #[test]
    fn test_complex_composition() {
        use super::contracts::{I32NonNegative, I32Positive};
        use super::{AndContract, NotContract, OrContract};

        // (Positive AND NonNegative) OR (NOT Positive)
        // This is basically: value >= 0 OR value < 0 (always true)
        let _pos_and_nonneg = AndContract::new(I32Positive, I32NonNegative);
        let _not_pos = NotContract::new(I32Positive);

        // Should accept any i32
        assert!(OrContract::<
            AndContract<I32Positive, I32NonNegative>,
            NotContract<I32Positive>,
        >::requires(&42));
        assert!(OrContract::<
            AndContract<I32Positive, I32NonNegative>,
            NotContract<I32Positive>,
        >::requires(&0));
        assert!(OrContract::<
            AndContract<I32Positive, I32NonNegative>,
            NotContract<I32Positive>,
        >::requires(&-1));
    }

    #[test]
    fn test_string_max_length_invariant() {
        use super::contracts::StringMaxLength;

        let contract = StringMaxLength::<100>;
        assert!(contract.invariant()); // Max length is positive

        let invalid = StringMaxLength::<0>;
        assert!(!invalid.invariant()); // Max length is 0 (invalid)
    }
}