use crate::support;
use serde_json::{Value, json};
use support::{
MockMemoryDaemon, StdioSession, find_session_event, project_with_agents,
spawn_mock_memory_daemon,
};
use tokio::sync::watch;
fn huge_injected_text() -> String {
"PKCE keystone context. ".repeat(1000)
}
const HELD_BACK_TEXT: &str = "PKCE required for the OAuth token exchange — held back by budget";
const INJECTED_RUN_ID: &str = "run-e2e-slice-c";
async fn spawn_recall_mock_daemon() -> (MockMemoryDaemon, watch::Sender<Option<String>>) {
let (tag_tx, tag_rx) = watch::channel(None::<String>);
let daemon = spawn_mock_memory_daemon(move |_method: &str, _params: Value| {
let mut rx = tag_rx.clone();
Box::pin(async move {
let tag = loop {
if let Some(tag) = rx.borrow().clone() {
break tag;
}
if rx.changed().await.is_err() {
break String::new();
}
};
let results = vec![
json!({
"content": huge_injected_text(),
"score": 0.93,
"tags": [tag, "turn"],
"run_id": INJECTED_RUN_ID,
}),
json!({
"content": HELD_BACK_TEXT,
"score": 0.41,
"tags": [tag, "turn"],
}),
];
let inner =
json!({"palace": "p", "query": "pkce oauth flow", "results": results}).to_string();
Ok(json!({"content": [{"type": "text", "text": inner}]}))
})
})
.await;
(daemon, tag_tx)
}
async fn run_recall_task_to_completion(
daemon: &mut StdioSession,
tag_tx: &watch::Sender<Option<String>>,
) -> Vec<Value> {
let run_resp = daemon
.call(
1,
"task.run",
json!({"task_description": "recall what we know about the pkce oauth flow"}),
)
.await;
assert!(run_resp["error"].is_null(), "task.run failed: {run_resp}");
let session_id = run_resp["result"]["session_id"]
.as_str()
.expect("task.run must return a session_id")
.to_string();
let _ = tag_tx.send(Some(format!("session:{session_id}")));
let attach_resp = daemon
.call(2, "session.attach", json!({"session_id": session_id}))
.await;
assert!(
attach_resp["error"].is_null(),
"attach failed: {attach_resp}"
);
let mut envelopes: Vec<Value> = attach_resp["result"]["events"]
.as_array()
.expect("attach must return a replay events array")
.clone();
let mut iterations = 0;
let is_done = |envs: &[Value]| {
envs.iter()
.any(|e| e["kind"].as_str() == Some("session_done"))
};
while !is_done(&envelopes) {
iterations += 1;
assert!(
iterations < 20,
"gave up waiting for session_done after {iterations} read rounds; \
envelopes so far: {envelopes:?}"
);
let lines = daemon.read_lines(20).await;
assert!(
!lines.is_empty(),
"timed out waiting for more events; envelopes so far: {envelopes:?}"
);
for line in &lines {
if let Some(envelope) = find_session_event(line, &session_id) {
envelopes.push(envelope);
}
}
}
envelopes
}
#[tokio::test]
async fn held_back_recall_result_carries_its_text_and_run_id_over_the_wire() {
let (mock_daemon, tag_tx) = spawn_recall_mock_daemon().await;
let mock_socket = mock_daemon.socket().display().to_string();
let project = project_with_agents();
let mut daemon = StdioSession::spawn_with_mock_llm_variant_and_env(
project.path(),
trusty_code::task::mock_llm::MOCK_LLM_ECHO_RECALL,
&[(
trusty_common::memory_rpc::TRUSTY_MEMORY_SOCKET_ENV,
&mock_socket,
)],
);
let envelopes = run_recall_task_to_completion(&mut daemon, &tag_tx).await;
let recall_events: Vec<&Value> = envelopes
.iter()
.filter(|e| e["kind"].as_str() == Some("memory_recalled"))
.collect();
assert_eq!(
recall_events.len(),
1,
"expected exactly one memory_recalled event; got: {recall_events:?}\n\
all envelopes: {envelopes:?}"
);
let results = recall_events[0]["event"]["results"]
.as_array()
.expect("results must be an array");
assert_eq!(
results.len(),
2,
"expected both the injected and held-back result to be REPORTED \
(only rendering, not telemetry, drops the held-back one): {results:?}"
);
let injected = &results[0];
assert_eq!(injected["injected"], true);
assert_eq!(
injected["text"].as_str().unwrap_or_default(),
huge_injected_text(),
"the injected result's full text must reach the wire"
);
assert_eq!(
injected["run_id"].as_str(),
Some(INJECTED_RUN_ID),
"a run_id present on the daemon response must thread through"
);
let held_back = &results[1];
assert_eq!(
held_back["injected"], false,
"the second (lower-scored, over-budget) result must be held back"
);
assert_eq!(
held_back["text"].as_str().unwrap_or_default(),
HELD_BACK_TEXT,
"THE point of this slice: a held-back result's actual TEXT must \
still reach Event::MemoryRecalled, not just its score"
);
assert_eq!(
held_back["run_id"],
Value::Null,
"run_id must gracefully default to null (never panic) when the \
daemon response carries no such field"
);
}