Skip to main content

ShadowMemory

Struct ShadowMemory 

Source
pub struct ShadowMemory { /* private fields */ }
Expand description

Append-only per-session event store for cross-turn goal trajectory analysis.

Create via ShadowMemory::new with a ShadowMemoryConfig. Returns None when the config has enabled = false, so callers can wrap it in Option<ShadowMemory>.

Wired into the agent tool executor via crates/zeph-core/src/agent/tool_execution/tier_loop.rs: after every tool batch completes, goal_drift_score() is called and a zeph_common::SecurityEventCategory::GoalDrift security event is emitted when an alert occurs.

§Examples

use zeph_sanitizer::shadow_memory::{ShadowMemory, ShadowEvent};
use zeph_config::ShadowMemoryConfig;

let config = ShadowMemoryConfig { enabled: true, ..Default::default() };
let mut mem = ShadowMemory::new(&config).expect("enabled");

// Returns None when disabled.
let config_off = ShadowMemoryConfig { enabled: false, ..Default::default() };
assert!(ShadowMemory::new(&config_off).is_none());

Implementations§

Source§

impl ShadowMemory

Source

pub fn new(config: &ShadowMemoryConfig) -> Option<Self>

Construct a new ShadowMemory from config.

Returns None when config.enabled is false.

§Examples
use zeph_sanitizer::shadow_memory::ShadowMemory;
use zeph_config::ShadowMemoryConfig;

let config = ShadowMemoryConfig { enabled: true, ..Default::default() };
assert!(ShadowMemory::new(&config).is_some());
Source

pub fn record(&mut self, event: ShadowEvent)

Append a safety event after a tool batch completes.

Evicts the oldest event with O(1) cost when max_events is reached. Truncates event.goal_summary to 100 characters at a UTF-8 boundary.

§Examples
use zeph_sanitizer::shadow_memory::{ShadowMemory, ShadowEvent};
use zeph_config::ShadowMemoryConfig;

let config = ShadowMemoryConfig { enabled: true, max_events: 2, ..Default::default() };
let mut mem = ShadowMemory::new(&config).unwrap();

mem.record(ShadowEvent { turn: 0, tools: vec![], max_permission_class: 0,
    deviation_score: 0.0, goal_summary: "task A".to_owned() });
mem.record(ShadowEvent { turn: 1, tools: vec![], max_permission_class: 0,
    deviation_score: 0.0, goal_summary: "task B".to_owned() });
mem.record(ShadowEvent { turn: 2, tools: vec![], max_permission_class: 0,
    deviation_score: 0.0, goal_summary: "task C".to_owned() });

assert_eq!(mem.len(), 2);
Source

pub fn goal_drift_score(&self) -> GoalDriftResult

Compute the goal drift score over the trailing window.

Returns a GoalDriftResult with both the raw score and a pre-computed alert flag. Callers must use result.should_alert to decide whether to emit a security event — do not compare result.score against the threshold directly.

Returns score 0.0 / should_alert = false when fewer than 2 events are recorded (no baseline to compare).

§Algorithm
  1. Semantic drift: average pairwise Jaccard distance between consecutive goal_summary values in the window. Empty summaries produce maximum distance.
  2. Permission escalation: +0.3 when max_permission_class increases from window start to window end.
  3. Deviation accumulation: fraction of events where deviation_score exceeds drift_threshold * 0.5.

Weighted combination: 0.5 * semantic_drift + 0.25 * perm_escalation + 0.25 * deviation_ratio.

Note: Jaccard distance is gameable by synonym substitution (known v1 limitation).

§Examples
use zeph_sanitizer::shadow_memory::{ShadowMemory, ShadowEvent};
use zeph_config::ShadowMemoryConfig;

let config = ShadowMemoryConfig { enabled: true, ..Default::default() };
let mut mem = ShadowMemory::new(&config).unwrap();

// Fewer than 2 events → 0.0, no alert
let result = mem.goal_drift_score();
assert!(result.score < 1e-6);
assert!(!result.should_alert);
Source

pub fn config(&self) -> &ShadowMemoryConfig

Returns a reference to the config used to construct this instance.

Source

pub fn len(&self) -> usize

Number of recorded events.

§Examples
use zeph_sanitizer::shadow_memory::{ShadowMemory, ShadowEvent};
use zeph_config::ShadowMemoryConfig;

let config = ShadowMemoryConfig { enabled: true, ..Default::default() };
let mut mem = ShadowMemory::new(&config).unwrap();
assert_eq!(mem.len(), 0);
Source

pub fn is_empty(&self) -> bool

Returns true when no events have been recorded.

§Examples
use zeph_sanitizer::shadow_memory::ShadowMemory;
use zeph_config::ShadowMemoryConfig;

let config = ShadowMemoryConfig { enabled: true, ..Default::default() };
let mem = ShadowMemory::new(&config).unwrap();
assert!(mem.is_empty());

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

impl<L> LayerExt<L> for L

Source§

fn named_layer<S>(&self, service: S) -> Layered<<L as Layer<S>>::Service, S>
where L: Layer<S>,

Applies the layer to a service and wraps it in Layered.
Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more