reef-core 0.4.0

Provider-neutral primitives for building LLM agents: run lifecycle, transcript, tools, hooks
Documentation
//! Non-model-visible audit facts.
//!
//! Audit payloads are owned opaque bytes. This module deliberately does not use
//! provider-extension envelopes: audit facts and provider data are separate lanes.

use std::fmt;

use crate::redact::Bytes;

/// An owned, non-model-visible audit fact.
#[derive(Clone, Eq, PartialEq)]
pub struct Event {
    kind: String,
    payload: Option<Box<[u8]>>,
}

impl fmt::Debug for Event {
    /// Names the kind and sizes the payload, never printing a payload byte.
    ///
    /// `kind` is a producer-supplied classification (ADR-018 Tier 1) and prints
    /// verbatim. `payload` is owned opaque bytes (Tier 2), so it renders as its
    /// length and never its content; the three states `None`, `Some(<0 bytes>)`
    /// and `Some(<N bytes>)` stay distinct, because the whole reason this type
    /// keeps `Option` is that "attached nothing" and "attached an empty blob"
    /// are two different facts (ADR-019 D5). The bytes are the very lane this
    /// module exists to keep off the model-visible path, so a derived `Debug`
    /// would put them back on the one that reaches logs and `dbg!`.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("Event")
            .field("kind", &self.kind)
            .field(
                "payload",
                &self.payload.as_deref().map(|payload| Bytes(payload.len())),
            )
            .finish()
    }
}

impl Event {
    /// Creates an audit fact from its producer-defined kind and optional payload.
    ///
    /// The payload is retained verbatim and is not parsed or canonicalized.
    #[must_use]
    pub const fn new(kind: String, payload: Option<Box<[u8]>>) -> Self {
        Self { kind, payload }
    }

    /// Returns the producer-defined event kind.
    #[must_use]
    pub fn kind(&self) -> &str {
        &self.kind
    }

    /// Returns the opaque payload, preserving absent versus present-empty.
    #[must_use]
    pub fn payload(&self) -> Option<&[u8]> {
        self.payload.as_deref()
    }

    /// Transfers ownership of the kind and payload.
    #[must_use]
    pub fn into_parts(self) -> (String, Option<Box<[u8]>>) {
        (self.kind, self.payload)
    }
}

/// The serialized form of [`Event`] (ADR-019 D5): `kind` then `payload`.
///
/// The payload is a byte string, and its absence is written rather than omitted:
/// "the producer attached nothing" and "the producer attached an empty blob" are
/// two different facts, and this type exists to keep them apart.
#[cfg(feature = "serde")]
mod serde_impl {
    use std::fmt::{self, Formatter};

    use serde_core::de::{Deserialize, Deserializer, Error as _, MapAccess, SeqAccess, Visitor};
    use serde_core::ser::{Serialize, SerializeStruct, Serializer};

    use super::Event;
    use crate::wire::{self, ByteBuf, Bytes, IdentifierSeed};

    const FIELDS: &[&str] = &["kind", "payload"];

    impl Serialize for Event {
        fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
        where
            S: Serializer,
        {
            let mut record = serializer.serialize_struct("Event", 2)?;
            record.serialize_field("kind", &self.kind)?;
            record.serialize_field("payload", &self.payload.as_deref().map(Bytes))?;
            record.end()
        }
    }

    impl<'de> Deserialize<'de> for Event {
        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where
            D: Deserializer<'de>,
        {
            deserializer.deserialize_struct("Event", FIELDS, EventVisitor)
        }
    }

    struct EventVisitor;

    impl<'de> Visitor<'de> for EventVisitor {
        type Value = Event;

        fn expecting(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
            formatter.write_str("an audit event")
        }

        fn visit_seq<A>(self, mut sequence: A) -> Result<Self::Value, A::Error>
        where
            A: SeqAccess<'de>,
        {
            let kind = wire::element(&mut sequence, 0)?;
            let payload = wire::element::<Option<ByteBuf>, _>(&mut sequence, 1)?;
            wire::end(&mut sequence, 2)?;
            Ok(Event::new(kind, ByteBuf::into_optional(payload)))
        }

        fn visit_map<A>(self, mut entries: A) -> Result<Self::Value, A::Error>
        where
            A: MapAccess<'de>,
        {
            let mut kind = None;
            let mut payload = None::<Option<ByteBuf>>;
            while let Some(field) = entries.next_key_seed(IdentifierSeed(FIELDS))? {
                match field.0.as_str() {
                    "kind" => wire::accept(&mut kind, entries.next_value()?, "kind")?,
                    "payload" => wire::accept(&mut payload, entries.next_value()?, "payload")?,
                    unknown => return Err(A::Error::unknown_field(unknown, FIELDS)),
                }
            }
            Ok(Event::new(
                wire::require(kind, "kind")?,
                ByteBuf::into_optional(wire::require(payload, "payload")?),
            ))
        }
    }
}

#[cfg(test)]
#[path = "audit_tests.rs"]
mod audit_tests;