omega-cognitive-kernel 1.4.0

Online strategy-patch runtime: training-free RuleEffect adaptation with audit and rollback
Documentation
use alloc::collections::{BTreeMap, BTreeSet};
use alloc::string::String;
use core::fmt;
use serde::{Deserialize, Serialize};

/// Operating mode of an Adaptive Kernel Protocol v1 session.
///
/// The protocol always defaults to [`AdaptiveMode::Keep`] so no executable
/// policy mutation occurs unless explicitly enabled by the host.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum AdaptiveMode {
    /// Observe only; emit no executable or shadow policy proposals.
    #[default]
    Keep,
    /// Emit non-executable trial snapshots that cannot be acknowledged as applied.
    Shadow,
    /// Emit bounded, immutable policy snapshots eligible for host application.
    Active,
}

/// Lifecycle state of an adaptive policy proposal.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ProposalState {
    /// Observation received before durable commit.
    Observed,
    /// Proposal persisted by the kernel (not yet applied by the host).
    RecordCommitted,
    /// Host confirmed exact application of the full candidate policy snapshot.
    Applied,
    /// Proposal rejected by the host or policy gate.
    Rejected,
    /// Proposal expired before execution or retention window elapsed.
    Expired,
    /// Execution outcome is unknown; further active proposals are blocked until reconciled.
    ReconciliationRequired,
    /// Execution outcome was observed and consumed once by learning.
    Settled,
}

/// Immutable versioned parameter snapshot transferred across process boundaries.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct PolicySnapshot {
    /// Monotonically increasing policy version (never reused on recovery).
    pub version: u64,
    /// Complete parameter map representing the full policy state.
    pub params: BTreeMap<String, f64>,
}

impl PolicySnapshot {
    /// Creates a validated [`PolicySnapshot`], rejecting non-finite parameter values.
    pub fn new(version: u64, params: BTreeMap<String, f64>) -> Result<Self, AdaptiveError> {
        if params.values().any(|value| !value.is_finite()) {
            return Err(AdaptiveError::NonFiniteInput);
        }
        Ok(Self { version, params })
    }
}

/// Configuration for [`crate::adaptive::AdaptiveStateMachine`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct AdaptiveConfig {
    /// Requested operating mode (defaults to [`AdaptiveMode::Keep`]).
    pub mode: AdaptiveMode,
    /// Maximum number of concurrent pending active proposals (defaults to `1`).
    pub max_pending_active_proposals: usize,
    /// Maximum number of completed request responses retained before tombstoning.
    pub completed_response_limit: usize,
}

impl Default for AdaptiveConfig {
    fn default() -> Self {
        Self {
            mode: AdaptiveMode::Keep,
            max_pending_active_proposals: 1,
            completed_response_limit: 1024,
        }
    }
}

/// Decision kind returned by a proposal request.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ProposalDecision {
    /// Stay on the confirmed policy with no candidate mutation.
    Keep,
    /// Stay on the confirmed policy because an active proposal or reconciliation is pending.
    KeepPending,
    /// Non-executable shadow proposal.
    ShadowProposal,
    /// Executable active proposal carrying a complete immutable snapshot.
    ActiveProposal,
}

/// Input to propose a bounded policy update under a caller-supplied idempotency key.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProposalRequest {
    /// Stable idempotency identifier for this API request.
    pub request_id: String,
    /// Stable identifier for the candidate proposal if one is created.
    pub proposal_id: String,
    /// Canonical digest of the request payload used to detect conflicting retries.
    pub request_digest: String,
    /// Mode requested by the host for this call.
    pub requested_mode: AdaptiveMode,
    /// Complete candidate parameters proposed for the next version (if any).
    pub candidate_params: Option<BTreeMap<String, f64>>,
}

/// Deterministic response returned by [`crate::adaptive::AdaptiveStateMachine::propose`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ProposalResponse {
    /// Idempotency key echoed from the request.
    pub request_id: String,
    /// Proposal identifier associated with this response (if created).
    pub proposal_id: Option<String>,
    /// Outcome decision (`keep`, `keep_pending`, `shadow_proposal`, `active_proposal`).
    pub decision: ProposalDecision,
    /// Lifecycle state of the proposal after commit.
    pub state: ProposalState,
    /// Confirmed policy version active on the kernel at response time.
    pub confirmed_policy_version: u64,
    /// Candidate policy snapshot when a shadow or active proposal is emitted.
    pub candidate_snapshot: Option<PolicySnapshot>,
    /// Number of new checkpoints created by this call (`0` on idempotent replay).
    pub new_checkpoint_count: u64,
}

/// Host acknowledgement binding an applied execution to a specific proposal snapshot.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ExecutionReceipt {
    /// Identifier of the proposal being acknowledged.
    pub proposal_id: String,
    /// Unique identifier for the host execution instance.
    pub execution_id: String,
    /// Exact parameter snapshot applied by the host.
    pub applied_params: BTreeMap<String, f64>,
}

/// Outcome classification reported by the host after executing an applied policy.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum FeedbackOutcome {
    /// Execution completed with finite external metrics.
    Completed {
        /// External reward observed by the host.
        reward: f64,
        /// Observed prediction-error delta.
        error_delta: f64,
        /// Observed risk delta.
        risk_delta: f64,
    },
    /// Execution outcome could not be determined; requires reconciliation.
    Unknown,
}

/// External outcome feedback bound to a specific proposal and execution receipt.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct FeedbackRequest {
    /// Stable idempotency identifier for this feedback message.
    pub feedback_id: String,
    /// Proposal identifier that produced the execution.
    pub proposal_id: String,
    /// Execution identifier previously acknowledged by the host.
    pub execution_id: String,
    /// Observed external outcome.
    pub outcome: FeedbackOutcome,
}

/// Deterministic receipt returned after processing [`FeedbackRequest`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct FeedbackReceipt {
    /// Idempotency identifier echoed from the feedback request.
    pub feedback_id: String,
    /// Proposal identifier associated with this feedback.
    pub proposal_id: String,
    /// Lifecycle state of the proposal after processing feedback.
    pub state: ProposalState,
    /// Whether this call caused a new learning update (`false` on duplicate or unknown).
    pub learning_applied: bool,
}

/// Bounded recovery recommendation pointing back to a prior safe parameter set.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct RecoveryRecommendation {
    /// Parameter values to restore.
    pub recovery_params: BTreeMap<String, f64>,
    /// Strictly newer policy version that will be assigned once applied.
    pub next_candidate_version: u64,
}

/// Journal recovery state inspected when restoring from an interrupted commit.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct JournalRecoveryInput {
    /// Whether a prepared journal entry exists for the request.
    pub journal_prepared: bool,
    /// Snapshot revision observed in durable storage.
    pub snapshot_revision: u64,
    /// Whether the final commit marker was written before interruption.
    pub committed_marker: bool,
}

/// Action required to reconcile an interrupted durable commit on restore.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum JournalRecoveryAction {
    /// Commit already finalized; replay persisted response directly.
    ReplayCommitted,
    /// Verify the saved snapshot revision, then finalize the commit marker without re-executing.
    VerifyRevisionThenCompleteCommit,
    /// No prepared journal entry exists; treat as a fresh request.
    None,
}

/// Fail-closed protocol errors defined by Adaptive Kernel Protocol v1.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum AdaptiveError {
    /// Same `request_id` or `feedback_id` was reused with a different payload digest.
    StepIdConflict,
    /// Requested state transition is illegal for the proposal's mode or current state.
    InvalidTransition,
    /// Host applied a partial or mismatched parameter set rather than the full snapshot.
    PolicySnapshotMismatch,
    /// Caller supplied a `NaN` or infinite floating-point value.
    NonFiniteInput,
    /// Referenced request or proposal has expired and been tombstoned.
    Expired,
    /// Referenced proposal or execution does not exist.
    UnknownProposal,
    /// Candidate parameter violated a configured [`ParameterBound`] (`min`, `max`, or `max_step_delta`).
    ParameterOutOfBounds,
}

/// Hard safety bounds enforced on a single adaptive parameter before proposal commit.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ParameterBound {
    /// Minimum permitted finite parameter value (inclusive).
    pub min: f64,
    /// Maximum permitted finite parameter value (inclusive).
    pub max: f64,
    /// Optional maximum absolute change allowed from the currently confirmed value in one proposal.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub max_step_delta: Option<f64>,
}

impl ParameterBound {
    /// Constructs a validated finite [`ParameterBound`].
    pub fn new(min: f64, max: f64, max_step_delta: Option<f64>) -> Result<Self, AdaptiveError> {
        if !min.is_finite() || !max.is_finite() || min > max {
            return Err(AdaptiveError::NonFiniteInput);
        }
        if let Some(delta) = max_step_delta {
            if !delta.is_finite() || delta < 0.0 {
                return Err(AdaptiveError::NonFiniteInput);
            }
        }
        Ok(Self {
            min,
            max,
            max_step_delta,
        })
    }

    /// Returns `true` when `candidate` satisfies `[min, max]` and `max_step_delta` (if configured).
    pub fn allows(&self, current: Option<f64>, candidate: f64) -> bool {
        if !candidate.is_finite() || candidate < self.min || candidate > self.max {
            return false;
        }
        if let (Some(max_delta), Some(cur)) = (self.max_step_delta, current) {
            if (candidate - cur).abs() > max_delta + 1e-12 {
                return false;
            }
        }
        true
    }
}

impl fmt::Display for AdaptiveError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::StepIdConflict => {
                write!(f, "request or feedback id reused with conflicting payload")
            }
            Self::InvalidTransition => write!(f, "invalid adaptive proposal state transition"),
            Self::PolicySnapshotMismatch => {
                write!(f, "applied parameters do not match candidate snapshot")
            }
            Self::NonFiniteInput => write!(f, "non-finite floating-point value rejected"),
            Self::Expired => write!(f, "expired request tombstone cannot be re-executed"),
            Self::UnknownProposal => write!(f, "unknown adaptive proposal or execution identifier"),
            Self::ParameterOutOfBounds => {
                write!(f, "candidate parameter violates configured safety bounds")
            }
        }
    }
}

#[cfg(feature = "std")]
impl std::error::Error for AdaptiveError {}

/// Persisted request-idempotency entry stored in [`AdaptivePersistedState`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PersistedRequestRecord {
    /// Canonical request digest used to detect conflicting retries.
    pub digest: String,
    /// Original deterministic response returned for this request.
    pub response: ProposalResponse,
}

/// Persisted proposal lifecycle entry stored in [`AdaptivePersistedState`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PersistedProposalRecord {
    /// Mode under which the proposal was created.
    pub mode: AdaptiveMode,
    /// Current lifecycle state of the proposal.
    pub state: ProposalState,
    /// Candidate policy snapshot associated with the proposal.
    pub snapshot: PolicySnapshot,
    /// Host execution identifier once acknowledged as applied.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub execution_id: Option<String>,
}

/// Persisted feedback-idempotency entry stored in [`AdaptivePersistedState`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct PersistedFeedbackRecord {
    /// Proposal identifier bound to the feedback.
    pub proposal_id: String,
    /// Execution identifier bound to the feedback.
    pub execution_id: String,
    /// External outcome reported by the host.
    pub outcome: FeedbackOutcome,
    /// Original receipt returned for this feedback identifier.
    pub receipt: FeedbackReceipt,
}

/// Serializable durable state of [`crate::adaptive::AdaptiveStateMachine`] (schema `v7`).
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct AdaptivePersistedState {
    /// Persisted session mode.
    pub mode: AdaptiveMode,
    /// Confirmed baseline/active policy snapshot.
    pub confirmed_policy: PolicySnapshot,
    /// Next monotonically allocated candidate policy version.
    pub next_candidate_version: u64,
    /// Monotonic state revision counter.
    pub revision: u64,
    /// Total consumed learning updates.
    pub learning_updates: u64,
    /// Total checkpoints created across proposals.
    pub checkpoint_count: u64,
    /// Whether active adaptation permission was explicitly granted.
    pub active_permission_granted: bool,
    /// Currently pending active proposal identifier, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub pending_active_proposal_id: Option<String>,
    /// Whether reconciliation is required before issuing new active proposals.
    pub reconciliation_required: bool,
    /// Tracked proposals keyed by `proposal_id`.
    #[serde(default)]
    pub proposals: BTreeMap<String, PersistedProposalRecord>,
    /// Idempotency cache keyed by `request_id`.
    #[serde(default)]
    pub requests: BTreeMap<String, PersistedRequestRecord>,
    /// Feedback idempotency cache keyed by `feedback_id`.
    #[serde(default)]
    pub feedbacks: BTreeMap<String, PersistedFeedbackRecord>,
    /// Expired request tombstones that must never be re-executed.
    #[serde(default)]
    pub expired_tombstones: BTreeSet<String>,
    /// Optional per-parameter safety bounds enforced on proposals.
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    pub parameter_bounds: BTreeMap<String, ParameterBound>,
}