Luigit
repositories / smith

smith

There are many coding harnesses - but this one is fast

owned by admin

smith-core/src/control.rs

Raw
//! SMH-SPEC-SPEC0001, SMH-SPEC-PLUG0001: frontend-independent durable session control.
use crate::agent::TurnOutcome;
use crate::store::{AdmissionReceipt, WorkStatus};
use smith::error::Result;
use smith::id::EntryId;

/// Authority held by this backend, independent of provider configuration.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum AccessMode {
    /// Inspection only; never creates a file or prepares an executor.
    ReadOnly,
    /// Serialized durable writer authority.
    Writer,
}

/// Durable receipt and its current state, not an execution promise.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct WorkReceipt {
    /// Immutable admission identity and destination.
    pub receipt: AdmissionReceipt,
    /// Last acknowledged durable transition.
    pub status: WorkStatus,
    /// Acknowledged cancellation intent, not a fabricated terminal outcome.
    pub cancel_requested: bool,
}

/// Admission acknowledgement distinguishes new input from a keyed retry.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Admission {
    /// Original receipt and current durable state.
    pub work: WorkReceipt,
    /// Only new admissions may be scheduled by the accepting frontend.
    pub is_new: bool,
}

/// Executor-owned phase, independent of guest logs and durable terminal state.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ExecutionPhase {
    /// Provider and actionable lifecycle work.
    Running,
    /// Root work resolved; bounded notification cleanup remains joined.
    Notifying,
}

/// Origin of durably accepted notification-window input.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum AdmissionSource {
    /// JSON-RPC user prompt, never a guest-created provider request.
    Rpc,
}

/// Durable scheduling intent associated with one notification-window admission.
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct NotificationAdmission {
    /// Original frontend origin.
    pub source: AdmissionSource,
    /// Root whose notifications delayed this input.
    pub notifying_root: EntryId,
    /// Original accepted input identity.
    pub submission_id: EntryId,
    /// Original delivery preference, not rewritten by terminal scheduling.
    pub delivery: crate::agent::Delivery,
}

/// Non-executing control plane; calls remain available while execution blocks.
pub trait DurableControl: Send + Sync {
    /// Report actual authority, never inferred from command-line flags.
    fn access_mode(&self) -> AccessMode;
    /// Admit text or return its original keyed receipt without scheduling again.
    ///
    /// # Errors
    /// Rejects read-only authority, conflicting keys, unresolved work, or uncertain storage.
    fn admit(&self, text: &str, key: Option<&str>) -> Result<Admission>;
    /// Return the exact currently bound root and its executor-owned phase.
    ///
    /// # Errors
    /// Returns control-plane availability faults.
    fn execution_phase(&self) -> Result<Option<(EntryId, ExecutionPhase)>> {
        Ok(None)
    }
    /// Admit follow-up input only while this exact root is notifying.
    ///
    /// # Errors
    /// Rejects absent notification authority or unavailable queue capacity.
    fn admit_notification(
        &self,
        _root: EntryId,
        _text: &str,
        _key: Option<&str>,
        _delivery: crate::agent::Delivery,
    ) -> Result<Admission> {
        Err(smith::error::SmithError::Session {
            code: smith::error::SessionCode::SessionIncompleteContext,
            message: "notification admission unavailable".into(),
        })
    }
    /// Inspect acknowledged durable state without starting work.
    ///
    /// # Errors
    /// Returns storage, integrity, or writer-uncertainty faults.
    fn inspect(&self, id: EntryId) -> Result<Option<WorkReceipt>>;
    /// Persist cancellation intent before signalling the bound executor.
    /// `None` resolves once to the currently live bound root, never recovery work.
    ///
    /// # Errors
    /// Rejects read-only, queued, terminal, duplicate, absent, or uncertain work.
    fn abort(&self, id: Option<EntryId>) -> Result<EntryId>;
}

/// Writer response to a terminal command, before resident state adoption.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SettlementDisposition {
    /// Exact command crossed the durable acknowledgement boundary.
    Committed,
    /// Cancellation intent won serialization; command wrote no output or settlement.
    CancelBeforeCommit,
}

/// Blocking execution plane; frontend owns its thread and observation lifetime.
/// Dropping observation never requests cancellation or fabricates settlement.
pub trait DurableExecutor: Send {
    /// Execute exactly this queued identity, never another pending root.
    /// Report ordered, secret-masked progress live; progress is not durable settlement.
    /// A successful result requires acknowledged terminal persistence.
    ///
    /// # Errors
    /// Returns preparation, claim, execution, or settlement faults without implicit retry.
    fn execute(
        &mut self,
        id: EntryId,
        observe: &mut dyn FnMut(&smith::stream::StreamEvent),
    ) -> Result<TurnOutcome>;
}

#[cfg(test)]
mod tests {
    #[test]
    #[cfg(target_arch = "x86_64")]
    fn control_receipts_have_exact_layout() {
        assert_eq!(std::mem::size_of::<super::WorkReceipt>(), 51);
        assert_eq!(std::mem::size_of::<super::Admission>(), 52);
        assert_eq!(std::mem::size_of::<super::ExecutionPhase>(), 1);
        assert_eq!(std::mem::size_of::<super::NotificationAdmission>(), 33);
    }
}