eidetic-engine 0.15.2

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
//! Stable degradation codes (EE-240).
//!
//! Degradation codes describe conditions where `ee` continues to operate
//! but with reduced capabilities. Unlike error codes (which halt commands),
//! degradation codes explain *what's missing* and *how behavior changes*.
//!
//! Each degradation has:
//! - A stable identifier (e.g., `D001`)
//! - A subsystem that's affected
//! - A description of the degraded behavior
//! - Canonical response severity (`info` through `critical`)
//! - Whether it's recoverable without user intervention
//!
//! These codes appear in:
//! - `ee status --json` under the `degraded[]` array
//! - The `_meta.degraded` field in any response envelope
//! - Diagnostic output from `ee doctor`

use std::{fmt, str::FromStr};

use serde::{Deserialize, Serialize};

/// Canonical response-degradation severity levels.
///
/// The declaration order is the public severity order. Keep it aligned with
/// `tests/fixtures/failure_modes/SCHEMA.md` and the response-envelope contract.
#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, Ord, PartialEq, PartialOrd, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum DegradationSeverity {
    /// Purely informational; no action is required.
    #[default]
    Info,
    /// Informational, but worth surfacing to the agent.
    Low,
    /// Degraded behavior that remains non-blocking.
    Warning,
    /// The response was affected and repair is recommended.
    Medium,
    /// The response is unreliable and repair is strongly recommended.
    High,
    /// Unrecoverable degradation requiring operator action.
    Critical,
}

impl DegradationSeverity {
    /// Every canonical value in ascending severity order.
    pub const ALL: [Self; 6] = [
        Self::Info,
        Self::Low,
        Self::Warning,
        Self::Medium,
        Self::High,
        Self::Critical,
    ];

    /// Stable string representation for JSON output.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Info => "info",
            Self::Low => "low",
            Self::Warning => "warning",
            Self::Medium => "medium",
            Self::High => "high",
            Self::Critical => "critical",
        }
    }

    /// Stable zero-based rank in the canonical ordering.
    #[must_use]
    pub const fn rank(self) -> u8 {
        self as u8
    }

    /// Parse a canonical severity value, accepting surrounding whitespace and
    /// ASCII case differences but rejecting non-contract vocabulary.
    #[must_use]
    pub fn parse(s: &str) -> Option<Self> {
        match s.trim().to_ascii_lowercase().as_str() {
            "info" => Some(Self::Info),
            "low" => Some(Self::Low),
            "warning" => Some(Self::Warning),
            "medium" => Some(Self::Medium),
            "high" => Some(Self::High),
            "critical" => Some(Self::Critical),
            _ => None,
        }
    }

    /// Parse external input with an explicit lowest-severity fallback.
    ///
    /// The retired `advisory` severity maps to `low`, preserving its meaning as
    /// a real but minor limitation. Other unknown values map to `info`.
    /// Contract validation should use [`Self::parse`] or [`FromStr`] when
    /// accepting an unknown value would be unsafe.
    #[must_use]
    pub fn parse_lossy(s: &str) -> Self {
        if s.trim().eq_ignore_ascii_case("advisory") {
            Self::Low
        } else {
            Self::parse(s).unwrap_or(Self::Info)
        }
    }
}

impl FromStr for DegradationSeverity {
    type Err = ParseDegradationSeverityError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::parse(s).ok_or_else(|| ParseDegradationSeverityError {
            value: s.to_owned(),
        })
    }
}

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

/// Error returned when a value is outside the canonical severity vocabulary.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParseDegradationSeverityError {
    value: String,
}

impl fmt::Display for ParseDegradationSeverityError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "unknown degradation severity {:?}; expected info, low, warning, medium, high, or critical",
            self.value
        )
    }
}

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

/// Subsystem affected by degradation.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DegradedSubsystem {
    /// Search and retrieval (Frankensearch).
    Search,
    /// Database storage (FrankenSQLite).
    Storage,
    /// CASS session import.
    Cass,
    /// Graph analytics (FrankenNetworkX).
    Graph,
    /// Context packing.
    Pack,
    /// Memory curation.
    Curate,
    /// Policy enforcement.
    Policy,
    /// External network access.
    Network,
    /// Optional science analytics.
    Science,
}

impl DegradedSubsystem {
    /// Stable string representation.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Search => "search",
            Self::Storage => "storage",
            Self::Cass => "cass",
            Self::Graph => "graph",
            Self::Pack => "pack",
            Self::Curate => "curate",
            Self::Policy => "policy",
            Self::Network => "network",
            Self::Science => "science",
        }
    }
}

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

/// A stable degradation code.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DegradationCode {
    /// Stable identifier, e.g., "D001"
    pub id: &'static str,
    /// Affected subsystem
    pub subsystem: DegradedSubsystem,
    /// Severity level
    pub severity: DegradationSeverity,
    /// Human-readable description
    pub description: &'static str,
    /// What behavior changes in this degraded state
    pub behavior_change: &'static str,
    /// Whether auto-recovery is possible
    pub auto_recoverable: bool,
    /// Suggested repair command, if applicable
    pub repair: Option<&'static str>,
}

impl DegradationCode {
    /// Numeric portion of the code (e.g., 1 for D001).
    #[must_use]
    pub const fn number(&self) -> u16 {
        let bytes = self.id.as_bytes();
        if bytes.len() >= 4 {
            let d1 = (bytes[1] as u16).wrapping_sub(b'0' as u16);
            let d2 = (bytes[2] as u16).wrapping_sub(b'0' as u16);
            let d3 = (bytes[3] as u16).wrapping_sub(b'0' as u16);
            d1 * 100 + d2 * 10 + d3
        } else {
            0
        }
    }
}

// ============================================================================
// Degradation Code Registry
//
// Codes are grouped by subsystem. Each code is stable and should not be
// reused once assigned. Add new codes at the end of each section.
// ============================================================================

// Search degradations (D001 - D099)
pub const SEMANTIC_SEARCH_UNAVAILABLE: DegradationCode = DegradationCode {
    id: "D001",
    subsystem: DegradedSubsystem::Search,
    severity: DegradationSeverity::Warning,
    description: "Semantic search unavailable",
    behavior_change: "Falling back to lexical (BM25) search only",
    auto_recoverable: true,
    repair: Some("ee index reembed --dry-run"),
};

pub const EMBEDDING_MODEL_MISSING: DegradationCode = DegradationCode {
    id: "D002",
    subsystem: DegradedSubsystem::Search,
    severity: DegradationSeverity::Warning,
    description: "Embedding model not loaded",
    behavior_change: "Semantic similarity disabled; lexical matching only",
    auto_recoverable: false,
    repair: Some("ee index rebuild"),
};

pub const SEARCH_INDEX_STALE: DegradationCode = DegradationCode {
    id: "D003",
    subsystem: DegradedSubsystem::Search,
    severity: DegradationSeverity::Low,
    description: "Search index is behind database",
    behavior_change: "Recent memories may not appear in search results",
    auto_recoverable: true,
    repair: Some("ee index rebuild"),
};

pub const FTS5_UNAVAILABLE: DegradationCode = DegradationCode {
    id: "D004",
    subsystem: DegradedSubsystem::Search,
    severity: DegradationSeverity::Critical,
    description: "FTS5 extension not available",
    behavior_change: "Full-text search disabled; only exact matches work",
    auto_recoverable: false,
    repair: None,
};

// Storage degradations (D100 - D199)
pub const DATABASE_READ_ONLY: DegradationCode = DegradationCode {
    id: "D100",
    subsystem: DegradedSubsystem::Storage,
    severity: DegradationSeverity::Warning,
    description: "Database is in read-only mode",
    behavior_change: "Write operations will fail; reads work normally",
    auto_recoverable: false,
    repair: Some("ee doctor --fix-plan --json"),
};

pub const WAL_MODE_DISABLED: DegradationCode = DegradationCode {
    id: "D101",
    subsystem: DegradedSubsystem::Storage,
    severity: DegradationSeverity::Low,
    description: "WAL mode not enabled",
    behavior_change: "Reduced concurrent read performance",
    auto_recoverable: false,
    repair: Some("ee init --workspace . --repair-plan --json"),
};

pub const LARGE_DATABASE: DegradationCode = DegradationCode {
    id: "D102",
    subsystem: DegradedSubsystem::Storage,
    severity: DegradationSeverity::Low,
    description: "Database size exceeds recommended threshold",
    behavior_change: "Some operations may be slower",
    auto_recoverable: false,
    repair: Some("ee doctor --fix-plan --json"),
};

pub const ADVISORY_LOCK_TIMEOUT: DegradationCode = DegradationCode {
    id: "D103",
    subsystem: DegradedSubsystem::Storage,
    severity: DegradationSeverity::Warning,
    description: "Advisory lock acquisition exceeded its retry budget",
    behavior_change: "Concurrent write operation could not prove exclusive ownership",
    auto_recoverable: true,
    repair: Some("ee diag advisory-lock --workspace . --resource-type workspace --release --json"),
};

pub const SNAPSHOT_PIN_EXPIRED: DegradationCode = DegradationCode {
    id: "D104",
    subsystem: DegradedSubsystem::Storage,
    severity: DegradationSeverity::Warning,
    description: "Read snapshot pin exceeded its configured lifetime",
    behavior_change: "The stale read snapshot is poisoned so later reads fail cleanly",
    auto_recoverable: true,
    repair: Some("ee config set storage.read_pool.max_pin_duration_seconds 1"),
};

pub const SNAPSHOT_RELEASE_FAILED: DegradationCode = DegradationCode {
    id: "D105",
    subsystem: DegradedSubsystem::Storage,
    severity: DegradationSeverity::Warning,
    description: "Read snapshot release failed",
    behavior_change: "The affected pooled connection is abandoned instead of returned to the idle pool",
    auto_recoverable: true,
    repair: Some("ee doctor --workspace . --json"),
};

pub const SNAPSHOT_PIN_FORCE_RELEASED: DegradationCode = DegradationCode {
    id: "D106",
    subsystem: DegradedSubsystem::Storage,
    severity: DegradationSeverity::Warning,
    description: "Read snapshot pin was force-released during workspace close",
    behavior_change: "The remaining pinned reader is poisoned so shutdown can complete without leaking WAL frames",
    auto_recoverable: true,
    repair: Some("ee status --workspace . --json"),
};

/// Response degraded code for advisory lock acquisition timeout.
pub const ADVISORY_LOCK_TIMEOUT_CODE: &str = "advisory_lock_timeout";
/// Response degraded code for read snapshot pins held beyond their max lifetime.
pub const SNAPSHOT_PIN_EXPIRED_CODE: &str = "snapshot_pin_expired";
/// Response degraded code for failed read snapshot rollback or commit cleanup.
pub const SNAPSHOT_RELEASE_FAILED_CODE: &str = "snapshot_release_failed";
/// Response degraded code for pins force-poisoned during workspace close.
pub const SNAPSHOT_PIN_FORCE_RELEASED_CODE: &str = "snapshot_pin_force_released";

// CASS degradations (D200 - D299)
pub const CASS_NOT_FOUND: DegradationCode = DegradationCode {
    id: "D200",
    subsystem: DegradedSubsystem::Cass,
    severity: DegradationSeverity::Warning,
    description: "CASS binary not found",
    behavior_change: "Session import disabled; explicit memories work",
    auto_recoverable: false,
    repair: None,
};

pub const CASS_VERSION_MISMATCH: DegradationCode = DegradationCode {
    id: "D201",
    subsystem: DegradedSubsystem::Cass,
    severity: DegradationSeverity::Warning,
    description: "CASS version incompatible",
    behavior_change: "Session import may fail or produce unexpected results",
    auto_recoverable: false,
    repair: None,
};

pub const CASS_INDEX_STALE: DegradationCode = DegradationCode {
    id: "D202",
    subsystem: DegradedSubsystem::Cass,
    severity: DegradationSeverity::Low,
    description: "CASS index is stale",
    behavior_change: "Recent sessions may not be available for import",
    auto_recoverable: true,
    repair: Some("cass index --full"),
};

// Graph degradations (D300 - D399)
pub const GRAPH_SNAPSHOT_STALE: DegradationCode = DegradationCode {
    id: "D300",
    subsystem: DegradedSubsystem::Graph,
    severity: DegradationSeverity::Low,
    description: "Graph snapshot is stale",
    behavior_change: "Graph metrics may not reflect recent changes",
    auto_recoverable: true,
    repair: Some("ee graph centrality-refresh"),
};

pub const GRAPH_METRICS_UNAVAILABLE: DegradationCode = DegradationCode {
    id: "D301",
    subsystem: DegradedSubsystem::Graph,
    severity: DegradationSeverity::Warning,
    description: "Graph metrics not computed",
    behavior_change: "Related memories and why explanations limited",
    auto_recoverable: true,
    repair: Some("ee graph centrality-refresh"),
};

/// Response degraded code for stale PPR graph input snapshots.
pub const GRAPH_PPR_SNAPSHOT_STALE_CODE: &str = "graph_ppr_snapshot_stale";
/// Response degraded code for PPR reranking without retrieval seeds.
pub const GRAPH_PPR_EMPTY_SEED_SET_CODE: &str = "graph_ppr_empty_seed_set";
/// Response degraded code while pack PPR awaits an upstream FrankenNetworkX API.
pub const GRAPH_PPR_UPSTREAM_UNAVAILABLE_CODE: &str = "graph_ppr_upstream_unavailable";
/// Response degraded code for Pack DNA without a trust-anchor dominator.
pub const GRAPH_PACK_DNA_NO_DOMINATOR_CODE: &str = "graph_pack_dna_no_dominator";
/// Response degraded code for Pack DNA graph explanation timeout.
pub const GRAPH_PACK_DNA_TIMEOUT_CODE: &str = "graph_pack_dna_timeout";
/// Response degraded code for causal explanation requests without evidence.
pub const GRAPH_CAUSAL_NO_EVIDENCE_CODE: &str = "graph_causal_no_evidence";
/// Response degraded code for structural health with no contradiction edges.
pub const GRAPH_HEALTH_NO_CONTRADICTIONS_CODE: &str = "graph_health_no_contradictions";
/// Response degraded code for curate graph analysis on disconnected graphs.
pub const GRAPH_CURATE_DISCONNECTED_GRAPH_CODE: &str = "graph_curate_disconnected_graph";
/// Response degraded code for proximity queries across disconnected components.
pub const GRAPH_PROXIMITY_UNREACHABLE_CODE: &str = "graph_proximity_unreachable";
/// Response degraded code for dominance analysis without a revision chain.
pub const GRAPH_DOMINANCE_NO_REVISION_CHAIN_CODE: &str = "graph_dominance_no_revision_chain";
/// Response degraded code for skyline analysis with degenerate communities.
pub const GRAPH_SKYLINE_DEGENERATE_COMMUNITIES_CODE: &str = "graph_skyline_degenerate_communities";
/// Response degraded code for HITS algorithm convergence failure.
pub const GRAPH_HITS_CONVERGENCE_FAILURE_CODE: &str = "graph_hits_convergence_failure";

/// Response degraded code for conformal calibration with too little evidence.
pub const CONFORMAL_CALIBRATION_INSUFFICIENT_CODE: &str = "conformal_calibration_insufficient";
/// Response degraded code for malformed search score calibration rows.
pub const SEARCH_SCORE_CALIBRATION_ROWS_CORRUPT_CODE: &str =
    "search_score_calibration_rows_corrupt";
/// Response degraded code for oversized search score calibration JSONL.
pub const SEARCH_SCORE_CALIBRATION_FILE_TOO_LARGE_CODE: &str =
    "search_score_calibration_file_too_large";
/// Response degraded code for I/O failures reading the calibration JSONL.
///
/// Distinguishes a genuinely absent file (no calibration evidence yet) from
/// an existing file that the process could not read (permission denied,
/// invalid UTF-8, interrupted I/O, etc.). Without this code, operators
/// cannot tell whether `status: absent` means "no evidence captured" or
/// "evidence captured but I/O is broken" — bd-25z97.
pub const SEARCH_SCORE_CALIBRATION_UNREADABLE_CODE: &str = "search_score_calibration_unreadable";

/// Response degraded code for outcome feedback absorbed by the harmful
/// burst-rate guard.
///
/// The event is preserved in `feedback_quarantine` and does NOT affect
/// live scoring; the degraded entry tells agents that observed rate
/// exceeded the configured per-source cap so they can stop retrying or
/// raise the cap intentionally rather than diagnosing a silent absorb.
/// bd-3qs2i.3.1.
pub const HARMFUL_BURST_QUARANTINE_CODE: &str = "harmful_burst_quarantine";
/// Response degraded code for outcome feedback absorbed by the SPRT guard.
///
/// The event is preserved in `feedback_quarantine` and does NOT affect
/// live scoring; unlike `harmful_burst_quarantine`, this means the source's
/// recent helpful/harmful sequence crossed the sequential probability
/// quarantine threshold before the simple burst-rate cap fired.
pub const SPRT_QUARANTINE_CODE: &str = "sprt_quarantine";

// Pack degradations (D400 - D499)
pub const TOKEN_BUDGET_EXCEEDED: DegradationCode = DegradationCode {
    id: "D400",
    subsystem: DegradedSubsystem::Pack,
    severity: DegradationSeverity::Low,
    description: "Token budget exceeded",
    behavior_change: "Context pack truncated; some memories omitted",
    auto_recoverable: true,
    repair: None,
};

pub const MMR_FALLBACK: DegradationCode = DegradationCode {
    id: "D401",
    subsystem: DegradedSubsystem::Pack,
    severity: DegradationSeverity::Low,
    description: "MMR diversity selection disabled",
    behavior_change: "Pack may contain redundant memories",
    auto_recoverable: true,
    repair: None,
};

pub const PACK_BUDGET_TOO_SMALL: DegradationCode = DegradationCode {
    id: "D402",
    subsystem: DegradedSubsystem::Pack,
    severity: DegradationSeverity::Warning,
    description: "Pack budget too small",
    behavior_change: "Context pack has matching candidates but cannot fit any candidate within the requested token budget",
    auto_recoverable: true,
    repair: None,
};

// Curate degradations (D500 - D599)
pub const CURATION_QUEUE_FULL: DegradationCode = DegradationCode {
    id: "D500",
    subsystem: DegradedSubsystem::Curate,
    severity: DegradationSeverity::Low,
    description: "Curation candidate queue is full",
    behavior_change: "New candidates will be dropped until reviewed",
    auto_recoverable: false,
    repair: Some("ee curate candidates --all --json"),
};

pub const AUTO_CURATION_DISABLED: DegradationCode = DegradationCode {
    id: "D501",
    subsystem: DegradedSubsystem::Curate,
    severity: DegradationSeverity::Low,
    description: "Automatic curation disabled",
    behavior_change: "Rules will not auto-promote; manual review required",
    auto_recoverable: false,
    repair: Some("ee curate candidates --json"),
};

// Policy degradations (D600 - D699)
pub const POLICY_NOT_LOADED: DegradationCode = DegradationCode {
    id: "D600",
    subsystem: DegradedSubsystem::Policy,
    severity: DegradationSeverity::Warning,
    description: "Policy file not loaded",
    behavior_change: "Default policies in effect; custom rules ignored",
    auto_recoverable: false,
    repair: Some("ee doctor --fix-plan --json"),
};

pub const REDACTION_PATTERNS_STALE: DegradationCode = DegradationCode {
    id: "D601",
    subsystem: DegradedSubsystem::Policy,
    severity: DegradationSeverity::Low,
    description: "Redaction patterns may be outdated",
    behavior_change: "Some sensitive data may not be caught",
    auto_recoverable: false,
    repair: Some("ee doctor --fix-plan --json"),
};

// Network degradations (D700 - D799)
pub const NETWORK_UNAVAILABLE: DegradationCode = DegradationCode {
    id: "D700",
    subsystem: DegradedSubsystem::Network,
    severity: DegradationSeverity::Warning,
    description: "Network access unavailable",
    behavior_change: "Remote operations disabled; local-only mode",
    auto_recoverable: true,
    repair: None,
};

/// Response degraded code for stale or partial Agent Mail archive evidence.
pub const AGENT_MAIL_ARCHIVE_DEGRADED_CODE: &str = "agent_mail_archive_degraded";

/// Response degraded code when workspace hygiene cannot invoke git.
pub const WORKSPACE_HYGIENE_GIT_UNAVAILABLE_CODE: &str = "git_unavailable";
/// Response degraded code when workspace hygiene runs outside a git checkout.
pub const WORKSPACE_HYGIENE_GIT_NOT_REPOSITORY_CODE: &str = "git_not_repository";
/// Response degraded code when workspace hygiene omits optional metadata.
pub const WORKSPACE_HYGIENE_PARTIAL_METADATA_CODE: &str = "workspace_hygiene_partial_metadata";
/// Response degraded code when workspace hygiene skips content secret scanning.
pub const WORKSPACE_HYGIENE_SECRET_SCAN_SKIPPED_CODE: &str =
    "workspace_hygiene_secret_scan_skipped";
/// Response degraded code when workspace hygiene cannot read Agent Mail state.
pub const WORKSPACE_HYGIENE_AGENT_MAIL_UNAVAILABLE_CODE: &str =
    "workspace_hygiene_agent_mail_unavailable";
/// Response degraded code when workspace hygiene times out reading Agent Mail.
pub const WORKSPACE_HYGIENE_AGENT_MAIL_TIMEOUT_CODE: &str = "workspace_hygiene_agent_mail_timeout";
/// Response degraded code when workspace hygiene cannot read Beads state.
pub const WORKSPACE_HYGIENE_BEADS_UNAVAILABLE_CODE: &str = "workspace_hygiene_beads_unavailable";
/// Degraded code for transient Beads JSONL partial-write read races.
pub const BEADS_JSONL_PARTIAL_WRITE_TRANSIENT_CODE: &str = "beads_jsonl_partial_write_transient";
/// Response degraded code when workspace hygiene cannot parse Beads metadata.
pub const WORKSPACE_HYGIENE_BEADS_PARSE_ERROR_CODE: &str = "workspace_hygiene_beads_parse_error";
/// Response degraded code when workspace hygiene sees active Beads reservations.
pub const WORKSPACE_HYGIENE_BEADS_RESERVED_CODE: &str = "workspace_hygiene_beads_reserved";
/// Response degraded code when workspace hygiene config is invalid.
pub const WORKSPACE_HYGIENE_CONFIG_INVALID_CODE: &str = "workspace_hygiene_config_invalid";
/// Response degraded code when workspace hygiene truncates a large report.
pub const WORKSPACE_HYGIENE_OUTPUT_TRUNCATED_CODE: &str = "workspace_hygiene_output_truncated";

// Science degradations (D800 - D899)
pub const SCIENCE_BACKEND_UNAVAILABLE: DegradationCode = DegradationCode {
    id: "D800",
    subsystem: DegradedSubsystem::Science,
    severity: DegradationSeverity::Warning,
    description: "Science analytics backend unavailable",
    behavior_change: "Optional science analytics are disabled; deterministic core diagnostics still work",
    auto_recoverable: false,
    repair: Some("ee doctor --json"),
};

pub const SCIENCE_INPUT_TOO_LARGE: DegradationCode = DegradationCode {
    id: "D801",
    subsystem: DegradedSubsystem::Science,
    severity: DegradationSeverity::Warning,
    description: "Science analytics input too large",
    behavior_change: "Science analysis is skipped for oversized inputs; use a smaller sample or narrower query",
    auto_recoverable: false,
    repair: None,
};

pub const SCIENCE_BUDGET_EXCEEDED: DegradationCode = DegradationCode {
    id: "D802",
    subsystem: DegradedSubsystem::Science,
    severity: DegradationSeverity::Warning,
    description: "Science analytics budget exceeded",
    behavior_change: "Science analysis stops at the configured budget; core command output remains available",
    auto_recoverable: false,
    repair: None,
};

/// Response degraded code for missing latency evidence in perf diagnostics.
pub const PERF_LATENCY_EVIDENCE_MISSING_CODE: &str = "perf_latency_evidence_missing";
/// Response degraded code for partial latency evidence in perf diagnostics.
pub const PERF_LATENCY_EVIDENCE_PARTIAL_CODE: &str = "perf_latency_evidence_partial";

/// All registered degradation codes for enumeration.
pub const ALL_DEGRADATION_CODES: &[DegradationCode] = &[
    // Search
    SEMANTIC_SEARCH_UNAVAILABLE,
    EMBEDDING_MODEL_MISSING,
    SEARCH_INDEX_STALE,
    FTS5_UNAVAILABLE,
    // Storage
    DATABASE_READ_ONLY,
    WAL_MODE_DISABLED,
    LARGE_DATABASE,
    ADVISORY_LOCK_TIMEOUT,
    SNAPSHOT_PIN_EXPIRED,
    SNAPSHOT_RELEASE_FAILED,
    SNAPSHOT_PIN_FORCE_RELEASED,
    // CASS
    CASS_NOT_FOUND,
    CASS_VERSION_MISMATCH,
    CASS_INDEX_STALE,
    // Graph
    GRAPH_SNAPSHOT_STALE,
    GRAPH_METRICS_UNAVAILABLE,
    // Pack
    TOKEN_BUDGET_EXCEEDED,
    MMR_FALLBACK,
    PACK_BUDGET_TOO_SMALL,
    // Database
    CURATION_QUEUE_FULL,
    AUTO_CURATION_DISABLED,
    // Policy
    POLICY_NOT_LOADED,
    REDACTION_PATTERNS_STALE,
    // Network
    NETWORK_UNAVAILABLE,
    // Science
    SCIENCE_BACKEND_UNAVAILABLE,
    SCIENCE_INPUT_TOO_LARGE,
    SCIENCE_BUDGET_EXCEEDED,
];

/// Look up a degradation code by its stable ID (e.g., "D001").
#[must_use]
pub fn lookup(id: &str) -> Option<DegradationCode> {
    ALL_DEGRADATION_CODES
        .iter()
        .find(|code| code.id == id)
        .copied()
}

/// Look up degradation codes by subsystem.
#[must_use]
pub fn by_subsystem(subsystem: DegradedSubsystem) -> Vec<DegradationCode> {
    ALL_DEGRADATION_CODES
        .iter()
        .filter(|code| code.subsystem == subsystem)
        .copied()
        .collect()
}

/// Look up degradation codes by severity.
#[must_use]
pub fn by_severity(severity: DegradationSeverity) -> Vec<DegradationCode> {
    ALL_DEGRADATION_CODES
        .iter()
        .filter(|code| code.severity == severity)
        .copied()
        .collect()
}

/// Active degradation state.
///
/// Represents a degradation that's currently in effect, with optional
/// context about when it was detected and why.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ActiveDegradation {
    /// The degradation code.
    pub code: DegradationCode,
    /// When the degradation was first detected.
    pub detected_at: Option<String>,
    /// Additional context about the degradation.
    pub context: Option<String>,
}

impl ActiveDegradation {
    /// Create a new active degradation.
    #[must_use]
    pub const fn new(code: DegradationCode) -> Self {
        Self {
            code,
            detected_at: None,
            context: None,
        }
    }

    /// Builder: set detection time.
    #[must_use]
    pub fn at(mut self, timestamp: impl Into<String>) -> Self {
        self.detected_at = Some(timestamp.into());
        self
    }

    /// Builder: add context.
    #[must_use]
    pub fn with_context(mut self, context: impl Into<String>) -> Self {
        self.context = Some(context.into());
        self
    }
}

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

    type TestResult = Result<(), String>;

    fn ensure<T: std::fmt::Debug + PartialEq>(actual: T, expected: T, ctx: &str) -> TestResult {
        if actual == expected {
            Ok(())
        } else {
            Err(format!("{ctx}: expected {expected:?}, got {actual:?}"))
        }
    }

    #[test]
    fn degradation_code_ids_are_unique() -> TestResult {
        let mut seen = std::collections::HashSet::new();
        for code in ALL_DEGRADATION_CODES {
            if !seen.insert(code.id) {
                return Err(format!("Duplicate degradation code ID: {}", code.id));
            }
        }
        Ok(())
    }

    #[test]
    fn degradation_code_ids_follow_format() -> TestResult {
        for code in ALL_DEGRADATION_CODES {
            if !code.id.starts_with('D') {
                return Err(format!("Code {} does not start with D", code.id));
            }
            if code.id.len() != 4 {
                return Err(format!("Code {} is not 4 characters", code.id));
            }
        }
        Ok(())
    }

    #[test]
    fn degradation_code_numbers_are_in_range() -> TestResult {
        for code in ALL_DEGRADATION_CODES {
            let num = code.number();
            let expected_range = match code.subsystem {
                DegradedSubsystem::Search => 1..100,
                DegradedSubsystem::Storage => 100..200,
                DegradedSubsystem::Cass => 200..300,
                DegradedSubsystem::Graph => 300..400,
                DegradedSubsystem::Pack => 400..500,
                DegradedSubsystem::Curate => 500..600,
                DegradedSubsystem::Policy => 600..700,
                DegradedSubsystem::Network => 700..800,
                DegradedSubsystem::Science => 800..900,
            };
            if !expected_range.contains(&num) {
                return Err(format!(
                    "Code {} has number {} outside range {:?}",
                    code.id, num, expected_range
                ));
            }
        }
        Ok(())
    }

    #[test]
    fn lookup_finds_existing_code() -> TestResult {
        let found = lookup("D001");
        ensure(found.is_some(), true, "D001 exists")?;
        ensure(found.map(|c| c.id), Some("D001"), "found correct code")
    }

    #[test]
    fn lookup_returns_none_for_unknown() -> TestResult {
        ensure(lookup("D999"), None, "unknown code returns None")
    }

    #[test]
    fn by_subsystem_returns_correct_codes() -> TestResult {
        let search = by_subsystem(DegradedSubsystem::Search);
        ensure(search.len() >= 3, true, "at least 3 search codes")?;
        for code in &search {
            ensure(
                code.subsystem,
                DegradedSubsystem::Search,
                "correct subsystem",
            )?;
        }
        Ok(())
    }

    #[test]
    fn by_severity_returns_correct_codes() -> TestResult {
        let warnings = by_severity(DegradationSeverity::Warning);
        ensure(warnings.len() >= 3, true, "at least 3 warning codes")?;
        for code in &warnings {
            ensure(
                code.severity,
                DegradationSeverity::Warning,
                "correct severity",
            )?;
        }
        Ok(())
    }

    #[test]
    fn severity_ordering() -> TestResult {
        for pair in DegradationSeverity::ALL.windows(2) {
            ensure(pair[0] < pair[1], true, "canonical severity ordering")?;
        }
        Ok(())
    }

    #[test]
    fn severity_strings_are_stable() -> TestResult {
        let expected = [
            (DegradationSeverity::Info, "info", 0),
            (DegradationSeverity::Low, "low", 1),
            (DegradationSeverity::Warning, "warning", 2),
            (DegradationSeverity::Medium, "medium", 3),
            (DegradationSeverity::High, "high", 4),
            (DegradationSeverity::Critical, "critical", 5),
        ];
        for (severity, name, rank) in expected {
            ensure(severity.as_str(), name, "severity string")?;
            ensure(severity.rank(), rank, "severity rank")?;
            ensure(
                serde_json::to_string(&severity).map_err(|error| error.to_string())?,
                format!("\"{name}\""),
                "serialized severity",
            )?;
        }
        Ok(())
    }

    #[test]
    fn severity_parsers_distinguish_contract_values_from_fallbacks() -> TestResult {
        ensure(
            DegradationSeverity::parse(" Warning "),
            Some(DegradationSeverity::Warning),
            "strict parser trims and lowercases",
        )?;
        ensure(
            DegradationSeverity::parse("advisory"),
            None,
            "retired advisory value is not canonical",
        )?;
        ensure(
            "unknown".parse::<DegradationSeverity>().is_err(),
            true,
            "FromStr rejects unknown values",
        )?;
        ensure(
            DegradationSeverity::parse_lossy("advisory"),
            DegradationSeverity::Low,
            "retired advisory maps to low",
        )?;
        ensure(
            DegradationSeverity::parse_lossy("unknown"),
            DegradationSeverity::Info,
            "unknown values fall back to info",
        )?;
        ensure(
            serde_json::from_str::<DegradationSeverity>("\"medium\"")
                .map_err(|error| error.to_string())?,
            DegradationSeverity::Medium,
            "deserialized severity",
        )
    }

    #[test]
    fn subsystem_strings_are_stable() -> TestResult {
        ensure(DegradedSubsystem::Search.as_str(), "search", "search")?;
        ensure(DegradedSubsystem::Storage.as_str(), "storage", "storage")?;
        ensure(DegradedSubsystem::Cass.as_str(), "cass", "cass")?;
        ensure(DegradedSubsystem::Graph.as_str(), "graph", "graph")?;
        ensure(DegradedSubsystem::Pack.as_str(), "pack", "pack")?;
        ensure(DegradedSubsystem::Curate.as_str(), "curate", "curate")?;
        ensure(DegradedSubsystem::Policy.as_str(), "policy", "policy")?;
        ensure(DegradedSubsystem::Network.as_str(), "network", "network")?;
        ensure(DegradedSubsystem::Science.as_str(), "science", "science")
    }

    #[test]
    fn all_subsystems_have_at_least_one_code() -> TestResult {
        let subsystems = [
            DegradedSubsystem::Search,
            DegradedSubsystem::Storage,
            DegradedSubsystem::Cass,
            DegradedSubsystem::Graph,
            DegradedSubsystem::Pack,
            DegradedSubsystem::Curate,
            DegradedSubsystem::Policy,
            DegradedSubsystem::Network,
            DegradedSubsystem::Science,
        ];
        for sub in subsystems {
            let codes = by_subsystem(sub);
            if codes.is_empty() {
                return Err(format!("Subsystem {:?} has no codes", sub));
            }
        }
        Ok(())
    }

    #[test]
    fn science_degradation_codes_are_registered() -> TestResult {
        let science = by_subsystem(DegradedSubsystem::Science);
        ensure(
            science.iter().map(|code| code.id).collect(),
            vec!["D800", "D801", "D802"],
            "science code ids",
        )?;
        ensure(
            science
                .iter()
                .map(|code| code.description)
                .collect::<Vec<_>>(),
            vec![
                "Science analytics backend unavailable",
                "Science analytics input too large",
                "Science analytics budget exceeded",
            ],
            "science code descriptions",
        )
    }

    #[test]
    fn active_degradation_builder() {
        let active = ActiveDegradation::new(SEMANTIC_SEARCH_UNAVAILABLE)
            .at("2026-01-01T00:00:00Z")
            .with_context("Model file missing");

        assert_eq!(active.code.id, "D001");
        assert_eq!(active.detected_at, Some("2026-01-01T00:00:00Z".to_string()));
        assert_eq!(active.context, Some("Model file missing".to_string()));
    }
}