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.
32//! Test: `recall_session::tests::*`.
33
34use async_trait::async_trait;
35use serde::Deserialize;
36use serde_json::{Value, json};
37use tracing::warn;
38use trusty_common::mcp::memory_rpc::call_memory_tool_at;
39
40use crate::agent_loop::estimate_tokens;
41use crate::memory_envelope::{parse_tools_call_envelope, tools_call_params};
42use crate::tools::traits::{ToolExecutor, ToolResult};
43
44/// The tool's registered/advertised name.
45pub const RECALL_SESSION_TOOL_NAME: &str = "recall_session";
46
47/// Default `top_k` when the model omits it.
48pub const DEFAULT_TOP_K: usize = 5;
49
50/// Hard cap on `top_k` regardless of what the model requests — keeps a
51/// single call bounded even if the model asks for an unreasonable count.
52pub const MAX_TOP_K: usize = 10;
53
54/// Daemon-side over-fetch multiplier (spike guidance on #2348: the daemon
55/// cannot tag-filter server-side, so client-side filtering needs a wider
56/// candidate pool than the final `top_k` to avoid starving the session-tagged
57/// subset).
58const OVER_FETCH_FACTOR: usize = 4;
59
60/// Token budget for this tool's rendered result text — the epic #2343
61/// `recall_injection_reserve` (~4K of the ~80K max_overhead_fraction budget
62/// on a 200K window).
63const TOKEN_BUDGET: usize = 4000;
64
65/// Parsed `recall_session` tool-call arguments.
66#[derive(Debug, Deserialize)]
67struct RecallSessionArgs {
68    query: String,
69    #[serde(default)]
70    top_k: Option<usize>,
71}
72
73/// `ToolExecutor` for the `recall_session` tool (#2348).
74///
75/// Why: gives the model an explicit way to query ITS OWN durable session
76/// history rather than relying on whatever still fits in its visible
77/// context window.
78/// What: holds the (session-scoped) identifiers needed to issue a
79/// `memory_recall` call against the right daemon/palace and filter to the
80/// right session — all three are resolved once, at construction, by the
81/// caller (`task::executor::run_and_record`, reusing
82/// `session::TurnMemorySink::base_url`/`palace` rather than re-deriving
83/// them).
84/// Test: `tests::*`.
85pub struct RecallSessionTool {
86    session_id: String,
87    base_url: String,
88    palace: String,
89}
90
91impl RecallSessionTool {
92    /// Construct a tool scoped to one session's daemon/palace/id.
93    pub fn new(
94        session_id: impl Into<String>,
95        base_url: impl Into<String>,
96        palace: impl Into<String>,
97    ) -> Self {
98        Self {
99            session_id: session_id.into(),
100            base_url: base_url.into(),
101            palace: palace.into(),
102        }
103    }
104
105    /// The exact tag `memory_sink::write_turn` writes for this session —
106    /// the client-side filter predicate.
107    fn session_tag(&self) -> String {
108        format!("session:{}", self.session_id)
109    }
110}
111
112/// Whether a single `memory_recall` result entry carries `tag`.
113fn result_has_tag(result: &Value, tag: &str) -> bool {
114    result
115        .get("tags")
116        .and_then(|t| t.as_array())
117        .map(|tags| tags.iter().any(|t| t.as_str() == Some(tag)))
118        .unwrap_or(false)
119}
120
121/// Filter `results` to those tagged `tag`, then cap at `top_k`.
122///
123/// Why: shared by `execute` and directly unit-testable without a mock
124/// server. Results arrive score-sorted highest-first from the daemon, so a
125/// prefix `truncate` after filtering preserves that ordering.
126/// What: preserves input order; drops non-matching entries; returns at most
127/// `top_k` entries.
128/// Test: `tests::filter_and_cap_keeps_only_tagged_results_in_order`.
129fn filter_and_cap(results: &[Value], tag: &str, top_k: usize) -> Vec<Value> {
130    let mut filtered: Vec<Value> = results
131        .iter()
132        .filter(|r| result_has_tag(r, tag))
133        .cloned()
134        .collect();
135    filtered.truncate(top_k);
136    filtered
137}
138
139/// Render filtered results into the tool's final text, dropping WHOLE
140/// lowest-scored entries (never mid-text) to fit [`TOKEN_BUDGET`].
141///
142/// Why: the epic's budget model caps this tool's contribution to the
143/// prompt; truncating mid-result would produce a half-sentence a model
144/// might misread as complete. Dropping whole entries from the tail keeps
145/// every included result fully legible.
146/// What: `results` must already be capped/ordered (highest-score first,
147/// per [`filter_and_cap`]). The first result is always included even if it
148/// alone exceeds the budget — an over-budget single result is still more
149/// useful than an empty response.
150/// Test: `tests::render_drops_whole_lowest_scored_entries_over_budget`.
151fn render_results(query: &str, results: &[Value]) -> String {
152    let mut entries: Vec<String> = Vec::new();
153    let mut budget_used = 0usize;
154    for r in results {
155        let content = r.get("content").and_then(|c| c.as_str()).unwrap_or("");
156        let entry_tokens = estimate_tokens(content);
157        if !entries.is_empty() && budget_used + entry_tokens > TOKEN_BUDGET {
158            break;
159        }
160        budget_used += entry_tokens;
161        entries.push(content.to_string());
162    }
163    format!(
164        "Session memory results for \"{query}\":\n\n{}",
165        entries.join("\n\n---\n\n")
166    )
167}
168
169#[async_trait]
170impl ToolExecutor for RecallSessionTool {
171    fn name(&self) -> &str {
172        RECALL_SESSION_TOOL_NAME
173    }
174
175    /// JSON schema for `recall_session`.
176    ///
177    /// Why: the description explicitly scopes the tool to THIS session's own
178    /// history so the model does not mistake it for a general/cross-session
179    /// or cross-project search.
180    /// Test: `tests::schema_has_required_fields`.
181    fn schema(&self) -> Value {
182        json!({
183            "type": "function",
184            "function": {
185                "name": RECALL_SESSION_TOOL_NAME,
186                "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.",
187                "parameters": {
188                    "type": "object",
189                    "properties": {
190                        "query": {
191                            "type": "string",
192                            "description": "What to search for in this session's history."
193                        },
194                        "top_k": {
195                            "type": "integer",
196                            "description": "Maximum number of results to return (default 5, max 10)."
197                        }
198                    },
199                    "required": ["query"],
200                    "additionalProperties": false
201                }
202            }
203        })
204    }
205
206    /// Execute a session-scoped recall query, fail-open on any daemon or
207    /// parsing failure.
208    ///
209    /// Why: an explicit model tool call must never derail the agent loop —
210    /// a `ToolResult::err`/`fatal` here would surface as a tool error the
211    /// model might retry-loop on; "session memory unavailable" as a
212    /// SUCCESSFUL result lets the model simply proceed without it.
213    /// Test: `tests::execute_returns_only_session_tagged_results`,
214    /// `tests::execute_over_fetches_top_k_times_factor`,
215    /// `tests::execute_is_fail_open_on_unreachable_daemon`,
216    /// `tests::execute_rejects_malformed_args_recoverably`.
217    async fn execute(&self, args: Value) -> ToolResult {
218        let parsed: RecallSessionArgs = match serde_json::from_value(args) {
219            Ok(p) => p,
220            Err(e) => {
221                return ToolResult::err(format!(
222                    "recall_session arguments did not match the expected shape ({e}). \
223                     'query' (string) is required."
224                ));
225            }
226        };
227        let top_k = parsed.top_k.unwrap_or(DEFAULT_TOP_K).clamp(1, MAX_TOP_K);
228        let fetch_k = top_k * OVER_FETCH_FACTOR;
229
230        let rpc_params = tools_call_params(
231            "memory_recall",
232            json!({
233                "palace": self.palace,
234                "query": parsed.query,
235                "top_k": fetch_k,
236            }),
237        );
238
239        let envelope = match call_memory_tool_at(&self.base_url, "tools/call", rpc_params).await {
240            Ok(v) => v,
241            Err(e) => {
242                warn!(
243                    session_id = %self.session_id,
244                    error = %e,
245                    "recall_session: memory_recall RPC failed (fail-open)"
246                );
247                return ToolResult::ok(
248                    "session memory unavailable (trusty-memory unreachable)".to_string(),
249                );
250            }
251        };
252
253        let Some(body) = parse_tools_call_envelope(&envelope) else {
254            warn!(
255                session_id = %self.session_id,
256                "recall_session: unexpected memory_recall response shape (fail-open)"
257            );
258            return ToolResult::ok(
259                "session memory unavailable (unexpected response shape)".to_string(),
260            );
261        };
262
263        let results = body
264            .get("results")
265            .and_then(|r| r.as_array())
266            .cloned()
267            .unwrap_or_default();
268        let filtered = filter_and_cap(&results, &self.session_tag(), top_k);
269
270        if filtered.is_empty() {
271            return ToolResult::ok(format!(
272                "No session memory found for query: {}",
273                parsed.query
274            ));
275        }
276
277        ToolResult::ok(render_results(&parsed.query, &filtered))
278    }
279}
280
281// ── Tests ─────────────────────────────────────────────────────────────────────
282
283#[cfg(test)]
284mod tests {
285    use std::sync::{Arc, Mutex};
286
287    use axum::extract::State;
288    use axum::routing::post;
289    use axum::{Json, Router};
290    use tokio::net::TcpListener;
291
292    use super::*;
293
294    /// A `memory_recall` result entry with `content`/`score`/`tags`.
295    fn result_entry(content: &str, score: f64, tags: &[&str]) -> Value {
296        json!({
297            "drawer_id": "00000000-0000-0000-0000-000000000000",
298            "content": content,
299            "score": score,
300            "layer": 1,
301            "tags": tags,
302            "importance": 0.5,
303            "drawer_type": "session_note",
304        })
305    }
306
307    /// Wrap a `serialize_recall`-shaped body as the real spike-verified
308    /// `tools/call` envelope: the inner JSON STRINGIFIED inside
309    /// `content[0].text`.
310    fn tools_call_envelope(palace: &str, query: &str, results: Vec<Value>) -> Value {
311        let inner = json!({"palace": palace, "query": query, "results": results}).to_string();
312        json!({"content": [{"type": "text", "text": inner}]})
313    }
314
315    // NOTE (#2424): the envelope-unwrap unit tests moved with the helper to
316    // `crate::memory_envelope::tests` when `parse_recall_envelope` was
317    // promoted to the shared `parse_tools_call_envelope`.
318
319    // ── `filter_and_cap` ─────────────────────────────────────────────────
320
321    #[test]
322    fn filter_and_cap_keeps_only_tagged_results_in_order() {
323        let results = vec![
324            result_entry("a", 0.9, &["session:s1", "turn"]),
325            result_entry("b", 0.8, &["session:other", "turn"]),
326            result_entry("c", 0.7, &["session:s1", "turn"]),
327        ];
328        let filtered = filter_and_cap(&results, "session:s1", 10);
329        assert_eq!(filtered.len(), 2);
330        assert_eq!(filtered[0]["content"], "a");
331        assert_eq!(filtered[1]["content"], "c");
332    }
333
334    #[test]
335    fn filter_and_cap_respects_top_k() {
336        let results = vec![
337            result_entry("a", 0.9, &["session:s1"]),
338            result_entry("b", 0.8, &["session:s1"]),
339            result_entry("c", 0.7, &["session:s1"]),
340        ];
341        let filtered = filter_and_cap(&results, "session:s1", 2);
342        assert_eq!(filtered.len(), 2);
343        assert_eq!(filtered[0]["content"], "a");
344        assert_eq!(filtered[1]["content"], "b");
345    }
346
347    // ── `render_results` ─────────────────────────────────────────────────
348
349    #[test]
350    fn render_drops_whole_lowest_scored_entries_over_budget() {
351        // Each "x" repeated 4 chars ~ 1 token by the chars/4 heuristic.
352        // Build one huge entry that alone exceeds the budget, followed by a
353        // small one; expect the small one dropped, not mid-text truncated.
354        let huge = "x".repeat((TOKEN_BUDGET + 100) * 4);
355        let results = vec![result_entry(&huge, 0.9, &["session:s1"]), {
356            let mut r = result_entry("small tail entry", 0.8, &["session:s1"]);
357            r["content"] = json!("small tail entry");
358            r
359        }];
360        let rendered = render_results("q", &results);
361        assert!(
362            rendered.contains(&huge),
363            "first entry always included whole"
364        );
365        assert!(
366            !rendered.contains("small tail entry"),
367            "second (lower-scored) entry must be dropped whole, not merged/truncated in"
368        );
369    }
370
371    #[test]
372    fn render_includes_all_entries_within_budget() {
373        let results = vec![
374            result_entry("first", 0.9, &["session:s1"]),
375            result_entry("second", 0.8, &["session:s1"]),
376        ];
377        let rendered = render_results("q", &results);
378        assert!(rendered.contains("first"));
379        assert!(rendered.contains("second"));
380    }
381
382    // ── schema ───────────────────────────────────────────────────────────
383
384    #[test]
385    fn schema_has_required_fields() {
386        let tool = RecallSessionTool::new("s1", "http://x", "p");
387        let schema = tool.schema();
388        let params = &schema["function"]["parameters"];
389        assert_eq!(schema["function"]["name"], RECALL_SESSION_TOOL_NAME);
390        let required: Vec<&str> = params["required"]
391            .as_array()
392            .expect("required array")
393            .iter()
394            .filter_map(|v| v.as_str())
395            .collect();
396        assert_eq!(required, vec!["query"]);
397        assert_eq!(params["additionalProperties"], json!(false));
398    }
399
400    // ── `execute` end-to-end against a mock daemon ───────────────────────
401
402    /// One captured `/rpc` call: JSON-RPC `method` + `params`.
403    type Captured = Arc<Mutex<Vec<(String, Value)>>>;
404
405    /// Spin up a mock `/rpc` server that always replies with the
406    /// spike-verified `tools/call` envelope shape for `memory_recall`,
407    /// capturing every request's method/params.
408    async fn spawn_recall_mock(results: Vec<Value>) -> (String, Captured) {
409        let captured: Captured = Arc::new(Mutex::new(Vec::new()));
410        let store = Arc::clone(&captured);
411        let results_state = Arc::new(results);
412
413        async fn handle(
414            State((store, results)): State<(Captured, Arc<Vec<Value>>)>,
415            Json(body): Json<Value>,
416        ) -> Json<Value> {
417            let method = body["method"].as_str().unwrap_or_default().to_string();
418            let params = body["params"].clone();
419            store
420                .lock()
421                .unwrap_or_else(|e| e.into_inner())
422                .push((method, params.clone()));
423            let palace = params["arguments"]["palace"]
424                .as_str()
425                .unwrap_or_default()
426                .to_string();
427            let query = params["arguments"]["query"]
428                .as_str()
429                .unwrap_or_default()
430                .to_string();
431            let envelope = tools_call_envelope(&palace, &query, (*results).clone());
432            Json(json!({"jsonrpc": "2.0", "id": 1, "result": envelope}))
433        }
434
435        let app = Router::new()
436            .route("/rpc", post(handle))
437            .with_state((store, results_state));
438        let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind mock");
439        let addr = listener.local_addr().expect("addr");
440        tokio::spawn(async move {
441            let _ = axum::serve(listener, app).await;
442        });
443        (format!("http://{addr}"), captured)
444    }
445
446    #[tokio::test]
447    async fn execute_returns_only_session_tagged_results() {
448        let results = vec![
449            result_entry("mine: file is at src/foo.rs", 0.9, &["session:s1", "turn"]),
450            result_entry("other session's note", 0.8, &["session:s2", "turn"]),
451            result_entry("mine again", 0.7, &["session:s1", "turn"]),
452        ];
453        let (base_url, _captured) = spawn_recall_mock(results).await;
454        let tool = RecallSessionTool::new("s1", base_url, "p");
455
456        let result = tool.execute(json!({"query": "foo"})).await;
457        assert!(!result.is_error());
458        assert!(result.content().contains("src/foo.rs"));
459        assert!(result.content().contains("mine again"));
460        assert!(!result.content().contains("other session's note"));
461    }
462
463    #[tokio::test]
464    async fn execute_over_fetches_top_k_times_factor() {
465        let (base_url, captured) = spawn_recall_mock(vec![]).await;
466        let tool = RecallSessionTool::new("s1", base_url, "p");
467
468        let _ = tool.execute(json!({"query": "foo", "top_k": 3})).await;
469
470        let calls = captured.lock().unwrap_or_else(|e| e.into_inner()).clone();
471        assert_eq!(calls.len(), 1);
472        let (method, params) = &calls[0];
473        assert_eq!(method, "tools/call");
474        assert_eq!(params["name"], "memory_recall");
475        assert_eq!(params["arguments"]["top_k"], json!(3 * OVER_FETCH_FACTOR));
476    }
477
478    #[tokio::test]
479    async fn execute_clamps_top_k_to_max() {
480        let (base_url, captured) = spawn_recall_mock(vec![]).await;
481        let tool = RecallSessionTool::new("s1", base_url, "p");
482
483        let _ = tool.execute(json!({"query": "foo", "top_k": 999})).await;
484
485        let calls = captured.lock().unwrap_or_else(|e| e.into_inner()).clone();
486        assert_eq!(
487            calls[0].1["arguments"]["top_k"],
488            json!(MAX_TOP_K * OVER_FETCH_FACTOR)
489        );
490    }
491
492    #[tokio::test]
493    async fn execute_is_fail_open_on_unreachable_daemon() {
494        let tool = RecallSessionTool::new("s1", "http://127.0.0.1:1", "p");
495        let result = tool.execute(json!({"query": "anything"})).await;
496        assert!(!result.is_error(), "must not surface as a tool error");
497        assert!(result.content().contains("unavailable"));
498    }
499
500    #[tokio::test]
501    async fn execute_rejects_malformed_args_recoverably() {
502        let tool = RecallSessionTool::new("s1", "http://127.0.0.1:1", "p");
503        let result = tool.execute(json!({"top_k": 3})).await; // missing 'query'
504        assert!(result.is_error());
505        assert!(!result.is_fatal());
506    }
507
508    #[tokio::test]
509    async fn execute_empty_when_no_session_tagged_results() {
510        let results = vec![result_entry("belongs elsewhere", 0.9, &["session:other"])];
511        let (base_url, _captured) = spawn_recall_mock(results).await;
512        let tool = RecallSessionTool::new("s1", base_url, "p");
513
514        let result = tool.execute(json!({"query": "anything"})).await;
515        assert!(!result.is_error());
516        assert!(result.content().contains("No session memory found"));
517    }
518}