Skip to main content

trusty_code/tools/
recall_session.rs

1//! `recall_session` tool (#2348): session-scoped memory query (RAG over
2//! session history).
3//!
4//! Why: epic #2343 (Infinite Sessions) requires all other session context
5//! beyond the 5 pinned goal slots and the compressed working history to be
6//! retrieved ON DEMAND by querying trusty-memory, rather than kept resident
7//! in the prompt. #2345's turn recorder already dual-writes every turn into
8//! trusty-memory (tagged `session:<id>`, `turn`) as the semantic recall
9//! surface; this tool is the model-invoked query side of that surface — an
10//! explicit tool call the model makes when it needs something from earlier
11//! in THIS session that has scrolled out of its visible context, never an
12//! automatic per-turn injection.
13//! What: [`RecallSessionTool`] implements `ToolExecutor`. `execute` calls
14//! trusty-memory's `memory_recall` via the `tools/call` MCP envelope
15//! (spike-verified on issue #2348: the daemon wraps the tool result as a
16//! STRINGIFIED JSON blob inside `result.content[0].text`, not a raw JSON
17//! value — `crate::memory_envelope::parse_tools_call_envelope`, the shared
18//! unwrap this module originally owned and #2424 promoted so the turn
19//! recorder writes through the same shape, handles that), over-fetching
20//! `top_k * `[`OVER_FETCH_FACTOR`] results because the daemon cannot
21//! tag-filter server-side (filtering happens client-side, AFTER the
22//! daemon's own truncation — see the spike comment on #2348). Results are
23//! filtered to those tagged `session:<id>` (matching the exact tag
24//! `memory_sink::write_turn` writes), capped at `top_k` (clamped to
25//! [`MAX_TOP_K`]), and truncated to fit [`TOKEN_BUDGET`] (the epic's
26//! `recall_injection_reserve`) by dropping WHOLE lowest-scored results
27//! (never mid-text) — daemon results already arrive score-sorted
28//! highest-first, so this is a simple prefix take. Unreachable daemon /
29//! malformed response is fail-open: a successful (non-error) `ToolResult`
30//! carrying an explicit "unavailable" message plus a `tracing::warn!`, so a
31//! flaky trusty-memory never derails the agent loop. (#2857) Dropping
32//! lowest-scored results for the token budget also logs, at `tracing::info!`
33//! — a degradation the model silently acts on (see [`render_results`]).
34//! Test: `recall_session::tests::*`.
35
36use async_trait::async_trait;
37use serde::Deserialize;
38use serde_json::{Value, json};
39use tracing::warn;
40use trusty_common::memory_rpc::call_memory_tool_at;
41
42use crate::agent_loop::estimate_tokens;
43use crate::events::RecalledMemory;
44use crate::memory_envelope::{parse_tools_call_envelope, tools_call_params};
45use crate::tools::telemetry::{RecallTelemetry, ToolTelemetry};
46use crate::tools::traits::{ToolExecutor, ToolResult};
47
48/// The tool's registered/advertised name.
49pub const RECALL_SESSION_TOOL_NAME: &str = "recall_session";
50
51/// Default `top_k` when the model omits it.
52pub const DEFAULT_TOP_K: usize = 5;
53
54/// Hard cap on `top_k` regardless of what the model requests — keeps a
55/// single call bounded even if the model asks for an unreasonable count.
56pub const MAX_TOP_K: usize = 10;
57
58/// Daemon-side over-fetch multiplier (spike guidance on #2348: the daemon
59/// cannot tag-filter server-side, so client-side filtering needs a wider
60/// candidate pool than the final `top_k` to avoid starving the session-tagged
61/// subset).
62const OVER_FETCH_FACTOR: usize = 4;
63
64/// Token budget for this tool's rendered result text — the epic #2343
65/// `recall_injection_reserve` (~4K of the ~80K max_overhead_fraction budget
66/// on a 200K window).
67const TOKEN_BUDGET: usize = 4000;
68
69/// Parsed `recall_session` tool-call arguments.
70#[derive(Debug, Deserialize)]
71struct RecallSessionArgs {
72    query: String,
73    #[serde(default)]
74    top_k: Option<usize>,
75}
76
77/// `ToolExecutor` for the `recall_session` tool (#2348).
78///
79/// Why: gives the model an explicit way to query ITS OWN durable session
80/// history rather than relying on whatever still fits in its visible
81/// context window.
82/// What: holds the (session-scoped) identifiers needed to issue a
83/// `memory_recall` call against the right daemon/palace and filter to the
84/// right session — all three are resolved once, at construction, by the
85/// caller (`task::executor::run_and_record`, reusing
86/// `session::TurnMemorySink::socket`/`palace` rather than re-deriving
87/// them).
88/// Test: `tests::*`.
89pub struct RecallSessionTool {
90    session_id: String,
91    socket: std::path::PathBuf,
92    palace: String,
93}
94
95impl RecallSessionTool {
96    /// Construct a tool scoped to one session's daemon/palace/id.
97    pub fn new(
98        session_id: impl Into<String>,
99        socket: impl Into<std::path::PathBuf>,
100        palace: impl Into<String>,
101    ) -> Self {
102        Self {
103            session_id: session_id.into(),
104            socket: socket.into(),
105            palace: palace.into(),
106        }
107    }
108
109    /// The exact tag `memory_sink::write_turn` writes for this session —
110    /// the client-side filter predicate.
111    fn session_tag(&self) -> String {
112        format!("session:{}", self.session_id)
113    }
114}
115
116/// Whether a single `memory_recall` result entry carries `tag`.
117fn result_has_tag(result: &Value, tag: &str) -> bool {
118    result
119        .get("tags")
120        .and_then(|t| t.as_array())
121        .map(|tags| tags.iter().any(|t| t.as_str() == Some(tag)))
122        .unwrap_or(false)
123}
124
125/// Filter `results` to those tagged `tag`, then cap at `top_k`.
126///
127/// Why: shared by `execute` and directly unit-testable without a mock
128/// server. Results arrive score-sorted highest-first from the daemon, so a
129/// prefix `truncate` after filtering preserves that ordering.
130/// What: preserves input order; drops non-matching entries; returns at most
131/// `top_k` entries.
132/// Test: `tests::filter_and_cap_keeps_only_tagged_results_in_order`.
133fn filter_and_cap(results: &[Value], tag: &str, top_k: usize) -> Vec<Value> {
134    let mut filtered: Vec<Value> = results
135        .iter()
136        .filter(|r| result_has_tag(r, tag))
137        .cloned()
138        .collect();
139    filtered.truncate(top_k);
140    filtered
141}
142
143/// Render filtered results into the tool's final text, dropping WHOLE
144/// lowest-scored entries (never mid-text) to fit [`TOKEN_BUDGET`].
145///
146/// Why: the epic's budget model caps this tool's contribution to the
147/// prompt; truncating mid-result would produce a half-sentence a model
148/// might misread as complete. Dropping whole entries from the tail keeps
149/// every included result fully legible.
150/// What: `results` must already be capped/ordered (highest-score first,
151/// per [`filter_and_cap`]). The first result is always included even if it
152/// alone exceeds the budget — an over-budget single result is still more
153/// useful than an empty response. (#2857) When one or more lowest-scored
154/// results are dropped for budget, emits `tracing::info!` with the dropped/
155/// included counts — the model silently receives fewer memories than it
156/// asked for, so an operator diagnosing "the model missed a fact it should
157/// have recalled" needs this visible from stderr, not just inferable from
158/// the rendered text length.
159///
160/// (UI Phase 1) Also returns HOW MANY leading results made it into that
161/// text. Because the loop takes a strict prefix (it `break`s at the first
162/// over-budget entry rather than skipping it and trying the next), the
163/// included set is always `results[..injected_count]` — so one count fully
164/// describes the injected/held-back split, and
165/// [`recall_telemetry`] turns it into the per-result `injected` flags.
166/// Test: `tests::render_drops_whole_lowest_scored_entries_over_budget`,
167/// `tests::render_includes_all_entries_within_budget`.
168fn render_results(query: &str, results: &[Value]) -> (String, usize) {
169    let mut entries: Vec<String> = Vec::new();
170    let mut budget_used = 0usize;
171    for r in results {
172        let content = r.get("content").and_then(|c| c.as_str()).unwrap_or("");
173        let entry_tokens = estimate_tokens(content);
174        if !entries.is_empty() && budget_used + entry_tokens > TOKEN_BUDGET {
175            break;
176        }
177        budget_used += entry_tokens;
178        entries.push(content.to_string());
179    }
180    let dropped = results.len() - entries.len();
181    if dropped > 0 {
182        tracing::info!(
183            dropped,
184            included = entries.len(),
185            budget_tokens = TOKEN_BUDGET,
186            "recall_session: token budget exceeded — dropping lowest-scored result(s)"
187        );
188    }
189    let injected_count = entries.len();
190    (
191        format!(
192            "Session memory results for \"{query}\":\n\n{}",
193            entries.join("\n\n---\n\n")
194        ),
195        injected_count,
196    )
197}
198
199/// Build the structured account of what was recalled and what reached the
200/// model (UI Phase 1; `text`/`run_id` added for DOC-39 Slice C).
201///
202/// Why: this is the whole point of `Event::MemoryRecalled` — the UI renders
203/// held-back memories ("41% · held") beside injected ones, and only this
204/// tool ever knows which was which. Slice C extends that to the memory-
205/// provenance debugging surface ("what memory drove this / what was held
206/// back"), which needs the actual recalled TEXT, not just a score — a held
207/// -back result the UI can only count but never read is not debuggable.
208/// What: `results` is the filtered/capped, score-sorted list; the first
209/// `injected_count` of them entered context (see [`render_results`]) and the
210/// rest were recalled but dropped whole by the token budget. A result whose
211/// entry carries no numeric `score` reports `0.0` rather than being omitted
212/// — the UI must still see that the memory was recalled and held back.
213/// `text`/`run_id` are read from the SAME already-parsed `content` value
214/// `render_results` reads from (no second parse): `text` falls back to an
215/// empty string, `run_id` to `None`, when the entry carries no such field —
216/// never a panic.
217/// Test: `tests::telemetry_marks_budget_dropped_results_held_back`,
218/// `tests::telemetry_marks_all_injected_when_within_budget`,
219/// `tests::telemetry_carries_recalled_text_and_run_id`.
220fn recall_telemetry(query: &str, results: &[Value], injected_count: usize) -> RecallTelemetry {
221    RecallTelemetry {
222        query: query.to_string(),
223        results: results
224            .iter()
225            .enumerate()
226            .map(|(i, r)| RecalledMemory {
227                score: r.get("score").and_then(Value::as_f64).unwrap_or(0.0),
228                injected: i < injected_count,
229                text: r
230                    .get("content")
231                    .and_then(Value::as_str)
232                    .unwrap_or("")
233                    .to_string(),
234                run_id: r.get("run_id").and_then(Value::as_str).map(str::to_string),
235            })
236            .collect(),
237    }
238}
239
240#[async_trait]
241impl ToolExecutor for RecallSessionTool {
242    fn name(&self) -> &str {
243        RECALL_SESSION_TOOL_NAME
244    }
245
246    /// JSON schema for `recall_session`.
247    ///
248    /// Why: the description explicitly scopes the tool to THIS session's own
249    /// history so the model does not mistake it for a general/cross-session
250    /// or cross-project search.
251    /// Test: `tests::schema_has_required_fields`.
252    fn schema(&self) -> Value {
253        json!({
254            "type": "function",
255            "function": {
256                "name": RECALL_SESSION_TOOL_NAME,
257                "description": "Search THIS session's own history stored in durable memory. Use when you need something from earlier in this session that is no longer visible in your current context (e.g. a decision, file path, or fact from many turns ago). Does not search other sessions or other projects.",
258                "parameters": {
259                    "type": "object",
260                    "properties": {
261                        "query": {
262                            "type": "string",
263                            "description": "What to search for in this session's history."
264                        },
265                        "top_k": {
266                            "type": "integer",
267                            "description": "Maximum number of results to return (default 5, max 10)."
268                        }
269                    },
270                    "required": ["query"],
271                    "additionalProperties": false
272                }
273            }
274        })
275    }
276
277    /// Execute a session-scoped recall query, fail-open on any daemon or
278    /// parsing failure.
279    ///
280    /// Why: an explicit model tool call must never derail the agent loop —
281    /// a `ToolResult::err`/`fatal` here would surface as a tool error the
282    /// model might retry-loop on; "session memory unavailable" as a
283    /// SUCCESSFUL result lets the model simply proceed without it.
284    /// Test: `tests::execute_returns_only_session_tagged_results`,
285    /// `tests::execute_over_fetches_top_k_times_factor`,
286    /// `tests::execute_is_fail_open_on_unreachable_daemon`,
287    /// `tests::execute_rejects_malformed_args_recoverably`.
288    async fn execute(&self, args: Value) -> ToolResult {
289        let parsed: RecallSessionArgs = match serde_json::from_value(args) {
290            Ok(p) => p,
291            Err(e) => {
292                return ToolResult::err(format!(
293                    "recall_session arguments did not match the expected shape ({e}). \
294                     'query' (string) is required."
295                ));
296            }
297        };
298        let top_k = parsed.top_k.unwrap_or(DEFAULT_TOP_K).clamp(1, MAX_TOP_K);
299        let fetch_k = top_k * OVER_FETCH_FACTOR;
300
301        let rpc_params = tools_call_params(
302            "memory_recall",
303            json!({
304                "palace": self.palace,
305                "query": parsed.query,
306                "top_k": fetch_k,
307            }),
308        );
309
310        let envelope = match call_memory_tool_at(&self.socket, "tools/call", rpc_params).await {
311            Ok(v) => v,
312            Err(e) => {
313                warn!(
314                    session_id = %self.session_id,
315                    error = %e,
316                    "recall_session: memory_recall RPC failed (fail-open)"
317                );
318                return ToolResult::ok(
319                    "session memory unavailable (trusty-memory unreachable)".to_string(),
320                );
321            }
322        };
323
324        let Some(body) = parse_tools_call_envelope(&envelope) else {
325            warn!(
326                session_id = %self.session_id,
327                "recall_session: unexpected memory_recall response shape (fail-open)"
328            );
329            return ToolResult::ok(
330                "session memory unavailable (unexpected response shape)".to_string(),
331            );
332        };
333
334        let results = body
335            .get("results")
336            .and_then(|r| r.as_array())
337            .cloned()
338            .unwrap_or_default();
339        let filtered = filter_and_cap(&results, &self.session_tag(), top_k);
340
341        if filtered.is_empty() {
342            return ToolResult::ok(format!(
343                "No session memory found for query: {}",
344                parsed.query
345            ));
346        }
347
348        // (UI Phase 1) The render decides the injected/held-back split; the
349        // telemetry reports it. Both derive from the SAME call so they can
350        // never disagree about what the model actually saw.
351        let (text, injected_count) = render_results(&parsed.query, &filtered);
352        ToolResult::ok(text).with_telemetry(ToolTelemetry::Recall(recall_telemetry(
353            &parsed.query,
354            &filtered,
355            injected_count,
356        )))
357    }
358}
359
360#[cfg(test)]
361#[path = "recall_session_tests.rs"]
362mod tests;