eidetic-engine 0.15.1

Durable, local-first, explainable memory for coding agents.
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
//! Procedural rule domain types (EE-084).
//!
//! Procedural rules are distilled lessons, patterns, and policies from
//! experience. They have lifecycle (maturity), scope (where they apply),
//! and feedback tracking.

use std::fmt;
use std::str::FromStr;

fn normalized_rule_token(input: &str) -> String {
    let trimmed = input.trim();
    let mut normalized = String::with_capacity(trimmed.len());
    let mut previous_was_lowercase = false;
    let mut previous_was_separator = false;

    for character in trimmed.chars() {
        match character {
            '-' | '_' => {
                if !normalized.is_empty() && !previous_was_separator {
                    normalized.push('_');
                }
                previous_was_lowercase = false;
                previous_was_separator = true;
            }
            character if character.is_ascii_uppercase() => {
                if previous_was_lowercase && !previous_was_separator {
                    normalized.push('_');
                }
                normalized.push(character.to_ascii_lowercase());
                previous_was_lowercase = false;
                previous_was_separator = false;
            }
            character => {
                normalized.push(character.to_ascii_lowercase());
                previous_was_lowercase = character.is_ascii_lowercase();
                previous_was_separator = false;
            }
        }
    }

    normalized
}

/// Scope of a procedural rule - where it applies.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum RuleScope {
    /// Applies to all workspaces.
    Global,
    /// Applies to the current workspace.
    Workspace,
    /// Applies to a specific project within workspace.
    Project,
    /// Applies to a specific directory pattern.
    Directory,
    /// Applies to files matching a pattern.
    FilePattern,
}

impl RuleScope {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Global => "global",
            Self::Workspace => "workspace",
            Self::Project => "project",
            Self::Directory => "directory",
            Self::FilePattern => "file_pattern",
        }
    }

    #[must_use]
    pub const fn all() -> [Self; 5] {
        [
            Self::Global,
            Self::Workspace,
            Self::Project,
            Self::Directory,
            Self::FilePattern,
        ]
    }

    #[must_use]
    pub const fn requires_pattern(self) -> bool {
        matches!(self, Self::Directory | Self::FilePattern)
    }
}

impl fmt::Display for RuleScope {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Error when parsing an invalid rule scope string.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseRuleScopeError {
    input: String,
}

impl ParseRuleScopeError {
    pub fn input(&self) -> &str {
        &self.input
    }
}

impl fmt::Display for ParseRuleScopeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unknown rule scope `{}`; expected one of global, workspace, project, directory, file_pattern",
            self.input
        )
    }
}

impl std::error::Error for ParseRuleScopeError {}

impl FromStr for RuleScope {
    type Err = ParseRuleScopeError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_rule_token(input).as_str() {
            "global" => Ok(Self::Global),
            "workspace" => Ok(Self::Workspace),
            "project" => Ok(Self::Project),
            "directory" => Ok(Self::Directory),
            "file_pattern" => Ok(Self::FilePattern),
            _ => Err(ParseRuleScopeError {
                input: input.to_owned(),
            }),
        }
    }
}

/// Maturity level of a procedural rule.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum RuleMaturity {
    /// Newly created, not yet reviewed.
    Draft,
    /// Proposed for validation.
    Candidate,
    /// Validated by positive outcomes.
    Validated,
    /// No longer recommended but kept for history.
    Deprecated,
    /// Replaced by another rule.
    Superseded,
}

impl RuleMaturity {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Draft => "draft",
            Self::Candidate => "candidate",
            Self::Validated => "validated",
            Self::Deprecated => "deprecated",
            Self::Superseded => "superseded",
        }
    }

    #[must_use]
    pub const fn all() -> [Self; 5] {
        [
            Self::Draft,
            Self::Candidate,
            Self::Validated,
            Self::Deprecated,
            Self::Superseded,
        ]
    }

    #[must_use]
    pub const fn is_active(self) -> bool {
        matches!(self, Self::Draft | Self::Candidate | Self::Validated)
    }

    #[must_use]
    pub const fn is_terminal(self) -> bool {
        matches!(self, Self::Deprecated | Self::Superseded)
    }
}

impl fmt::Display for RuleMaturity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Error when parsing an invalid rule maturity string.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseRuleMaturityError {
    input: String,
}

impl ParseRuleMaturityError {
    pub fn input(&self) -> &str {
        &self.input
    }
}

impl fmt::Display for ParseRuleMaturityError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unknown rule maturity `{}`; expected one of draft, candidate, validated, deprecated, superseded",
            self.input
        )
    }
}

impl std::error::Error for ParseRuleMaturityError {}

impl FromStr for RuleMaturity {
    type Err = ParseRuleMaturityError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_rule_token(input).as_str() {
            "draft" => Ok(Self::Draft),
            "candidate" => Ok(Self::Candidate),
            "validated" => Ok(Self::Validated),
            "deprecated" => Ok(Self::Deprecated),
            "superseded" => Ok(Self::Superseded),
            _ => Err(ParseRuleMaturityError {
                input: input.to_owned(),
            }),
        }
    }
}

/// Event that asks the rule lifecycle planner to evaluate a transition.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum RuleLifecycleTrigger {
    /// Move a draft rule into the validation queue.
    ProposeValidation,
    /// Record that the rule helped an observed outcome.
    OutcomeHelpful,
    /// Record that the rule harmed or wasted an observed outcome.
    OutcomeHarmful,
    /// Record validation evidence for the rule.
    ValidationPassed,
    /// Record that validation contradicted the rule.
    ValidationContradicted,
    /// Record explicit review approval.
    ReviewApproved,
    /// Explicitly deprecate the rule.
    Deprecate,
    /// Replace the rule with another rule.
    Supersede,
}

impl RuleLifecycleTrigger {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::ProposeValidation => "propose_validation",
            Self::OutcomeHelpful => "outcome_helpful",
            Self::OutcomeHarmful => "outcome_harmful",
            Self::ValidationPassed => "validation_passed",
            Self::ValidationContradicted => "validation_contradicted",
            Self::ReviewApproved => "review_approved",
            Self::Deprecate => "deprecate",
            Self::Supersede => "supersede",
        }
    }

    #[must_use]
    pub const fn all() -> [Self; 8] {
        [
            Self::ProposeValidation,
            Self::OutcomeHelpful,
            Self::OutcomeHarmful,
            Self::ValidationPassed,
            Self::ValidationContradicted,
            Self::ReviewApproved,
            Self::Deprecate,
            Self::Supersede,
        ]
    }
}

impl fmt::Display for RuleLifecycleTrigger {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Error when parsing an invalid rule lifecycle trigger string.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseRuleLifecycleTriggerError {
    input: String,
}

impl ParseRuleLifecycleTriggerError {
    pub fn input(&self) -> &str {
        &self.input
    }
}

impl fmt::Display for ParseRuleLifecycleTriggerError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unknown rule lifecycle trigger `{}`; expected one of propose_validation, outcome_helpful, outcome_harmful, validation_passed, validation_contradicted, review_approved, deprecate, supersede",
            self.input
        )
    }
}

impl std::error::Error for ParseRuleLifecycleTriggerError {}

impl FromStr for RuleLifecycleTrigger {
    type Err = ParseRuleLifecycleTriggerError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_rule_token(input).as_str() {
            "propose_validation" => Ok(Self::ProposeValidation),
            "outcome_helpful" => Ok(Self::OutcomeHelpful),
            "outcome_harmful" => Ok(Self::OutcomeHarmful),
            "validation_passed" => Ok(Self::ValidationPassed),
            "validation_contradicted" => Ok(Self::ValidationContradicted),
            "review_approved" => Ok(Self::ReviewApproved),
            "deprecate" => Ok(Self::Deprecate),
            "supersede" => Ok(Self::Supersede),
            _ => Err(ParseRuleLifecycleTriggerError {
                input: input.to_owned(),
            }),
        }
    }
}

/// Planned lifecycle action produced by the transition evaluator.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum RuleLifecycleAction {
    /// Keep the current maturity while recording evidence.
    Retain,
    /// Move to a stronger maturity state.
    Promote,
    /// Move to a weaker maturity state.
    Demote,
    /// Retire the rule but retain it for history.
    Deprecate,
    /// Replace the rule with another rule.
    Supersede,
    /// Reject the requested transition.
    Reject,
}

impl RuleLifecycleAction {
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Retain => "retain",
            Self::Promote => "promote",
            Self::Demote => "demote",
            Self::Deprecate => "deprecate",
            Self::Supersede => "supersede",
            Self::Reject => "reject",
        }
    }

    #[must_use]
    pub const fn all() -> [Self; 6] {
        [
            Self::Retain,
            Self::Promote,
            Self::Demote,
            Self::Deprecate,
            Self::Supersede,
            Self::Reject,
        ]
    }
}

impl fmt::Display for RuleLifecycleAction {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Error when parsing an invalid rule lifecycle action string.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseRuleLifecycleActionError {
    input: String,
}

impl ParseRuleLifecycleActionError {
    pub fn input(&self) -> &str {
        &self.input
    }
}

impl fmt::Display for ParseRuleLifecycleActionError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "unknown rule lifecycle action `{}`; expected one of retain, promote, demote, deprecate, supersede, reject",
            self.input
        )
    }
}

impl std::error::Error for ParseRuleLifecycleActionError {}

impl FromStr for RuleLifecycleAction {
    type Err = ParseRuleLifecycleActionError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        match normalized_rule_token(input).as_str() {
            "retain" => Ok(Self::Retain),
            "promote" => Ok(Self::Promote),
            "demote" => Ok(Self::Demote),
            "deprecate" => Ok(Self::Deprecate),
            "supersede" => Ok(Self::Supersede),
            "reject" => Ok(Self::Reject),
            _ => Err(ParseRuleLifecycleActionError {
                input: input.to_owned(),
            }),
        }
    }
}

/// Evidence available to a rule lifecycle transition.
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct RuleLifecycleEvidence {
    pub helpful_outcomes: u32,
    pub harmful_outcomes: u32,
    pub distinct_harmful_sources: u32,
    pub protected_rule: bool,
    pub manual_curation_approved: bool,
    pub intervening_helpful_from_harmful_sources: bool,
    pub validation_passes: u32,
    pub validation_contradictions: u32,
    pub review_approved: bool,
    pub superseding_rule_id: Option<String>,
}

impl RuleLifecycleEvidence {
    #[must_use]
    pub const fn new() -> Self {
        Self {
            helpful_outcomes: 0,
            harmful_outcomes: 0,
            distinct_harmful_sources: 0,
            protected_rule: false,
            manual_curation_approved: false,
            intervening_helpful_from_harmful_sources: false,
            validation_passes: 0,
            validation_contradictions: 0,
            review_approved: false,
            superseding_rule_id: None,
        }
    }

    #[must_use]
    pub fn with_helpful_outcomes(mut self, count: u32) -> Self {
        self.helpful_outcomes = count;
        self
    }

    #[must_use]
    pub fn with_harmful_outcomes(mut self, count: u32, distinct_sources: u32) -> Self {
        self.harmful_outcomes = count;
        self.distinct_harmful_sources = distinct_sources;
        self
    }

    #[must_use]
    pub fn with_protected_rule(mut self, protected: bool) -> Self {
        self.protected_rule = protected;
        self
    }

    #[must_use]
    pub fn with_manual_curation_approved(mut self, approved: bool) -> Self {
        self.manual_curation_approved = approved;
        self
    }

    #[must_use]
    pub fn with_intervening_helpful_from_harmful_sources(mut self, helpful: bool) -> Self {
        self.intervening_helpful_from_harmful_sources = helpful;
        self
    }

    #[must_use]
    pub fn with_validation_passes(mut self, count: u32) -> Self {
        self.validation_passes = count;
        self
    }

    #[must_use]
    pub fn with_validation_contradictions(mut self, count: u32) -> Self {
        self.validation_contradictions = count;
        self
    }

    #[must_use]
    pub fn with_review_approved(mut self, approved: bool) -> Self {
        self.review_approved = approved;
        self
    }

    #[must_use]
    pub fn with_superseding_rule(mut self, rule_id: impl Into<String>) -> Self {
        self.superseding_rule_id = Some(rule_id.into());
        self
    }

    #[must_use]
    pub const fn has_validation_and_helpful_outcome(&self) -> bool {
        self.validation_passes > 0 && self.helpful_outcomes > 0
    }

    #[must_use]
    pub const fn protected_harmful_threshold(&self) -> u32 {
        let helpful_threshold = self.helpful_outcomes.saturating_mul(2).saturating_add(1);
        if helpful_threshold > 2 {
            helpful_threshold
        } else {
            2
        }
    }

    #[must_use]
    pub const fn has_harmful_quorum(&self) -> bool {
        if self.intervening_helpful_from_harmful_sources || self.distinct_harmful_sources < 2 {
            return false;
        }
        if self.protected_rule {
            return self.manual_curation_approved
                && self.harmful_outcomes >= self.protected_harmful_threshold();
        }
        self.harmful_outcomes >= 2
    }

    #[must_use]
    pub fn has_superseding_rule(&self) -> bool {
        self.superseding_rule_id
            .as_deref()
            .is_some_and(|id| !id.trim().is_empty())
    }
}

#[derive(Clone, Copy, Debug)]
struct RuleLifecycleAllowed {
    next_maturity: RuleMaturity,
    action: RuleLifecycleAction,
    requires_curation: bool,
    confidence_delta: f64,
    utility_delta: f64,
    reason: &'static str,
}

impl RuleLifecycleAllowed {
    const fn new(
        next_maturity: RuleMaturity,
        action: RuleLifecycleAction,
        reason: &'static str,
    ) -> Self {
        Self {
            next_maturity,
            action,
            requires_curation: false,
            confidence_delta: 0.0,
            utility_delta: 0.0,
            reason,
        }
    }

    const fn requiring_curation(mut self) -> Self {
        self.requires_curation = true;
        self
    }

    const fn with_deltas(mut self, confidence_delta: f64, utility_delta: f64) -> Self {
        self.confidence_delta = confidence_delta;
        self.utility_delta = utility_delta;
        self
    }
}

/// Pure transition plan for procedural rule lifecycle changes.
#[derive(Clone, Debug, PartialEq)]
pub struct RuleLifecycleTransition {
    pub prior_maturity: RuleMaturity,
    pub next_maturity: RuleMaturity,
    pub trigger: RuleLifecycleTrigger,
    pub action: RuleLifecycleAction,
    pub allowed: bool,
    pub requires_curation: bool,
    pub audit_required: bool,
    pub confidence_delta: f64,
    pub utility_delta: f64,
    pub reason: String,
}

impl RuleLifecycleTransition {
    #[must_use]
    pub fn evaluate(
        prior_maturity: RuleMaturity,
        trigger: RuleLifecycleTrigger,
        evidence: &RuleLifecycleEvidence,
    ) -> Self {
        if prior_maturity.is_terminal() && trigger != RuleLifecycleTrigger::Supersede {
            return Self::reject(
                prior_maturity,
                trigger,
                "terminal rule states require an explicit supersession transition",
            );
        }

        match trigger {
            RuleLifecycleTrigger::ProposeValidation => {
                if prior_maturity == RuleMaturity::Draft {
                    Self::allowed(
                        prior_maturity,
                        trigger,
                        RuleLifecycleAllowed::new(
                            RuleMaturity::Candidate,
                            RuleLifecycleAction::Promote,
                            "draft rule moved into the validation queue",
                        ),
                    )
                } else {
                    Self::reject(
                        prior_maturity,
                        trigger,
                        "only draft rules can be proposed for validation",
                    )
                }
            }
            RuleLifecycleTrigger::OutcomeHelpful => Self::allowed(
                prior_maturity,
                trigger,
                RuleLifecycleAllowed::new(
                    prior_maturity,
                    RuleLifecycleAction::Retain,
                    "helpful outcome adjusts confidence and utility without silent promotion",
                )
                .with_deltas(0.04, 0.08),
            ),
            RuleLifecycleTrigger::OutcomeHarmful => {
                if evidence.has_harmful_quorum() {
                    Self::allowed(
                        prior_maturity,
                        trigger,
                        RuleLifecycleAllowed::new(
                            RuleMaturity::Deprecated,
                            RuleLifecycleAction::Deprecate,
                            "harmful outcomes from distinct sources require curation before deprecation or inversion",
                        )
                        .requiring_curation()
                        .with_deltas(-0.10, -0.12),
                    )
                } else {
                    Self::allowed(
                        prior_maturity,
                        trigger,
                        RuleLifecycleAllowed::new(
                            prior_maturity,
                            RuleLifecycleAction::Retain,
                            "harmful outcome is recorded, but distinct-source quorum is not met",
                        )
                        .with_deltas(-0.10, -0.12),
                    )
                }
            }
            RuleLifecycleTrigger::ValidationPassed => {
                if prior_maturity == RuleMaturity::Draft {
                    Self::allowed(
                        prior_maturity,
                        trigger,
                        RuleLifecycleAllowed::new(
                            RuleMaturity::Candidate,
                            RuleLifecycleAction::Promote,
                            "validation evidence promotes a draft only into curation-backed candidacy",
                        )
                        .requiring_curation()
                        .with_deltas(0.06, 0.04),
                    )
                } else if prior_maturity == RuleMaturity::Candidate
                    && evidence.has_validation_and_helpful_outcome()
                    && evidence.review_approved
                {
                    Self::allowed(
                        prior_maturity,
                        trigger,
                        RuleLifecycleAllowed::new(
                            RuleMaturity::Validated,
                            RuleLifecycleAction::Promote,
                            "candidate has helpful outcome, validation evidence, and explicit review approval",
                        )
                        .with_deltas(0.06, 0.04),
                    )
                } else if prior_maturity == RuleMaturity::Candidate
                    && evidence.has_validation_and_helpful_outcome()
                {
                    Self::allowed(
                        prior_maturity,
                        trigger,
                        RuleLifecycleAllowed::new(
                            prior_maturity,
                            RuleLifecycleAction::Retain,
                            "candidate has evidence but still needs explicit review before validation",
                        )
                        .requiring_curation()
                        .with_deltas(0.06, 0.04),
                    )
                } else {
                    Self::allowed(
                        prior_maturity,
                        trigger,
                        RuleLifecycleAllowed::new(
                            prior_maturity,
                            RuleLifecycleAction::Retain,
                            "validation evidence is incomplete for maturity promotion",
                        )
                        .requiring_curation()
                        .with_deltas(0.06, 0.04),
                    )
                }
            }
            RuleLifecycleTrigger::ValidationContradicted => {
                let next = if prior_maturity == RuleMaturity::Validated {
                    RuleMaturity::Candidate
                } else {
                    prior_maturity
                };
                let action = if next == prior_maturity {
                    RuleLifecycleAction::Retain
                } else {
                    RuleLifecycleAction::Demote
                };
                Self::allowed(
                    prior_maturity,
                    trigger,
                    RuleLifecycleAllowed::new(
                        next,
                        action,
                        "contradictory validation evidence weakens the rule and demotes validated rules to candidacy",
                    )
                    .with_deltas(-0.08, -0.05),
                )
            }
            RuleLifecycleTrigger::ReviewApproved => {
                if prior_maturity == RuleMaturity::Candidate
                    && evidence.has_validation_and_helpful_outcome()
                {
                    Self::allowed(
                        prior_maturity,
                        trigger,
                        RuleLifecycleAllowed::new(
                            RuleMaturity::Validated,
                            RuleLifecycleAction::Promote,
                            "explicit review approval completes the candidate-to-validated transition",
                        ),
                    )
                } else {
                    Self::reject(
                        prior_maturity,
                        trigger,
                        "review approval requires candidate maturity plus helpful and validation evidence",
                    )
                }
            }
            RuleLifecycleTrigger::Deprecate => Self::allowed(
                prior_maturity,
                trigger,
                RuleLifecycleAllowed::new(
                    RuleMaturity::Deprecated,
                    RuleLifecycleAction::Deprecate,
                    "explicit deprecation retires the rule while preserving history",
                )
                .with_deltas(0.0, -0.05),
            ),
            RuleLifecycleTrigger::Supersede => {
                if evidence.has_superseding_rule() {
                    Self::allowed(
                        prior_maturity,
                        trigger,
                        RuleLifecycleAllowed::new(
                            RuleMaturity::Superseded,
                            RuleLifecycleAction::Supersede,
                            "explicit supersession replaces the rule with a newer rule",
                        )
                        .with_deltas(0.0, -0.03),
                    )
                } else {
                    Self::reject(
                        prior_maturity,
                        trigger,
                        "supersession requires a non-empty superseding rule id",
                    )
                }
            }
        }
    }

    #[must_use]
    pub fn changes_maturity(&self) -> bool {
        self.prior_maturity != self.next_maturity
    }

    #[must_use]
    pub fn is_demotion(&self) -> bool {
        matches!(
            self.action,
            RuleLifecycleAction::Demote | RuleLifecycleAction::Deprecate
        )
    }

    fn allowed(
        prior_maturity: RuleMaturity,
        trigger: RuleLifecycleTrigger,
        decision: RuleLifecycleAllowed,
    ) -> Self {
        Self {
            prior_maturity,
            next_maturity: decision.next_maturity,
            trigger,
            action: decision.action,
            allowed: true,
            requires_curation: decision.requires_curation,
            audit_required: true,
            confidence_delta: decision.confidence_delta,
            utility_delta: decision.utility_delta,
            reason: decision.reason.to_owned(),
        }
    }

    fn reject(
        prior_maturity: RuleMaturity,
        trigger: RuleLifecycleTrigger,
        reason: &'static str,
    ) -> Self {
        Self {
            prior_maturity,
            next_maturity: prior_maturity,
            trigger,
            action: RuleLifecycleAction::Reject,
            allowed: false,
            requires_curation: false,
            audit_required: true,
            confidence_delta: 0.0,
            utility_delta: 0.0,
            reason: reason.to_owned(),
        }
    }
}

impl RuleMaturity {
    #[must_use]
    pub fn evaluate_lifecycle_transition(
        self,
        trigger: RuleLifecycleTrigger,
        evidence: &RuleLifecycleEvidence,
    ) -> RuleLifecycleTransition {
        RuleLifecycleTransition::evaluate(self, trigger, evidence)
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use super::{
        ParseRuleLifecycleActionError, ParseRuleLifecycleTriggerError, ParseRuleMaturityError,
        ParseRuleScopeError, RuleLifecycleAction, RuleLifecycleEvidence, RuleLifecycleTransition,
        RuleLifecycleTrigger, RuleMaturity, RuleScope,
    };

    #[test]
    fn rule_scope_round_trip_for_every_variant() {
        for scope in RuleScope::all() {
            let rendered = scope.to_string();
            assert_eq!(RuleScope::from_str(&rendered), Ok(scope));
        }
        assert_eq!(
            RuleScope::from_str(" File-Pattern "),
            Ok(RuleScope::FilePattern)
        );
        assert_eq!(
            RuleScope::from_str("filePattern"),
            Ok(RuleScope::FilePattern)
        );
        assert_eq!(
            RuleScope::from_str("FilePattern"),
            Ok(RuleScope::FilePattern)
        );
    }

    #[test]
    fn rule_scope_rejects_unknown_input() {
        let err = RuleScope::from_str("unknown_scope");
        assert!(matches!(err, Err(ParseRuleScopeError { .. })));
    }

    #[test]
    fn rule_scope_requires_pattern() {
        assert!(!RuleScope::Global.requires_pattern());
        assert!(!RuleScope::Workspace.requires_pattern());
        assert!(!RuleScope::Project.requires_pattern());
        assert!(RuleScope::Directory.requires_pattern());
        assert!(RuleScope::FilePattern.requires_pattern());
    }

    #[test]
    fn rule_maturity_round_trip_for_every_variant() {
        for maturity in RuleMaturity::all() {
            let rendered = maturity.to_string();
            assert_eq!(RuleMaturity::from_str(&rendered), Ok(maturity));
        }
        assert_eq!(
            RuleMaturity::from_str(" VALIDATED "),
            Ok(RuleMaturity::Validated)
        );
    }

    #[test]
    fn rule_maturity_rejects_unknown_input() {
        let err = RuleMaturity::from_str("unknown_maturity");
        assert!(matches!(err, Err(ParseRuleMaturityError { .. })));
    }

    #[test]
    fn rule_maturity_active_and_terminal_states() {
        assert!(RuleMaturity::Draft.is_active());
        assert!(RuleMaturity::Candidate.is_active());
        assert!(RuleMaturity::Validated.is_active());
        assert!(!RuleMaturity::Deprecated.is_active());
        assert!(!RuleMaturity::Superseded.is_active());

        assert!(!RuleMaturity::Draft.is_terminal());
        assert!(!RuleMaturity::Candidate.is_terminal());
        assert!(!RuleMaturity::Validated.is_terminal());
        assert!(RuleMaturity::Deprecated.is_terminal());
        assert!(RuleMaturity::Superseded.is_terminal());
    }

    #[test]
    fn rule_lifecycle_trigger_round_trip_for_every_variant() {
        for trigger in RuleLifecycleTrigger::all() {
            let rendered = trigger.to_string();
            assert_eq!(RuleLifecycleTrigger::from_str(&rendered), Ok(trigger));
        }
        assert_eq!(
            RuleLifecycleTrigger::from_str(" Outcome-Helpful "),
            Ok(RuleLifecycleTrigger::OutcomeHelpful)
        );
        assert_eq!(
            RuleLifecycleTrigger::from_str("validationContradicted"),
            Ok(RuleLifecycleTrigger::ValidationContradicted)
        );
        assert_eq!(
            RuleLifecycleTrigger::from_str("ReviewApproved"),
            Ok(RuleLifecycleTrigger::ReviewApproved)
        );
    }

    #[test]
    fn rule_lifecycle_trigger_rejects_unknown_input() {
        let err = RuleLifecycleTrigger::from_str("unknown_trigger");
        assert!(matches!(err, Err(ParseRuleLifecycleTriggerError { .. })));
    }

    #[test]
    fn rule_lifecycle_action_round_trip_for_every_variant() {
        for action in RuleLifecycleAction::all() {
            let rendered = action.to_string();
            assert_eq!(RuleLifecycleAction::from_str(&rendered), Ok(action));
        }
        assert_eq!(
            RuleLifecycleAction::from_str(" DEMOTE "),
            Ok(RuleLifecycleAction::Demote)
        );
    }

    #[test]
    fn rule_lifecycle_action_rejects_unknown_input() {
        let err = RuleLifecycleAction::from_str("unknown_action");
        assert!(matches!(err, Err(ParseRuleLifecycleActionError { .. })));
    }

    #[test]
    fn draft_can_be_proposed_for_validation() {
        let transition = RuleLifecycleTransition::evaluate(
            RuleMaturity::Draft,
            RuleLifecycleTrigger::ProposeValidation,
            &RuleLifecycleEvidence::new(),
        );

        assert!(transition.allowed);
        assert_eq!(transition.next_maturity, RuleMaturity::Candidate);
        assert_eq!(transition.action, RuleLifecycleAction::Promote);
        assert!(transition.changes_maturity());
    }

    #[test]
    fn candidate_requires_review_before_validated_transition() {
        let evidence = RuleLifecycleEvidence::new()
            .with_helpful_outcomes(1)
            .with_validation_passes(1);
        let transition = RuleMaturity::Candidate
            .evaluate_lifecycle_transition(RuleLifecycleTrigger::ValidationPassed, &evidence);

        assert!(transition.allowed);
        assert!(transition.requires_curation);
        assert_eq!(transition.next_maturity, RuleMaturity::Candidate);
        assert_eq!(transition.action, RuleLifecycleAction::Retain);
        assert!(!transition.changes_maturity());
    }

    #[test]
    fn candidate_with_review_and_evidence_promotes_to_validated() {
        let evidence = RuleLifecycleEvidence::new()
            .with_helpful_outcomes(2)
            .with_validation_passes(1)
            .with_review_approved(true);
        let transition = RuleLifecycleTransition::evaluate(
            RuleMaturity::Candidate,
            RuleLifecycleTrigger::ValidationPassed,
            &evidence,
        );

        assert!(transition.allowed);
        assert!(!transition.requires_curation);
        assert_eq!(transition.next_maturity, RuleMaturity::Validated);
        assert_eq!(transition.action, RuleLifecycleAction::Promote);
        assert!(transition.confidence_delta > 0.0);
    }

    #[test]
    fn harmful_outcomes_from_distinct_sources_require_curation_deprecation() {
        let evidence = RuleLifecycleEvidence::new().with_harmful_outcomes(2, 2);
        let transition = RuleLifecycleTransition::evaluate(
            RuleMaturity::Validated,
            RuleLifecycleTrigger::OutcomeHarmful,
            &evidence,
        );

        assert!(transition.allowed);
        assert!(transition.requires_curation);
        assert_eq!(transition.next_maturity, RuleMaturity::Deprecated);
        assert_eq!(transition.action, RuleLifecycleAction::Deprecate);
        assert!(transition.is_demotion());
        assert!(transition.utility_delta < 0.0);
    }

    #[test]
    fn single_harmful_outcome_records_delta_without_maturity_change() {
        let evidence = RuleLifecycleEvidence::new().with_harmful_outcomes(1, 1);
        let transition = RuleLifecycleTransition::evaluate(
            RuleMaturity::Candidate,
            RuleLifecycleTrigger::OutcomeHarmful,
            &evidence,
        );

        assert!(transition.allowed);
        assert_eq!(transition.next_maturity, RuleMaturity::Candidate);
        assert_eq!(transition.action, RuleLifecycleAction::Retain);
        assert!(transition.confidence_delta < 0.0);
        assert!(transition.utility_delta < 0.0);
    }

    #[test]
    fn harmful_quorum_requires_distinct_sources() {
        let evidence = RuleLifecycleEvidence::new().with_harmful_outcomes(4, 1);
        let transition = RuleLifecycleTransition::evaluate(
            RuleMaturity::Validated,
            RuleLifecycleTrigger::OutcomeHarmful,
            &evidence,
        );

        assert!(transition.allowed);
        assert!(!transition.requires_curation);
        assert_eq!(transition.next_maturity, RuleMaturity::Validated);
        assert_eq!(transition.action, RuleLifecycleAction::Retain);
    }

    #[test]
    fn harmful_quorum_is_blocked_by_intervening_helpful_from_same_sources() {
        let evidence = RuleLifecycleEvidence::new()
            .with_harmful_outcomes(2, 2)
            .with_intervening_helpful_from_harmful_sources(true);
        let transition = RuleLifecycleTransition::evaluate(
            RuleMaturity::Validated,
            RuleLifecycleTrigger::OutcomeHarmful,
            &evidence,
        );

        assert!(transition.allowed);
        assert!(!transition.requires_curation);
        assert_eq!(transition.next_maturity, RuleMaturity::Validated);
        assert_eq!(transition.action, RuleLifecycleAction::Retain);
    }

    #[test]
    fn protected_rule_requires_manual_curation_and_asymmetric_threshold() {
        let below_threshold = RuleLifecycleEvidence::new()
            .with_helpful_outcomes(2)
            .with_harmful_outcomes(4, 2)
            .with_protected_rule(true)
            .with_manual_curation_approved(true);
        assert_eq!(below_threshold.protected_harmful_threshold(), 5);
        assert!(!below_threshold.has_harmful_quorum());

        let without_manual_curation = RuleLifecycleEvidence::new()
            .with_helpful_outcomes(2)
            .with_harmful_outcomes(5, 2)
            .with_protected_rule(true);
        assert!(!without_manual_curation.has_harmful_quorum());

        let eligible = RuleLifecycleEvidence::new()
            .with_helpful_outcomes(2)
            .with_harmful_outcomes(5, 2)
            .with_protected_rule(true)
            .with_manual_curation_approved(true);
        let transition = RuleLifecycleTransition::evaluate(
            RuleMaturity::Validated,
            RuleLifecycleTrigger::OutcomeHarmful,
            &eligible,
        );

        assert!(transition.allowed);
        assert!(transition.requires_curation);
        assert_eq!(transition.next_maturity, RuleMaturity::Deprecated);
        assert_eq!(transition.action, RuleLifecycleAction::Deprecate);
    }

    #[test]
    fn validation_contradiction_demotes_validated_rule_to_candidate() {
        let evidence = RuleLifecycleEvidence::new().with_validation_contradictions(1);
        let transition = RuleLifecycleTransition::evaluate(
            RuleMaturity::Validated,
            RuleLifecycleTrigger::ValidationContradicted,
            &evidence,
        );

        assert!(transition.allowed);
        assert_eq!(transition.next_maturity, RuleMaturity::Candidate);
        assert_eq!(transition.action, RuleLifecycleAction::Demote);
        assert!(transition.is_demotion());
    }

    #[test]
    fn supersede_requires_non_empty_replacement_rule() {
        let missing = RuleLifecycleTransition::evaluate(
            RuleMaturity::Validated,
            RuleLifecycleTrigger::Supersede,
            &RuleLifecycleEvidence::new(),
        );
        assert!(!missing.allowed);
        assert_eq!(missing.action, RuleLifecycleAction::Reject);

        let present = RuleLifecycleTransition::evaluate(
            RuleMaturity::Validated,
            RuleLifecycleTrigger::Supersede,
            &RuleLifecycleEvidence::new().with_superseding_rule("rule_new_release"),
        );
        assert!(present.allowed);
        assert_eq!(present.next_maturity, RuleMaturity::Superseded);
        assert_eq!(present.action, RuleLifecycleAction::Supersede);
    }

    #[test]
    fn terminal_states_reject_non_supersession_transitions() {
        let transition = RuleLifecycleTransition::evaluate(
            RuleMaturity::Deprecated,
            RuleLifecycleTrigger::OutcomeHelpful,
            &RuleLifecycleEvidence::new().with_helpful_outcomes(1),
        );

        assert!(!transition.allowed);
        assert_eq!(transition.next_maturity, RuleMaturity::Deprecated);
        assert_eq!(transition.action, RuleLifecycleAction::Reject);
        assert!(transition.audit_required);
    }
}