Skip to main content

omega_cognitive_kernel/adaptive/
types.rs

1use alloc::collections::{BTreeMap, BTreeSet};
2use alloc::string::String;
3use core::fmt;
4use serde::{Deserialize, Serialize};
5
6/// Operating mode of an Adaptive Kernel Protocol v1 session.
7///
8/// The protocol always defaults to [`AdaptiveMode::Keep`] so no executable
9/// policy mutation occurs unless explicitly enabled by the host.
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
11#[serde(rename_all = "snake_case")]
12#[non_exhaustive]
13pub enum AdaptiveMode {
14    /// Observe only; emit no executable or shadow policy proposals.
15    #[default]
16    Keep,
17    /// Emit non-executable trial snapshots that cannot be acknowledged as applied.
18    Shadow,
19    /// Emit bounded, immutable policy snapshots eligible for host application.
20    Active,
21}
22
23/// Lifecycle state of an adaptive policy proposal.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(rename_all = "snake_case")]
26#[non_exhaustive]
27pub enum ProposalState {
28    /// Observation received before durable commit.
29    Observed,
30    /// Proposal persisted by the kernel (not yet applied by the host).
31    RecordCommitted,
32    /// Host confirmed exact application of the full candidate policy snapshot.
33    Applied,
34    /// Proposal rejected by the host or policy gate.
35    Rejected,
36    /// Proposal expired before execution or retention window elapsed.
37    Expired,
38    /// Execution outcome is unknown; further active proposals are blocked until reconciled.
39    ReconciliationRequired,
40    /// Execution outcome was observed and consumed once by learning.
41    Settled,
42}
43
44/// Immutable versioned parameter snapshot transferred across process boundaries.
45#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
46#[non_exhaustive]
47pub struct PolicySnapshot {
48    /// Monotonically increasing policy version (never reused on recovery).
49    pub version: u64,
50    /// Complete parameter map representing the full policy state.
51    pub params: BTreeMap<String, f64>,
52}
53
54impl PolicySnapshot {
55    /// Creates a validated [`PolicySnapshot`], rejecting non-finite parameter values.
56    pub fn new(version: u64, params: BTreeMap<String, f64>) -> Result<Self, AdaptiveError> {
57        if params.values().any(|value| !value.is_finite()) {
58            return Err(AdaptiveError::NonFiniteInput);
59        }
60        Ok(Self { version, params })
61    }
62}
63
64/// Configuration for [`crate::adaptive::AdaptiveStateMachine`].
65#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66pub struct AdaptiveConfig {
67    /// Requested operating mode (defaults to [`AdaptiveMode::Keep`]).
68    pub mode: AdaptiveMode,
69    /// Maximum number of concurrent pending active proposals (defaults to `1`).
70    pub max_pending_active_proposals: usize,
71    /// Maximum number of completed request responses retained before tombstoning.
72    pub completed_response_limit: usize,
73}
74
75impl Default for AdaptiveConfig {
76    fn default() -> Self {
77        Self {
78            mode: AdaptiveMode::Keep,
79            max_pending_active_proposals: 1,
80            completed_response_limit: 1024,
81        }
82    }
83}
84
85/// Decision kind returned by a proposal request.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "snake_case")]
88#[non_exhaustive]
89pub enum ProposalDecision {
90    /// Stay on the confirmed policy with no candidate mutation.
91    Keep,
92    /// Stay on the confirmed policy because an active proposal or reconciliation is pending.
93    KeepPending,
94    /// Non-executable shadow proposal.
95    ShadowProposal,
96    /// Executable active proposal carrying a complete immutable snapshot.
97    ActiveProposal,
98}
99
100/// Input to propose a bounded policy update under a caller-supplied idempotency key.
101#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
102pub struct ProposalRequest {
103    /// Stable idempotency identifier for this API request.
104    pub request_id: String,
105    /// Stable identifier for the candidate proposal if one is created.
106    pub proposal_id: String,
107    /// Canonical digest of the request payload used to detect conflicting retries.
108    pub request_digest: String,
109    /// Mode requested by the host for this call.
110    pub requested_mode: AdaptiveMode,
111    /// Complete candidate parameters proposed for the next version (if any).
112    pub candidate_params: Option<BTreeMap<String, f64>>,
113}
114
115/// Deterministic response returned by [`crate::adaptive::AdaptiveStateMachine::propose`].
116#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
117#[non_exhaustive]
118pub struct ProposalResponse {
119    /// Idempotency key echoed from the request.
120    pub request_id: String,
121    /// Proposal identifier associated with this response (if created).
122    pub proposal_id: Option<String>,
123    /// Outcome decision (`keep`, `keep_pending`, `shadow_proposal`, `active_proposal`).
124    pub decision: ProposalDecision,
125    /// Lifecycle state of the proposal after commit.
126    pub state: ProposalState,
127    /// Confirmed policy version active on the kernel at response time.
128    pub confirmed_policy_version: u64,
129    /// Candidate policy snapshot when a shadow or active proposal is emitted.
130    pub candidate_snapshot: Option<PolicySnapshot>,
131    /// Number of new checkpoints created by this call (`0` on idempotent replay).
132    pub new_checkpoint_count: u64,
133}
134
135/// Host acknowledgement binding an applied execution to a specific proposal snapshot.
136#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
137pub struct ExecutionReceipt {
138    /// Identifier of the proposal being acknowledged.
139    pub proposal_id: String,
140    /// Unique identifier for the host execution instance.
141    pub execution_id: String,
142    /// Exact parameter snapshot applied by the host.
143    pub applied_params: BTreeMap<String, f64>,
144}
145
146/// Outcome classification reported by the host after executing an applied policy.
147#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
148#[serde(rename_all = "snake_case")]
149#[non_exhaustive]
150pub enum FeedbackOutcome {
151    /// Execution completed with finite external metrics.
152    Completed {
153        /// External reward observed by the host.
154        reward: f64,
155        /// Observed prediction-error delta.
156        error_delta: f64,
157        /// Observed risk delta.
158        risk_delta: f64,
159    },
160    /// Execution outcome could not be determined; requires reconciliation.
161    Unknown,
162}
163
164/// External outcome feedback bound to a specific proposal and execution receipt.
165#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
166pub struct FeedbackRequest {
167    /// Stable idempotency identifier for this feedback message.
168    pub feedback_id: String,
169    /// Proposal identifier that produced the execution.
170    pub proposal_id: String,
171    /// Execution identifier previously acknowledged by the host.
172    pub execution_id: String,
173    /// Observed external outcome.
174    pub outcome: FeedbackOutcome,
175}
176
177/// Deterministic receipt returned after processing [`FeedbackRequest`].
178#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
179#[non_exhaustive]
180pub struct FeedbackReceipt {
181    /// Idempotency identifier echoed from the feedback request.
182    pub feedback_id: String,
183    /// Proposal identifier associated with this feedback.
184    pub proposal_id: String,
185    /// Lifecycle state of the proposal after processing feedback.
186    pub state: ProposalState,
187    /// Whether this call caused a new learning update (`false` on duplicate or unknown).
188    pub learning_applied: bool,
189}
190
191/// Bounded recovery recommendation pointing back to a prior safe parameter set.
192#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
193#[non_exhaustive]
194pub struct RecoveryRecommendation {
195    /// Parameter values to restore.
196    pub recovery_params: BTreeMap<String, f64>,
197    /// Strictly newer policy version that will be assigned once applied.
198    pub next_candidate_version: u64,
199}
200
201/// Journal recovery state inspected when restoring from an interrupted commit.
202#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
203pub struct JournalRecoveryInput {
204    /// Whether a prepared journal entry exists for the request.
205    pub journal_prepared: bool,
206    /// Snapshot revision observed in durable storage.
207    pub snapshot_revision: u64,
208    /// Whether the final commit marker was written before interruption.
209    pub committed_marker: bool,
210}
211
212/// Action required to reconcile an interrupted durable commit on restore.
213#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
214#[serde(rename_all = "snake_case")]
215#[non_exhaustive]
216pub enum JournalRecoveryAction {
217    /// Commit already finalized; replay persisted response directly.
218    ReplayCommitted,
219    /// Verify the saved snapshot revision, then finalize the commit marker without re-executing.
220    VerifyRevisionThenCompleteCommit,
221    /// No prepared journal entry exists; treat as a fresh request.
222    None,
223}
224
225/// Fail-closed protocol errors defined by Adaptive Kernel Protocol v1.
226#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
227#[non_exhaustive]
228pub enum AdaptiveError {
229    /// Same `request_id` or `feedback_id` was reused with a different payload digest.
230    StepIdConflict,
231    /// Requested state transition is illegal for the proposal's mode or current state.
232    InvalidTransition,
233    /// Host applied a partial or mismatched parameter set rather than the full snapshot.
234    PolicySnapshotMismatch,
235    /// Caller supplied a `NaN` or infinite floating-point value.
236    NonFiniteInput,
237    /// Referenced request or proposal has expired and been tombstoned.
238    Expired,
239    /// Referenced proposal or execution does not exist.
240    UnknownProposal,
241}
242
243impl fmt::Display for AdaptiveError {
244    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
245        match self {
246            Self::StepIdConflict => {
247                write!(f, "request or feedback id reused with conflicting payload")
248            }
249            Self::InvalidTransition => write!(f, "invalid adaptive proposal state transition"),
250            Self::PolicySnapshotMismatch => {
251                write!(f, "applied parameters do not match candidate snapshot")
252            }
253            Self::NonFiniteInput => write!(f, "non-finite floating-point value rejected"),
254            Self::Expired => write!(f, "expired request tombstone cannot be re-executed"),
255            Self::UnknownProposal => write!(f, "unknown adaptive proposal or execution identifier"),
256        }
257    }
258}
259
260#[cfg(feature = "std")]
261impl std::error::Error for AdaptiveError {}
262
263/// Persisted request-idempotency entry stored in [`AdaptivePersistedState`].
264#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
265pub struct PersistedRequestRecord {
266    /// Canonical request digest used to detect conflicting retries.
267    pub digest: String,
268    /// Original deterministic response returned for this request.
269    pub response: ProposalResponse,
270}
271
272/// Persisted proposal lifecycle entry stored in [`AdaptivePersistedState`].
273#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
274pub struct PersistedProposalRecord {
275    /// Mode under which the proposal was created.
276    pub mode: AdaptiveMode,
277    /// Current lifecycle state of the proposal.
278    pub state: ProposalState,
279    /// Candidate policy snapshot associated with the proposal.
280    pub snapshot: PolicySnapshot,
281    /// Host execution identifier once acknowledged as applied.
282    #[serde(default, skip_serializing_if = "Option::is_none")]
283    pub execution_id: Option<String>,
284}
285
286/// Persisted feedback-idempotency entry stored in [`AdaptivePersistedState`].
287#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
288pub struct PersistedFeedbackRecord {
289    /// Proposal identifier bound to the feedback.
290    pub proposal_id: String,
291    /// Execution identifier bound to the feedback.
292    pub execution_id: String,
293    /// External outcome reported by the host.
294    pub outcome: FeedbackOutcome,
295    /// Original receipt returned for this feedback identifier.
296    pub receipt: FeedbackReceipt,
297}
298
299/// Serializable durable state of [`crate::adaptive::AdaptiveStateMachine`] (schema `v7`).
300#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
301#[non_exhaustive]
302pub struct AdaptivePersistedState {
303    /// Persisted session mode.
304    pub mode: AdaptiveMode,
305    /// Confirmed baseline/active policy snapshot.
306    pub confirmed_policy: PolicySnapshot,
307    /// Next monotonically allocated candidate policy version.
308    pub next_candidate_version: u64,
309    /// Monotonic state revision counter.
310    pub revision: u64,
311    /// Total consumed learning updates.
312    pub learning_updates: u64,
313    /// Total checkpoints created across proposals.
314    pub checkpoint_count: u64,
315    /// Whether active adaptation permission was explicitly granted.
316    pub active_permission_granted: bool,
317    /// Currently pending active proposal identifier, if any.
318    #[serde(default, skip_serializing_if = "Option::is_none")]
319    pub pending_active_proposal_id: Option<String>,
320    /// Whether reconciliation is required before issuing new active proposals.
321    pub reconciliation_required: bool,
322    /// Tracked proposals keyed by `proposal_id`.
323    #[serde(default)]
324    pub proposals: BTreeMap<String, PersistedProposalRecord>,
325    /// Idempotency cache keyed by `request_id`.
326    #[serde(default)]
327    pub requests: BTreeMap<String, PersistedRequestRecord>,
328    /// Feedback idempotency cache keyed by `feedback_id`.
329    #[serde(default)]
330    pub feedbacks: BTreeMap<String, PersistedFeedbackRecord>,
331    /// Expired request tombstones that must never be re-executed.
332    #[serde(default)]
333    pub expired_tombstones: BTreeSet<String>,
334}