Skip to main content

trusty_code/session/
registry_search_audit.rs

1//! `session.get_search_audit`'s retained search/recall audit trail (issue
2//! #3072). Split out of `registry.rs` purely to keep that production file
3//! under the crate's 500-SLOC cap — this is a child module of `registry`
4//! (declared via `#[path = ...] mod search_audit;`), so it shares full
5//! access to `SessionRegistry`'s private `lock` helper exactly as if these
6//! methods were still defined in that file.
7//!
8//! Why: DOC-39 §4.7 (Search tab, 10d) and #3027 (the 8b search/recall
9//! monitor card) both need a REST-pollable history of `search_code`/
10//! `recall_session` activity, but `Event::SearchPerformed`/
11//! `Event::MemoryRecalled` (`crate::events`) are emitted ONLY on the SSE
12//! stream (`GET /sessions/{id}/events`) — a client that attaches late, or
13//! never opens an SSE connection at all (DOC-39 §2.1 forbids the GUI from
14//! becoming an ad hoc SSE consumer for this), cannot see them. This module
15//! is the daemon-owned, ALWAYS-RETAINED (bounded, not ring-evicted) list
16//! that closes that gap — the same shape `registry_agents.rs` used for
17//! #2962's `session.get_agents`, adapted for a growing history rather than a
18//! small per-agent roster.
19//!
20//! **Why a dedicated cap distinct from the ring buffer:** the ring buffer
21//! (`SessionEntry::ring`, `DEFAULT_RING_CAPACITY` = 1000) evicts EVERY event
22//! kind together, so a session dominated by tool-call chatter can age a
23//! search/recall record out of the ring long before `SEARCH_AUDIT_CAP`
24//! search/recall records have happened — exactly the silent-data-loss shape
25//! the #2962 code-critic HIGH flagged for `session.get_agents` (see
26//! `registry_agents.rs`'s module docs). Storing search/recall records in
27//! their OWN bounded list, independent of ring pressure from unrelated
28//! events, avoids that: a session's search/recall history survives exactly
29//! [`SEARCH_AUDIT_CAP`] records regardless of how much other traffic passes
30//! through the ring in between.
31//! What: [`push_search_audit`](SessionRegistry::push_search_audit) appends
32//! one [`SearchAuditRecord`] onto `SessionEntry::search_audit`, evicting the
33//! OLDEST record first once the list is at [`SEARCH_AUDIT_CAP`] — called
34//! from `record_search_performed`/`record_memory_recalled`
35//! (`registry_events.rs`) immediately before they call `self.record(...)` to
36//! emit the matching SSE event, mirroring `record_context_budget`'s
37//! cache-then-emit ordering. [`get_search_audit`](SessionRegistry::get_search_audit)
38//! returns the retained list verbatim, oldest-first — `[]` for a session
39//! with no search/recall activity yet (never an error), `-32007
40//! session_not_found` for an unknown session.
41//! Test: `tests::*` in this module (registry-level);
42//! `session::protocol_search_audit::tests::*` (RPC-level wiring).
43
44use super::*;
45
46/// Maximum number of [`SearchAuditRecord`]s retained per session — the
47/// OLDEST record is dropped once a session's `SEARCH_AUDIT_CAP`+1'th
48/// search/recall fires. Chosen generously above what a single interactive
49/// session realistically produces (DOC-39 §4.7's audit list is a debugging
50/// aid, not a permanent record — `session.get_transcript`/the durable memory
51/// palace are the sources of truth for long-term history) while still
52/// bounding per-session memory on a long-running or looping agent.
53pub(super) const SEARCH_AUDIT_CAP: usize = 200;
54
55impl SessionRegistry {
56    /// Append one [`SearchAuditRecord`] onto `id`'s retained search/recall
57    /// audit trail, evicting the oldest record first once at
58    /// [`SEARCH_AUDIT_CAP`] (issue #3072).
59    ///
60    /// Why: the write half of this module's gap-closing list — see the
61    /// module docs for why this is a DEDICATED cap rather than a fold over
62    /// the shared ring buffer.
63    /// What: a no-op if `id` is unknown, mirroring `SessionRegistry::record`'s
64    /// same "no hard error, caller already checked existence" contract —
65    /// every call site here is `record_search_performed`/
66    /// `record_memory_recalled`, both of which already call `ensure_exists`
67    /// before reaching this.
68    /// Test: `tests::push_search_audit_evicts_oldest_once_at_cap`.
69    pub(super) fn push_search_audit(&self, id: &str, record: SearchAuditRecord) {
70        let mut sessions = self.lock();
71        if let Some(entry) = sessions.get_mut(id) {
72            if entry.search_audit.len() >= SEARCH_AUDIT_CAP {
73                entry.search_audit.pop_front();
74            }
75            entry.search_audit.push_back(record);
76        }
77    }
78
79    /// `session.get_search_audit(session_id) -> { search_audit:
80    /// [SearchAuditRecord] }` (issue #3072).
81    ///
82    /// Why: the query surface DOC-39 §4.7's Search tab and #3027's monitor
83    /// card poll instead of buffering the SSE stream client-side — see
84    /// module docs.
85    /// What: `-32007 session_not_found` if `id` is unknown; otherwise the
86    /// retained `SearchAuditRecord` list, oldest-first, verbatim. A session
87    /// with no search/recall activity yet returns an empty list, not an
88    /// error — the same "empty means nothing yet" convention
89    /// `session.get_agents`/`session.get_goals` use.
90    /// Test: `tests::get_search_audit_empty_session_returns_empty_list`,
91    /// `tests::get_search_audit_returns_records_after_recording`,
92    /// `tests::get_search_audit_unknown_session_errors`.
93    pub fn get_search_audit(&self, id: &str) -> Result<Vec<SearchAuditRecord>, RpcError> {
94        let sessions = self.lock();
95        let entry = sessions
96            .get(id)
97            .ok_or_else(|| RpcError::session_not_found(id))?;
98        Ok(entry.search_audit.iter().cloned().collect())
99    }
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105    use chrono::Utc;
106
107    fn search_record(query: &str) -> SearchAuditRecord {
108        SearchAuditRecord::Search {
109            agent: "pm".to_string(),
110            agent_id: "pm-1".to_string(),
111            lane: "grep".to_string(),
112            query: query.to_string(),
113            hit_count: Some(3),
114            latency_ms: 10,
115            at: Utc::now(),
116        }
117    }
118
119    /// A session with no search/recall activity yet returns an empty list,
120    /// not an error.
121    #[test]
122    fn get_search_audit_empty_session_returns_empty_list() {
123        let registry = SessionRegistry::new();
124        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
125
126        let records = registry.get_search_audit(&session.id).unwrap();
127
128        assert!(records.is_empty());
129    }
130
131    /// Records pushed via `push_search_audit` are returned, in push order.
132    #[test]
133    fn get_search_audit_returns_records_after_recording() {
134        let registry = SessionRegistry::new();
135        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
136
137        registry.push_search_audit(&session.id, search_record("first"));
138        registry.push_search_audit(&session.id, search_record("second"));
139
140        let records = registry.get_search_audit(&session.id).unwrap();
141
142        assert_eq!(records.len(), 2);
143        assert!(matches!(&records[0], SearchAuditRecord::Search { query, .. } if query == "first"));
144        assert!(
145            matches!(&records[1], SearchAuditRecord::Search { query, .. } if query == "second")
146        );
147    }
148
149    /// Once a session is at `SEARCH_AUDIT_CAP` records, the next push evicts
150    /// the OLDEST record rather than growing unbounded — the retention
151    /// contract this module exists to enforce.
152    #[test]
153    fn push_search_audit_evicts_oldest_once_at_cap() {
154        let registry = SessionRegistry::new();
155        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
156
157        for i in 0..SEARCH_AUDIT_CAP {
158            registry.push_search_audit(&session.id, search_record(&format!("q-{i}")));
159        }
160        // One more push past the cap.
161        registry.push_search_audit(&session.id, search_record("q-overflow"));
162
163        let records = registry.get_search_audit(&session.id).unwrap();
164
165        assert_eq!(records.len(), SEARCH_AUDIT_CAP);
166        // The very first record ("q-0") must have been evicted.
167        assert!(
168            !records
169                .iter()
170                .any(|r| matches!(r, SearchAuditRecord::Search { query, .. } if query == "q-0"))
171        );
172        // The overflow record must be present, as the newest (last) entry.
173        assert!(matches!(
174            records.last(),
175            Some(SearchAuditRecord::Search { query, .. }) if query == "q-overflow"
176        ));
177    }
178
179    /// An unknown session must map to `-32007 session_not_found`.
180    #[test]
181    fn get_search_audit_unknown_session_errors() {
182        let registry = SessionRegistry::new();
183        let err = registry.get_search_audit("nope").unwrap_err();
184        assert_eq!(err.code, -32007);
185    }
186
187    /// `push_search_audit` on an unknown session is a silent no-op, mirroring
188    /// `SessionRegistry::record`'s contract — it never panics or surfaces an
189    /// error to a caller that already validated existence.
190    #[test]
191    fn push_search_audit_unknown_session_is_noop() {
192        let registry = SessionRegistry::new();
193        // Must not panic.
194        registry.push_search_audit("nope", search_record("x"));
195    }
196}