Skip to main content

trusty_code/session/
memory_sink.rs

1//! Turn recorder (#2345): durable per-turn dual-write to trusty-memory.
2//!
3//! Why: epic #2343 (Infinite Sessions) requires every PM prompt/response
4//! turn to be durably recorded in trusty-memory, independent of the
5//! in-process `Transcript` (#2344), which only lives as long as the daemon
6//! process. Without this, a daemon restart or crash loses the entire
7//! conversation; #2348's `recall_session` tool also needs a semantic
8//! recall surface over session history that a bare `chat_turn_append` record
9//! alone would not give it (it stores the exact turn but is not
10//! embedded/indexed for recall the way `memory_remember` is).
11//! What: [`TurnMemorySink`] owns a bounded `tokio::sync::mpsc` queue and a
12//! background drain task. [`TurnMemorySink::enqueue`] is the non-blocking
13//! producer side, called from `task::executor::run_and_record` at each turn
14//! boundary. The drain task calls BOTH `chat_turn_append` (the exact
15//! chronological record) and `memory_remember` (tagged
16//! `["session:<id>", "turn"]`, `force: true` — the semantic recall surface
17//! for #2348) via the MCP `tools/call` envelope
18//! (`crate::memory_envelope::call_tool_wrapped`; #2424 — trusty-memory's
19//! direct-dispatch allowlist has no `chat_*` methods, so direct dispatch of
20//! `chat_turn_append` fails `-32601` on every write), against a base URL
21//! resolved ONCE at construction — never blocking or failing the calling
22//! turn: any RPC failure is logged via `tracing::warn!` and dropped.
23//! (#2424) Before the FIRST write, the drain task ensures the target palace
24//! exists ([`ensure_palace`]) — `memory_remember` does NOT auto-create a
25//! palace and fails `-32603 "palace metadata missing"` against a missing
26//! one, which is exactly how the #2343 soak lost all 50 turns. The ensure
27//! result is cached on success so steady state adds zero extra RPCs.
28//! (#2363) `memory_remember`'s dedup gate (jaro_winkler >0.92,
29//! 5-min same-palace window) is documented as hostile to sequential
30//! conversational turns, so every turn-recorder write passes `force: true`
31//! to bypass it outright, along with the other content-QUALITY gates
32//! (blocklist, short-content, noise pattern). Issue #2520 (two-tier
33//! `force`): `force: true` no longer bypasses secret/credential detection —
34//! this sink deliberately does NOT set the separate `allow_secret_like`
35//! opt-in, so a turn whose raw LLM/tool-use content looks secret-shaped is
36//! correctly REJECTED rather than persisted; this is a behavior change from
37//! when `force` was a blanket bypass and is the intended safe default for an
38//! automated writer. A `"status":"skipped"` response is still checked and
39//! warned on as a belt-and-braces guard in case a gate skips the write.
40//! [`TurnMemorySink::base_url`]/[`TurnMemorySink::palace`] expose
41//! this sink's already-resolved binding so #2348's `recall_session` tool can
42//! target the SAME daemon/palace the turn recorder writes into, without a
43//! second, independent resolution.
44//! [`derive_palace_id_for_project`] mirrors
45//! `trusty_common::catchup`'s (private) palace-derivation convention so a
46//! session's turns land in the same palace its PM catch-up digest reads
47//! from.
48//! Test: `memory_sink::tests::*`.
49
50use std::path::Path;
51
52use serde_json::json;
53use tokio::sync::mpsc;
54use tracing::{info, warn};
55
56use crate::memory_envelope::call_tool_wrapped;
57
58/// Bounded mpsc queue capacity (#2345 scope: "~50").
59///
60/// Why: bounds memory use when trusty-memory is slow or unreachable for a
61/// long stretch; a session realistically produces at most one turn per LLM
62/// round trip, so 50 in-flight turns is generous slack before the overflow
63/// policy below kicks in.
64/// Test: `memory_sink::tests::enqueue_drops_newest_when_queue_full`.
65pub const QUEUE_CAPACITY: usize = 50;
66
67/// One user-prompt/assistant-response turn queued for durable dual-write.
68#[derive(Debug, Clone)]
69struct QueuedTurn {
70    session_id: String,
71    prompt: String,
72    response: String,
73}
74
75/// Async, fire-and-forget durable-write sink for one session's turns (#2345).
76///
77/// Why: see module docs.
78/// What: `enqueue` never blocks the calling turn and never fails visibly —
79/// see its docs for the overflow policy. The background drain task owns the
80/// only receiver, so it keeps running for exactly as long as this sink (and
81/// therefore the channel's sender half) stays alive — the session's
82/// `SessionEntry` holds the constructed `Arc<TurnMemorySink>` for the
83/// session's lifetime (built once, lazily, on the session's first
84/// `task.run` — see `SessionRegistry::memory_sink_for`), so the drain task
85/// naturally survives across every run on that session, not just one.
86pub struct TurnMemorySink {
87    tx: mpsc::Sender<QueuedTurn>,
88    /// This sink's already-resolved trusty-memory base URL (#2348 reuse).
89    base_url: String,
90    /// This sink's already-resolved palace id (#2348 reuse).
91    palace: String,
92}
93
94impl TurnMemorySink {
95    /// Construct a sink writing to `palace` at the given (already-resolved)
96    /// `base_url`, and spawn its background drain task with the default
97    /// [`QUEUE_CAPACITY`].
98    /// Test: `memory_sink::tests::enqueue_drain_happy_path`.
99    pub fn new(base_url: String, palace: String) -> Self {
100        Self::with_capacity(base_url, palace, QUEUE_CAPACITY)
101    }
102
103    /// Same as [`Self::new`] with an explicit queue capacity — tests use a
104    /// tiny capacity to exercise the overflow policy cheaply.
105    ///
106    /// Why: `base_url` is resolved ONCE by the caller (mirroring
107    /// `catchup::pm_catchup_context`'s own
108    /// `resolve_memory_base_url_or_unreachable()` call) rather than
109    /// re-resolved on every enqueued turn — the daemon's bound address does
110    /// not change mid-session, and re-resolving on every turn would add
111    /// discovery-file I/O to the hot drain path for no benefit. Tests inject
112    /// a mock server's URL directly here instead of mutating the
113    /// process-global `TRUSTY_MEMORY_URL` env var (unsafe across parallel
114    /// tests).
115    /// What: spawns [`drain`] as a detached `tokio::spawn`ed task owning the
116    /// receiver half of a `capacity`-bounded channel; returns the sink
117    /// holding only the sender half.
118    /// Test: `memory_sink::tests::enqueue_drops_newest_when_queue_full`.
119    pub fn with_capacity(base_url: String, palace: String, capacity: usize) -> Self {
120        let (tx, rx) = mpsc::channel(capacity);
121        tokio::spawn(drain(base_url.clone(), palace.clone(), rx));
122        Self {
123            tx,
124            base_url,
125            palace,
126        }
127    }
128
129    /// This sink's already-resolved trusty-memory base URL.
130    ///
131    /// Why: #2348's `recall_session` tool must read from the SAME daemon the
132    /// turn recorder writes into; re-deriving it independently would risk the
133    /// two disagreeing (e.g. after a discovery-file update mid-session) and
134    /// adds a redundant resolution for no benefit.
135    /// What: Returns the URL passed to (or resolved by) [`Self::new`]/
136    /// [`Self::with_capacity`] at construction — fixed for the sink's
137    /// lifetime, mirroring `write_turn`'s own binding.
138    /// Test: `memory_sink::tests::base_url_and_palace_expose_construction_args`.
139    pub fn base_url(&self) -> &str {
140        &self.base_url
141    }
142
143    /// This sink's already-resolved palace id.
144    ///
145    /// Why: see [`Self::base_url`] — the same reuse rationale applies to the
146    /// palace binding.
147    /// What: Returns the palace passed to [`Self::new`]/[`Self::with_capacity`]
148    /// at construction.
149    /// Test: `memory_sink::tests::base_url_and_palace_expose_construction_args`.
150    pub fn palace(&self) -> &str {
151        &self.palace
152    }
153
154    /// Enqueue one turn for durable dual-write, never blocking the caller.
155    ///
156    /// Why: turn recording must NEVER stall or fail a running turn (#2345
157    /// acceptance criteria) — a slow or wedged drain task must not back up
158    /// into the agent loop.
159    /// What: `try_send`s onto the bounded channel. Overflow policy: DROP THE
160    /// NEWEST turn (this call's turn) rather than evicting an
161    /// already-queued older one — the simplest policy `mpsc::Sender::
162    /// try_send` supports directly (no peek/pop-front on the sender side
163    /// without a different channel type), logged via `tracing::warn!` so an
164    /// operator can see it happened. A closed receiver (the drain task
165    /// panicked or was dropped) degrades the same way: logged, dropped, no
166    /// error surfaced to the caller.
167    /// Test: `memory_sink::tests::enqueue_drops_newest_when_queue_full`.
168    pub fn enqueue(
169        &self,
170        session_id: impl Into<String>,
171        prompt: impl Into<String>,
172        response: impl Into<String>,
173    ) {
174        let turn = QueuedTurn {
175            session_id: session_id.into(),
176            prompt: prompt.into(),
177            response: response.into(),
178        };
179        match self.tx.try_send(turn) {
180            Ok(()) => {}
181            Err(mpsc::error::TrySendError::Full(_)) => {
182                warn!("turn_recorder: queue full (capacity reached) — dropping newest turn");
183            }
184            Err(mpsc::error::TrySendError::Closed(_)) => {
185                warn!("turn_recorder: drain task gone — dropping turn");
186            }
187        }
188    }
189}
190
191/// Background drain loop: pop turns off the channel and dual-write each one,
192/// fail-open (see [`write_turn`]), ensuring the target palace exists before
193/// the first write (#2424).
194///
195/// Why: the ensure lives HERE (drain-task-local state) rather than on the
196/// sink struct so it needs no locking — the drain task is the only writer —
197/// and so a failed ensure is naturally retried on the next turn (the flag is
198/// only set on success), covering a daemon that comes up mid-session.
199/// What: on success `palace_ensured` latches true and steady state adds
200/// zero extra RPCs per turn; on failure the turn's writes are still
201/// attempted (fail-open — they carry their own warnings).
202/// Test: `memory_sink::tests::ensure_palace_creates_missing_palace_once`,
203/// `memory_sink::tests::ensure_palace_skips_create_when_palace_exists`.
204async fn drain(base_url: String, palace: String, mut rx: mpsc::Receiver<QueuedTurn>) {
205    let mut palace_ensured = false;
206    while let Some(turn) = rx.recv().await {
207        if !palace_ensured {
208            palace_ensured = ensure_palace(&base_url, &palace).await;
209        }
210        write_turn(&base_url, &palace, &turn).await;
211    }
212}
213
214/// Ensure `palace` exists on the target daemon, creating it if missing
215/// (#2424). Returns `true` when the palace is known to exist afterwards.
216///
217/// Why: `memory_remember` does NOT auto-create its palace — against a
218/// missing one it fails `-32603 "palace metadata missing"`, which silently
219/// killed the semantic half of every soak write. Probe-then-create (rather
220/// than unconditional `palace_create`) because trusty-memory's
221/// `handle_palace_create` OVERWRITES `palace.json` for an existing palace
222/// (resetting `created_at`/`description`) — an existing project palace
223/// shared with the PM catch-up digest must not have its metadata clobbered
224/// on every session start.
225/// What: `palace_info` via `tools/call`; on error (the daemon's signal for
226/// "metadata missing" — or any other failure, in which case the create
227/// simply fails too and we stay fail-open), `palace_create` with
228/// `force: true` (the spec-001 documented bypass for app-managed palaces
229/// whose slug does not match the DAEMON's cwd-derived project slug; a no-op
230/// authz gate in default single-tenant mode) via `tools/call`. Never
231/// propagates an error — failure is logged and reported as `false` so the
232/// caller retries on the next turn.
233/// Test: `memory_sink::tests::ensure_palace_creates_missing_palace_once`,
234/// `memory_sink::tests::ensure_palace_skips_create_when_palace_exists`.
235async fn ensure_palace(base_url: &str, palace: &str) -> bool {
236    if call_tool_wrapped(base_url, "palace_info", json!({"palace": palace}))
237        .await
238        .is_ok()
239    {
240        return true;
241    }
242    let create_params = json!({
243        "name": palace,
244        "force": true,
245        "description": "trusty-code session turn history (auto-created by the turn recorder)",
246    });
247    match call_tool_wrapped(base_url, "palace_create", create_params).await {
248        Ok(_) => {
249            info!(palace = %palace, "turn_recorder: created missing palace (#2424)");
250            true
251        }
252        Err(e) => {
253            warn!(
254                palace = %palace,
255                error = %e,
256                "turn_recorder: palace ensure failed (fail-open, will retry next turn)"
257            );
258            false
259        }
260    }
261}
262
263/// Dual-write one turn: `chat_turn_append` (the exact chronological record)
264/// THEN `memory_remember` (the semantic recall surface, #2348).
265///
266/// Why: the exact and semantic representations are independent trusty-memory
267/// endpoints; a mid-outage failure of one must not block the other, so each
268/// call's error is handled separately rather than short-circuiting on the
269/// first failure. (#2424) BOTH calls go through the MCP `tools/call`
270/// envelope (`call_tool_wrapped`) — trusty-memory's direct-dispatch
271/// allowlist (`TOOL_METHODS`) has no `chat_*` entries, so the previous
272/// direct-method dispatch of `chat_turn_append` failed `-32601 Method not
273/// found` on 100% of writes; `memory_remember` IS direct-dispatchable but
274/// uses the same envelope anyway so both halves share one verified shape.
275/// (#2363) `memory_remember` passes `force: true` because
276/// its dedup gate (jaro_winkler >0.92, same-palace, 5-min window) is
277/// documented as hostile to sequential conversational turns — near-duplicate
278/// consecutive turns are the NORMAL case here, not noise; `force: true` also
279/// bypasses the other content-QUALITY gates (blocklist, short-content, noise
280/// pattern). Issue #2520: `force` does NOT bypass secret/credential
281/// detection — a turn whose content looks secret-shaped comes back as an
282/// `Err` from `call_tool_wrapped` (not a `"skipped"` status) and is logged
283/// via the fail-open `Err(e)` arm below, same as any other RPC failure. A
284/// `"status": "skipped"` response (from a gate `force` does NOT bypass, e.g.
285/// a quality/blocklist gate that some OTHER path still applies) is still
286/// checked and warned on so a silently thinned recall surface is at least
287/// observable in logs — (#2424) `call_tool_wrapped` returns the PARSED inner
288/// tool result, so the skipped detection sees the same shape it did under
289/// direct dispatch.
290/// What: never propagates an error — every failure is logged via
291/// `tracing::warn!` and swallowed, matching
292/// `resolve_memory_base_url_or_unreachable`'s fail-open contract (mirrored
293/// here, not reused directly, since `base_url` is already resolved by the
294/// caller of [`TurnMemorySink::new`]).
295/// Test: `memory_sink::tests::enqueue_drain_happy_path`,
296/// `memory_sink::tests::write_turn_is_fail_open_on_unreachable_daemon`,
297/// `memory_sink::tests::write_turn_warns_on_skipped_status`.
298async fn write_turn(base_url: &str, palace: &str, turn: &QueuedTurn) {
299    let append_params = json!({
300        "palace": palace,
301        "session_id": turn.session_id,
302        "prompt": turn.prompt,
303        "response": turn.response,
304    });
305    if let Err(e) = call_tool_wrapped(base_url, "chat_turn_append", append_params).await {
306        warn!(
307            session_id = %turn.session_id,
308            error = %e,
309            "turn_recorder: chat_turn_append failed (fail-open)"
310        );
311    }
312
313    let remember_params = json!({
314        "palace": palace,
315        "text": format!("User: {}\n\nAssistant: {}", turn.prompt, turn.response),
316        "tags": [format!("session:{}", turn.session_id), "turn"],
317        "force": true,
318    });
319    match call_tool_wrapped(base_url, "memory_remember", remember_params).await {
320        Ok(result) => {
321            if result.get("status").and_then(|v| v.as_str()) == Some("skipped") {
322                let reason = result
323                    .get("reason")
324                    .and_then(|v| v.as_str())
325                    .unwrap_or("unknown");
326                warn!(
327                    session_id = %turn.session_id,
328                    reason = %reason,
329                    "turn_recorder: memory_remember returned status=skipped despite force=true \
330                     (#2363) — session recall surface may be thinning"
331                );
332            }
333        }
334        Err(e) => {
335            warn!(
336                session_id = %turn.session_id,
337                error = %e,
338                "turn_recorder: memory_remember failed (fail-open)"
339            );
340        }
341    }
342}
343
344/// Derive the palace id for a project directory (#2345).
345///
346/// Why: mirrors `trusty_common::catchup`'s own (private-to-that-module)
347/// `derive_palace_id_for` convention exactly, so a session's turns land in
348/// the SAME palace `catchup::pm_catchup_context` reads its digest from — the
349/// PM's own catch-up section and the turn recorder's writes must agree on
350/// "which palace is this project."
351/// What: probes `git config --get remote.origin.url` from `project_dir`,
352/// then calls `trusty_common::derive_palace_id` (explicit override env ->
353/// git owner/repo slug -> parent/dir slug), falling back to the directory's
354/// basename (or `"unknown-project"`) when all three yield `None`.
355/// Test: `memory_sink::tests::derive_palace_id_for_project_falls_back_to_dirname`.
356pub fn derive_palace_id_for_project(project_dir: &Path) -> String {
357    let remote = std::process::Command::new("git")
358        .arg("-C")
359        .arg(project_dir)
360        .args(["config", "--get", "remote.origin.url"])
361        .output()
362        .ok()
363        .filter(|o| o.status.success())
364        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
365        .filter(|s| !s.is_empty());
366
367    let override_val = trusty_common::palace_override_from_env();
368    trusty_common::derive_palace_id(project_dir, remote.as_deref(), override_val.as_deref())
369        .unwrap_or_else(|| {
370            project_dir
371                .file_name()
372                .and_then(|n| n.to_str())
373                .unwrap_or("unknown-project")
374                .to_string()
375        })
376}
377
378#[cfg(test)]
379#[path = "memory_sink_tests.rs"]
380mod tests;