omega_cognitive_kernel/adaptive/contracts.rs
1//! Stable v1 runtime contracts for the five-signal kernel boundary.
2//!
3//! The contracts in this module deliberately contain no runtime algorithm. They
4//! are the shared vocabulary between the memory, bridge, and training domains.
5//! Concrete implementations remain owned by the host application or by the
6//! corresponding domain module.
7
8use alloc::string::String;
9use alloc::vec::Vec;
10use serde::{Deserialize, Serialize};
11
12/// A single state/action/result observation owned by the kernel runtime.
13///
14/// The default `Action` and `Outcome` types keep the public spelling
15/// `Experience<State>` convenient while allowing strongly typed integrations
16/// to use `Experience<State, Action, Outcome>` without maintaining shadow state.
17#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
18pub struct Experience<State, Action = String, Outcome = String> {
19 /// State observed before the action.
20 pub state: State,
21 /// Action selected or executed for this experience.
22 pub action: Action,
23 /// Result reported by the executor or host.
24 pub outcome: Outcome,
25 /// Stable episode identifier, when the host groups experiences into episodes.
26 #[serde(default, skip_serializing_if = "Option::is_none")]
27 pub episode_id: Option<String>,
28}
29
30impl<State, Action, Outcome> Experience<State, Action, Outcome> {
31 /// Creates an experience from one state, action, and observed outcome.
32 pub fn new(state: State, action: Action, outcome: Outcome) -> Self {
33 Self {
34 state,
35 action,
36 outcome,
37 episode_id: None,
38 }
39 }
40
41 /// Associates the experience with an episode without changing its facts.
42 pub fn in_episode(mut self, episode_id: impl Into<String>) -> Self {
43 self.episode_id = Some(episode_id.into());
44 self
45 }
46}
47
48/// The only five lifecycle signals accepted by a v1 runtime boundary.
49#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
50#[non_exhaustive]
51pub enum Signal<State, Action = String, Outcome = String> {
52 /// Read memory and ask the bridge to coordinate the next action.
53 PreAct {
54 /// Current state supplied by the host.
55 state: State,
56 },
57 /// Record an executed result and make it available to training.
58 PostAct {
59 /// The completed state/action/outcome fact.
60 experience: Experience<State, Action, Outcome>,
61 },
62 /// Close an episode and trigger episode-level evaluation or learning.
63 EpisodeFinish {
64 /// Stable episode identifier.
65 episode_id: String,
66 /// Experiences belonging to the completed episode.
67 experiences: Vec<Experience<State, Action, Outcome>>,
68 },
69 /// Apply an audited, boundary-checked human or rule intervention.
70 Intervention {
71 /// State at which the intervention was requested.
72 state: State,
73 /// Action or policy value affected by the intervention.
74 action: Action,
75 /// Mandatory reason retained for auditability.
76 reason: String,
77 },
78 /// Accept an external evaluation as a learning signal, not a self-evaluation.
79 Feedback {
80 /// Experience being evaluated.
81 experience: Experience<State, Action, Outcome>,
82 /// External score supplied by the evaluator.
83 score: f64,
84 },
85}
86
87/// Memory-domain contract for runtime state and experience persistence.
88///
89/// Implementations may use a bounded ring, a database, or a snapshot-backed
90/// store. The kernel contract only requires that the same experience is used by
91/// persistence, audit, and training consumers.
92pub trait Memory<State, Action = String, Outcome = String> {
93 /// Implementation-specific failure type.
94 type Error;
95
96 /// Records one experience as the canonical fact for downstream consumers.
97 fn record(&mut self, experience: Experience<State, Action, Outcome>)
98 -> Result<(), Self::Error>;
99
100 /// Returns the number of retained experiences.
101 fn len(&self) -> usize;
102
103 /// Returns whether no experience is currently retained.
104 fn is_empty(&self) -> bool {
105 self.len() == 0
106 }
107}
108
109/// Bridge-domain contract for coordinating the existing control plane.
110///
111/// L0/L1/L2, `RuleEffect`, and `ControlDirective` implementations belong behind
112/// this boundary; this trait does not prescribe or duplicate their algorithms.
113pub trait Bridge<State, Action = String> {
114 /// Implementation-specific failure type.
115 type Error;
116
117 /// Coordinates a pre-action state into a host-facing action.
118 fn pre_act(&mut self, state: &State) -> Result<Action, Self::Error>;
119
120 /// Applies a boundary-checked intervention and returns the controlled action.
121 fn intervene(
122 &mut self,
123 state: &State,
124 action: Action,
125 reason: &str,
126 ) -> Result<Action, Self::Error>;
127}
128
129/// Training-domain contract for consuming the unified experience stream.
130///
131/// This is intentionally an orchestration contract. Concrete training
132/// algorithms remain outside the kernel and can implement this trait.
133pub trait Training<State, Action = String, Outcome = String> {
134 /// Implementation-specific failure type.
135 type Error;
136
137 /// Consumes one post-action experience.
138 fn post_act(
139 &mut self,
140 experience: &Experience<State, Action, Outcome>,
141 ) -> Result<(), Self::Error>;
142
143 /// Consumes all experiences at the end of an episode.
144 fn episode_finish(
145 &mut self,
146 episode_id: &str,
147 experiences: &[Experience<State, Action, Outcome>],
148 ) -> Result<(), Self::Error>;
149
150 /// Consumes an externally supplied evaluation score.
151 fn feedback(
152 &mut self,
153 experience: &Experience<State, Action, Outcome>,
154 score: f64,
155 ) -> Result<(), Self::Error>;
156}
157
158/// Compile-time marker for implementations that expose the unified signal boundary.
159pub trait SignalHandler<State, Action = String, Outcome = String> {
160 /// Implementation-specific failure type.
161 type Error;
162
163 /// Processes exactly one lifecycle signal.
164 fn handle_signal(&mut self, signal: Signal<State, Action, Outcome>) -> Result<(), Self::Error>;
165}
166
167#[cfg(test)]
168mod tests {
169 use super::{Experience, Signal};
170 use alloc::string::String;
171 use alloc::vec;
172
173 #[test]
174 fn signal_round_trip_preserves_experience_facts() {
175 let experience =
176 Experience::new(String::from("s0"), String::from("a0"), String::from("ok"))
177 .in_episode("episode-1");
178 let signal = Signal::PostAct { experience };
179 let encoded = serde_json::to_string(&signal).expect("signal serializes");
180 let decoded: Signal<String> = serde_json::from_str(&encoded).expect("signal deserializes");
181 assert_eq!(decoded, signal);
182 }
183
184 #[test]
185 fn episode_finish_is_a_single_signal_with_ordered_facts() {
186 let facts = vec![
187 Experience::new(String::from("s0"), String::from("a0"), String::from("ok")),
188 Experience::new(String::from("s1"), String::from("a1"), String::from("done")),
189 ];
190 let signal = Signal::EpisodeFinish {
191 episode_id: String::from("episode-1"),
192 experiences: facts,
193 };
194 match signal {
195 Signal::EpisodeFinish { experiences, .. } => assert_eq!(experiences.len(), 2),
196 _ => panic!("unexpected signal variant"),
197 }
198 }
199}