meerkat-runtime 0.5.2

v9 runtime control-plane for Meerkat agent lifecycle
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
//! Generated-authority module for the InputLifecycle machine.
//!
//! This module provides typed enums and a sealed mutator trait that enforces
//! all InputLifecycle state mutations flow through the machine authority.
//! Handwritten shell code calls [`InputLifecycleAuthority::apply`] and executes
//! returned effects; it cannot mutate canonical state directly.
//!
//! The transition table encoded here is the single source of truth, matching
//! the machine schema in `meerkat-machine-schema/src/catalog/input_lifecycle.rs`:
//!
//! - 9 states: Accepted, Queued, Staged, Applied, AppliedPendingConsumption,
//!   Consumed, Superseded, Coalesced, Abandoned
//! - 9 inputs: QueueAccepted, StageForRun, RollbackStaged, MarkApplied,
//!   MarkAppliedPendingConsumption, Consume, Supersede, Coalesce, Abandon
//! - 4 fields: terminal_outcome, last_run_id, last_boundary_sequence, attempt_count
//! - 4 terminal states: Consumed, Superseded, Coalesced, Abandoned
//! - 4 effects: InputLifecycleNotice, RecordTerminalOutcome,
//!   RecordRunAssociation, RecordBoundarySequence

use chrono::{DateTime, Utc};
use meerkat_core::lifecycle::{InputId, RunId};

use crate::input_state::{
    InputAbandonReason, InputLifecycleState, InputStateHistoryEntry, InputTerminalOutcome,
};

// ---------------------------------------------------------------------------
// Typed input enum -- mirrors the machine schema's input variants
// ---------------------------------------------------------------------------

/// Typed inputs for the InputLifecycle machine.
///
/// Shell code classifies raw commands into these typed inputs, then calls
/// [`InputLifecycleAuthority::apply`]. The authority decides transition legality.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InputLifecycleInput {
    /// Accepted -> Queued: input has been policy-resolved and is ready for queueing.
    QueueAccepted,
    /// Queued -> Staged: input is being staged for a specific run.
    StageForRun { run_id: RunId },
    /// Staged -> Queued: rollback on run failure.
    RollbackStaged,
    /// Staged -> Applied: the input's boundary primitive has been applied.
    MarkApplied { run_id: RunId },
    /// Applied -> AppliedPendingConsumption: boundary receipt confirms application.
    MarkAppliedPendingConsumption { boundary_sequence: u64 },
    /// AppliedPendingConsumption -> Consumed: run completed successfully.
    Consume,
    /// Queued -> Superseded: a newer input with the same supersession scope arrived.
    Supersede,
    /// Queued -> Coalesced: input was merged into an aggregate.
    Coalesce,
    /// Any non-terminal -> Abandoned: input was abandoned (retire/reset/destroy/cancel).
    Abandon { reason: InputAbandonReason },
    /// Accepted -> Consumed: shortcut for Ignore+OnAccept policy (no queue/run cycle).
    ConsumeOnAccept,
}

// ---------------------------------------------------------------------------
// Typed effect enum -- mirrors the machine schema's effect variants
// ---------------------------------------------------------------------------

/// Effects emitted by InputLifecycle transitions.
///
/// Shell code receives these from [`InputLifecycleAuthority::apply`] and is
/// responsible for executing the side effects (e.g. emitting events, persisting).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum InputLifecycleEffect {
    /// Notify observers of the new lifecycle state.
    InputLifecycleNotice { new_state: InputLifecycleState },
    /// Record the terminal outcome for this input.
    RecordTerminalOutcome { outcome: InputTerminalOutcome },
    /// Record the run association (which run touched this input).
    RecordRunAssociation { run_id: RunId },
    /// Record the boundary receipt sequence number.
    RecordBoundarySequence { boundary_sequence: u64 },
}

// ---------------------------------------------------------------------------
// Transition result
// ---------------------------------------------------------------------------

/// Successful transition outcome from the InputLifecycle authority.
#[derive(Debug)]
pub struct InputLifecycleTransition {
    /// The phase after the transition.
    pub next_phase: InputLifecycleState,
    /// Effects to be executed by shell code.
    pub effects: Vec<InputLifecycleEffect>,
}

// ---------------------------------------------------------------------------
// Error type
// ---------------------------------------------------------------------------

/// Errors from the input lifecycle authority.
#[derive(Debug, Clone, thiserror::Error)]
#[non_exhaustive]
pub enum InputLifecycleError {
    /// The transition is not valid from the current state.
    #[error("Invalid transition: {from:?} via {input} (current phase rejects this input)")]
    InvalidTransition {
        from: InputLifecycleState,
        input: String,
    },
    /// The input is already in a terminal state.
    #[error("Input is in terminal state {state:?}")]
    TerminalState { state: InputLifecycleState },
    /// A guard condition was not met.
    #[error("Guard failed: {guard} (from {from:?})")]
    GuardFailed {
        from: InputLifecycleState,
        guard: String,
    },
}

// ---------------------------------------------------------------------------
// Canonical machine state (fields)
// ---------------------------------------------------------------------------

/// Canonical machine-owned fields for InputLifecycle.
///
/// These fields are owned exclusively by the authority and cannot be mutated
/// by handwritten shell code.
/// Maximum number of stage → rollback cycles before the machine abandons the input.
///
/// This prevents unbounded `Queued → Staged → Queued` livelock when an executor
/// keeps failing on the same input. The value is part of the machine schema.
const MAX_STAGE_ATTEMPTS: u32 = 3;

#[derive(Debug, Clone)]
struct InputLifecycleFields {
    terminal_outcome: Option<InputTerminalOutcome>,
    last_run_id: Option<RunId>,
    last_boundary_sequence: Option<u64>,
    /// How many times this input has been staged for a run. Incremented on
    /// `StageForRun`, checked on `RollbackStaged`. When `attempt_count >=
    /// MAX_STAGE_ATTEMPTS`, `RollbackStaged` transitions to `Abandoned`
    /// instead of `Queued`.
    attempt_count: u32,
}

// ---------------------------------------------------------------------------
// Sealed mutator trait -- only the authority implements this
// ---------------------------------------------------------------------------

mod sealed {
    pub trait Sealed {}
}

/// Sealed trait for InputLifecycle state mutation.
///
/// Only [`InputLifecycleAuthority`] implements this. Handwritten code cannot
/// create alternative implementations, ensuring single-source-of-truth
/// semantics for lifecycle state.
pub trait InputLifecycleMutator: sealed::Sealed {
    /// Apply a typed input to the current machine state.
    ///
    /// Returns the transition result including next state and effects,
    /// or an error if the transition is not legal from the current state.
    fn apply(
        &mut self,
        input: InputLifecycleInput,
    ) -> Result<InputLifecycleTransition, InputLifecycleError>;
}

// ---------------------------------------------------------------------------
// Authority implementation
// ---------------------------------------------------------------------------

/// The canonical authority for InputLifecycle state.
///
/// Holds the canonical phase + fields and delegates all transitions through
/// the encoded transition table. The authority OWNS the canonical state --
/// callers cannot get `&mut` access to the inner fields.
#[derive(Debug, Clone)]
pub struct InputLifecycleAuthority {
    /// Canonical phase.
    phase: InputLifecycleState,
    /// Canonical machine-owned fields.
    fields: InputLifecycleFields,
    /// State transition history.
    history: Vec<InputStateHistoryEntry>,
    /// Timestamp of last state change.
    updated_at: DateTime<Utc>,
}

impl sealed::Sealed for InputLifecycleAuthority {}

impl Default for InputLifecycleAuthority {
    fn default() -> Self {
        Self::new()
    }
}

impl InputLifecycleAuthority {
    /// Create a new authority in the Accepted state.
    pub fn new() -> Self {
        Self::new_at(Utc::now())
    }

    /// Create a new authority in the Accepted state with a caller-owned timestamp.
    ///
    /// Use this when the caller already captured a canonical `now` to ensure
    /// `updated_at` is consistent with sibling timestamps (e.g., `created_at`
    /// on the owning `InputState`).
    pub fn new_at(now: DateTime<Utc>) -> Self {
        Self {
            phase: InputLifecycleState::Accepted,
            fields: InputLifecycleFields {
                terminal_outcome: None,
                last_run_id: None,
                last_boundary_sequence: None,
                attempt_count: 0,
            },
            history: Vec::new(),
            updated_at: now,
        }
    }

    /// Create an authority initialized to a specific phase (for recovery).
    pub fn with_phase(phase: InputLifecycleState) -> Self {
        Self {
            phase,
            fields: InputLifecycleFields {
                terminal_outcome: None,
                last_run_id: None,
                last_boundary_sequence: None,
                attempt_count: 0,
            },
            history: Vec::new(),
            updated_at: Utc::now(),
        }
    }

    /// Restore an authority from persisted state (for crash recovery).
    ///
    /// This reconstructs the authority from a previously-serialized snapshot,
    /// including all canonical fields and history.
    pub fn restore(
        phase: InputLifecycleState,
        terminal_outcome: Option<InputTerminalOutcome>,
        last_run_id: Option<RunId>,
        last_boundary_sequence: Option<u64>,
        attempt_count: u32,
        history: Vec<InputStateHistoryEntry>,
        updated_at: DateTime<Utc>,
    ) -> Self {
        Self {
            phase,
            fields: InputLifecycleFields {
                terminal_outcome,
                last_run_id,
                last_boundary_sequence,
                attempt_count,
            },
            history,
            updated_at,
        }
    }

    /// Current phase (read from canonical state).
    pub fn phase(&self) -> InputLifecycleState {
        self.phase
    }

    /// Whether the current phase is terminal.
    pub fn is_terminal(&self) -> bool {
        self.phase.is_terminal()
    }

    /// Current terminal outcome (if in a terminal state).
    pub fn terminal_outcome(&self) -> Option<&InputTerminalOutcome> {
        self.fields.terminal_outcome.as_ref()
    }

    /// Last run ID that touched this input.
    pub fn last_run_id(&self) -> Option<&RunId> {
        self.fields.last_run_id.as_ref()
    }

    /// Last boundary sequence number.
    pub fn last_boundary_sequence(&self) -> Option<u64> {
        self.fields.last_boundary_sequence
    }

    /// Number of times this input has been staged for a run.
    pub fn attempt_count(&self) -> u32 {
        self.fields.attempt_count
    }

    /// State transition history.
    pub fn history(&self) -> &[InputStateHistoryEntry] {
        &self.history
    }

    /// Timestamp of last state change.
    pub fn updated_at(&self) -> DateTime<Utc> {
        self.updated_at
    }

    /// Check if a transition is legal without applying it.
    pub fn can_accept(&self, input: &InputLifecycleInput) -> bool {
        self.evaluate(input).is_ok()
    }

    /// Require that the authority is in one of the given phases.
    pub fn require_phase(
        &self,
        allowed: &[InputLifecycleState],
    ) -> Result<(), InputLifecycleError> {
        if allowed.contains(&self.phase) {
            Ok(())
        } else {
            Err(InputLifecycleError::InvalidTransition {
                from: self.phase,
                input: format!("require_phase({allowed:?})"),
            })
        }
    }

    /// Evaluate a transition without committing it.
    fn evaluate(
        &self,
        input: &InputLifecycleInput,
    ) -> Result<
        (
            InputLifecycleState,
            InputLifecycleFields,
            Vec<InputLifecycleEffect>,
        ),
        InputLifecycleError,
    > {
        #[allow(clippy::enum_glob_use)]
        use InputLifecycleInput::*;
        #[allow(clippy::enum_glob_use)]
        use InputLifecycleState::*;

        let phase = self.phase;
        let mut fields = self.fields.clone();
        let mut effects = Vec::new();

        // Terminal states reject ALL inputs.
        if phase.is_terminal() {
            return Err(InputLifecycleError::TerminalState { state: phase });
        }

        let next_phase = match (phase, input) {
            // QueueAccepted: Accepted -> Queued
            (Accepted, QueueAccepted) => {
                effects.push(InputLifecycleEffect::InputLifecycleNotice { new_state: Queued });
                Queued
            }

            // StageForRun: Queued -> Staged (increments attempt_count)
            (Queued, StageForRun { run_id }) => {
                fields.last_run_id = Some(run_id.clone());
                fields.attempt_count += 1;
                effects.push(InputLifecycleEffect::InputLifecycleNotice { new_state: Staged });
                effects.push(InputLifecycleEffect::RecordRunAssociation {
                    run_id: run_id.clone(),
                });
                Staged
            }

            // RollbackStaged: Staged -> Queued (if attempts remain)
            //                  Staged -> Abandoned (if max attempts exhausted)
            (Staged, RollbackStaged) => {
                if fields.attempt_count >= MAX_STAGE_ATTEMPTS {
                    let outcome = InputTerminalOutcome::Abandoned {
                        reason: crate::input_state::InputAbandonReason::MaxAttemptsExhausted {
                            attempts: fields.attempt_count,
                        },
                    };
                    fields.terminal_outcome = Some(outcome.clone());
                    effects.push(InputLifecycleEffect::InputLifecycleNotice {
                        new_state: Abandoned,
                    });
                    effects.push(InputLifecycleEffect::RecordTerminalOutcome { outcome });
                    Abandoned
                } else {
                    effects.push(InputLifecycleEffect::InputLifecycleNotice { new_state: Queued });
                    Queued
                }
            }

            // MarkApplied: Staged -> Applied (guard: matches_last_run)
            (Staged, MarkApplied { run_id }) => {
                if self.fields.last_run_id.as_ref() != Some(run_id) {
                    return Err(InputLifecycleError::GuardFailed {
                        from: phase,
                        guard: format!(
                            "matches_last_run: expected {:?}, got {run_id:?}",
                            self.fields.last_run_id
                        ),
                    });
                }
                effects.push(InputLifecycleEffect::InputLifecycleNotice { new_state: Applied });
                Applied
            }

            // MarkAppliedPendingConsumption: Applied -> AppliedPendingConsumption
            (Applied, MarkAppliedPendingConsumption { boundary_sequence }) => {
                fields.last_boundary_sequence = Some(*boundary_sequence);
                effects.push(InputLifecycleEffect::InputLifecycleNotice {
                    new_state: AppliedPendingConsumption,
                });
                effects.push(InputLifecycleEffect::RecordBoundarySequence {
                    boundary_sequence: *boundary_sequence,
                });
                AppliedPendingConsumption
            }

            // Consume: AppliedPendingConsumption -> Consumed
            (AppliedPendingConsumption, Consume) => {
                let outcome = InputTerminalOutcome::Consumed;
                fields.terminal_outcome = Some(outcome.clone());
                effects.push(InputLifecycleEffect::InputLifecycleNotice {
                    new_state: Consumed,
                });
                effects.push(InputLifecycleEffect::RecordTerminalOutcome { outcome });
                Consumed
            }

            // Supersede: Queued -> Superseded
            (Queued, Supersede) => {
                let outcome = InputTerminalOutcome::Superseded {
                    superseded_by: InputId::new(), // placeholder, caller sets via set_terminal_outcome
                };
                fields.terminal_outcome = Some(outcome.clone());
                effects.push(InputLifecycleEffect::InputLifecycleNotice {
                    new_state: Superseded,
                });
                effects.push(InputLifecycleEffect::RecordTerminalOutcome { outcome });
                Superseded
            }

            // Coalesce: Queued -> Coalesced
            (Queued, Coalesce) => {
                let outcome = InputTerminalOutcome::Coalesced {
                    aggregate_id: InputId::new(), // placeholder, caller sets via set_terminal_outcome
                };
                fields.terminal_outcome = Some(outcome.clone());
                effects.push(InputLifecycleEffect::InputLifecycleNotice {
                    new_state: Coalesced,
                });
                effects.push(InputLifecycleEffect::RecordTerminalOutcome { outcome });
                Coalesced
            }

            // Abandon: any non-terminal -> Abandoned
            (
                Accepted | Queued | Staged | Applied | AppliedPendingConsumption,
                Abandon { reason },
            ) => {
                let outcome = InputTerminalOutcome::Abandoned {
                    reason: reason.clone(),
                };
                fields.terminal_outcome = Some(outcome.clone());
                effects.push(InputLifecycleEffect::InputLifecycleNotice {
                    new_state: Abandoned,
                });
                effects.push(InputLifecycleEffect::RecordTerminalOutcome { outcome });
                Abandoned
            }

            // ConsumeOnAccept: Accepted -> Consumed (Ignore+OnAccept shortcut)
            (Accepted, ConsumeOnAccept) => {
                let outcome = InputTerminalOutcome::Consumed;
                fields.terminal_outcome = Some(outcome.clone());
                effects.push(InputLifecycleEffect::InputLifecycleNotice {
                    new_state: Consumed,
                });
                effects.push(InputLifecycleEffect::RecordTerminalOutcome { outcome });
                Consumed
            }

            // All other combinations are illegal.
            _ => {
                return Err(InputLifecycleError::InvalidTransition {
                    from: phase,
                    input: format!("{input:?}"),
                });
            }
        };

        Ok((next_phase, fields, effects))
    }

    /// Set the terminal outcome after a transition.
    ///
    /// Used by shell code for Superseded/Coalesced which need caller-provided
    /// data (superseded_by / aggregate_id) that the authority's transition
    /// doesn't know at evaluate-time.
    pub fn set_terminal_outcome(&mut self, outcome: InputTerminalOutcome) {
        self.fields.terminal_outcome = Some(outcome);
    }

    /// Stamp receipt metadata onto the authority state.
    ///
    /// Used by the store layer after it generates an authoritative receipt
    /// with a sequence number. This is NOT a lifecycle transition -- it's
    /// operational metadata enrichment by the persistence layer.
    pub fn stamp_receipt_metadata(&mut self, run_id: RunId, boundary_sequence: u64) {
        self.fields.last_run_id = Some(run_id);
        self.fields.last_boundary_sequence = Some(boundary_sequence);
    }
}

impl InputLifecycleMutator for InputLifecycleAuthority {
    fn apply(
        &mut self,
        input: InputLifecycleInput,
    ) -> Result<InputLifecycleTransition, InputLifecycleError> {
        let from = self.phase;
        let reason = format!("{input:?}");
        let (next_phase, next_fields, effects) = self.evaluate(&input)?;

        let now = Utc::now();

        // Record history.
        self.history.push(InputStateHistoryEntry {
            timestamp: now,
            from,
            to: next_phase,
            reason: Some(reason),
        });

        // Commit: update canonical state.
        self.phase = next_phase;
        self.fields = next_fields;
        self.updated_at = now;

        Ok(InputLifecycleTransition {
            next_phase,
            effects,
        })
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(
    clippy::unwrap_used,
    clippy::expect_used,
    clippy::redundant_clone,
    clippy::panic
)]
mod tests {
    use super::*;

    fn make_authority() -> InputLifecycleAuthority {
        InputLifecycleAuthority::new()
    }

    fn make_at_phase(phase: InputLifecycleState) -> InputLifecycleAuthority {
        InputLifecycleAuthority::with_phase(phase)
    }

    // ---- Happy path: full lifecycle ----

    #[test]
    fn accepted_to_queued() {
        let mut auth = make_authority();
        let t = auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        assert_eq!(t.next_phase, InputLifecycleState::Queued);
        assert_eq!(auth.phase(), InputLifecycleState::Queued);
        assert_eq!(auth.history().len(), 1);
        assert_eq!(auth.history()[0].from, InputLifecycleState::Accepted);
        assert_eq!(auth.history()[0].to, InputLifecycleState::Queued);
    }

    #[test]
    fn queued_to_staged() {
        let mut auth = make_authority();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        let run_id = RunId::new();
        let t = auth
            .apply(InputLifecycleInput::StageForRun {
                run_id: run_id.clone(),
            })
            .unwrap();
        assert_eq!(t.next_phase, InputLifecycleState::Staged);
        assert_eq!(auth.last_run_id(), Some(&run_id));
        assert!(
            t.effects
                .iter()
                .any(|e| matches!(e, InputLifecycleEffect::RecordRunAssociation { .. }))
        );
    }

    #[test]
    fn staged_to_applied() {
        let mut auth = make_authority();
        let run_id = RunId::new();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::StageForRun {
            run_id: run_id.clone(),
        })
        .unwrap();
        let t = auth
            .apply(InputLifecycleInput::MarkApplied {
                run_id: run_id.clone(),
            })
            .unwrap();
        assert_eq!(t.next_phase, InputLifecycleState::Applied);
    }

    #[test]
    fn applied_to_applied_pending_consumption() {
        let mut auth = make_authority();
        let run_id = RunId::new();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::StageForRun {
            run_id: run_id.clone(),
        })
        .unwrap();
        auth.apply(InputLifecycleInput::MarkApplied {
            run_id: run_id.clone(),
        })
        .unwrap();
        let t = auth
            .apply(InputLifecycleInput::MarkAppliedPendingConsumption {
                boundary_sequence: 42,
            })
            .unwrap();
        assert_eq!(t.next_phase, InputLifecycleState::AppliedPendingConsumption);
        assert_eq!(auth.last_boundary_sequence(), Some(42));
        assert!(t.effects.iter().any(|e| matches!(
            e,
            InputLifecycleEffect::RecordBoundarySequence {
                boundary_sequence: 42
            }
        )));
    }

    #[test]
    fn applied_pending_to_consumed() {
        let mut auth = make_authority();
        let run_id = RunId::new();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::StageForRun {
            run_id: run_id.clone(),
        })
        .unwrap();
        auth.apply(InputLifecycleInput::MarkApplied {
            run_id: run_id.clone(),
        })
        .unwrap();
        auth.apply(InputLifecycleInput::MarkAppliedPendingConsumption {
            boundary_sequence: 1,
        })
        .unwrap();
        let t = auth.apply(InputLifecycleInput::Consume).unwrap();
        assert_eq!(t.next_phase, InputLifecycleState::Consumed);
        assert!(auth.is_terminal());
        assert!(matches!(
            auth.terminal_outcome(),
            Some(InputTerminalOutcome::Consumed)
        ));
    }

    #[test]
    fn full_happy_path_history() {
        let mut auth = make_authority();
        let run_id = RunId::new();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::StageForRun {
            run_id: run_id.clone(),
        })
        .unwrap();
        auth.apply(InputLifecycleInput::MarkApplied {
            run_id: run_id.clone(),
        })
        .unwrap();
        auth.apply(InputLifecycleInput::MarkAppliedPendingConsumption {
            boundary_sequence: 1,
        })
        .unwrap();
        auth.apply(InputLifecycleInput::Consume).unwrap();
        assert_eq!(auth.history().len(), 5);
    }

    // ---- Staged rollback ----

    #[test]
    fn staged_to_queued_rollback() {
        let mut auth = make_authority();
        let run_id = RunId::new();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::StageForRun {
            run_id: run_id.clone(),
        })
        .unwrap();
        let t = auth.apply(InputLifecycleInput::RollbackStaged).unwrap();
        assert_eq!(t.next_phase, InputLifecycleState::Queued);
        assert_eq!(auth.phase(), InputLifecycleState::Queued);
    }

    // ---- MarkApplied guard: matches_last_run ----

    #[test]
    fn mark_applied_rejects_wrong_run_id() {
        let mut auth = make_authority();
        let run_id = RunId::new();
        let wrong_run_id = RunId::new();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::StageForRun {
            run_id: run_id.clone(),
        })
        .unwrap();
        let result = auth.apply(InputLifecycleInput::MarkApplied {
            run_id: wrong_run_id,
        });
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            InputLifecycleError::GuardFailed { .. }
        ));
        // Phase unchanged on failure.
        assert_eq!(auth.phase(), InputLifecycleState::Staged);
    }

    // ---- Hard rule: AppliedPendingConsumption -> Queued REJECTED ----

    #[test]
    fn applied_pending_to_queued_rejected() {
        let mut auth = make_authority();
        let run_id = RunId::new();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::StageForRun {
            run_id: run_id.clone(),
        })
        .unwrap();
        auth.apply(InputLifecycleInput::MarkApplied {
            run_id: run_id.clone(),
        })
        .unwrap();
        auth.apply(InputLifecycleInput::MarkAppliedPendingConsumption {
            boundary_sequence: 1,
        })
        .unwrap();

        let result = auth.apply(InputLifecycleInput::RollbackStaged);
        assert!(result.is_err());
        assert_eq!(auth.phase(), InputLifecycleState::AppliedPendingConsumption);
    }

    // ---- Terminal states reject ALL transitions ----

    #[test]
    fn consumed_rejects_all() {
        let mut auth = make_authority();
        let run_id = RunId::new();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::StageForRun {
            run_id: run_id.clone(),
        })
        .unwrap();
        auth.apply(InputLifecycleInput::MarkApplied {
            run_id: run_id.clone(),
        })
        .unwrap();
        auth.apply(InputLifecycleInput::MarkAppliedPendingConsumption {
            boundary_sequence: 1,
        })
        .unwrap();
        auth.apply(InputLifecycleInput::Consume).unwrap();

        let result = auth.apply(InputLifecycleInput::QueueAccepted);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            InputLifecycleError::TerminalState { .. }
        ));
    }

    #[test]
    fn superseded_rejects_all() {
        let mut auth = make_authority();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::Supersede).unwrap();
        assert!(auth.is_terminal());

        let result = auth.apply(InputLifecycleInput::QueueAccepted);
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            InputLifecycleError::TerminalState { .. }
        ));
    }

    #[test]
    fn coalesced_rejects_all() {
        let mut auth = make_authority();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::Coalesce).unwrap();
        assert!(auth.is_terminal());

        let result = auth.apply(InputLifecycleInput::QueueAccepted);
        assert!(result.is_err());
    }

    #[test]
    fn abandoned_rejects_all() {
        let mut auth = make_authority();
        auth.apply(InputLifecycleInput::Abandon {
            reason: InputAbandonReason::Retired,
        })
        .unwrap();
        assert!(auth.is_terminal());

        let result = auth.apply(InputLifecycleInput::QueueAccepted);
        assert!(result.is_err());
    }

    // ---- Abandon from various states ----

    #[test]
    fn abandon_from_accepted() {
        let mut auth = make_authority();
        let t = auth
            .apply(InputLifecycleInput::Abandon {
                reason: InputAbandonReason::Retired,
            })
            .unwrap();
        assert_eq!(t.next_phase, InputLifecycleState::Abandoned);
        assert!(matches!(
            auth.terminal_outcome(),
            Some(InputTerminalOutcome::Abandoned {
                reason: InputAbandonReason::Retired,
            })
        ));
    }

    #[test]
    fn abandon_from_queued() {
        let mut auth = make_authority();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        let t = auth
            .apply(InputLifecycleInput::Abandon {
                reason: InputAbandonReason::Reset,
            })
            .unwrap();
        assert_eq!(t.next_phase, InputLifecycleState::Abandoned);
    }

    #[test]
    fn abandon_from_staged() {
        let mut auth = make_authority();
        let run_id = RunId::new();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::StageForRun {
            run_id: run_id.clone(),
        })
        .unwrap();
        let t = auth
            .apply(InputLifecycleInput::Abandon {
                reason: InputAbandonReason::Destroyed,
            })
            .unwrap();
        assert_eq!(t.next_phase, InputLifecycleState::Abandoned);
    }

    #[test]
    fn abandon_from_applied() {
        let mut auth = make_authority();
        let run_id = RunId::new();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::StageForRun {
            run_id: run_id.clone(),
        })
        .unwrap();
        auth.apply(InputLifecycleInput::MarkApplied {
            run_id: run_id.clone(),
        })
        .unwrap();
        let t = auth
            .apply(InputLifecycleInput::Abandon {
                reason: InputAbandonReason::Cancelled,
            })
            .unwrap();
        assert_eq!(t.next_phase, InputLifecycleState::Abandoned);
    }

    #[test]
    fn abandon_from_applied_pending() {
        let mut auth = make_authority();
        let run_id = RunId::new();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::StageForRun {
            run_id: run_id.clone(),
        })
        .unwrap();
        auth.apply(InputLifecycleInput::MarkApplied {
            run_id: run_id.clone(),
        })
        .unwrap();
        auth.apply(InputLifecycleInput::MarkAppliedPendingConsumption {
            boundary_sequence: 1,
        })
        .unwrap();
        let t = auth
            .apply(InputLifecycleInput::Abandon {
                reason: InputAbandonReason::Retired,
            })
            .unwrap();
        assert_eq!(t.next_phase, InputLifecycleState::Abandoned);
    }

    // ---- ConsumeOnAccept (Ignore + OnAccept) ----

    #[test]
    fn consume_on_accept_from_accepted() {
        let mut auth = make_authority();
        let t = auth.apply(InputLifecycleInput::ConsumeOnAccept).unwrap();
        assert_eq!(t.next_phase, InputLifecycleState::Consumed);
        assert!(auth.is_terminal());
        assert!(matches!(
            auth.terminal_outcome(),
            Some(InputTerminalOutcome::Consumed)
        ));
    }

    #[test]
    fn consume_on_accept_from_queued_rejected() {
        let mut auth = make_authority();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        let result = auth.apply(InputLifecycleInput::ConsumeOnAccept);
        assert!(result.is_err());
    }

    // ---- Invalid transitions ----

    #[test]
    fn accepted_to_staged_invalid() {
        let mut auth = make_authority();
        let result = auth.apply(InputLifecycleInput::StageForRun {
            run_id: RunId::new(),
        });
        assert!(result.is_err());
    }

    #[test]
    fn accepted_to_applied_invalid() {
        let mut auth = make_authority();
        let result = auth.apply(InputLifecycleInput::MarkApplied {
            run_id: RunId::new(),
        });
        assert!(result.is_err());
    }

    #[test]
    fn queued_to_applied_invalid() {
        let mut auth = make_authority();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        let result = auth.apply(InputLifecycleInput::MarkApplied {
            run_id: RunId::new(),
        });
        assert!(result.is_err());
    }

    #[test]
    fn queued_to_consumed_invalid() {
        let mut auth = make_authority();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        let result = auth.apply(InputLifecycleInput::Consume);
        assert!(result.is_err());
    }

    // ---- Supersede / Coalesce ----

    #[test]
    fn supersede_from_queued() {
        let mut auth = make_authority();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        let t = auth.apply(InputLifecycleInput::Supersede).unwrap();
        assert_eq!(t.next_phase, InputLifecycleState::Superseded);
        assert!(auth.is_terminal());
        assert!(
            t.effects
                .iter()
                .any(|e| matches!(e, InputLifecycleEffect::RecordTerminalOutcome { .. }))
        );
    }

    #[test]
    fn supersede_from_accepted_rejected() {
        let mut auth = make_authority();
        let result = auth.apply(InputLifecycleInput::Supersede);
        assert!(result.is_err());
    }

    #[test]
    fn coalesce_from_queued() {
        let mut auth = make_authority();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        let t = auth.apply(InputLifecycleInput::Coalesce).unwrap();
        assert_eq!(t.next_phase, InputLifecycleState::Coalesced);
        assert!(auth.is_terminal());
    }

    #[test]
    fn coalesce_from_accepted_rejected() {
        let mut auth = make_authority();
        let result = auth.apply(InputLifecycleInput::Coalesce);
        assert!(result.is_err());
    }

    // ---- Set terminal outcome ----

    #[test]
    fn set_terminal_outcome_superseded() {
        let mut auth = make_authority();
        let superseder = InputId::new();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::Supersede).unwrap();
        auth.set_terminal_outcome(InputTerminalOutcome::Superseded {
            superseded_by: superseder.clone(),
        });
        match auth.terminal_outcome() {
            Some(InputTerminalOutcome::Superseded { superseded_by }) => {
                assert_eq!(superseded_by, &superseder);
            }
            other => panic!("expected Superseded, got {other:?}"),
        }
    }

    #[test]
    fn set_terminal_outcome_coalesced() {
        let mut auth = make_authority();
        let aggregate = InputId::new();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::Coalesce).unwrap();
        auth.set_terminal_outcome(InputTerminalOutcome::Coalesced {
            aggregate_id: aggregate.clone(),
        });
        match auth.terminal_outcome() {
            Some(InputTerminalOutcome::Coalesced { aggregate_id }) => {
                assert_eq!(aggregate_id, &aggregate);
            }
            other => panic!("expected Coalesced, got {other:?}"),
        }
    }

    // ---- History recording ----

    #[test]
    fn history_records_reason() {
        let mut auth = make_authority();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        assert!(auth.history()[0].reason.is_some());
        assert!(
            auth.history()[0]
                .reason
                .as_deref()
                .is_some_and(|r| r.contains("QueueAccepted"))
        );
    }

    #[test]
    fn history_records_timestamps() {
        let mut auth = make_authority();
        let before = Utc::now();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        let after = Utc::now();
        assert!(auth.history()[0].timestamp >= before);
        assert!(auth.history()[0].timestamp <= after);
    }

    // ---- can_accept probing ----

    #[test]
    fn can_accept_probes_without_mutation() {
        let auth = make_authority();
        assert!(auth.can_accept(&InputLifecycleInput::QueueAccepted));
        assert!(!auth.can_accept(&InputLifecycleInput::Consume));
        // Phase is still Accepted -- no mutation.
        assert_eq!(auth.phase(), InputLifecycleState::Accepted);
    }

    // ---- require_phase ----

    #[test]
    fn require_phase_accepts_allowed() {
        let auth = make_authority();
        assert!(
            auth.require_phase(&[InputLifecycleState::Accepted, InputLifecycleState::Queued])
                .is_ok()
        );
    }

    #[test]
    fn require_phase_rejects_disallowed() {
        let auth = make_authority();
        let result = auth.require_phase(&[InputLifecycleState::Queued]);
        assert!(matches!(
            result,
            Err(InputLifecycleError::InvalidTransition { .. })
        ));
    }

    // ---- Phase unchanged on failure ----

    #[test]
    fn phase_unchanged_on_rejected_transition() {
        let mut auth = make_authority();
        let _ = auth.apply(InputLifecycleInput::Consume);
        assert_eq!(auth.phase(), InputLifecycleState::Accepted);
        assert!(auth.history().is_empty());
    }

    // ---- Restore from persisted state ----

    #[test]
    fn restore_preserves_all_fields() {
        let run_id = RunId::new();
        let auth = InputLifecycleAuthority::restore(
            InputLifecycleState::Applied,
            None,
            Some(run_id.clone()),
            Some(42),
            2, // attempt_count
            vec![InputStateHistoryEntry {
                timestamp: Utc::now(),
                from: InputLifecycleState::Accepted,
                to: InputLifecycleState::Queued,
                reason: Some("restored".into()),
            }],
            Utc::now(),
        );
        assert_eq!(auth.phase(), InputLifecycleState::Applied);
        assert_eq!(auth.last_run_id(), Some(&run_id));
        assert_eq!(auth.last_boundary_sequence(), Some(42));
        assert_eq!(auth.attempt_count(), 2);
        assert_eq!(auth.history().len(), 1);
    }

    #[test]
    fn restore_preserves_attempt_count_for_retry_bound() {
        // Regression test: attempt_count must survive recovery so that
        // MAX_STAGE_ATTEMPTS is not reset on restart.
        let auth = InputLifecycleAuthority::restore(
            InputLifecycleState::Queued,
            None,
            None,
            None,
            2, // 2 prior attempts
            Vec::new(),
            Utc::now(),
        );

        // One more stage + rollback should push to Abandoned (3 >= MAX_STAGE_ATTEMPTS)
        let mut auth = auth;
        auth.apply(InputLifecycleInput::StageForRun {
            run_id: RunId::new(),
        })
        .unwrap();
        assert_eq!(auth.attempt_count(), 3);

        let t = auth.apply(InputLifecycleInput::RollbackStaged).unwrap();
        assert_eq!(
            t.next_phase,
            InputLifecycleState::Abandoned,
            "after 3 attempts (2 restored + 1 new), rollback should abandon"
        );
    }

    // ---- Abandon from all non-terminal states ----

    #[test]
    fn abandon_from_all_non_terminal_states() {
        for phase in [
            InputLifecycleState::Accepted,
            InputLifecycleState::Queued,
            InputLifecycleState::Staged,
            InputLifecycleState::Applied,
            InputLifecycleState::AppliedPendingConsumption,
        ] {
            let mut auth = make_at_phase(phase);
            let t = auth.apply(InputLifecycleInput::Abandon {
                reason: InputAbandonReason::Destroyed,
            });
            assert!(
                t.is_ok(),
                "abandon should succeed from {phase:?}, got {t:?}"
            );
            assert!(auth.is_terminal());
        }
    }

    // ---- Abandon from terminal states rejected ----

    #[test]
    fn abandon_from_terminal_states_rejected() {
        for phase in [
            InputLifecycleState::Consumed,
            InputLifecycleState::Superseded,
            InputLifecycleState::Coalesced,
            InputLifecycleState::Abandoned,
        ] {
            let mut auth = make_at_phase(phase);
            let result = auth.apply(InputLifecycleInput::Abandon {
                reason: InputAbandonReason::Destroyed,
            });
            assert!(
                result.is_err(),
                "abandon should be rejected from terminal {phase:?}"
            );
        }
    }

    // ---- Effects emitted correctly ----

    #[test]
    fn consume_emits_notice_and_terminal_outcome() {
        let mut auth = make_authority();
        let run_id = RunId::new();
        auth.apply(InputLifecycleInput::QueueAccepted).unwrap();
        auth.apply(InputLifecycleInput::StageForRun {
            run_id: run_id.clone(),
        })
        .unwrap();
        auth.apply(InputLifecycleInput::MarkApplied {
            run_id: run_id.clone(),
        })
        .unwrap();
        auth.apply(InputLifecycleInput::MarkAppliedPendingConsumption {
            boundary_sequence: 1,
        })
        .unwrap();
        let t = auth.apply(InputLifecycleInput::Consume).unwrap();
        assert!(t.effects.iter().any(|e| matches!(
            e,
            InputLifecycleEffect::InputLifecycleNotice {
                new_state: InputLifecycleState::Consumed
            }
        )));
        assert!(t.effects.iter().any(|e| matches!(
            e,
            InputLifecycleEffect::RecordTerminalOutcome {
                outcome: InputTerminalOutcome::Consumed
            }
        )));
    }

    #[test]
    fn abandon_emits_notice_and_terminal_outcome() {
        let mut auth = make_authority();
        let t = auth
            .apply(InputLifecycleInput::Abandon {
                reason: InputAbandonReason::Cancelled,
            })
            .unwrap();
        assert!(t.effects.iter().any(|e| matches!(
            e,
            InputLifecycleEffect::InputLifecycleNotice {
                new_state: InputLifecycleState::Abandoned
            }
        )));
        assert!(t.effects.iter().any(|e| matches!(
            e,
            InputLifecycleEffect::RecordTerminalOutcome {
                outcome: InputTerminalOutcome::Abandoned {
                    reason: InputAbandonReason::Cancelled,
                },
            }
        )));
    }
}