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
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
//! SRR6.46.14 — Steward periodic drift reconciliation (pure decision module).
//!
//! Opt-in user-requested steward job that periodically reconciles
//! auto-enrollment with the current tailnet state. Closes the
//! "I added a teammate but my agent never picked them up" UX gap
//! without forcing the user to manually run `ee mesh auto-enroll`
//! whenever the tailnet changes.
//!
//! This module owns the **pure decision logic**:
//!
//! - [`decide_steward_outcome`] takes the resolved facts (enabled flag,
//!   drift severity + drift kind, today's reconciliation count, daily
//!   cap) and returns the outcome (`NoOp`, `Triggered`, `Refused`,
//!   `DailyCapReached`, `NotEnabled`) plus the audit reason string
//!   the caller emits.
//! - [`apply_interval_jitter`] computes the next-fire wall-clock
//!   given the base interval and a ±jitter window. Pure: a caller-
//!   supplied jitter value drives the result, so tests can pin a
//!   deterministic seed.
//! - [`build_steward_status`] and [`apply_steward_decision_to_state`]
//!   pin the future `ee mesh steward status --json` contract without
//!   doing filesystem or CLI work in this hot checkout.
//!
//! Why opt-in (not default-on): quietly mutating peer-group config on
//! a schedule violates the SRR6.46.5 forensic-audit-row consent model.
//! With opt-in, the user actively requests the convenience and signs
//! up for the audit-trail side effect.
//!
//! The state-file IO (`~/.local/share/ee/steward/auto_enroll_state.json`),
//! the `ee mesh steward [status | run-now]` CLI surface, and the
//! daemon-side scheduler all land in follow-up slices — those touch
//! `src/cli/mod.rs`, `src/steward/mod.rs`, and the filesystem, which
//! are hot-file zones at the time this module lands.

use serde::{Deserialize, Serialize};

/// JSON schema identifier for the `ee mesh steward status --json`
/// surface. Pinned here so the future renderer and the schema-lifecycle
/// drift gate agree on exactly one string.
pub const STEWARD_STATUS_SCHEMA_V1: &str = "ee.mesh.steward.status.v1";

/// Audit event types the steward emits. Held as `&'static str`
/// constants so the audit-row caller cannot drift from the documented
/// SRR6.46.14 vocabulary.
pub mod audit_events {
    pub const RECONCILIATION_SKIPPED: &str = "mesh.steward_reconciliation_skipped";
    pub const RECONCILIATION_TRIGGERED: &str = "mesh.steward_reconciliation_triggered";
    pub const RECONCILIATION_REFUSED: &str = "mesh.steward_reconciliation_refused";
    pub const RECONCILIATION_DAILY_CAP_REACHED: &str =
        "mesh.steward_reconciliation_daily_cap_reached";
}

/// Default reconciliation interval (15 minutes), overridable via
/// `EE_MESH_STEWARD_RECONCILIATION_INTERVAL_SECONDS`.
pub const STEWARD_DEFAULT_INTERVAL_SECONDS: u64 = 900;

/// Default jitter (±60 seconds), overridable via
/// `EE_MESH_STEWARD_RECONCILIATION_JITTER_SECONDS`. Avoids the
/// "discovery thundering herd" where every machine on the tailnet
/// reconciles at the same wall-clock second.
pub const STEWARD_DEFAULT_JITTER_SECONDS: u64 = 60;

/// Default per-day reconciliation cap (100), overridable via
/// `EE_MESH_STEWARD_RECONCILIATION_MAX_DAILY`. Prevents a buggy
/// interval setting from running thousands of reconciliations.
pub const STEWARD_DEFAULT_MAX_DAILY: u64 = 100;

/// `EE_MESH_AUTO_ENROLL_ON_DEMAND` default: off. The steward may not
/// mutate peer-group config on a schedule unless the user opts in.
pub const STEWARD_AUTO_ENROLL_ON_DEMAND_ENV: &str = "EE_MESH_AUTO_ENROLL_ON_DEMAND";

pub const STEWARD_RECONCILIATION_INTERVAL_ENV: &str =
    "EE_MESH_STEWARD_RECONCILIATION_INTERVAL_SECONDS";
pub const STEWARD_RECONCILIATION_JITTER_ENV: &str = "EE_MESH_STEWARD_RECONCILIATION_JITTER_SECONDS";
pub const STEWARD_RECONCILIATION_MAX_DAILY_ENV: &str = "EE_MESH_STEWARD_RECONCILIATION_MAX_DAILY";

pub const STEWARD_AUTO_ENROLL_DISABLED_CODE: &str = "steward_auto_enroll_disabled";
pub const STEWARD_AUTO_ENROLL_DAILY_CAP_REACHED_CODE: &str =
    "steward_auto_enroll_daily_cap_reached";
pub const STEWARD_AUTO_ENROLL_CONSECUTIVE_FAILURES_CODE: &str =
    "steward_auto_enroll_consecutive_failures";

const STEWARD_CONSECUTIVE_FAILURE_WARNING_THRESHOLD: u64 = 3;

// ============================================================================
// Configuration + status contract
// ============================================================================

#[derive(Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StewardConfig {
    pub enabled: bool,
    pub interval_seconds: u64,
    pub jitter_seconds: u64,
    pub max_daily: u64,
}

impl Default for StewardConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            interval_seconds: STEWARD_DEFAULT_INTERVAL_SECONDS,
            jitter_seconds: STEWARD_DEFAULT_JITTER_SECONDS,
            max_daily: STEWARD_DEFAULT_MAX_DAILY,
        }
    }
}

impl StewardConfig {
    #[must_use]
    pub const fn enabled(self) -> bool {
        self.enabled
    }

    /// Resolve the steward config from already-read environment values.
    ///
    /// Callers must read `EE_*` variables through `src/config/env_registry.rs`;
    /// this module accepts values as data so it does not bypass the registry.
    pub fn from_env_values(
        enabled: Option<&str>,
        interval_seconds: Option<&str>,
        jitter_seconds: Option<&str>,
        max_daily: Option<&str>,
    ) -> Result<Self, StewardConfigError> {
        let defaults = Self::default();
        Ok(Self {
            enabled: parse_opt_in(STEWARD_AUTO_ENROLL_ON_DEMAND_ENV, enabled, defaults.enabled)?,
            interval_seconds: parse_positive_u64(
                STEWARD_RECONCILIATION_INTERVAL_ENV,
                interval_seconds,
                defaults.interval_seconds,
            )?,
            jitter_seconds: parse_u64(
                STEWARD_RECONCILIATION_JITTER_ENV,
                jitter_seconds,
                defaults.jitter_seconds,
            )?,
            max_daily: parse_u64(
                STEWARD_RECONCILIATION_MAX_DAILY_ENV,
                max_daily,
                defaults.max_daily,
            )?,
        })
    }
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub enum StewardConfigError {
    InvalidBool {
        env_var: &'static str,
        value: String,
    },
    InvalidNumber {
        env_var: &'static str,
        value: String,
    },
    ZeroNotAllowed {
        env_var: &'static str,
    },
}

impl StewardConfigError {
    #[must_use]
    pub const fn env_var(&self) -> &'static str {
        match self {
            Self::InvalidBool { env_var, .. }
            | Self::InvalidNumber { env_var, .. }
            | Self::ZeroNotAllowed { env_var } => env_var,
        }
    }
}

fn parse_opt_in(
    env_var: &'static str,
    value: Option<&str>,
    default: bool,
) -> Result<bool, StewardConfigError> {
    let Some(value) = value else {
        return Ok(default);
    };
    match value.trim().to_ascii_lowercase().as_str() {
        "1" | "true" | "yes" | "on" => Ok(true),
        "0" | "false" | "no" | "off" => Ok(false),
        _ => Err(StewardConfigError::InvalidBool {
            env_var,
            value: value.to_owned(),
        }),
    }
}

fn parse_positive_u64(
    env_var: &'static str,
    value: Option<&str>,
    default: u64,
) -> Result<u64, StewardConfigError> {
    let parsed = parse_u64(env_var, value, default)?;
    if parsed == 0 {
        return Err(StewardConfigError::ZeroNotAllowed { env_var });
    }
    Ok(parsed)
}

fn parse_u64(
    env_var: &'static str,
    value: Option<&str>,
    default: u64,
) -> Result<u64, StewardConfigError> {
    let Some(value) = value else {
        return Ok(default);
    };
    value
        .trim()
        .parse::<u64>()
        .map_err(|_| StewardConfigError::InvalidNumber {
            env_var,
            value: value.to_owned(),
        })
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct StewardStateSnapshot {
    pub last_reconciliation_at: Option<String>,
    pub last_reconciliation_outcome: StewardStatusOutcome,
    pub reconciliations_today: u64,
    pub consecutive_failures_24h: u64,
}

impl Default for StewardStateSnapshot {
    fn default() -> Self {
        Self {
            last_reconciliation_at: None,
            last_reconciliation_outcome: StewardStatusOutcome::NotYetRun,
            reconciliations_today: 0,
            consecutive_failures_24h: 0,
        }
    }
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StewardStatus {
    pub schema: &'static str,
    pub enabled: bool,
    pub interval_seconds: u64,
    pub last_reconciliation_at: Option<String>,
    pub last_reconciliation_outcome: StewardStatusOutcome,
    pub reconciliations_today: u64,
    pub next_reconciliation_approx_at: Option<String>,
    pub degraded: Vec<StewardDegradation>,
}

#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StewardDegradation {
    pub code: &'static str,
    pub severity: &'static str,
    pub repair: &'static str,
}

#[must_use]
pub fn build_steward_status(
    config: StewardConfig,
    state: &StewardStateSnapshot,
    next_reconciliation_approx_at: Option<String>,
) -> StewardStatus {
    StewardStatus {
        schema: STEWARD_STATUS_SCHEMA_V1,
        enabled: config.enabled,
        interval_seconds: config.interval_seconds,
        last_reconciliation_at: state.last_reconciliation_at.clone(),
        last_reconciliation_outcome: state.last_reconciliation_outcome,
        reconciliations_today: state.reconciliations_today,
        next_reconciliation_approx_at,
        degraded: steward_status_degradations(config, state),
    }
}

fn steward_status_degradations(
    config: StewardConfig,
    state: &StewardStateSnapshot,
) -> Vec<StewardDegradation> {
    let mut degraded = Vec::new();
    if !config.enabled {
        degraded.push(StewardDegradation {
            code: STEWARD_AUTO_ENROLL_DISABLED_CODE,
            severity: "info",
            repair: "Set EE_MESH_AUTO_ENROLL_ON_DEMAND=1 to enable opt-in steward reconciliation.",
        });
    }
    if config.enabled && state.reconciliations_today >= config.max_daily {
        degraded.push(StewardDegradation {
            code: STEWARD_AUTO_ENROLL_DAILY_CAP_REACHED_CODE,
            severity: "warning",
            repair: "Raise EE_MESH_STEWARD_RECONCILIATION_MAX_DAILY or investigate flapping drift.",
        });
    }
    if state.consecutive_failures_24h >= STEWARD_CONSECUTIVE_FAILURE_WARNING_THRESHOLD {
        degraded.push(StewardDegradation {
            code: STEWARD_AUTO_ENROLL_CONSECUTIVE_FAILURES_CODE,
            severity: "medium",
            repair: "Review `ee audit timeline --event-type mesh.steward_reconciliation_failed`.",
        });
    }
    degraded
}

#[must_use]
pub fn apply_steward_decision_to_state(
    mut state: StewardStateSnapshot,
    decision: StewardDecision,
    observed_at: impl Into<String>,
) -> StewardStateSnapshot {
    if decision.outcome == StewardOutcome::NotEnabled {
        return state;
    }
    state.last_reconciliation_at = Some(observed_at.into());
    state.last_reconciliation_outcome = decision.status_outcome();
    if decision.outcome.increments_reconciliation_counter() {
        state.reconciliations_today = state.reconciliations_today.saturating_add(1);
    }
    state.consecutive_failures_24h = 0;
    state
}

#[must_use]
pub fn record_steward_failure(
    mut state: StewardStateSnapshot,
    observed_at: impl Into<String>,
) -> StewardStateSnapshot {
    state.last_reconciliation_at = Some(observed_at.into());
    state.consecutive_failures_24h = state.consecutive_failures_24h.saturating_add(1);
    state
}

// ============================================================================
// Input vocabulary
// ============================================================================

/// SRR6.46.4 drift severity classes the steward consults.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DriftSeverity {
    /// `discovery == materialized` exactly and no soft-stale peers.
    None,
    /// ≤2 new peers OR transient unreachable (soft_stale).
    Info,
    /// >2 new peers OR hard-stale peers. Actionable.
    Warning,
    /// `tailnetChanged` or `manualConflictPresent`. The steward MUST
    /// refuse to auto-resolve these — they are explicit user-action
    /// signals.
    Medium,
}

impl DriftSeverity {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Info => "info",
            Self::Warning => "warning",
            Self::Medium => "medium",
        }
    }
}

/// What is causing the drift. Discriminates between the
/// auto-resolvable `Warning` cases and selects the audit-reason
/// string the steward emits.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum DriftKind {
    /// `discovery` lists peers not in `materialized`. The steward
    /// runs `ee mesh auto-enroll` to absorb them.
    NewPeersAvailable,
    /// Hard-stale peers in `materialized` per SRR6.46.13 grace
    /// period. The steward runs `ee mesh auto-enroll` to remove them.
    StalePeersInConfig,
    /// `tailnetChanged` — the host's tailnet bound differs from the
    /// one auto-enrollment was materialized against. Steward refuses;
    /// this is SRR6.46.8's user-action territory.
    TailnetChanged,
    /// `manualConflictPresent` — the user has hand-edited the
    /// peer-group binding since the last auto-enrollment. Steward
    /// refuses; auto-overwriting manual edits would violate consent.
    ManualConflictPresent,
    /// No actionable drift. Steward no-ops.
    None,
}

impl DriftKind {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NewPeersAvailable => "new_peers_available",
            Self::StalePeersInConfig => "stale_peers_in_config",
            Self::TailnetChanged => "tailnet_changed",
            Self::ManualConflictPresent => "manual_conflict_present",
            Self::None => "none",
        }
    }
}

/// Inputs to [`decide_steward_outcome`]. Pure-data; no `&Cx`, no IO.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct StewardDecisionInput {
    /// Whether `EE_MESH_AUTO_ENROLL_ON_DEMAND=1` is set. When false,
    /// the steward unconditionally no-ops with [`StewardOutcome::NotEnabled`].
    pub enabled: bool,
    pub drift_severity: DriftSeverity,
    pub drift_kind: DriftKind,
    /// Number of reconciliations the steward has already run today,
    /// per the state file's daily counter.
    pub reconciliations_today: u64,
    /// Per-day cap from `EE_MESH_STEWARD_RECONCILIATION_MAX_DAILY`.
    pub max_daily: u64,
}

// ============================================================================
// Outputs
// ============================================================================

/// Outcome of one steward pass.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StewardOutcome {
    /// `EE_MESH_AUTO_ENROLL_ON_DEMAND` is not set. The steward unwinds
    /// without consulting anything else.
    NotEnabled,
    /// Drift severity is `none` or `info`; no reconciliation needed.
    /// Emits `mesh.steward_reconciliation_skipped` with
    /// `reason: no_actionable_drift`.
    NoOp,
    /// Drift severity is `warning` AND drift kind is auto-resolvable.
    /// Emits `mesh.steward_reconciliation_triggered` with one of:
    /// `reason: new_peers`, `reason: stale_peers`. The caller runs
    /// `ee mesh auto-enroll` AFTER recording the audit row.
    Triggered,
    /// Drift severity is `medium`. Emits
    /// `mesh.steward_reconciliation_refused` with
    /// `reason: requires_user_action`. The steward MUST NOT touch
    /// peer-group config in this state — the user has to intervene.
    Refused,
    /// Today's reconciliation count has reached the cap. Emits
    /// `mesh.steward_reconciliation_daily_cap_reached`. Cap check
    /// runs before drift evaluation: a buggy interval should not
    /// thrash the audit log with one row per second.
    DailyCapReached,
}

impl StewardOutcome {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NotEnabled => "not_enabled",
            Self::NoOp => "no_op",
            Self::Triggered => "triggered",
            Self::Refused => "refused",
            Self::DailyCapReached => "daily_cap_reached",
        }
    }

    /// Map an outcome to the audit event type the caller emits.
    /// Returns `None` for [`StewardOutcome::NotEnabled`] — when the
    /// feature is off, the steward unwinds silently rather than
    /// flooding the audit log on every scheduler tick.
    #[must_use]
    pub fn audit_event_type(self) -> Option<&'static str> {
        match self {
            Self::NotEnabled => None,
            Self::NoOp => Some(audit_events::RECONCILIATION_SKIPPED),
            Self::Triggered => Some(audit_events::RECONCILIATION_TRIGGERED),
            Self::Refused => Some(audit_events::RECONCILIATION_REFUSED),
            Self::DailyCapReached => Some(audit_events::RECONCILIATION_DAILY_CAP_REACHED),
        }
    }

    /// Whether this outcome consumes one daily reconciliation slot.
    /// Only a triggered auto-enroll pass reconciles durable peer-group
    /// state; skipped/refused/cap-reached ticks remain audit/status
    /// observations.
    #[must_use]
    pub fn increments_reconciliation_counter(self) -> bool {
        matches!(self, Self::Triggered)
    }
}

/// Status-surface vocabulary for
/// `ee mesh steward status --json.lastReconciliationOutcome`.
///
/// This intentionally differs from [`StewardOutcome::as_str`]:
/// [`StewardOutcome::NoOp`] is an execution outcome, while the status
/// contract exposes the user-facing reason `no_actionable_drift`.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum StewardStatusOutcome {
    NoActionableDrift,
    Triggered,
    Refused,
    DailyCapReached,
    NotYetRun,
}

impl StewardStatusOutcome {
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            Self::NoActionableDrift => "no_actionable_drift",
            Self::Triggered => "triggered",
            Self::Refused => "refused",
            Self::DailyCapReached => "daily_cap_reached",
            Self::NotYetRun => "not_yet_run",
        }
    }
}

/// Canonical reason string the steward emits alongside the audit row.
/// Held as constants because downstream surfaces (status, doctor)
/// pattern-match on these strings.
pub mod reasons {
    pub const NO_ACTIONABLE_DRIFT: &str = "no_actionable_drift";
    pub const NEW_PEERS: &str = "new_peers";
    pub const STALE_PEERS: &str = "stale_peers";
    pub const REQUIRES_USER_ACTION: &str = "requires_user_action";
    pub const DAILY_CAP_REACHED: &str = "daily_cap_reached";
    pub const NOT_ENABLED: &str = "not_enabled";
}

/// Outcome plus the canonical reason string the caller threads into
/// the audit row's `details.reason` field.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct StewardDecision {
    pub outcome: StewardOutcome,
    pub reason: &'static str,
}

impl StewardDecision {
    /// Map a pass decision into the stable status-schema vocabulary.
    #[must_use]
    pub fn status_outcome(self) -> StewardStatusOutcome {
        match self.outcome {
            StewardOutcome::NotEnabled => StewardStatusOutcome::NotYetRun,
            StewardOutcome::NoOp => StewardStatusOutcome::NoActionableDrift,
            StewardOutcome::Triggered => StewardStatusOutcome::Triggered,
            StewardOutcome::Refused => StewardStatusOutcome::Refused,
            StewardOutcome::DailyCapReached => StewardStatusOutcome::DailyCapReached,
        }
    }
}

// ============================================================================
// Core decision function
// ============================================================================

/// Decide what the steward should do given a resolved input. Pure:
/// no IO, no audit emission, no scheduler interaction. The caller
/// records the audit row, runs `ee mesh auto-enroll` for
/// [`StewardOutcome::Triggered`], and bumps the daily counter.
///
/// Evaluation order (load-bearing):
/// 1. `enabled == false` → [`StewardOutcome::NotEnabled`]. Skip all
///    further checks; the steward is effectively a no-op.
/// 2. `reconciliations_today >= max_daily` → [`StewardOutcome::DailyCapReached`].
///    The cap check runs BEFORE drift evaluation so a buggy interval
///    cannot thrash the audit log with one row per second when
///    something is wrong.
/// 3. `drift_severity == Medium` → [`StewardOutcome::Refused`]. This
///    takes priority over a coincidentally non-actionable drift_kind
///    because Medium is the "explicit user-action signal" tier.
/// 4. `drift_severity == None | Info` → [`StewardOutcome::NoOp`].
/// 5. `drift_severity == Warning`:
///    - `drift_kind == NewPeersAvailable` → [`StewardOutcome::Triggered`]
///      with `reason: new_peers`.
///    - `drift_kind == StalePeersInConfig` → [`StewardOutcome::Triggered`]
///      with `reason: stale_peers`.
///    - any other kind → [`StewardOutcome::NoOp`] (defensive default;
///      severity claimed warning but kind is non-actionable, so the
///      steward declines rather than guess).
#[must_use]
pub fn decide_steward_outcome(input: &StewardDecisionInput) -> StewardDecision {
    if !input.enabled {
        return StewardDecision {
            outcome: StewardOutcome::NotEnabled,
            reason: reasons::NOT_ENABLED,
        };
    }

    if input.reconciliations_today >= input.max_daily {
        return StewardDecision {
            outcome: StewardOutcome::DailyCapReached,
            reason: reasons::DAILY_CAP_REACHED,
        };
    }

    if input.drift_severity == DriftSeverity::Medium {
        return StewardDecision {
            outcome: StewardOutcome::Refused,
            reason: reasons::REQUIRES_USER_ACTION,
        };
    }

    match input.drift_severity {
        DriftSeverity::None | DriftSeverity::Info => StewardDecision {
            outcome: StewardOutcome::NoOp,
            reason: reasons::NO_ACTIONABLE_DRIFT,
        },
        DriftSeverity::Warning => match input.drift_kind {
            DriftKind::NewPeersAvailable => StewardDecision {
                outcome: StewardOutcome::Triggered,
                reason: reasons::NEW_PEERS,
            },
            DriftKind::StalePeersInConfig => StewardDecision {
                outcome: StewardOutcome::Triggered,
                reason: reasons::STALE_PEERS,
            },
            // Severity claims warning but kind isn't auto-resolvable;
            // decline rather than guess. The state machine staying
            // honest matters more than chasing every drift signal.
            _ => StewardDecision {
                outcome: StewardOutcome::NoOp,
                reason: reasons::NO_ACTIONABLE_DRIFT,
            },
        },
        DriftSeverity::Medium => unreachable!("medium handled above"),
    }
}

// ============================================================================
// Interval jitter
// ============================================================================

/// Compute the next-fire delay given a base interval and a jitter
/// window. Pure: the caller supplies the jitter value (in the
/// inclusive range `[-jitter_seconds, +jitter_seconds]`) so tests
/// can pin a deterministic seed without depending on system RNG.
///
/// Returns the effective delay clamped to a minimum of 1 second:
/// even with a worst-case negative jitter, the steward should not
/// fire back-to-back.
#[must_use]
pub fn apply_interval_jitter(
    base_interval_seconds: u64,
    jitter_window_seconds: u64,
    raw_jitter_signed: i64,
) -> u64 {
    let clamped_jitter = clamp_jitter_to_window(raw_jitter_signed, jitter_window_seconds);
    let signed_base = i128::from(base_interval_seconds);
    let adjusted = signed_base.saturating_add(i128::from(clamped_jitter));
    let bounded = adjusted.max(1);
    u64::try_from(bounded).unwrap_or(u64::MAX)
}

fn clamp_jitter_to_window(raw: i64, window: u64) -> i64 {
    let window_signed = i64::try_from(window).unwrap_or(i64::MAX);
    raw.clamp(-window_signed, window_signed)
}

// ============================================================================
// Inline tests (AGENTS.md L300-302 / bd-3usjw.62 Rule 7)
// ============================================================================

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

    fn input(
        enabled: bool,
        severity: DriftSeverity,
        kind: DriftKind,
        reconciliations_today: u64,
        max_daily: u64,
    ) -> StewardDecisionInput {
        StewardDecisionInput {
            enabled,
            drift_severity: severity,
            drift_kind: kind,
            reconciliations_today,
            max_daily,
        }
    }

    // ---- config / status ---------------------------------------------------

    #[test]
    fn steward_config_defaults_to_disabled_with_documented_limits() {
        let config = StewardConfig::default();
        assert!(!config.enabled());
        assert_eq!(config.interval_seconds, STEWARD_DEFAULT_INTERVAL_SECONDS);
        assert_eq!(config.jitter_seconds, STEWARD_DEFAULT_JITTER_SECONDS);
        assert_eq!(config.max_daily, STEWARD_DEFAULT_MAX_DAILY);
    }

    #[test]
    fn steward_config_resolves_env_values_without_reading_process_env() {
        let config = StewardConfig::from_env_values(Some("1"), Some("1200"), Some("45"), Some("7"))
            .expect("valid config");
        assert!(config.enabled);
        assert_eq!(config.interval_seconds, 1200);
        assert_eq!(config.jitter_seconds, 45);
        assert_eq!(config.max_daily, 7);
    }

    #[test]
    fn steward_config_rejects_invalid_opt_in_value() {
        let error =
            StewardConfig::from_env_values(Some("maybe"), None, None, None).expect_err("invalid");
        assert_eq!(error.env_var(), STEWARD_AUTO_ENROLL_ON_DEMAND_ENV);
        assert!(matches!(error, StewardConfigError::InvalidBool { .. }));
    }

    #[test]
    fn steward_config_rejects_zero_interval_but_allows_zero_daily_cap() {
        let interval_error =
            StewardConfig::from_env_values(None, Some("0"), None, None).expect_err("zero");
        assert_eq!(
            interval_error.env_var(),
            STEWARD_RECONCILIATION_INTERVAL_ENV
        );
        assert!(matches!(
            interval_error,
            StewardConfigError::ZeroNotAllowed { .. }
        ));

        let config = StewardConfig::from_env_values(Some("true"), Some("1"), Some("0"), Some("0"))
            .expect("zero cap is a valid never-reconcile cap");
        assert_eq!(config.jitter_seconds, 0);
        assert_eq!(config.max_daily, 0);
    }

    #[test]
    fn steward_status_disabled_surfaces_info_degradation_only_when_requested() {
        let status = build_steward_status(
            StewardConfig::default(),
            &StewardStateSnapshot::default(),
            None,
        );
        assert_eq!(status.schema, STEWARD_STATUS_SCHEMA_V1);
        assert!(!status.enabled);
        assert_eq!(
            status.last_reconciliation_outcome,
            StewardStatusOutcome::NotYetRun
        );
        assert_eq!(status.degraded.len(), 1);
        assert_eq!(status.degraded[0].code, STEWARD_AUTO_ENROLL_DISABLED_CODE);
        assert_eq!(status.degraded[0].severity, "info");
    }

    #[test]
    fn steward_status_daily_cap_and_consecutive_failures_are_degraded() {
        let config = StewardConfig::from_env_values(Some("1"), Some("900"), Some("60"), Some("2"))
            .expect("valid");
        let state = StewardStateSnapshot {
            reconciliations_today: 2,
            consecutive_failures_24h: 3,
            ..StewardStateSnapshot::default()
        };

        let status = build_steward_status(config, &state, Some("2026-05-20T12:15:00Z".to_owned()));

        let codes: Vec<&str> = status
            .degraded
            .iter()
            .map(|degradation| degradation.code)
            .collect();
        assert!(codes.contains(&STEWARD_AUTO_ENROLL_DAILY_CAP_REACHED_CODE));
        assert!(codes.contains(&STEWARD_AUTO_ENROLL_CONSECUTIVE_FAILURES_CODE));
        assert_eq!(
            status.next_reconciliation_approx_at.as_deref(),
            Some("2026-05-20T12:15:00Z")
        );
    }

    #[test]
    fn applying_triggered_decision_updates_status_state_and_daily_counter() {
        let decision = decide_steward_outcome(&input(
            true,
            DriftSeverity::Warning,
            DriftKind::NewPeersAvailable,
            1,
            STEWARD_DEFAULT_MAX_DAILY,
        ));

        let state = apply_steward_decision_to_state(
            StewardStateSnapshot {
                reconciliations_today: 1,
                consecutive_failures_24h: 2,
                ..StewardStateSnapshot::default()
            },
            decision,
            "2026-05-20T12:30:00Z",
        );

        assert_eq!(
            state.last_reconciliation_at.as_deref(),
            Some("2026-05-20T12:30:00Z")
        );
        assert_eq!(
            state.last_reconciliation_outcome,
            StewardStatusOutcome::Triggered
        );
        assert_eq!(state.reconciliations_today, 2);
        assert_eq!(state.consecutive_failures_24h, 0);
    }

    #[test]
    fn disabled_decision_does_not_touch_state_file_projection() {
        let original = StewardStateSnapshot {
            last_reconciliation_at: Some("2026-05-20T11:00:00Z".to_owned()),
            last_reconciliation_outcome: StewardStatusOutcome::Refused,
            reconciliations_today: 4,
            consecutive_failures_24h: 1,
        };
        let decision = decide_steward_outcome(&input(
            false,
            DriftSeverity::Warning,
            DriftKind::NewPeersAvailable,
            4,
            STEWARD_DEFAULT_MAX_DAILY,
        ));

        assert_eq!(
            apply_steward_decision_to_state(original.clone(), decision, "2026-05-20T12:30:00Z"),
            original
        );
    }

    #[test]
    fn recording_steward_failure_increments_consecutive_failure_counter() {
        let state = record_steward_failure(
            StewardStateSnapshot {
                consecutive_failures_24h: 2,
                ..StewardStateSnapshot::default()
            },
            "2026-05-20T12:35:00Z",
        );

        assert_eq!(state.consecutive_failures_24h, 3);
        assert_eq!(
            state.last_reconciliation_at.as_deref(),
            Some("2026-05-20T12:35:00Z")
        );
    }

    // ---- enabled gate ------------------------------------------------------

    #[test]
    fn disabled_steward_short_circuits_and_emits_no_audit() {
        let decision = decide_steward_outcome(&input(
            false,
            DriftSeverity::Warning,
            DriftKind::NewPeersAvailable,
            0,
            STEWARD_DEFAULT_MAX_DAILY,
        ));
        assert_eq!(decision.outcome, StewardOutcome::NotEnabled);
        assert_eq!(decision.reason, reasons::NOT_ENABLED);
        // Audit event type is None — disabled state should not flood the log.
        assert!(decision.outcome.audit_event_type().is_none());
    }

    // ---- daily cap runs BEFORE drift evaluation ---------------------------

    #[test]
    fn daily_cap_reached_short_circuits_even_when_drift_actionable() {
        let decision = decide_steward_outcome(&input(
            true,
            DriftSeverity::Warning,
            DriftKind::NewPeersAvailable,
            100,
            100,
        ));
        assert_eq!(decision.outcome, StewardOutcome::DailyCapReached);
        assert_eq!(decision.reason, reasons::DAILY_CAP_REACHED);
        assert_eq!(
            decision.outcome.audit_event_type(),
            Some(audit_events::RECONCILIATION_DAILY_CAP_REACHED)
        );
    }

    #[test]
    fn daily_cap_zero_means_never_reconcile() {
        let decision = decide_steward_outcome(&input(
            true,
            DriftSeverity::Warning,
            DriftKind::NewPeersAvailable,
            0,
            0,
        ));
        assert_eq!(decision.outcome, StewardOutcome::DailyCapReached);
    }

    // ---- medium severity ALWAYS refuses -----------------------------------

    #[test]
    fn medium_severity_with_tailnet_change_refuses() {
        let decision = decide_steward_outcome(&input(
            true,
            DriftSeverity::Medium,
            DriftKind::TailnetChanged,
            0,
            100,
        ));
        assert_eq!(decision.outcome, StewardOutcome::Refused);
        assert_eq!(decision.reason, reasons::REQUIRES_USER_ACTION);
        assert_eq!(
            decision.outcome.audit_event_type(),
            Some(audit_events::RECONCILIATION_REFUSED)
        );
    }

    #[test]
    fn medium_severity_with_manual_conflict_refuses() {
        let decision = decide_steward_outcome(&input(
            true,
            DriftSeverity::Medium,
            DriftKind::ManualConflictPresent,
            0,
            100,
        ));
        assert_eq!(decision.outcome, StewardOutcome::Refused);
    }

    #[test]
    fn medium_severity_does_not_trip_triggered_even_with_actionable_kind() {
        // Inputs are contradictory by spec; ensure the severity wins.
        let decision = decide_steward_outcome(&input(
            true,
            DriftSeverity::Medium,
            DriftKind::NewPeersAvailable,
            0,
            100,
        ));
        assert_eq!(decision.outcome, StewardOutcome::Refused);
    }

    // ---- info / none → NoOp ------------------------------------------------

    #[test]
    fn severity_none_yields_noop() {
        let decision =
            decide_steward_outcome(&input(true, DriftSeverity::None, DriftKind::None, 5, 100));
        assert_eq!(decision.outcome, StewardOutcome::NoOp);
        assert_eq!(decision.reason, reasons::NO_ACTIONABLE_DRIFT);
        assert_eq!(
            decision.outcome.audit_event_type(),
            Some(audit_events::RECONCILIATION_SKIPPED)
        );
    }

    #[test]
    fn severity_info_yields_noop_even_with_new_peers_kind() {
        // Info severity captures ≤2 new peers — below the actionable bar.
        let decision = decide_steward_outcome(&input(
            true,
            DriftSeverity::Info,
            DriftKind::NewPeersAvailable,
            5,
            100,
        ));
        assert_eq!(decision.outcome, StewardOutcome::NoOp);
    }

    // ---- warning + actionable kind → Triggered ----------------------------

    #[test]
    fn warning_new_peers_triggers_with_new_peers_reason() {
        let decision = decide_steward_outcome(&input(
            true,
            DriftSeverity::Warning,
            DriftKind::NewPeersAvailable,
            5,
            100,
        ));
        assert_eq!(decision.outcome, StewardOutcome::Triggered);
        assert_eq!(decision.reason, reasons::NEW_PEERS);
        assert_eq!(
            decision.outcome.audit_event_type(),
            Some(audit_events::RECONCILIATION_TRIGGERED)
        );
    }

    #[test]
    fn warning_stale_peers_triggers_with_stale_peers_reason() {
        let decision = decide_steward_outcome(&input(
            true,
            DriftSeverity::Warning,
            DriftKind::StalePeersInConfig,
            5,
            100,
        ));
        assert_eq!(decision.outcome, StewardOutcome::Triggered);
        assert_eq!(decision.reason, reasons::STALE_PEERS);
    }

    #[test]
    fn warning_with_none_kind_declines_rather_than_guess() {
        // Defensive: severity says warning but kind says nothing actionable.
        let decision = decide_steward_outcome(&input(
            true,
            DriftSeverity::Warning,
            DriftKind::None,
            5,
            100,
        ));
        assert_eq!(decision.outcome, StewardOutcome::NoOp);
    }

    // ---- Schema constant + enum strings ------------------------------------

    #[test]
    fn schema_constant_matches_documented_version() {
        assert_eq!(STEWARD_STATUS_SCHEMA_V1, "ee.mesh.steward.status.v1");
    }

    #[test]
    fn enum_strings_match_snake_case_serde() {
        for variant in [
            DriftSeverity::None,
            DriftSeverity::Info,
            DriftSeverity::Warning,
            DriftSeverity::Medium,
        ] {
            let serialized = serde_json::to_string(&variant).expect("serialize");
            assert!(serialized.contains(variant.as_str()), "{serialized}");
        }
        for variant in [
            DriftKind::NewPeersAvailable,
            DriftKind::StalePeersInConfig,
            DriftKind::TailnetChanged,
            DriftKind::ManualConflictPresent,
            DriftKind::None,
        ] {
            let serialized = serde_json::to_string(&variant).expect("serialize");
            assert!(serialized.contains(variant.as_str()), "{serialized}");
        }
        for variant in [
            StewardOutcome::NotEnabled,
            StewardOutcome::NoOp,
            StewardOutcome::Triggered,
            StewardOutcome::Refused,
            StewardOutcome::DailyCapReached,
        ] {
            let serialized = serde_json::to_string(&variant).expect("serialize");
            assert!(serialized.contains(variant.as_str()), "{serialized}");
        }
        for variant in [
            StewardStatusOutcome::NoActionableDrift,
            StewardStatusOutcome::Triggered,
            StewardStatusOutcome::Refused,
            StewardStatusOutcome::DailyCapReached,
            StewardStatusOutcome::NotYetRun,
        ] {
            let serialized = serde_json::to_string(&variant).expect("serialize");
            assert!(serialized.contains(variant.as_str()), "{serialized}");
        }
    }

    #[test]
    fn status_outcome_uses_schema_vocabulary_not_execution_vocabulary() {
        let noop = decide_steward_outcome(&input(
            true,
            DriftSeverity::None,
            DriftKind::None,
            0,
            STEWARD_DEFAULT_MAX_DAILY,
        ));
        assert_eq!(noop.outcome.as_str(), "no_op");
        assert_eq!(noop.status_outcome().as_str(), reasons::NO_ACTIONABLE_DRIFT);

        let disabled = decide_steward_outcome(&input(
            false,
            DriftSeverity::Warning,
            DriftKind::NewPeersAvailable,
            0,
            STEWARD_DEFAULT_MAX_DAILY,
        ));
        assert_eq!(disabled.status_outcome(), StewardStatusOutcome::NotYetRun);
    }

    #[test]
    fn daily_counter_only_increments_after_triggered_reconciliation() {
        for outcome in [
            StewardOutcome::NotEnabled,
            StewardOutcome::NoOp,
            StewardOutcome::Refused,
            StewardOutcome::DailyCapReached,
        ] {
            assert!(!outcome.increments_reconciliation_counter());
        }
        assert!(StewardOutcome::Triggered.increments_reconciliation_counter());
    }

    // ---- Jitter ------------------------------------------------------------

    #[test]
    fn jitter_zero_returns_base_interval_unchanged() {
        assert_eq!(apply_interval_jitter(900, 60, 0), 900);
    }

    #[test]
    fn jitter_positive_within_window_adds_to_base() {
        assert_eq!(apply_interval_jitter(900, 60, 30), 930);
    }

    #[test]
    fn jitter_negative_within_window_subtracts_from_base() {
        assert_eq!(apply_interval_jitter(900, 60, -30), 870);
    }

    #[test]
    fn jitter_at_window_edge_is_honored() {
        assert_eq!(apply_interval_jitter(900, 60, 60), 960);
        assert_eq!(apply_interval_jitter(900, 60, -60), 840);
    }

    #[test]
    fn jitter_beyond_window_is_clamped() {
        assert_eq!(apply_interval_jitter(900, 60, 1000), 960);
        assert_eq!(apply_interval_jitter(900, 60, -1000), 840);
    }

    #[test]
    fn jitter_clamps_to_minimum_one_second_even_at_negative_extreme() {
        // Tiny base interval, large jitter window — must still fire eventually.
        assert_eq!(apply_interval_jitter(5, 100, -100), 1);
    }

    #[test]
    fn jitter_does_not_overflow_with_huge_inputs() {
        let result = apply_interval_jitter(u64::MAX, 1000, 999);
        // Saturates at u64::MAX rather than panicking.
        assert_eq!(result, u64::MAX);
    }
}