//! Verified clause-level episodic overrides for sub-millisecond fast-path recall. //! //! Basis: Hippocampal fast-path memory over canonical normalized clause keys. //! Span: Covers exact clause skeletons verified by an external oracle before neural consolidation. //! Minimality: Cannot be derived from static neural weights because background retraining takes //! minutes while interactive corrections must take effect on the very next command. //! Tightness: Every stored key is canonicalized and every stored label belongs to the closed //! 48-action + `reject` vocabulary. use std::collections::BTreeMap; use std::fs; use std::path::Path; use serde::{Deserialize, Serialize}; use thiserror::Error; use crate::catalog::ActionCatalog; use crate::config::expected_labels; use crate::dataset::{DatasetError, clause_key}; /// Validation or IO failure when constructing or reading episodic memory. #[derive(Debug, Error)] pub enum EpisodicError { /// Serialized schema version or entry invariant failed. #[error("invalid episodic memory: {0}")] Invalid(&'static str), /// An entry references a label outside the closed action set. #[error("unknown episodic label: {0}")] UnknownLabel(String), /// A key is not in canonical normalized clause form. #[error("non-canonical episodic clause key: {0}")] NonCanonicalKey(String), ///Clause normalization failed. #[error(transparent)] Dataset(#[from] DatasetError), /// Filesystem read failed. #[error(transparent)] Io(#[from] std::io::Error), /// JSON decoding failed. #[error(transparent)] Json(#[from] serde_json::Error), } /// Immutable verified map from canonical normalized clause keys to closed-set labels. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(deny_unknown_fields)] pub struct EpisodicMemory { /// Schema version, currently one. pub format_version: u32, /// Canonical normalized clause key -> action label or `"reject"`. pub entries: BTreeMap, } impl Default for EpisodicMemory { fn default() -> Self { Self { format_version: 1, entries: BTreeMap::new(), } } } impl EpisodicMemory { /// Construct a validated episodic map from canonical closed-set entries. pub fn new(entries: BTreeMap) -> Result { Self::new_with_catalog(entries, None) } /// Construct a validated episodic map against an optional open `ActionCatalog`. pub fn new_with_catalog( entries: BTreeMap, catalog: Option<&ActionCatalog>, ) -> Result { let memory = Self { format_version: 1, entries, }; memory.validate_with_catalog(catalog)?; Ok(memory) } /// Decode and validate serialized episodic JSON bytes against the closed action set. pub fn from_bytes(bytes: &[u8]) -> Result { Self::from_bytes_with_catalog(bytes, None) } /// Decode and validate serialized episodic JSON bytes against an optional `ActionCatalog`. pub fn from_bytes_with_catalog( bytes: &[u8], catalog: Option<&ActionCatalog>, ) -> Result { let memory: Self = serde_json::from_slice(bytes)?; memory.validate_with_catalog(catalog)?; Ok(memory) } /// Load episodic memory from `path`, returning an empty map when the file is absent. pub fn load_optional(path: &Path) -> Result { Self::load_optional_with_catalog(path, None) } /// Load episodic memory from `path` validated against an optional open `ActionCatalog`. pub fn load_optional_with_catalog( path: &Path, catalog: Option<&ActionCatalog>, ) -> Result { match fs::read(path) { Ok(bytes) => Self::from_bytes_with_catalog(&bytes, catalog), Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(Self::default()), Err(error) => Err(error.into()), } } /// Verify schema version, key normalization idempotence, and closed-set labels. pub fn validate(&self) -> Result<(), EpisodicError> { self.validate_with_catalog(None) } /// Verify schema version, key normalization idempotence, and catalog/closed labels. pub fn validate_with_catalog(&self, catalog: Option<&ActionCatalog>) -> Result<(), EpisodicError> { if self.format_version != 1 { return Err(EpisodicError::Invalid("unsupported episodic format_version")); } let closed = if catalog.is_none() { Some(expected_labels()) } else { None }; for (key, label) in &self.entries { if key.is_empty() || clause_key(key)? != *key { return Err(EpisodicError::NonCanonicalKey(key.clone())); } let valid = match (catalog, &closed) { (Some(cat), _) => label == "reject" || cat.get(label).is_some(), (None, Some(allowed)) => allowed.contains(label), (None, None) => false, }; if !valid { return Err(EpisodicError::UnknownLabel(label.clone())); } } Ok(()) } /// Look up a clause text (as produced by `parse_command`) in episodic memory. pub fn lookup_clause(&self, clause_text: &str) -> Result, DatasetError> { if self.entries.is_empty() { return Ok(None); } let normalized = clause_key(clause_text)?; Ok(self.entries.get(&normalized).map(String::as_str)) } }