Skip to main content

gemini_adk_rs/
state.rs

1//! Typed key-value state container for agents.
2//!
3//! Supports optional delta tracking for transactional state management
4//! and prefix-scoped accessors for namespace isolation.
5
6use std::collections::{HashMap, VecDeque};
7use std::marker::PhantomData;
8use std::sync::Arc;
9use std::sync::atomic::{AtomicU64, Ordering};
10use std::time::SystemTime;
11
12use dashmap::DashMap;
13
14use crate::clock::{SharedClock, system_clock};
15use serde_json::Value;
16
17const DEFAULT_MUTATION_JOURNAL_CAPACITY: usize = 1024;
18
19/// A compile-time typed state key that eliminates typo bugs and type mismatches.
20///
21/// Create as a const and use with `State::get_key()` / `State::set_key()`:
22///
23/// ```rust,ignore
24/// const TURN_COUNT: StateKey<u32> = StateKey::new("session:turn_count");
25/// const SENTIMENT: StateKey<String> = StateKey::new("derived:sentiment");
26///
27/// state.set_key(&TURN_COUNT, 5);
28/// let count: Option<u32> = state.get_key(&TURN_COUNT);
29/// ```
30pub struct StateKey<T> {
31    key: &'static str,
32    _phantom: PhantomData<fn() -> T>,
33}
34
35impl<T> StateKey<T> {
36    /// Create a new typed state key.
37    pub const fn new(key: &'static str) -> Self {
38        Self {
39            key,
40            _phantom: PhantomData,
41        }
42    }
43
44    /// The string key.
45    pub const fn key(&self) -> &'static str {
46        self.key
47    }
48}
49
50/// Where a state mutation came from.
51#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
52#[serde(rename_all = "snake_case")]
53pub enum StateMutationOrigin {
54    /// Regular `State::set` or prefixed state write.
55    Set,
56    /// Direct committed-store write that bypasses delta tracking.
57    SetCommitted,
58    /// Removal of a single key.
59    Remove,
60    /// Removal caused by clearing a prefix.
61    ClearPrefix,
62    /// Delta changes committed into the base state.
63    Commit,
64}
65
66/// A single state mutation recorded in the bounded mutation journal.
67///
68/// Serializes to/from JSON for durable journaling (see [`JournalSink`]);
69/// `timestamp` is encoded as integer milliseconds since the Unix epoch.
70#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
71pub struct StateMutation {
72    /// Monotonic sequence number assigned when the mutation was recorded.
73    pub sequence: u64,
74    /// State key that changed.
75    pub key: String,
76    /// Value before the mutation, or `None` when the key did not exist.
77    pub old: Option<Value>,
78    /// Value after the mutation, or `None` when the key was removed.
79    pub new: Option<Value>,
80    /// Operation that recorded the mutation.
81    pub origin: StateMutationOrigin,
82    /// Wall-clock time at which the mutation was recorded.
83    /// Serialized as milliseconds since the Unix epoch (`timestamp_ms`).
84    #[serde(rename = "timestamp_ms", with = "systemtime_epoch_millis")]
85    pub timestamp: SystemTime,
86    /// Whether the mutation was written to a delta-tracked view.
87    pub delta: bool,
88}
89
90/// Serde codec mapping [`SystemTime`] to/from integer epoch milliseconds.
91mod systemtime_epoch_millis {
92    use std::time::{Duration, SystemTime, UNIX_EPOCH};
93
94    use serde::{Deserialize, Deserializer, Serializer};
95
96    pub(super) fn serialize<S: Serializer>(t: &SystemTime, ser: S) -> Result<S::Ok, S::Error> {
97        let millis = t
98            .duration_since(UNIX_EPOCH)
99            .map(|d| d.as_millis() as u64)
100            .unwrap_or(0);
101        ser.serialize_u64(millis)
102    }
103
104    pub(super) fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<SystemTime, D::Error> {
105        let millis = u64::deserialize(de)?;
106        Ok(UNIX_EPOCH + Duration::from_millis(millis))
107    }
108}
109
110/// Synchronous, durable sink for state mutations.
111///
112/// The in-memory mutation journal is a bounded ring (1024 entries) — long
113/// sessions lose history. A `JournalSink` receives every mutation as it is
114/// recorded so it can be persisted in full.
115///
116/// `write` runs on the state-write hot path (under the journal lock): it must
117/// be cheap, must not await, and must not panic — implementations log internal
118/// errors instead of surfacing them.
119pub trait JournalSink: Send + Sync {
120    /// Persist one mutation. Must not panic; log errors internally.
121    fn write(&self, m: &StateMutation);
122}
123
124/// Shared, swappable [`JournalSink`] slot — one slot per [`State`] family
125/// (clones and delta views share it, like the in-memory ring).
126#[derive(Clone, Default)]
127struct JournalSinkSlot(Arc<parking_lot::RwLock<Option<Arc<dyn JournalSink>>>>);
128
129/// The value that stands in for a redacted key wherever state leaves the
130/// process.
131pub const REDACTED: &str = "[redacted]";
132
133/// The redacted keys shared by a `State`, its clones and its delta views.
134#[derive(Clone, Default, Debug)]
135struct RedactionSlot(Arc<parking_lot::RwLock<Arc<std::collections::BTreeSet<String>>>>);
136
137/// The clock shared by a `State`, its clones and its delta views.
138#[derive(Clone)]
139struct ClockSlot(Arc<parking_lot::RwLock<SharedClock>>);
140
141impl Default for ClockSlot {
142    fn default() -> Self {
143        Self(Arc::new(parking_lot::RwLock::new(system_clock())))
144    }
145}
146
147impl std::fmt::Debug for ClockSlot {
148    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
149        f.debug_tuple("ClockSlot").field(&*self.0.read()).finish()
150    }
151}
152
153impl std::fmt::Debug for JournalSinkSlot {
154    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
155        let installed = self.0.read().is_some();
156        f.debug_tuple("JournalSinkSlot").field(&installed).finish()
157    }
158}
159
160const JOURNAL_FLUSH_INTERVAL: std::time::Duration = std::time::Duration::from_secs(1);
161
162/// Log a journal-sink internal error without panicking the write path
163/// (journaling is infallible by contract, so the error is only reported).
164fn journal_log_error(context: &'static str, e: &dyn std::fmt::Display) {
165    tracing::warn!(error = %e, "{context}");
166}
167
168struct FileJournalInner {
169    writer: std::io::BufWriter<std::fs::File>,
170    last_flush: std::time::Instant,
171}
172
173/// Durable [`JournalSink`] writing one JSON object per line (JSONL).
174///
175/// Writes are buffered behind a `parking_lot::Mutex` and flushed at least
176/// every second and on drop. I/O errors are logged via `tracing::warn!` —
177/// journaling never panics a state write.
178///
179/// ```jsonl
180/// {"sequence":1,"key":"app:last_city","old":null,"new":"London","origin":"set","timestamp_ms":1718000000000,"delta":false}
181/// ```
182pub struct FileJournalSink {
183    inner: parking_lot::Mutex<FileJournalInner>,
184}
185
186impl FileJournalSink {
187    /// Create (truncating) the journal file at `path`.
188    pub fn create(path: impl AsRef<std::path::Path>) -> std::io::Result<Self> {
189        let file = std::fs::File::create(path)?;
190        Ok(Self {
191            inner: parking_lot::Mutex::new(FileJournalInner {
192                writer: std::io::BufWriter::new(file),
193                last_flush: std::time::Instant::now(),
194            }),
195        })
196    }
197
198    /// Flush buffered mutations to disk now.
199    pub fn flush(&self) {
200        let mut inner = self.inner.lock();
201        if let Err(e) = std::io::Write::flush(&mut inner.writer) {
202            journal_log_error("FileJournalSink flush failed", &e);
203        }
204        inner.last_flush = std::time::Instant::now();
205    }
206}
207
208impl JournalSink for FileJournalSink {
209    fn write(&self, m: &StateMutation) {
210        let line = match serde_json::to_string(m) {
211            Ok(line) => line,
212            Err(e) => {
213                journal_log_error("FileJournalSink serialize failed", &e);
214                return;
215            }
216        };
217        let mut inner = self.inner.lock();
218        if let Err(e) = std::io::Write::write_all(&mut inner.writer, line.as_bytes())
219            .and_then(|()| std::io::Write::write_all(&mut inner.writer, b"\n"))
220        {
221            journal_log_error("FileJournalSink write failed", &e);
222            return;
223        }
224        if inner.last_flush.elapsed() >= JOURNAL_FLUSH_INTERVAL {
225            if let Err(e) = std::io::Write::flush(&mut inner.writer) {
226                journal_log_error("FileJournalSink flush failed", &e);
227            }
228            inner.last_flush = std::time::Instant::now();
229        }
230    }
231}
232
233/// Whether two state values say the same thing.
234///
235/// Strings compare after lowercasing and dropping spaces and punctuation, so
236/// "tomorrow at 7 pm" and "Tomorrow at 7 PM." are equal. Punctuation between
237/// two digits is kept: it is part of a number, time, date or identifier, so
238/// "1.0 mg" and "10 mg", or "10:30" and "1030", differ. Numbers
239/// compare by value (`4` and `4.0`), and a number equals a string that spells
240/// it ("4"). Arrays and objects compare element by element.
241///
242/// An extractor re-reads the transcript every turn and re-states values it
243/// already found in slightly different words; those re-statements are not
244/// corrections.
245pub fn equivalent_values(a: &Value, b: &Value) -> bool {
246    fn text(s: &str) -> String {
247        let chars: Vec<char> = s.chars().collect();
248        let digit = |c: Option<&char>| c.is_some_and(char::is_ascii_digit);
249        let mut out = String::new();
250        for (i, c) in chars.iter().enumerate() {
251            if c.is_alphanumeric() {
252                out.extend(c.to_lowercase());
253            } else if !c.is_whitespace() {
254                let before = chars[..i].iter().rev().find(|c| !c.is_whitespace());
255                let after = chars[i + 1..].iter().find(|c| !c.is_whitespace());
256                if digit(before) && digit(after) {
257                    out.push(*c);
258                }
259            }
260        }
261        out
262    }
263    fn number(v: &Value) -> Option<f64> {
264        match v {
265            Value::Number(n) => n.as_f64(),
266            Value::String(s) => s.trim().parse().ok(),
267            _ => None,
268        }
269    }
270    match (a, b) {
271        (Value::String(x), Value::String(y)) => text(x) == text(y),
272        (Value::Number(_), _) | (_, Value::Number(_)) => {
273            matches!((number(a), number(b)), (Some(x), Some(y)) if x == y)
274        }
275        (Value::Array(x), Value::Array(y)) => {
276            x.len() == y.len() && x.iter().zip(y).all(|(p, q)| equivalent_values(p, q))
277        }
278        (Value::Object(x), Value::Object(y)) => {
279            x.len() == y.len()
280                && x.iter()
281                    .all(|(k, v)| y.get(k).is_some_and(|w| equivalent_values(v, w)))
282        }
283        _ => a == b,
284    }
285}
286
287/// Read a journal written by [`FileJournalSink`].
288pub fn read_journal(path: impl AsRef<std::path::Path>) -> std::io::Result<Vec<StateMutation>> {
289    parse_journal(&std::fs::read_to_string(path)?)
290}
291
292/// Parse journal JSONL text: one [`StateMutation`] per non-blank line.
293pub fn parse_journal(data: &str) -> std::io::Result<Vec<StateMutation>> {
294    data.lines()
295        .enumerate()
296        .filter(|(_, line)| !line.trim().is_empty())
297        .map(|(n, line)| {
298            serde_json::from_str(line).map_err(|e| {
299                std::io::Error::new(
300                    std::io::ErrorKind::InvalidData,
301                    format!("journal line {}: {e}", n + 1),
302                )
303            })
304        })
305        .collect()
306}
307
308impl Drop for FileJournalSink {
309    fn drop(&mut self) {
310        if let Err(e) = std::io::Write::flush(&mut self.inner.lock().writer) {
311            journal_log_error("FileJournalSink final flush failed", &e);
312        }
313    }
314}
315
316/// In-memory [`JournalSink`] for tests and replay harnesses. Unbounded.
317#[derive(Default)]
318pub struct MemoryJournalSink {
319    entries: parking_lot::Mutex<Vec<StateMutation>>,
320}
321
322impl MemoryJournalSink {
323    /// Create an empty sink.
324    pub fn new() -> Self {
325        Self::default()
326    }
327
328    /// Snapshot all recorded mutations (in write order).
329    pub fn entries(&self) -> Vec<StateMutation> {
330        self.entries.lock().clone()
331    }
332
333    /// Number of recorded mutations.
334    pub fn len(&self) -> usize {
335        self.entries.lock().len()
336    }
337
338    /// Whether nothing has been recorded yet.
339    pub fn is_empty(&self) -> bool {
340        self.entries.lock().is_empty()
341    }
342}
343
344impl JournalSink for MemoryJournalSink {
345    fn write(&self, m: &StateMutation) {
346        self.entries.lock().push(m.clone());
347    }
348}
349
350/// Error returned by fallible state reads and writes.
351#[derive(Debug, thiserror::Error)]
352pub enum StateError {
353    /// The value could not be serialized to JSON.
354    #[error("failed to serialize state value for key '{key}': {source}")]
355    Serialize {
356        /// The key that was being written.
357        key: String,
358        /// The underlying serde error.
359        source: serde_json::Error,
360    },
361    /// A value is present at the key but does not deserialize to the
362    /// requested type (see [`State::try_get`]).
363    #[error("state value at key '{key}' is not the requested type: {source}")]
364    WrongType {
365        /// The key that was being read.
366        key: String,
367        /// The underlying serde error.
368        source: serde_json::Error,
369    },
370}
371
372/// A pending write in a delta-tracked view.
373///
374/// Unlike a bare value, this distinguishes a *write* from a *removal* so that a
375/// delta can record tombstones and `rollback()` can restore the base state
376/// after removals and prefix clears.
377#[derive(Debug, Clone)]
378enum DeltaOp {
379    /// Set the key to this value on commit.
380    Put(Value),
381    /// Remove the key on commit (tombstone — shadows the committed value).
382    Delete,
383}
384
385/// Provenance and confidence for a single state slot — the evidence behind a
386/// value, aggregated from the mutation journal and the `state_meta:{key}` record.
387///
388/// This is what lets the model confirm principled-ly ("I heard 6, right?"):
389/// whether a slot was directly set, resolved from a system, or carries low
390/// confidence, and when it last changed.
391#[derive(Debug, Clone, serde::Serialize)]
392pub struct SlotEvidence {
393    /// The state key.
394    pub key: String,
395    /// Whether the key currently has a value.
396    pub present: bool,
397    /// The current value, if any.
398    pub value: Option<Value>,
399    /// Provenance source from `state_meta:{key}.source` (e.g. `agent`/`fetch`/
400    /// `llm`/`extraction`), if recorded.
401    pub source: Option<String>,
402    /// Confidence from `state_meta:{key}.confidence` (0.0–1.0), if recorded.
403    pub confidence: Option<f64>,
404    /// Journal sequence of the most recent write to this key, if still in the
405    /// bounded journal window.
406    pub last_sequence: Option<u64>,
407    /// Origin of the most recent recorded write, if known.
408    pub last_origin: Option<StateMutationOrigin>,
409}
410
411/// A concurrent, type-safe state container that agents read from and write to.
412///
413/// By default, `set()` writes directly to the inner store. When delta tracking
414/// is enabled via `with_delta_tracking()`, writes go to a separate delta map
415/// (with tombstones) that can be atomically committed or rolled back.
416#[derive(Debug, Clone)]
417pub struct State {
418    inner: Arc<DashMap<String, Value>>,
419    delta: Arc<DashMap<String, DeltaOp>>,
420    mutations: Arc<parking_lot::Mutex<VecDeque<StateMutation>>>,
421    next_mutation_sequence: Arc<AtomicU64>,
422    mutation_capacity: usize,
423    journal_sink: JournalSinkSlot,
424    clock: ClockSlot,
425    redacted: RedactionSlot,
426    track_delta: bool,
427}
428
429impl Default for State {
430    fn default() -> Self {
431        Self::new()
432    }
433}
434
435impl State {
436    /// Create a new empty state container.
437    pub fn new() -> Self {
438        Self {
439            inner: Arc::new(DashMap::new()),
440            delta: Arc::new(DashMap::new()),
441            mutations: Arc::new(parking_lot::Mutex::new(VecDeque::new())),
442            next_mutation_sequence: Arc::new(AtomicU64::new(1)),
443            mutation_capacity: DEFAULT_MUTATION_JOURNAL_CAPACITY,
444            journal_sink: JournalSinkSlot::default(),
445            clock: ClockSlot::default(),
446            redacted: RedactionSlot::default(),
447            track_delta: false,
448        }
449    }
450
451    /// Create a new State with delta tracking enabled.
452    /// Writes go to the delta map; reads check delta first, then inner.
453    pub fn with_delta_tracking(&self) -> State {
454        State {
455            inner: self.inner.clone(),
456            delta: Arc::new(DashMap::new()),
457            mutations: self.mutations.clone(),
458            next_mutation_sequence: self.next_mutation_sequence.clone(),
459            mutation_capacity: self.mutation_capacity,
460            journal_sink: self.journal_sink.clone(),
461            clock: self.clock.clone(),
462            redacted: self.redacted.clone(),
463            track_delta: true,
464        }
465    }
466
467    /// Install a durable [`JournalSink`] that receives every state mutation.
468    ///
469    /// The sink is shared with all clones and delta views of this `State`
470    /// (like the in-memory ring) and is invoked synchronously on the write
471    /// path — keep it cheap. The in-memory ring keeps serving
472    /// [`recent_mutations`](Self::recent_mutations)/[`evidence`](Self::evidence);
473    /// the sink adds unbounded durability.
474    pub fn set_journal_sink(&self, sink: Arc<dyn JournalSink>) {
475        *self.journal_sink.0.write() = Some(sink);
476    }
477
478    /// Builder-style variant of [`set_journal_sink`](Self::set_journal_sink).
479    pub fn with_journal_sink(self, sink: Arc<dyn JournalSink>) -> Self {
480        self.set_journal_sink(sink);
481        self
482    }
483
484    /// Replace the [`Clock`](crate::clock::Clock) this state and everything
485    /// sharing it read the time from. Defaults to the system clock.
486    ///
487    /// The clock is shared with every clone and delta view, like the journal
488    /// sink. Swap it before a session starts; components that captured an
489    /// instant from the old clock compare it against the new one.
490    pub fn set_clock(&self, clock: SharedClock) {
491        *self.clock.0.write() = clock;
492    }
493
494    /// Builder-style variant of [`set_clock`](Self::set_clock).
495    pub fn with_clock(self, clock: SharedClock) -> Self {
496        self.set_clock(clock);
497        self
498    }
499
500    /// The clock this state reads the time from.
501    pub fn clock(&self) -> SharedClock {
502        self.clock.0.read().clone()
503    }
504
505    /// Mark keys as sensitive: wherever this state's values leave the
506    /// process, a redacted key's value is replaced by [`REDACTED`]. That
507    /// covers the durable journal sink, persistence snapshots
508    /// ([`to_redacted_hashmap`](Self::to_redacted_hashmap)) and the runtime's
509    /// extraction events. Reads inside the process (`get`, guards, tools)
510    /// still see the real value.
511    ///
512    /// A key `k` also covers its scoped forms: `app:k`, `user:k`,
513    /// `state_meta:k`, and any other `prefix:k`. Shared with clones and
514    /// delta views. Adds to the keys already marked.
515    pub fn redact_keys<I, S>(&self, keys: I)
516    where
517        I: IntoIterator<Item = S>,
518        S: Into<String>,
519    {
520        let mut guard = self.redacted.0.write();
521        let mut set = (**guard).clone();
522        set.extend(keys.into_iter().map(Into::into));
523        *guard = Arc::new(set);
524    }
525
526    /// The keys marked sensitive with [`redact_keys`](Self::redact_keys).
527    pub fn redacted_keys(&self) -> std::collections::BTreeSet<String> {
528        (**self.redacted.0.read()).clone()
529    }
530
531    /// Whether `key` (or the base key under its scope prefix) is marked
532    /// sensitive.
533    pub fn is_redacted(&self, key: &str) -> bool {
534        let set = self.redacted.0.read().clone();
535        if set.is_empty() {
536            return false;
537        }
538        set.contains(key)
539            || key
540                .rsplit_once(':')
541                .is_some_and(|(_, base)| set.contains(base))
542    }
543
544    /// `value` as it may leave the process under `key`.
545    pub fn redact_value(&self, key: &str, value: &Value) -> Value {
546        if self.is_redacted(key) {
547            Value::String(REDACTED.into())
548        } else {
549            value.clone()
550        }
551    }
552
553    /// Mask the redacted fields of a JSON object (one level deep); other
554    /// values pass through.
555    pub fn redact_fields(&self, value: &Value) -> Value {
556        match value {
557            Value::Object(obj) if !self.redacted.0.read().is_empty() => Value::Object(
558                obj.iter()
559                    .map(|(k, v)| (k.clone(), self.redact_value(k, v)))
560                    .collect(),
561            ),
562            other => other.clone(),
563        }
564    }
565
566    /// [`to_hashmap`](Self::to_hashmap) with redacted keys masked: what a
567    /// persistence snapshot or an export should hold.
568    pub fn to_redacted_hashmap(&self) -> HashMap<String, Value> {
569        self.to_hashmap()
570            .into_iter()
571            .map(|(k, v)| {
572                let v = self.redact_value(&k, &v);
573                (k, v)
574            })
575            .collect()
576    }
577
578    /// Get a value by key, attempting to deserialize to the requested type.
579    /// When delta tracking is enabled, checks delta first, then inner.
580    ///
581    /// This is the *lenient* read: a value that is present but of the wrong
582    /// type is reported as `None`, indistinguishable from an absent key. Use
583    /// [`try_get`](Self::try_get) when that distinction matters.
584    pub fn get<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
585        self.get_raw(key)
586            .and_then(|v| serde_json::from_value(v).ok())
587    }
588
589    /// Get a value by key, distinguishing "absent" from "present but the wrong
590    /// type".
591    ///
592    /// Returns `Ok(None)` when no value is stored at `key` (after the same
593    /// delta → inner → `derived:` lookup as [`get`](Self::get)), `Ok(Some(v))`
594    /// when the stored value deserializes to `T`, and
595    /// [`StateError::WrongType`] when a value exists but does not. This is the
596    /// *strict* read; [`get`](Self::get) is the lenient form that folds the
597    /// error case into `None`.
598    pub fn try_get<T: serde::de::DeserializeOwned>(
599        &self,
600        key: &str,
601    ) -> Result<Option<T>, StateError> {
602        match self.get_raw(key) {
603            None => Ok(None),
604            Some(v) => {
605                serde_json::from_value(v)
606                    .map(Some)
607                    .map_err(|source| StateError::WrongType {
608                        key: key.to_string(),
609                        source,
610                    })
611            }
612        }
613    }
614
615    /// Borrow a value by key without cloning, applying `f` to the reference.
616    ///
617    /// This is the zero-copy alternative to `get_raw()`. The closure receives
618    /// a `&Value` directly from the DashMap ref-guard, avoiding the
619    /// `Value::clone()` + `serde_json::from_value()` overhead of `get()`.
620    ///
621    /// Lookup order: delta (if tracking) → inner → derived fallback.
622    pub fn with<F, R>(&self, key: &str, f: F) -> Option<R>
623    where
624        F: FnOnce(&Value) -> R,
625    {
626        if self.track_delta {
627            match self.delta.get(key).map(|r| r.value().clone()) {
628                Some(DeltaOp::Put(v)) => return Some(f(&v)),
629                Some(DeltaOp::Delete) => return None, // tombstone shadows inner
630                None => {}
631            }
632        }
633        if let Some(ref_multi) = self.inner.get(key) {
634            return Some(f(ref_multi.value()));
635        }
636        if !key.contains(':') {
637            let mut derived_key = String::with_capacity(8 + key.len());
638            use std::fmt::Write;
639            let _ = write!(derived_key, "derived:{key}");
640            if self.track_delta {
641                match self.delta.get(&derived_key).map(|r| r.value().clone()) {
642                    Some(DeltaOp::Put(v)) => return Some(f(&v)),
643                    Some(DeltaOp::Delete) => return None,
644                    None => {}
645                }
646            }
647            if let Some(ref_multi) = self.inner.get(&derived_key) {
648                return Some(f(ref_multi.value()));
649            }
650        }
651        None
652    }
653
654    /// Get a raw JSON value by key.
655    /// When delta tracking is enabled, checks delta first, then inner.
656    /// If the key is not found and doesn't contain a prefix, also checks `derived:{key}`
657    /// as a transparent fallback for computed variables.
658    pub fn get_raw(&self, key: &str) -> Option<Value> {
659        if self.track_delta {
660            match self.delta.get(key).map(|r| r.value().clone()) {
661                Some(DeltaOp::Put(v)) => return Some(v),
662                Some(DeltaOp::Delete) => return None, // tombstone shadows inner
663                None => {}
664            }
665        }
666        if let Some(v) = self.inner.get(key) {
667            return Some(v.value().clone());
668        }
669        // Transparent derived fallback: if key has no prefix, check derived:{key}
670        if !key.contains(':') {
671            use std::fmt::Write;
672            let mut derived_key = String::with_capacity(8 + key.len());
673            let _ = write!(derived_key, "derived:{key}");
674            if self.track_delta {
675                match self.delta.get(&derived_key).map(|r| r.value().clone()) {
676                    Some(DeltaOp::Put(v)) => return Some(v),
677                    Some(DeltaOp::Delete) => return None,
678                    None => {}
679                }
680            }
681            return self.inner.get(&derived_key).map(|v| v.value().clone());
682        }
683        None
684    }
685
686    /// Get a typed value using a `StateKey<T>` (lenient — a wrong-typed value
687    /// reads as `None`; see [`get`](Self::get)).
688    pub fn get_key<T: serde::de::DeserializeOwned>(&self, key: &StateKey<T>) -> Option<T> {
689        self.get(key.key())
690    }
691
692    /// Get a typed value using a `StateKey<T>`, distinguishing "absent" from
693    /// "present but the wrong type" (see [`try_get`](Self::try_get)).
694    pub fn try_get_key<T: serde::de::DeserializeOwned>(
695        &self,
696        key: &StateKey<T>,
697    ) -> Result<Option<T>, StateError> {
698        self.try_get(key.key())
699    }
700
701    /// Set a typed value using a `StateKey<T>`.
702    ///
703    /// Returns [`StateError`] if `value` cannot be serialized to JSON.
704    pub fn set_key<T: serde::Serialize>(
705        &self,
706        key: &StateKey<T>,
707        value: T,
708    ) -> Result<(), StateError> {
709        self.set(key.key(), value)
710    }
711
712    /// Zero-copy borrow using a `StateKey<T>`.
713    pub fn with_key<T, F, R>(&self, key: &StateKey<T>, f: F) -> Option<R>
714    where
715        F: FnOnce(&Value) -> R,
716    {
717        self.with(key.key(), f)
718    }
719
720    /// Set a value by key.
721    ///
722    /// When delta tracking is enabled, writes to the delta view instead of the
723    /// committed store. Returns [`StateError`] if `value` cannot be serialized
724    /// to JSON — a public SDK write never panics on caller data.
725    pub fn set(
726        &self,
727        key: impl Into<String>,
728        value: impl serde::Serialize,
729    ) -> Result<(), StateError> {
730        let key = key.into();
731        let v = serde_json::to_value(value).map_err(|source| StateError::Serialize {
732            key: key.clone(),
733            source,
734        })?;
735        self.put_value(key, v, StateMutationOrigin::Set);
736        Ok(())
737    }
738
739    /// Infallible internal write of an already-serialized [`Value`].
740    ///
741    /// Shared by `set` and the value-level helpers (`merge`/`pick`/`rename`/
742    /// `from_hashmap`) so those do not re-serialize and cannot fail.
743    fn put_value(&self, key: String, v: Value, origin: StateMutationOrigin) {
744        let old = self.get_raw(&key);
745        if self.track_delta {
746            self.delta.insert(key.clone(), DeltaOp::Put(v.clone()));
747        } else {
748            self.inner.insert(key.clone(), v.clone());
749        }
750        self.record_mutation(key, old, Some(v), origin);
751    }
752
753    /// Set a value directly in the committed store, bypassing delta tracking.
754    ///
755    /// Returns [`StateError`] if `value` cannot be serialized to JSON.
756    pub fn set_committed(
757        &self,
758        key: impl Into<String>,
759        value: impl serde::Serialize,
760    ) -> Result<(), StateError> {
761        let key = key.into();
762        let v = serde_json::to_value(value).map_err(|source| StateError::Serialize {
763            key: key.clone(),
764            source,
765        })?;
766        let old = self.inner.insert(key.clone(), v.clone());
767        self.record_mutation(key, old, Some(v), StateMutationOrigin::SetCommitted);
768        Ok(())
769    }
770
771    /// Atomically read-modify-write a value under a per-key lock.
772    ///
773    /// If the key doesn't exist, `default` is used as the initial value. The
774    /// function `f` receives the current value and returns the new value. The
775    /// read-modify-write is performed while holding the map shard for `key`, so
776    /// concurrent `modify` calls on the same key do not lose updates. Returns
777    /// the new value, or [`StateError`] if it cannot be serialized.
778    pub fn modify<T, F>(&self, key: &str, default: T, f: F) -> Result<T, StateError>
779    where
780        T: serde::Serialize + serde::de::DeserializeOwned,
781        F: FnOnce(T) -> T,
782    {
783        use dashmap::mapref::entry::Entry;
784
785        let serialize = |key: &str, val: &T| {
786            serde_json::to_value(val).map_err(|source| StateError::Serialize {
787                key: key.to_string(),
788                source,
789            })
790        };
791
792        if self.track_delta {
793            // Atomic w.r.t. the delta shard; the committed base is read as the
794            // initial value only when the delta has no entry for this key.
795            match self.delta.entry(key.to_string()) {
796                Entry::Occupied(mut o) => {
797                    let current = match o.get() {
798                        DeltaOp::Put(v) => serde_json::from_value(v.clone()).unwrap_or(default),
799                        DeltaOp::Delete => default,
800                    };
801                    let old = self.inner.get(key).map(|r| r.value().clone());
802                    let new_val = f(current);
803                    let v = serialize(key, &new_val)?;
804                    o.insert(DeltaOp::Put(v.clone()));
805                    self.record_mutation(key.to_string(), old, Some(v), StateMutationOrigin::Set);
806                    Ok(new_val)
807                }
808                Entry::Vacant(slot) => {
809                    let base = self
810                        .inner
811                        .get(key)
812                        .and_then(|r| serde_json::from_value(r.value().clone()).ok());
813                    let old = self.inner.get(key).map(|r| r.value().clone());
814                    let new_val = f(base.unwrap_or(default));
815                    let v = serialize(key, &new_val)?;
816                    slot.insert(DeltaOp::Put(v.clone()));
817                    self.record_mutation(key.to_string(), old, Some(v), StateMutationOrigin::Set);
818                    Ok(new_val)
819                }
820            }
821        } else {
822            match self.inner.entry(key.to_string()) {
823                Entry::Occupied(mut o) => {
824                    let old = o.get().clone();
825                    let current = serde_json::from_value(old.clone()).unwrap_or(default);
826                    let new_val = f(current);
827                    let v = serialize(key, &new_val)?;
828                    o.insert(v.clone());
829                    self.record_mutation(
830                        key.to_string(),
831                        Some(old),
832                        Some(v),
833                        StateMutationOrigin::Set,
834                    );
835                    Ok(new_val)
836                }
837                Entry::Vacant(slot) => {
838                    let new_val = f(default);
839                    let v = serialize(key, &new_val)?;
840                    slot.insert(v.clone());
841                    self.record_mutation(key.to_string(), None, Some(v), StateMutationOrigin::Set);
842                    Ok(new_val)
843                }
844            }
845        }
846    }
847
848    /// Check if a key exists (in delta or inner).
849    ///
850    /// Applies the same transparent `derived:` fallback as [`Self::get`],
851    /// [`Self::get_raw`] and [`Self::with`]: an unprefixed key also matches the
852    /// computed variable `derived:{key}`. Flow predicates (`is_set`, `captured`)
853    /// evaluate through this method, so without the fallback a computed value
854    /// would read as permanently unknown while `get` returned it fine.
855    pub fn contains(&self, key: &str) -> bool {
856        if self.track_delta {
857            match self.delta.get(key).map(|r| r.value().clone()) {
858                Some(DeltaOp::Put(_)) => return true,
859                Some(DeltaOp::Delete) => return false, // tombstone shadows inner
860                None => {}
861            }
862        }
863        if self.inner.contains_key(key) {
864            return true;
865        }
866        if !key.contains(':') {
867            let derived_key = format!("derived:{key}");
868            if self.track_delta {
869                match self.delta.get(&derived_key).map(|r| r.value().clone()) {
870                    Some(DeltaOp::Put(_)) => return true,
871                    Some(DeltaOp::Delete) => return false,
872                    None => {}
873                }
874            }
875            return self.inner.contains_key(&derived_key);
876        }
877        false
878    }
879
880    /// Remove a key.
881    ///
882    /// In delta-tracking mode this records a tombstone in the delta view and
883    /// leaves the committed store untouched, so a subsequent `rollback()` fully
884    /// restores the base state. Returns the value that was visible before removal.
885    pub fn remove(&self, key: &str) -> Option<Value> {
886        if self.track_delta {
887            let removed = self.get_raw(key);
888            // Tombstone in the delta — never mutate `inner` directly, so rollback
889            // can restore the committed value.
890            self.delta.insert(key.to_string(), DeltaOp::Delete);
891            if let Some(ref old) = removed {
892                self.record_mutation(
893                    key.to_string(),
894                    Some(old.clone()),
895                    None,
896                    StateMutationOrigin::Remove,
897                );
898            }
899            removed
900        } else {
901            let removed = self.inner.remove(key).map(|(_, v)| v);
902            if let Some(ref old) = removed {
903                self.record_mutation(
904                    key.to_string(),
905                    Some(old.clone()),
906                    None,
907                    StateMutationOrigin::Remove,
908                );
909            }
910            removed
911        }
912    }
913
914    /// Get all keys (from both inner and delta when tracking).
915    ///
916    /// Keys tombstoned in the delta are excluded.
917    pub fn keys(&self) -> Vec<String> {
918        if !self.track_delta || self.delta.is_empty() {
919            return self.inner.iter().map(|r| r.key().clone()).collect();
920        }
921        let mut seen =
922            std::collections::HashSet::with_capacity(self.inner.len() + self.delta.len());
923        let mut keys = Vec::with_capacity(self.inner.len() + self.delta.len());
924        // Delta first so tombstones win over committed entries.
925        for entry in self.delta.iter() {
926            let key = entry.key().clone();
927            seen.insert(key.clone());
928            if matches!(entry.value(), DeltaOp::Put(_)) {
929                keys.push(key);
930            }
931        }
932        for entry in self.inner.iter() {
933            let key = entry.key().clone();
934            if seen.insert(key.clone()) {
935                keys.push(key);
936            }
937        }
938        keys
939    }
940
941    /// Create a new State containing only the specified keys.
942    pub fn pick(&self, keys: &[&str]) -> State {
943        let new = State::new().with_clock(self.clock());
944        new.redact_keys(self.redacted_keys());
945        for key in keys {
946            if let Some(v) = self.get_raw(key) {
947                new.put_value((*key).to_string(), v, StateMutationOrigin::Set);
948            }
949        }
950        new
951    }
952
953    /// Merge another state into this one (other's values overwrite on conflict).
954    pub fn merge(&self, other: &State) {
955        for entry in other.inner.iter() {
956            self.put_value(
957                entry.key().clone(),
958                entry.value().clone(),
959                StateMutationOrigin::Set,
960            );
961        }
962    }
963
964    /// Rename a key.
965    pub fn rename(&self, from: &str, to: &str) {
966        if let Some(v) = self.remove(from) {
967            self.put_value(to.to_string(), v, StateMutationOrigin::Set);
968        }
969    }
970
971    // ── Delta methods ──────────────────────────────────────────────────────
972
973    /// Whether delta tracking is enabled.
974    pub fn is_tracking_delta(&self) -> bool {
975        self.track_delta
976    }
977
978    /// Whether there are uncommitted delta changes.
979    pub fn has_delta(&self) -> bool {
980        self.track_delta && !self.delta.is_empty()
981    }
982
983    /// Get a snapshot of the current delta's pending writes (tombstones omitted).
984    pub fn delta(&self) -> HashMap<String, Value> {
985        self.delta
986            .iter()
987            .filter_map(|entry| match entry.value() {
988                DeltaOp::Put(v) => Some((entry.key().clone(), v.clone())),
989                DeltaOp::Delete => None,
990            })
991            .collect()
992    }
993
994    /// Commit delta changes into the inner store, then clear the delta.
995    ///
996    /// Pending puts are applied and tombstones remove the committed key, so a
997    /// removal made under delta tracking becomes durable only at commit time.
998    pub fn commit(&self) {
999        // Snapshot first so we don't iterate the delta while mutating `inner`.
1000        let ops: Vec<(String, DeltaOp)> = self
1001            .delta
1002            .iter()
1003            .map(|e| (e.key().clone(), e.value().clone()))
1004            .collect();
1005        for (key, op) in ops {
1006            match op {
1007                DeltaOp::Put(value) => {
1008                    let old = self.inner.insert(key.clone(), value.clone());
1009                    self.record_mutation_with_delta(
1010                        key,
1011                        old,
1012                        Some(value),
1013                        StateMutationOrigin::Commit,
1014                        false,
1015                    );
1016                }
1017                DeltaOp::Delete => {
1018                    if let Some((_, old)) = self.inner.remove(&key) {
1019                        self.record_mutation_with_delta(
1020                            key,
1021                            Some(old),
1022                            None,
1023                            StateMutationOrigin::Commit,
1024                            false,
1025                        );
1026                    }
1027                }
1028            }
1029        }
1030        self.delta.clear();
1031    }
1032
1033    /// Discard all uncommitted delta changes, restoring the committed base state.
1034    ///
1035    /// Because removals and prefix clears under delta tracking only write
1036    /// tombstones (never mutating `inner`), dropping the delta is sufficient to
1037    /// restore the base — including keys that were removed in the transaction.
1038    pub fn rollback(&self) {
1039        self.delta.clear();
1040    }
1041
1042    // ── Prefix accessors ───────────────────────────────────────────────────
1043
1044    /// Access state with the `app:` prefix scope.
1045    pub fn app(&self) -> PrefixedState<'_> {
1046        PrefixedState {
1047            state: self,
1048            prefix: "app:",
1049        }
1050    }
1051
1052    /// Access state with the `user:` prefix scope.
1053    pub fn user(&self) -> PrefixedState<'_> {
1054        PrefixedState {
1055            state: self,
1056            prefix: "user:",
1057        }
1058    }
1059
1060    /// Access state with the `temp:` prefix scope.
1061    pub fn temp(&self) -> PrefixedState<'_> {
1062        PrefixedState {
1063            state: self,
1064            prefix: "temp:",
1065        }
1066    }
1067
1068    /// Access state with the `session:` prefix scope (auto-tracked signals).
1069    pub fn session(&self) -> PrefixedState<'_> {
1070        PrefixedState {
1071            state: self,
1072            prefix: "session:",
1073        }
1074    }
1075
1076    /// Access state with the `turn:` prefix scope (reset each turn).
1077    pub fn turn(&self) -> PrefixedState<'_> {
1078        PrefixedState {
1079            state: self,
1080            prefix: "turn:",
1081        }
1082    }
1083
1084    /// Access state with the `bg:` prefix scope (background tasks).
1085    pub fn bg(&self) -> PrefixedState<'_> {
1086        PrefixedState {
1087            state: self,
1088            prefix: "bg:",
1089        }
1090    }
1091
1092    /// Access read-only state with the `derived:` prefix scope (computed vars only).
1093    pub fn derived(&self) -> ReadOnlyPrefixedState<'_> {
1094        ReadOnlyPrefixedState {
1095            state: self,
1096            prefix: "derived:",
1097        }
1098    }
1099
1100    // ── Utility methods ───────────────────────────────────────────────────
1101
1102    /// Snapshot the values of specific keys. Returns HashMap of key -> current value.
1103    /// Used by watchers to capture state before mutations.
1104    pub fn snapshot_values(&self, keys: &[&str]) -> HashMap<String, Value> {
1105        keys.iter()
1106            .filter_map(|&k| self.get_raw(k).map(|v| (k.to_string(), v)))
1107            .collect()
1108    }
1109
1110    /// Diff current state against a previous snapshot.
1111    /// Returns Vec of (key, old_value, new_value) for keys that changed.
1112    pub fn diff_values(
1113        &self,
1114        prev: &HashMap<String, Value>,
1115        keys: &[&str],
1116    ) -> Vec<(String, Value, Value)> {
1117        keys.iter()
1118            .filter_map(|&k| {
1119                let old = prev.get(k);
1120                let new = self.get_raw(k);
1121                match (old, new) {
1122                    (Some(o), Some(n)) if o != &n => Some((k.to_string(), o.clone(), n)),
1123                    (None, Some(n)) => Some((k.to_string(), Value::Null, n)),
1124                    (Some(o), None) => Some((k.to_string(), o.clone(), Value::Null)),
1125                    _ => None,
1126                }
1127            })
1128            .collect()
1129    }
1130
1131    /// Export all state as a HashMap (for persistence/serialization).
1132    pub fn to_hashmap(&self) -> std::collections::HashMap<String, serde_json::Value> {
1133        self.inner
1134            .iter()
1135            .map(|entry| (entry.key().clone(), entry.value().clone()))
1136            .collect()
1137    }
1138
1139    /// Restore state from a HashMap (for persistence/deserialization).
1140    pub fn from_hashmap(&self, map: std::collections::HashMap<String, serde_json::Value>) {
1141        for (key, value) in map {
1142            // Values are already `Value`, so this write cannot fail to serialize.
1143            let old = self.inner.insert(key.clone(), value.clone());
1144            self.record_mutation(key, old, Some(value), StateMutationOrigin::SetCommitted);
1145        }
1146    }
1147
1148    /// Remove all keys with the given prefix.
1149    ///
1150    /// In delta-tracking mode this writes tombstones for matching keys (from both
1151    /// the committed store and pending delta puts) without mutating the committed
1152    /// store, so `rollback()` restores everything that was cleared.
1153    pub fn clear_prefix(&self, prefix: &str) {
1154        if self.track_delta {
1155            let keys: Vec<String> = self
1156                .keys()
1157                .into_iter()
1158                .filter(|k| k.starts_with(prefix))
1159                .collect();
1160            for key in keys {
1161                let old = self.get_raw(&key);
1162                self.delta.insert(key.clone(), DeltaOp::Delete);
1163                if let Some(old) = old {
1164                    self.record_mutation(key, Some(old), None, StateMutationOrigin::ClearPrefix);
1165                }
1166            }
1167            return;
1168        }
1169        let keys_to_remove: Vec<String> = self
1170            .inner
1171            .iter()
1172            .filter(|entry| entry.key().starts_with(prefix))
1173            .map(|entry| entry.key().clone())
1174            .collect();
1175        for key in keys_to_remove {
1176            if let Some((_, old)) = self.inner.remove(&key) {
1177                self.record_mutation(key, Some(old), None, StateMutationOrigin::ClearPrefix);
1178            }
1179        }
1180    }
1181
1182    /// Return a snapshot of recent state mutations.
1183    pub fn recent_mutations(&self) -> Vec<StateMutation> {
1184        self.mutations.lock().iter().cloned().collect()
1185    }
1186
1187    /// Return the current monotonic cursor for the mutation journal.
1188    pub fn mutation_cursor(&self) -> u64 {
1189        self.next_mutation_sequence.load(Ordering::Relaxed) - 1
1190    }
1191
1192    /// Return mutations appended after a previously captured cursor.
1193    pub fn mutations_since(&self, cursor: u64) -> Vec<StateMutation> {
1194        let mutations = self.mutations.lock();
1195        mutations
1196            .iter()
1197            .filter(|mutation| mutation.sequence > cursor)
1198            .cloned()
1199            .collect()
1200    }
1201
1202    /// Mutations appended after `cursor`, or `None` if the bounded journal
1203    /// has already dropped some of them.
1204    ///
1205    /// A consumer that must see every change (a derived-value cache, say)
1206    /// uses this instead of [`mutations_since`](Self::mutations_since) and
1207    /// falls back to a full rescan on `None`.
1208    pub fn try_mutations_since(&self, cursor: u64) -> Option<Vec<StateMutation>> {
1209        let mutations = self.mutations.lock();
1210        let latest = self.next_mutation_sequence.load(Ordering::Relaxed) - 1;
1211        if latest > cursor {
1212            let oldest = mutations.front().map_or(u64::MAX, |m| m.sequence);
1213            if oldest > cursor + 1 {
1214                return None;
1215            }
1216        }
1217        Some(
1218            mutations
1219                .iter()
1220                .filter(|mutation| mutation.sequence > cursor)
1221                .cloned()
1222                .collect(),
1223        )
1224    }
1225
1226    /// Drain and return all recorded state mutations.
1227    pub fn drain_mutations(&self) -> Vec<StateMutation> {
1228        self.mutations.lock().drain(..).collect()
1229    }
1230
1231    /// Aggregate the [`SlotEvidence`] for a key: its current value, provenance
1232    /// (`state_meta:{key}`), confidence, and most-recent journal write.
1233    pub fn evidence(&self, key: &str) -> SlotEvidence {
1234        let value = self.get_raw(key);
1235        let meta = self.get::<Value>(&format!("state_meta:{key}"));
1236        let source = meta
1237            .as_ref()
1238            .and_then(|m| m.get("source"))
1239            .and_then(|s| s.as_str().map(String::from));
1240        let confidence = meta
1241            .as_ref()
1242            .and_then(|m| m.get("confidence"))
1243            .and_then(serde_json::Value::as_f64);
1244
1245        let mut last_sequence: Option<u64> = None;
1246        let mut last_origin: Option<StateMutationOrigin> = None;
1247        for m in self.recent_mutations() {
1248            if m.key == key && last_sequence.is_none_or(|s| m.sequence > s) {
1249                last_sequence = Some(m.sequence);
1250                last_origin = Some(m.origin);
1251            }
1252        }
1253
1254        SlotEvidence {
1255            key: key.to_string(),
1256            present: value.is_some(),
1257            value,
1258            source,
1259            confidence,
1260            last_sequence,
1261            last_origin,
1262        }
1263    }
1264
1265    fn record_mutation(
1266        &self,
1267        key: String,
1268        old: Option<Value>,
1269        new: Option<Value>,
1270        origin: StateMutationOrigin,
1271    ) {
1272        self.record_mutation_with_delta(key, old, new, origin, self.track_delta);
1273    }
1274
1275    fn record_mutation_with_delta(
1276        &self,
1277        key: String,
1278        old: Option<Value>,
1279        new: Option<Value>,
1280        origin: StateMutationOrigin,
1281        delta: bool,
1282    ) {
1283        let mut mutations = self.mutations.lock();
1284        if mutations.len() >= self.mutation_capacity {
1285            mutations.pop_front();
1286        }
1287        let sequence = self.next_mutation_sequence.fetch_add(1, Ordering::Relaxed);
1288        let mutation = StateMutation {
1289            sequence,
1290            key,
1291            old,
1292            new,
1293            origin,
1294            timestamp: self.clock().system_time(),
1295            delta,
1296        };
1297        // Durable sink runs under the journal lock so the file order matches
1298        // the ring order exactly. Sinks are sync + cheap by contract.
1299        if let Some(sink) = self.journal_sink.0.read().as_ref() {
1300            if self.is_redacted(&mutation.key) {
1301                let masked = |v: &Option<Value>| v.as_ref().map(|_| Value::String(REDACTED.into()));
1302                sink.write(&StateMutation {
1303                    old: masked(&mutation.old),
1304                    new: masked(&mutation.new),
1305                    ..mutation.clone()
1306                });
1307            } else {
1308                sink.write(&mutation);
1309            }
1310        }
1311        mutations.push_back(mutation);
1312    }
1313}
1314
1315/// A borrowed view of state that automatically prepends a prefix to all keys.
1316pub struct PrefixedState<'a> {
1317    state: &'a State,
1318    prefix: &'static str,
1319}
1320
1321impl<'a> PrefixedState<'a> {
1322    fn prefixed_key(&self, key: &str) -> String {
1323        format!("{}{}", self.prefix, key)
1324    }
1325
1326    /// Get a value by key (with prefix applied).
1327    pub fn get<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
1328        self.state.get(&self.prefixed_key(key))
1329    }
1330
1331    /// Get a raw JSON value by key (with prefix applied).
1332    pub fn get_raw(&self, key: &str) -> Option<Value> {
1333        self.state.get_raw(&self.prefixed_key(key))
1334    }
1335
1336    /// Zero-copy borrow a value by key (with prefix applied).
1337    pub fn with<F, R>(&self, key: &str, f: F) -> Option<R>
1338    where
1339        F: FnOnce(&Value) -> R,
1340    {
1341        self.state.with(&self.prefixed_key(key), f)
1342    }
1343
1344    /// Set a value by key (with prefix applied).
1345    ///
1346    /// Returns [`StateError`] if `value` cannot be serialized to JSON.
1347    pub fn set(
1348        &self,
1349        key: impl AsRef<str>,
1350        value: impl serde::Serialize,
1351    ) -> Result<(), StateError> {
1352        self.state.set(self.prefixed_key(key.as_ref()), value)
1353    }
1354
1355    /// Check if a key exists (with prefix applied).
1356    pub fn contains(&self, key: &str) -> bool {
1357        self.state.contains(&self.prefixed_key(key))
1358    }
1359
1360    /// Remove a key (with prefix applied).
1361    pub fn remove(&self, key: &str) -> Option<Value> {
1362        self.state.remove(&self.prefixed_key(key))
1363    }
1364
1365    /// Get all keys within this prefix scope (prefix stripped from results).
1366    pub fn keys(&self) -> Vec<String> {
1367        self.state
1368            .keys()
1369            .into_iter()
1370            .filter_map(|k| {
1371                k.strip_prefix(self.prefix)
1372                    .map(std::string::ToString::to_string)
1373            })
1374            .collect()
1375    }
1376}
1377
1378/// A borrowed, read-only view of state that automatically prepends a prefix to all keys.
1379///
1380/// Unlike `PrefixedState`, this does not expose `set()` or `remove()` methods,
1381/// making it suitable for computed/derived state that user code should not mutate.
1382pub struct ReadOnlyPrefixedState<'a> {
1383    state: &'a State,
1384    prefix: &'static str,
1385}
1386
1387impl<'a> ReadOnlyPrefixedState<'a> {
1388    fn prefixed_key(&self, key: &str) -> String {
1389        format!("{}{}", self.prefix, key)
1390    }
1391
1392    /// Get a value by key (with prefix applied).
1393    pub fn get<T: serde::de::DeserializeOwned>(&self, key: &str) -> Option<T> {
1394        self.state.get(&self.prefixed_key(key))
1395    }
1396
1397    /// Get a raw JSON value by key (with prefix applied).
1398    pub fn get_raw(&self, key: &str) -> Option<Value> {
1399        self.state.get_raw(&self.prefixed_key(key))
1400    }
1401
1402    /// Zero-copy borrow a value by key (with prefix applied).
1403    pub fn with<F, R>(&self, key: &str, f: F) -> Option<R>
1404    where
1405        F: FnOnce(&Value) -> R,
1406    {
1407        self.state.with(&self.prefixed_key(key), f)
1408    }
1409
1410    /// Check if a key exists (with prefix applied).
1411    pub fn contains(&self, key: &str) -> bool {
1412        self.state.contains(&self.prefixed_key(key))
1413    }
1414
1415    /// Get all keys within this prefix scope (prefix stripped from results).
1416    pub fn keys(&self) -> Vec<String> {
1417        self.state
1418            .keys()
1419            .into_iter()
1420            .filter_map(|k| {
1421                k.strip_prefix(self.prefix)
1422                    .map(std::string::ToString::to_string)
1423            })
1424            .collect()
1425    }
1426}
1427
1428#[cfg(test)]
1429mod tests {
1430    use super::*;
1431
1432    #[test]
1433    fn equivalent_values_ignore_wording_noise() {
1434        use serde_json::json;
1435        assert!(equivalent_values(
1436            &json!("tomorrow at 7 pm"),
1437            &json!("Tomorrow at 7 PM.")
1438        ));
1439        assert!(equivalent_values(&json!(4), &json!(4.0)));
1440        assert!(equivalent_values(&json!(4), &json!("4")));
1441        assert!(equivalent_values(
1442            &json!({ "verified": true, "name": "Rossi" }),
1443            &json!({ "name": "rossi", "verified": true })
1444        ));
1445        assert!(!equivalent_values(&json!("7 pm"), &json!("8 pm")));
1446        // Punctuation inside a number is part of it.
1447        assert!(!equivalent_values(&json!("1.0 mg"), &json!("10 mg")));
1448        assert!(!equivalent_values(&json!("10:30"), &json!("1030")));
1449        assert!(!equivalent_values(&json!("2026-10-20"), &json!("20261020")));
1450        assert!(equivalent_values(&json!("1.0 mg"), &json!("1.0 MG.")));
1451        assert!(equivalent_values(&json!("Rossi!"), &json!("rossi")));
1452        assert!(!equivalent_values(&json!(4), &json!(5)));
1453        assert!(!equivalent_values(&json!(true), &json!(false)));
1454        assert!(!equivalent_values(&json!("4"), &json!(true)));
1455    }
1456
1457    #[test]
1458    fn journal_sink_receives_every_mutation_in_ring_order() {
1459        let state = State::new();
1460        let sink = Arc::new(MemoryJournalSink::new());
1461        state.set_journal_sink(sink.clone());
1462
1463        let _ = state.set("a", 1);
1464        let _ = state.set("b", "two");
1465        state.remove("a");
1466
1467        let entries = sink.entries();
1468        assert_eq!(entries.len(), 3);
1469        assert_eq!(entries, state.recent_mutations());
1470        assert_eq!(entries[0].key, "a");
1471        assert_eq!(entries[2].origin, StateMutationOrigin::Remove);
1472    }
1473
1474    #[test]
1475    fn journal_sink_is_shared_with_clones_and_delta_views() {
1476        let state = State::new();
1477        let sink = Arc::new(MemoryJournalSink::new());
1478        state.set_journal_sink(sink.clone());
1479
1480        let clone = state.clone();
1481        let _ = clone.set("from_clone", true);
1482
1483        let tracked = state.with_delta_tracking();
1484        let _ = tracked.set("from_delta", 1);
1485        tracked.commit();
1486
1487        let keys: Vec<_> = sink.entries().iter().map(|m| m.key.clone()).collect();
1488        assert!(keys.contains(&"from_clone".to_string()));
1489        assert!(keys.contains(&"from_delta".to_string()));
1490        // Commit re-records the delta write into the committed store.
1491        assert!(
1492            sink.entries()
1493                .iter()
1494                .any(|m| m.origin == StateMutationOrigin::Commit)
1495        );
1496    }
1497
1498    #[test]
1499    fn journal_sink_outlives_ring_capacity() {
1500        // The ring is bounded; the sink is not.
1501        let state = State::new();
1502        let sink = Arc::new(MemoryJournalSink::new());
1503        state.set_journal_sink(sink.clone());
1504
1505        for i in 0..(DEFAULT_MUTATION_JOURNAL_CAPACITY + 10) {
1506            let _ = state.set(format!("k{i}"), i);
1507        }
1508
1509        assert_eq!(
1510            state.recent_mutations().len(),
1511            DEFAULT_MUTATION_JOURNAL_CAPACITY
1512        );
1513        assert_eq!(sink.len(), DEFAULT_MUTATION_JOURNAL_CAPACITY + 10);
1514        assert_eq!(sink.entries()[0].key, "k0");
1515    }
1516
1517    #[test]
1518    fn state_mutation_serde_round_trip_uses_epoch_millis() {
1519        let m = StateMutation {
1520            sequence: 42,
1521            key: "app:last_city".into(),
1522            old: None,
1523            new: Some(serde_json::json!("London")),
1524            origin: StateMutationOrigin::Set,
1525            timestamp: std::time::UNIX_EPOCH + std::time::Duration::from_millis(1_718_000_000_123),
1526            delta: false,
1527        };
1528        let json = serde_json::to_string(&m).unwrap();
1529        assert!(json.contains("\"timestamp_ms\":1718000000123"));
1530        assert!(json.contains("\"origin\":\"set\""));
1531        let back: StateMutation = serde_json::from_str(&json).unwrap();
1532        assert_eq!(back, m);
1533    }
1534
1535    #[test]
1536    fn file_journal_sink_round_trip() {
1537        let dir = std::env::temp_dir().join(format!(
1538            "gemini-rs-journal-test-{}-{}",
1539            std::process::id(),
1540            std::time::SystemTime::now()
1541                .duration_since(std::time::UNIX_EPOCH)
1542                .unwrap()
1543                .as_nanos()
1544        ));
1545        std::fs::create_dir_all(&dir).unwrap();
1546        let path = dir.join("session.journal.jsonl");
1547
1548        let state = State::new();
1549        {
1550            let sink = Arc::new(FileJournalSink::create(&path).unwrap());
1551            state.set_journal_sink(sink);
1552            let _ = state.set("a", 1);
1553            let _ = state.set("a", 2);
1554            state.remove("a");
1555            // Replace the sink so the file sink drops (and flushes).
1556            state.set_journal_sink(Arc::new(MemoryJournalSink::new()));
1557        }
1558
1559        let data = std::fs::read_to_string(&path).unwrap();
1560        let parsed: Vec<StateMutation> = data
1561            .lines()
1562            .filter(|l| !l.trim().is_empty())
1563            .map(|l| serde_json::from_str(l).unwrap())
1564            .collect();
1565        assert_eq!(parsed.len(), 3);
1566        assert_eq!(parsed[0].new, Some(serde_json::json!(1)));
1567        assert_eq!(parsed[2].origin, StateMutationOrigin::Remove);
1568
1569        let _ = std::fs::remove_dir_all(&dir);
1570    }
1571
1572    #[test]
1573    fn set_and_get_string() {
1574        let state = State::new();
1575        let _ = state.set("name", "Alice");
1576        assert_eq!(state.get::<String>("name"), Some("Alice".to_string()));
1577    }
1578
1579    #[test]
1580    fn set_and_get_json() {
1581        let state = State::new();
1582        let _ = state.set("data", serde_json::json!({"temp": 22}));
1583        let v: Value = state.get("data").unwrap();
1584        assert_eq!(v["temp"], 22);
1585    }
1586
1587    #[test]
1588    fn pick_subset() {
1589        let state = State::new();
1590        let _ = state.set("a", 1);
1591        let _ = state.set("b", 2);
1592        let _ = state.set("c", 3);
1593        let picked = state.pick(&["a", "c"]);
1594        assert!(picked.contains("a"));
1595        assert!(!picked.contains("b"));
1596        assert!(picked.contains("c"));
1597    }
1598
1599    #[test]
1600    fn merge_states() {
1601        let s1 = State::new();
1602        let _ = s1.set("a", 1);
1603        let s2 = State::new();
1604        let _ = s2.set("b", 2);
1605        s1.merge(&s2);
1606        assert!(s1.contains("a"));
1607        assert!(s1.contains("b"));
1608    }
1609
1610    #[test]
1611    fn rename_key() {
1612        let state = State::new();
1613        let _ = state.set("old", "value");
1614        state.rename("old", "new");
1615        assert!(!state.contains("old"));
1616        assert_eq!(state.get::<String>("new"), Some("value".to_string()));
1617    }
1618
1619    #[test]
1620    fn remove_returns_value() {
1621        let state = State::new();
1622        let _ = state.set("key", 42);
1623        let removed = state.remove("key");
1624        assert!(removed.is_some());
1625        assert!(!state.contains("key"));
1626    }
1627
1628    #[test]
1629    fn get_missing_returns_none() {
1630        let state = State::new();
1631        assert_eq!(state.get::<String>("nope"), None);
1632    }
1633
1634    // ── Delta tracking tests ──────────────────────────────────────────────
1635
1636    #[test]
1637    fn delta_tracking_writes_to_delta() {
1638        let state = State::new();
1639        let _ = state.set("committed", "yes");
1640
1641        let tracked = state.with_delta_tracking();
1642        let _ = tracked.set("new_key", "new_value");
1643
1644        // New key visible through tracked state
1645        assert_eq!(
1646            tracked.get::<String>("new_key"),
1647            Some("new_value".to_string())
1648        );
1649        // But NOT visible in original (non-delta) state's inner
1650        assert!(!state.contains("new_key"));
1651        // Committed key still visible through tracked state
1652        assert_eq!(tracked.get::<String>("committed"), Some("yes".to_string()));
1653    }
1654
1655    #[test]
1656    fn delta_has_delta_reports_correctly() {
1657        let state = State::new();
1658        let tracked = state.with_delta_tracking();
1659        assert!(!tracked.has_delta());
1660
1661        let _ = tracked.set("key", "val");
1662        assert!(tracked.has_delta());
1663    }
1664
1665    #[test]
1666    fn delta_commit_merges_to_inner() {
1667        let state = State::new();
1668        let tracked = state.with_delta_tracking();
1669        let _ = tracked.set("key", "val");
1670        assert!(!state.contains("key"));
1671
1672        tracked.commit();
1673        // Now visible in original state
1674        assert_eq!(state.get::<String>("key"), Some("val".to_string()));
1675        assert!(!tracked.has_delta());
1676    }
1677
1678    #[test]
1679    fn delta_rollback_discards_changes() {
1680        let state = State::new();
1681        let tracked = state.with_delta_tracking();
1682        let _ = tracked.set("key", "val");
1683        assert!(tracked.has_delta());
1684
1685        tracked.rollback();
1686        assert!(!tracked.has_delta());
1687        assert!(!state.contains("key"));
1688        assert!(!tracked.contains("key"));
1689    }
1690
1691    #[test]
1692    fn delta_snapshot() {
1693        let state = State::new();
1694        let tracked = state.with_delta_tracking();
1695        let _ = tracked.set("a", 1);
1696        let _ = tracked.set("b", 2);
1697
1698        let snapshot = tracked.delta();
1699        assert_eq!(snapshot.len(), 2);
1700        assert!(snapshot.contains_key("a"));
1701        assert!(snapshot.contains_key("b"));
1702    }
1703
1704    #[test]
1705    fn set_committed_bypasses_delta() {
1706        let state = State::new();
1707        let tracked = state.with_delta_tracking();
1708        let _ = tracked.set_committed("direct", "value");
1709
1710        // Visible immediately in inner
1711        assert_eq!(state.get::<String>("direct"), Some("value".to_string()));
1712        // Not in delta
1713        assert!(!tracked.has_delta());
1714        // Still visible through tracked (reads inner too)
1715        assert_eq!(tracked.get::<String>("direct"), Some("value".to_string()));
1716    }
1717
1718    #[test]
1719    fn mutation_journal_records_set_and_remove() {
1720        let state = State::new();
1721        let _ = state.set("key", "first");
1722        let _ = state.set("key", "second");
1723        state.remove("key");
1724
1725        let mutations = state.recent_mutations();
1726        assert_eq!(mutations.len(), 3);
1727        assert_eq!(mutations[0].key, "key");
1728        assert_eq!(mutations[0].old, None);
1729        assert_eq!(mutations[0].new, Some(serde_json::json!("first")));
1730        assert_eq!(mutations[0].origin, StateMutationOrigin::Set);
1731
1732        assert_eq!(mutations[1].old, Some(serde_json::json!("first")));
1733        assert_eq!(mutations[1].new, Some(serde_json::json!("second")));
1734
1735        assert_eq!(mutations[2].old, Some(serde_json::json!("second")));
1736        assert_eq!(mutations[2].new, None);
1737        assert_eq!(mutations[2].origin, StateMutationOrigin::Remove);
1738    }
1739
1740    #[test]
1741    fn mutation_journal_is_shared_with_delta_tracking() {
1742        let state = State::new();
1743        let _ = state.set("committed", "yes");
1744
1745        let tracked = state.with_delta_tracking();
1746        let _ = tracked.set("committed", "maybe");
1747        tracked.commit();
1748
1749        let mutations = state.recent_mutations();
1750        assert_eq!(mutations.len(), 3);
1751        assert_eq!(mutations[1].key, "committed");
1752        assert_eq!(mutations[1].old, Some(serde_json::json!("yes")));
1753        assert_eq!(mutations[1].new, Some(serde_json::json!("maybe")));
1754        assert_eq!(mutations[1].origin, StateMutationOrigin::Set);
1755        assert!(mutations[1].delta);
1756
1757        assert_eq!(mutations[2].origin, StateMutationOrigin::Commit);
1758        assert!(!mutations[2].delta);
1759    }
1760
1761    #[test]
1762    fn drain_mutations_clears_journal() {
1763        let state = State::new();
1764        let _ = state.set("a", 1);
1765        let _ = state.set("b", 2);
1766
1767        let drained = state.drain_mutations();
1768        assert_eq!(drained.len(), 2);
1769        assert!(state.recent_mutations().is_empty());
1770    }
1771
1772    #[test]
1773    fn redacted_keys_are_masked_wherever_state_leaves_the_process() {
1774        let sink = Arc::new(MemoryJournalSink::new());
1775        let state = State::new().with_journal_sink(sink.clone());
1776        state.redact_keys(["card_number"]);
1777        let _ = state.set("card_number", "4111111111111111");
1778        let _ = state.set("app:card_number", "4111111111111111");
1779        let _ = state.set("name", "Ada");
1780
1781        // Inside the process the value is real.
1782        assert_eq!(
1783            state.get::<String>("card_number").as_deref(),
1784            Some("4111111111111111")
1785        );
1786        // The durable journal never sees it, under either scope.
1787        for entry in sink.entries() {
1788            let leaked = entry
1789                .new
1790                .as_ref()
1791                .is_some_and(|v| v.to_string().contains("4111"));
1792            assert!(!leaked, "{} leaked into the journal sink", entry.key);
1793        }
1794        // Nor does a snapshot.
1795        let snapshot = state.to_redacted_hashmap();
1796        assert_eq!(snapshot["card_number"], serde_json::json!(REDACTED));
1797        assert_eq!(snapshot["app:card_number"], serde_json::json!(REDACTED));
1798        assert_eq!(snapshot["name"], serde_json::json!("Ada"));
1799        // Nor an object handed out, one level deep.
1800        assert_eq!(
1801            state.redact_fields(&serde_json::json!({ "card_number": "4111", "name": "Ada" })),
1802            serde_json::json!({ "card_number": REDACTED, "name": "Ada" })
1803        );
1804        // The in-memory journal keeps real values for evidence and watchers.
1805        assert!(
1806            state
1807                .recent_mutations()
1808                .iter()
1809                .any(|m| m.new == Some(serde_json::json!("4111111111111111")))
1810        );
1811    }
1812
1813    #[test]
1814    fn try_mutations_since_reports_a_gap_the_ring_dropped() {
1815        let state = State::new();
1816        let cursor = state.mutation_cursor();
1817        let _ = state.set("a", 1);
1818        assert_eq!(state.try_mutations_since(cursor).map(|m| m.len()), Some(1));
1819
1820        state.drain_mutations();
1821        let _ = state.set("b", 2);
1822        assert!(
1823            state.try_mutations_since(cursor).is_none(),
1824            "the write to `a` is gone from the journal"
1825        );
1826        let after_drain = state.mutation_cursor() - 1;
1827        assert_eq!(
1828            state.try_mutations_since(after_drain).map(|m| m.len()),
1829            Some(1)
1830        );
1831        assert_eq!(
1832            state
1833                .try_mutations_since(state.mutation_cursor())
1834                .map(|m| m.len()),
1835            Some(0)
1836        );
1837    }
1838
1839    #[test]
1840    fn mutation_cursor_reads_only_later_changes() {
1841        let state = State::new();
1842        let _ = state.set("before", 1);
1843        let cursor = state.mutation_cursor();
1844
1845        let _ = state.set("after", 2);
1846        state.remove("before");
1847
1848        let mutations = state.mutations_since(cursor);
1849        assert_eq!(mutations.len(), 2);
1850        assert_eq!(mutations[0].key, "after");
1851        assert_eq!(mutations[1].key, "before");
1852    }
1853
1854    #[test]
1855    fn no_delta_tracking_preserves_existing_behavior() {
1856        let state = State::new();
1857        assert!(!state.is_tracking_delta());
1858        let _ = state.set("key", "val");
1859        assert_eq!(state.get::<String>("key"), Some("val".to_string()));
1860        assert!(!state.has_delta());
1861    }
1862
1863    // ── Prefix tests ──────────────────────────────────────────────────────
1864
1865    #[test]
1866    fn prefix_app_set_and_get() {
1867        let state = State::new();
1868        let _ = state.app().set("flag", true);
1869
1870        // Accessible via prefix accessor
1871        assert_eq!(state.app().get::<bool>("flag"), Some(true));
1872        // Also accessible via raw key
1873        assert_eq!(state.get::<bool>("app:flag"), Some(true));
1874    }
1875
1876    #[test]
1877    fn prefix_user_set_and_get() {
1878        let state = State::new();
1879        let _ = state.user().set("name", "Alice");
1880        assert_eq!(
1881            state.user().get::<String>("name"),
1882            Some("Alice".to_string())
1883        );
1884        assert_eq!(state.get::<String>("user:name"), Some("Alice".to_string()));
1885    }
1886
1887    #[test]
1888    fn prefix_temp_set_and_get() {
1889        let state = State::new();
1890        let _ = state.temp().set("scratch", 42);
1891        assert_eq!(state.temp().get::<i32>("scratch"), Some(42));
1892    }
1893
1894    #[test]
1895    fn prefix_contains_and_remove() {
1896        let state = State::new();
1897        let _ = state.app().set("x", 1);
1898        assert!(state.app().contains("x"));
1899        state.app().remove("x");
1900        assert!(!state.app().contains("x"));
1901    }
1902
1903    #[test]
1904    fn prefix_keys() {
1905        let state = State::new();
1906        let _ = state.app().set("a", 1);
1907        let _ = state.app().set("b", 2);
1908        let _ = state.user().set("c", 3);
1909
1910        let app_keys = state.app().keys();
1911        assert_eq!(app_keys.len(), 2);
1912        assert!(app_keys.contains(&"a".to_string()));
1913        assert!(app_keys.contains(&"b".to_string()));
1914
1915        let user_keys = state.user().keys();
1916        assert_eq!(user_keys.len(), 1);
1917        assert!(user_keys.contains(&"c".to_string()));
1918    }
1919
1920    #[test]
1921    fn prefix_with_delta_tracking() {
1922        let state = State::new();
1923        let tracked = state.with_delta_tracking();
1924        let _ = tracked.app().set("flag", true);
1925
1926        // Visible in tracked state via prefix
1927        assert_eq!(tracked.app().get::<bool>("flag"), Some(true));
1928        // In delta, not committed
1929        assert!(tracked.has_delta());
1930        assert!(!state.contains("app:flag"));
1931
1932        tracked.commit();
1933        assert_eq!(state.get::<bool>("app:flag"), Some(true));
1934    }
1935
1936    // ── New prefix accessor tests ────────────────────────────────────────
1937
1938    #[test]
1939    fn prefix_session_set_and_get() {
1940        let state = State::new();
1941        let _ = state.session().set("turn_count", 5);
1942        assert_eq!(state.session().get::<i32>("turn_count"), Some(5));
1943        assert_eq!(state.get::<i32>("session:turn_count"), Some(5));
1944    }
1945
1946    #[test]
1947    fn prefix_turn_set_and_get() {
1948        let state = State::new();
1949        let _ = state.turn().set("transcript", "hello");
1950        assert_eq!(
1951            state.turn().get::<String>("transcript"),
1952            Some("hello".to_string())
1953        );
1954        assert_eq!(
1955            state.get::<String>("turn:transcript"),
1956            Some("hello".to_string())
1957        );
1958    }
1959
1960    #[test]
1961    fn prefix_bg_set_and_get() {
1962        let state = State::new();
1963        let _ = state.bg().set("task_id", "abc-123");
1964        assert_eq!(
1965            state.bg().get::<String>("task_id"),
1966            Some("abc-123".to_string())
1967        );
1968        assert_eq!(
1969            state.get::<String>("bg:task_id"),
1970            Some("abc-123".to_string())
1971        );
1972    }
1973
1974    #[test]
1975    fn prefix_session_contains_and_remove() {
1976        let state = State::new();
1977        let _ = state.session().set("x", 1);
1978        assert!(state.session().contains("x"));
1979        state.session().remove("x");
1980        assert!(!state.session().contains("x"));
1981    }
1982
1983    #[test]
1984    fn prefix_turn_keys() {
1985        let state = State::new();
1986        let _ = state.turn().set("a", 1);
1987        let _ = state.turn().set("b", 2);
1988        let _ = state.session().set("c", 3);
1989
1990        let turn_keys = state.turn().keys();
1991        assert_eq!(turn_keys.len(), 2);
1992        assert!(turn_keys.contains(&"a".to_string()));
1993        assert!(turn_keys.contains(&"b".to_string()));
1994    }
1995
1996    // ── try_get / try_get_key ─────────────────────────────────────────
1997
1998    #[test]
1999    fn try_get_distinguishes_absent_from_wrong_type() {
2000        let state = State::new();
2001        assert!(matches!(state.try_get::<u32>("missing"), Ok(None)));
2002
2003        state.set("n", 5u32).unwrap();
2004        assert_eq!(state.try_get::<u32>("n").unwrap(), Some(5));
2005
2006        state.set("s", "not a number").unwrap();
2007        // Lenient read folds the type error into `None`…
2008        assert_eq!(state.get::<u32>("s"), None);
2009        // …the strict read reports it.
2010        match state.try_get::<u32>("s") {
2011            Err(StateError::WrongType { key, .. }) => assert_eq!(key, "s"),
2012            other => panic!("expected WrongType, got {other:?}"),
2013        }
2014
2015        // Same derived: fallback as `get`.
2016        state.set("derived:risk", 0.5f64).unwrap();
2017        assert_eq!(state.try_get::<f64>("risk").unwrap(), Some(0.5));
2018
2019        const N: StateKey<u32> = StateKey::new("n");
2020        assert_eq!(state.try_get_key(&N).unwrap(), Some(5));
2021        const S: StateKey<u32> = StateKey::new("s");
2022        assert!(state.try_get_key(&S).is_err());
2023    }
2024
2025    // ── ReadOnlyPrefixedState (derived) tests ────────────────────────────
2026
2027    #[test]
2028    fn derived_read_only_get() {
2029        let state = State::new();
2030        // Write via raw key (simulating ComputedRegistry)
2031        let _ = state.set("derived:sentiment", "positive");
2032        assert_eq!(
2033            state.derived().get::<String>("sentiment"),
2034            Some("positive".to_string())
2035        );
2036    }
2037
2038    #[test]
2039    fn derived_read_only_get_raw() {
2040        let state = State::new();
2041        let _ = state.set("derived:score", serde_json::json!(0.95));
2042        let raw = state.derived().get_raw("score");
2043        assert!(raw.is_some());
2044        assert_eq!(raw.unwrap(), serde_json::json!(0.95));
2045    }
2046
2047    #[test]
2048    fn derived_read_only_contains() {
2049        let state = State::new();
2050        let _ = state.set("derived:exists", true);
2051        assert!(state.derived().contains("exists"));
2052        assert!(!state.derived().contains("missing"));
2053    }
2054
2055    #[test]
2056    fn derived_read_only_keys() {
2057        let state = State::new();
2058        let _ = state.set("derived:a", 1);
2059        let _ = state.set("derived:b", 2);
2060        let _ = state.set("app:c", 3);
2061
2062        let derived_keys = state.derived().keys();
2063        assert_eq!(derived_keys.len(), 2);
2064        assert!(derived_keys.contains(&"a".to_string()));
2065        assert!(derived_keys.contains(&"b".to_string()));
2066    }
2067
2068    #[test]
2069    fn derived_missing_key_returns_none() {
2070        let state = State::new();
2071        assert_eq!(state.derived().get::<String>("nope"), None);
2072        assert_eq!(state.derived().get_raw("nope"), None);
2073    }
2074
2075    // ── snapshot_values tests ────────────────────────────────────────────
2076
2077    #[test]
2078    fn snapshot_values_captures_existing_keys() {
2079        let state = State::new();
2080        let _ = state.set("a", 1);
2081        let _ = state.set("b", "hello");
2082        let _ = state.set("c", true);
2083
2084        let snap = state.snapshot_values(&["a", "b", "missing"]);
2085        assert_eq!(snap.len(), 2);
2086        assert_eq!(snap.get("a"), Some(&serde_json::json!(1)));
2087        assert_eq!(snap.get("b"), Some(&serde_json::json!("hello")));
2088        assert!(!snap.contains_key("missing"));
2089    }
2090
2091    #[test]
2092    fn snapshot_values_empty_keys() {
2093        let state = State::new();
2094        let _ = state.set("a", 1);
2095        let snap = state.snapshot_values(&[]);
2096        assert!(snap.is_empty());
2097    }
2098
2099    // ── diff_values tests ────────────────────────────────────────────────
2100
2101    #[test]
2102    fn diff_values_detects_changed_value() {
2103        let state = State::new();
2104        let _ = state.set("x", 1);
2105        let snap = state.snapshot_values(&["x"]);
2106
2107        let _ = state.set("x", 2);
2108        let diffs = state.diff_values(&snap, &["x"]);
2109        assert_eq!(diffs.len(), 1);
2110        assert_eq!(diffs[0].0, "x");
2111        assert_eq!(diffs[0].1, serde_json::json!(1));
2112        assert_eq!(diffs[0].2, serde_json::json!(2));
2113    }
2114
2115    #[test]
2116    fn diff_values_detects_new_key() {
2117        let state = State::new();
2118        let snap = state.snapshot_values(&["y"]);
2119
2120        let _ = state.set("y", "new");
2121        let diffs = state.diff_values(&snap, &["y"]);
2122        assert_eq!(diffs.len(), 1);
2123        assert_eq!(diffs[0].0, "y");
2124        assert_eq!(diffs[0].1, Value::Null);
2125        assert_eq!(diffs[0].2, serde_json::json!("new"));
2126    }
2127
2128    #[test]
2129    fn diff_values_detects_removed_key() {
2130        let state = State::new();
2131        let _ = state.set("z", 42);
2132        let snap = state.snapshot_values(&["z"]);
2133
2134        state.remove("z");
2135        let diffs = state.diff_values(&snap, &["z"]);
2136        assert_eq!(diffs.len(), 1);
2137        assert_eq!(diffs[0].0, "z");
2138        assert_eq!(diffs[0].1, serde_json::json!(42));
2139        assert_eq!(diffs[0].2, Value::Null);
2140    }
2141
2142    #[test]
2143    fn diff_values_no_change() {
2144        let state = State::new();
2145        let _ = state.set("stable", 10);
2146        let snap = state.snapshot_values(&["stable"]);
2147
2148        // No mutation
2149        let diffs = state.diff_values(&snap, &["stable"]);
2150        assert!(diffs.is_empty());
2151    }
2152
2153    #[test]
2154    fn diff_values_multiple_keys_mixed_changes() {
2155        let state = State::new();
2156        let _ = state.set("a", 1);
2157        let _ = state.set("b", 2);
2158        let snap = state.snapshot_values(&["a", "b", "c"]);
2159
2160        let _ = state.set("a", 10); // changed
2161        // b unchanged
2162        let _ = state.set("c", 3); // new
2163
2164        let diffs = state.diff_values(&snap, &["a", "b", "c"]);
2165        assert_eq!(diffs.len(), 2); // a changed, c new; b unchanged
2166        let diff_keys: Vec<&str> = diffs.iter().map(|(k, _, _)| k.as_str()).collect();
2167        assert!(diff_keys.contains(&"a"));
2168        assert!(diff_keys.contains(&"c"));
2169    }
2170
2171    // ── clear_prefix tests ───────────────────────────────────────────────
2172
2173    #[test]
2174    fn clear_prefix_removes_matching_keys() {
2175        let state = State::new();
2176        let _ = state.set("turn:a", 1);
2177        let _ = state.set("turn:b", 2);
2178        let _ = state.set("app:c", 3);
2179        let _ = state.set("session:d", 4);
2180
2181        state.clear_prefix("turn:");
2182        assert!(!state.contains("turn:a"));
2183        assert!(!state.contains("turn:b"));
2184        assert!(state.contains("app:c"));
2185        assert!(state.contains("session:d"));
2186    }
2187
2188    #[test]
2189    fn clear_prefix_no_matching_keys_is_noop() {
2190        let state = State::new();
2191        let _ = state.set("app:x", 1);
2192        state.clear_prefix("turn:");
2193        assert!(state.contains("app:x"));
2194    }
2195
2196    #[test]
2197    fn clear_prefix_also_clears_delta() {
2198        let state = State::new();
2199        let _ = state.set("turn:committed", 1);
2200        let tracked = state.with_delta_tracking();
2201        let _ = tracked.set("turn:delta_val", 2);
2202
2203        // Both committed and delta have turn: keys
2204        assert!(tracked.contains("turn:committed"));
2205        assert!(tracked.contains("turn:delta_val"));
2206
2207        tracked.clear_prefix("turn:");
2208        assert!(!tracked.contains("turn:committed"));
2209        assert!(!tracked.contains("turn:delta_val"));
2210    }
2211
2212    #[test]
2213    fn clear_prefix_via_turn_accessor() {
2214        let state = State::new();
2215        let _ = state.turn().set("x", 1);
2216        let _ = state.turn().set("y", 2);
2217        let _ = state.app().set("z", 3);
2218
2219        state.clear_prefix("turn:");
2220        assert!(state.turn().keys().is_empty());
2221        assert!(state.app().contains("z"));
2222    }
2223
2224    // ── modify() tests ──────────────────────────────────────────────────
2225
2226    #[test]
2227    fn modify_increment_existing() {
2228        let state = State::new();
2229        let _ = state.set("count", 5u32);
2230        let result = state.modify("count", 0u32, |n| n + 1).unwrap();
2231        assert_eq!(result, 6);
2232        assert_eq!(state.get::<u32>("count"), Some(6));
2233    }
2234
2235    #[test]
2236    fn modify_uses_default_when_missing() {
2237        let state = State::new();
2238        let result = state.modify("new_count", 0u32, |n| n + 1).unwrap();
2239        assert_eq!(result, 1);
2240        assert_eq!(state.get::<u32>("new_count"), Some(1));
2241    }
2242
2243    #[test]
2244    fn modify_with_delta_tracking() {
2245        let state = State::new();
2246        let _ = state.set("x", 10u32);
2247        let tracked = state.with_delta_tracking();
2248        let result = tracked.modify("x", 0u32, |n| n * 2).unwrap();
2249        assert_eq!(result, 20);
2250        // Written to delta, not committed
2251        assert_eq!(tracked.get::<u32>("x"), Some(20));
2252        assert_eq!(state.get::<u32>("x"), Some(10)); // original unchanged
2253    }
2254
2255    // ── derived fallback tests ──────────────────────────────────────────
2256
2257    #[test]
2258    fn get_falls_back_to_derived_prefix() {
2259        let state = State::new();
2260        let _ = state.set("derived:risk", 0.85);
2261        // Access without prefix — should find derived:risk
2262        assert_eq!(state.get::<f64>("risk"), Some(0.85));
2263    }
2264
2265    #[test]
2266    fn get_prefers_direct_key_over_derived() {
2267        let state = State::new();
2268        let _ = state.set("score", 1.0);
2269        let _ = state.set("derived:score", 0.5);
2270        // Direct key should win
2271        assert_eq!(state.get::<f64>("score"), Some(1.0));
2272    }
2273
2274    #[test]
2275    fn get_derived_fallback_skipped_for_prefixed_keys() {
2276        let state = State::new();
2277        let _ = state.set("derived:risk", 0.85);
2278        // Prefixed key should NOT trigger fallback
2279        assert_eq!(state.get::<f64>("app:risk"), None);
2280    }
2281
2282    #[test]
2283    fn get_derived_fallback_with_delta_tracking() {
2284        let state = State::new();
2285        let tracked = state.with_delta_tracking();
2286        let _ = tracked.set("derived:computed_val", 42);
2287        assert_eq!(tracked.get::<i32>("computed_val"), Some(42));
2288    }
2289
2290    // ── with() zero-copy borrow tests ──────────────────────────────────
2291
2292    #[test]
2293    fn with_reads_from_inner() {
2294        let state = State::new();
2295        let _ = state.set("name", "Alice");
2296        let len = state.with("name", |v| v.as_str().unwrap().len());
2297        assert_eq!(len, Some(5));
2298    }
2299
2300    #[test]
2301    fn with_reads_from_delta_first() {
2302        let state = State::new();
2303        let _ = state.set("x", 1);
2304        let tracked = state.with_delta_tracking();
2305        let _ = tracked.set("x", 99);
2306        let val = tracked.with("x", |v| v.as_i64().unwrap());
2307        assert_eq!(val, Some(99));
2308    }
2309
2310    #[test]
2311    fn with_falls_back_to_inner_when_not_in_delta() {
2312        let state = State::new();
2313        let _ = state.set("committed", "yes");
2314        let tracked = state.with_delta_tracking();
2315        let val = tracked.with("committed", |v| v.as_str().unwrap().to_string());
2316        assert_eq!(val, Some("yes".to_string()));
2317    }
2318
2319    #[test]
2320    fn with_falls_back_to_derived() {
2321        let state = State::new();
2322        let _ = state.set("derived:risk", 0.85);
2323        let val = state.with("risk", |v| v.as_f64().unwrap());
2324        assert_eq!(val, Some(0.85));
2325    }
2326
2327    #[test]
2328    fn with_derived_fallback_skipped_for_prefixed() {
2329        let state = State::new();
2330        let _ = state.set("derived:risk", 0.85);
2331        let val = state.with("app:risk", |v| v.as_f64().unwrap());
2332        assert_eq!(val, None);
2333    }
2334
2335    #[test]
2336    fn with_returns_none_for_missing() {
2337        let state = State::new();
2338        let val = state.with("missing", std::clone::Clone::clone);
2339        assert_eq!(val, None);
2340    }
2341
2342    #[test]
2343    fn with_on_prefixed_state() {
2344        let state = State::new();
2345        let _ = state.app().set("flag", true);
2346        let val = state.app().with("flag", |v| v.as_bool().unwrap());
2347        assert_eq!(val, Some(true));
2348    }
2349
2350    #[test]
2351    fn with_on_read_only_prefixed_state() {
2352        let state = State::new();
2353        let _ = state.set("derived:score", serde_json::json!(0.95));
2354        let val = state.derived().with("score", |v| v.as_f64().unwrap());
2355        assert_eq!(val, Some(0.95));
2356    }
2357
2358    // ── StateKey typed key tests ───────────────────────────────────────
2359
2360    const TURN_COUNT: StateKey<u32> = StateKey::new("session:turn_count");
2361    const NAME: StateKey<String> = StateKey::new("user:name");
2362
2363    #[test]
2364    fn state_key_get_and_set() {
2365        let state = State::new();
2366        let _ = state.set_key(&TURN_COUNT, 5);
2367        assert_eq!(state.get_key(&TURN_COUNT), Some(5));
2368    }
2369
2370    #[test]
2371    fn state_key_get_missing() {
2372        let state = State::new();
2373        assert_eq!(state.get_key(&TURN_COUNT), None);
2374    }
2375
2376    #[test]
2377    fn state_key_string_type() {
2378        let state = State::new();
2379        let _ = state.set_key(&NAME, "Alice".to_string());
2380        assert_eq!(state.get_key(&NAME), Some("Alice".to_string()));
2381    }
2382
2383    #[test]
2384    fn state_key_with() {
2385        let state = State::new();
2386        let _ = state.set_key(&TURN_COUNT, 42);
2387        let val = state.with_key(&TURN_COUNT, |v| v.as_u64().unwrap());
2388        assert_eq!(val, Some(42));
2389    }
2390
2391    #[test]
2392    fn state_key_interop_with_raw() {
2393        let state = State::new();
2394        let _ = state.set_key(&TURN_COUNT, 10);
2395        // Can also read via raw key
2396        assert_eq!(state.get::<u32>("session:turn_count"), Some(10));
2397    }
2398
2399    #[test]
2400    fn slot_evidence_aggregates_value_provenance_and_journal() {
2401        let state = State::new();
2402        let _ = state.set("party_size", 6u8);
2403        // Provenance written under the state_meta convention (as resolvers do).
2404        let _ = state.set(
2405            "state_meta:party_size",
2406            serde_json::json!({ "source": "extraction", "confidence": 0.9 }),
2407        );
2408
2409        let ev = state.evidence("party_size");
2410        assert!(ev.present);
2411        assert_eq!(ev.value, Some(serde_json::json!(6)));
2412        assert_eq!(ev.source.as_deref(), Some("extraction"));
2413        assert_eq!(ev.confidence, Some(0.9));
2414        assert!(ev.last_sequence.is_some());
2415        assert_eq!(ev.last_origin, Some(StateMutationOrigin::Set));
2416
2417        // An absent key reports no evidence.
2418        let missing = state.evidence("nope");
2419        assert!(!missing.present);
2420        assert!(missing.source.is_none());
2421    }
2422
2423    // ── Transaction-invariant tests (the verified correctness bugs) ──────────
2424
2425    #[test]
2426    fn rollback_restores_base_after_remove() {
2427        // Regression: previously remove() in delta mode deleted from the committed
2428        // store, so rollback() could not restore it.
2429        let base = State::new();
2430        let _ = base.set("k", "original");
2431
2432        let tx = base.with_delta_tracking();
2433        assert_eq!(tx.remove("k"), Some(serde_json::json!("original")));
2434        assert_eq!(tx.get::<String>("k"), None); // tombstoned in the tx view
2435        assert_eq!(base.get::<String>("k"), Some("original".into())); // base intact
2436
2437        tx.rollback();
2438        assert_eq!(tx.get::<String>("k"), Some("original".into()));
2439        assert_eq!(base.get::<String>("k"), Some("original".into()));
2440    }
2441
2442    #[test]
2443    fn rollback_restores_base_after_clear_prefix() {
2444        // Regression: clear_prefix() used to mutate the committed store directly.
2445        let base = State::new();
2446        let _ = base.set("app:a", 1u32);
2447        let _ = base.set("app:b", 2u32);
2448        let _ = base.set("user:c", 3u32);
2449
2450        let tx = base.with_delta_tracking();
2451        tx.clear_prefix("app:");
2452        assert_eq!(tx.get::<u32>("app:a"), None);
2453        assert_eq!(tx.get::<u32>("app:b"), None);
2454        assert_eq!(tx.get::<u32>("user:c"), Some(3));
2455        // Base untouched until commit.
2456        assert_eq!(base.get::<u32>("app:a"), Some(1));
2457
2458        tx.rollback();
2459        assert_eq!(tx.get::<u32>("app:a"), Some(1));
2460        assert_eq!(tx.get::<u32>("app:b"), Some(2));
2461    }
2462
2463    #[test]
2464    fn commit_applies_removals() {
2465        let base = State::new();
2466        let _ = base.set("k", "v");
2467        let tx = base.with_delta_tracking();
2468        tx.remove("k");
2469        tx.commit();
2470        assert_eq!(base.get::<String>("k"), None);
2471    }
2472
2473    #[test]
2474    fn commit_applies_prefix_clear() {
2475        let base = State::new();
2476        let _ = base.set("app:a", 1u32);
2477        let _ = base.set("user:c", 3u32);
2478        let tx = base.with_delta_tracking();
2479        tx.clear_prefix("app:");
2480        tx.commit();
2481        assert_eq!(base.get::<u32>("app:a"), None);
2482        assert_eq!(base.get::<u32>("user:c"), Some(3));
2483    }
2484
2485    #[test]
2486    fn modify_is_atomic_under_concurrency() {
2487        use std::sync::Arc;
2488        use std::thread;
2489
2490        let state = Arc::new(State::new());
2491        let _ = state.set("count", 0u64);
2492
2493        let threads = 8;
2494        let per_thread = 1000;
2495        let handles: Vec<_> = (0..threads)
2496            .map(|_| {
2497                let state = state.clone();
2498                thread::spawn(move || {
2499                    for _ in 0..per_thread {
2500                        let _ = state.modify("count", 0u64, |n| n + 1);
2501                    }
2502                })
2503            })
2504            .collect();
2505        for h in handles {
2506            h.join().unwrap();
2507        }
2508        // With a real per-key atomic RMW, no increments are lost.
2509        assert_eq!(
2510            state.get::<u64>("count"),
2511            Some((threads * per_thread) as u64)
2512        );
2513    }
2514}
2515
2516#[cfg(test)]
2517mod proptests {
2518    use super::*;
2519    use proptest::prelude::*;
2520
2521    // A transaction's puts and removes never leak to the base before commit, and
2522    // a rollback always restores the exact committed base.
2523    proptest! {
2524        #[test]
2525        fn rollback_always_restores_base(
2526            base_keys in proptest::collection::vec(("[a-c]", 0u32..5), 0..6),
2527            ops in proptest::collection::vec(
2528                prop_oneof![
2529                    ("[a-c]", 0u32..5).prop_map(|(k, v)| (k, Some(v))),
2530                    "[a-c]".prop_map(|k| (k, None)),
2531                ],
2532                0..12,
2533            ),
2534        ) {
2535            let base = State::new();
2536            for (k, v) in &base_keys {
2537                let _ = base.set(k.clone(), *v);
2538            }
2539            let snapshot = |s: &State| -> std::collections::BTreeMap<String, Value> {
2540                s.keys().into_iter().filter_map(|k| s.get_raw(&k).map(|v| (k, v))).collect()
2541            };
2542            let before = snapshot(&base);
2543
2544            let tx = base.with_delta_tracking();
2545            for (k, v) in &ops {
2546                match v {
2547                    Some(v) => { let _ = tx.set(k.clone(), *v); }
2548                    None => { tx.remove(k); }
2549                }
2550            }
2551            // Base is never mutated while the tx is open.
2552            prop_assert_eq!(&before, &snapshot(&base));
2553
2554            tx.rollback();
2555            prop_assert_eq!(&before, &snapshot(&tx));
2556        }
2557    }
2558}
2559
2560#[cfg(test)]
2561mod derived_contains_fallback {
2562    //! `contains` must agree with `get` about the transparent `derived:`
2563    //! fallback. Flow predicates (`is_set`, `captured`) evaluate through
2564    //! `contains`, so a computed variable that `get` returns but `contains`
2565    //! denies reads as permanently unknown to the flow.
2566    use super::State;
2567
2568    #[test]
2569    fn contains_sees_a_derived_value_through_the_unprefixed_key() {
2570        let state = State::new();
2571        state.set("derived:risk", 0.85).unwrap();
2572        assert_eq!(
2573            state.get::<f64>("risk"),
2574            Some(0.85),
2575            "precondition: get falls back"
2576        );
2577        assert!(
2578            state.contains("risk"),
2579            "contains must fall back the same way get does"
2580        );
2581    }
2582
2583    #[test]
2584    fn contains_fallback_respects_delta_tracking_and_tombstones() {
2585        let state = State::new();
2586        state.set("derived:score", 1u32).unwrap();
2587        let tracked = state.with_delta_tracking();
2588        assert!(
2589            tracked.contains("score"),
2590            "inner derived value visible through tracked view"
2591        );
2592        tracked.remove("derived:score");
2593        assert!(
2594            !tracked.contains("score"),
2595            "a tombstone on the derived key shadows inner"
2596        );
2597    }
2598
2599    #[test]
2600    fn contains_does_not_fall_back_for_prefixed_keys() {
2601        let state = State::new();
2602        state.set("derived:flag", true).unwrap();
2603        assert!(
2604            !state.contains("session:flag"),
2605            "only unprefixed keys get the fallback"
2606        );
2607    }
2608}