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//! (#4638) That auto-create is gated on [`PalaceCreation`], decided from the
29//! session's project root by `SessionRegistry::memory_sink_for`. The palace id
30//! is DERIVED from that root, so an ephemeral root (a `tempfile::TempDir`)
31//! yields a per-run-unique id and the ensure minted one permanent, unreadable
32//! palace per run — 5,667 `t-tmp<random>` orphans in three weeks, 97.8% of
33//! every palace on the machine, which made trusty-memory's O(n) full-registry
34//! handlers (#4637) unusable. A palace is an expensive object (usearch index,
35//! KG redb, drawer table, recall log), not a per-session scratch container:
36//! the intended shape is ONE durable palace per PROJECT with each session
37//! distinguished INSIDE it by `chat_turn_append`'s `session_id` and
38//! `memory_remember`'s `session:<id>` tag, and that shape is what
39//! [`PalaceCreation::Forbidden`] restores by making `palace_create`
40//! unreachable from an ephemeral root.
41//! (#2363) `memory_remember`'s dedup gate (jaro_winkler >0.92,
42//! 5-min same-palace window) is documented as hostile to sequential
43//! conversational turns, so every turn-recorder write passes `force: true`
44//! to bypass it outright, along with the other content-QUALITY gates
45//! (blocklist, short-content, noise pattern). Issue #2520 (two-tier
46//! `force`): `force: true` no longer bypasses secret/credential detection —
47//! this sink deliberately does NOT set the separate `allow_secret_like`
48//! opt-in, so a turn whose raw LLM/tool-use content looks secret-shaped is
49//! correctly REJECTED rather than persisted; this is a behavior change from
50//! when `force` was a blanket bypass and is the intended safe default for an
51//! automated writer. A `"status":"skipped"` response is still checked and
52//! warned on as a belt-and-braces guard in case a gate skips the write.
53//! [`TurnMemorySink::socket`]/[`TurnMemorySink::palace`] expose
54//! this sink's already-resolved binding so #2348's `recall_session` tool can
55//! target the SAME daemon/palace the turn recorder writes into, without a
56//! second, independent resolution.
57//! [`derive_palace_id_for_project`] mirrors
58//! `trusty_common::catchup`'s (private) palace-derivation convention so a
59//! session's turns land in the same palace its PM catch-up digest reads
60//! from.
61//! Test: `memory_sink::tests::*`.
62
63use std::path::Path;
64use std::sync::Arc;
65use std::sync::atomic::{AtomicU64, Ordering};
66
67use chrono::{DateTime, Utc};
68use serde::{Deserialize, Serialize};
69use serde_json::json;
70use tokio::sync::mpsc;
71use tracing::{debug, info, warn};
72
73use crate::memory_envelope::call_tool_wrapped;
74
75/// Bounded mpsc queue capacity (#2345 scope: "~50").
76///
77/// Why: bounds memory use when trusty-memory is slow or unreachable for a
78/// long stretch; a session realistically produces at most one turn per LLM
79/// round trip, so 50 in-flight turns is generous slack before the overflow
80/// policy below kicks in.
81/// Test: `memory_sink::tests::enqueue_drops_newest_when_queue_full`.
82pub const QUEUE_CAPACITY: usize = 50;
83
84/// Which half of the dual-write degraded, as the retained per-session status
85/// reports it (#2425).
86///
87/// Why: "the durable history is thinning" is not actionable on its own — an
88/// operator needs to know whether the daemon is unreachable, the palace is
89/// missing, a content gate rejected the write, or the local queue overflowed,
90/// because those have different remedies. This is a CLOSED vocabulary rather
91/// than the underlying error string precisely so it can be retained and
92/// reported without carrying daemon-controlled text into the operator surface.
93/// What: one variant per failure site in [`drain`]/[`write_turn`]/
94/// [`TurnMemorySink::enqueue`]. Serialises `snake_case`.
95/// Test: `memory_sink::tests::queue_full_and_closed_drain_are_immediate_failures`,
96/// `registry_tests::memory_degradation_event_is_redacted`.
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
98#[serde(rename_all = "snake_case")]
99pub enum MemoryFailureCategory {
100 /// The target palace could not be probed or created (#2424).
101 PalaceEnsure,
102 /// `chat_turn_append` returned an RPC error.
103 ChatTurnAppend,
104 /// `memory_remember` returned an RPC error.
105 MemoryRemember,
106 /// `memory_remember` returned `status=skipped` despite `force: true` (#2363).
107 MemoryRememberSkipped,
108 /// The bounded queue was full, so the newest turn was dropped.
109 QueueFull,
110 /// The drain task was gone, so the turn was dropped.
111 DrainClosed,
112}
113
114/// The durability verdict for exactly one queued turn (#2425).
115///
116/// Why: durability is defined over QUEUED-TURN order, but outcomes do not
117/// arrive in that order — a queue-full failure is reported synchronously by
118/// [`TurnMemorySink::enqueue`] while accepted turns finish later in the
119/// detached drain. `sequence` is what lets the consumer put them back in
120/// logical order (see `memory_outcome_reconciler`).
121/// What: `sequence` is assigned by `enqueue` from a monotonic per-sink
122/// counter, so it is dense and gap-free across both reporting paths.
123/// Test: `memory_sink::tests::queue_full_and_closed_drain_are_immediate_failures`.
124#[derive(Debug, Clone, PartialEq, Eq)]
125pub(crate) enum MemoryTurnOutcome {
126 Durable {
127 sequence: u64,
128 },
129 Degraded {
130 sequence: u64,
131 category: MemoryFailureCategory,
132 at: DateTime<Utc>,
133 },
134}
135
136/// Sink-side hook that reports each turn's durability verdict (#2425).
137///
138/// Why: the sink must stay a leaf — it knows nothing about sessions or the
139/// registry — but the retained status has to live on the session. An observer
140/// inverts that dependency so `registry_memory_sink` installs the coupling and
141/// the sink keeps its existing shape.
142/// What: called once per queued turn, on whichever thread produced the verdict
143/// (the caller's for a synchronous `enqueue` failure, the drain task's
144/// otherwise). Implementations MUST NOT block or panic — see
145/// `RegistryMemoryDurabilityObserver` for the fail-open contract.
146/// Test: `memory_sink::tests::queue_full_and_closed_drain_are_immediate_failures`,
147/// `memory_sink::tests::dropping_sink_releases_detached_drain_observer`.
148pub(crate) trait MemoryDurabilityObserver: Send + Sync {
149 fn observe(&self, outcome: MemoryTurnOutcome);
150}
151
152/// The observer a sink built without one gets — the pre-#2425 behaviour.
153struct NoopMemoryDurabilityObserver;
154
155impl MemoryDurabilityObserver for NoopMemoryDurabilityObserver {
156 fn observe(&self, _outcome: MemoryTurnOutcome) {}
157}
158
159/// Whether a sink is entitled to bring its target palace into EXISTENCE
160/// (#4638).
161///
162/// Why: the recorder's palace id is derived from the session's project root,
163/// so an EPHEMERAL root yields an id that is unique per run — and `drain`'s
164/// [`ensure_palace`] step then auto-created one permanent, unreadable palace
165/// for every such run. That is how 5,667 `t-tmp<random>` orphans accumulated
166/// in three weeks (97.8% of every palace on the machine), which in turn made
167/// trusty-memory's O(n) full-registry handlers (#4637) unusable. A palace is
168/// an expensive object (usearch vector index, KG redb, drawer table, recall
169/// log), not a cheap per-session namespace, so the entitlement to mint one is
170/// modelled explicitly rather than left implicit in "whoever writes first
171/// wins". Making it a two-variant enum rather than a `bool` parameter means no
172/// call site can pass the dangerous value by accident.
173/// What: [`Self::Allowed`] reproduces the pre-#4638 behavior exactly (probe,
174/// then `palace_create` on a miss — #2424); [`Self::Forbidden`] probes and
175/// writes into a palace that already exists but never creates one, so a sink
176/// carrying it can never increase the palace count.
177/// Test: `memory_sink::tests::forbidden_creation_never_creates_a_palace`,
178/// `memory_sink::tests::ensure_palace_creates_missing_palace_once`.
179#[derive(Debug, Clone, Copy, PartialEq, Eq)]
180pub enum PalaceCreation {
181 /// The project root is durable — auto-create the palace if missing (#2424).
182 Allowed,
183 /// The project root is ephemeral — never auto-create (#4638).
184 Forbidden,
185}
186
187/// One user-prompt/assistant-response turn queued for durable dual-write.
188#[derive(Debug, Clone)]
189struct QueuedTurn {
190 /// (#2425) Dense, monotonic position in this sink's queued-turn order.
191 sequence: u64,
192 session_id: String,
193 prompt: String,
194 response: String,
195}
196
197/// Async, fire-and-forget durable-write sink for one session's turns (#2345).
198///
199/// Why: see module docs.
200/// What: `enqueue` never blocks the calling turn and never fails visibly —
201/// see its docs for the overflow policy. The background drain task owns the
202/// only receiver, so it keeps running for exactly as long as this sink (and
203/// therefore the channel's sender half) stays alive — the session's
204/// `SessionEntry` holds the constructed `Arc<TurnMemorySink>` for the
205/// session's lifetime (built once, lazily, on the session's first
206/// `task.run` — see `SessionRegistry::memory_sink_for`), so the drain task
207/// naturally survives across every run on that session, not just one.
208pub struct TurnMemorySink {
209 tx: mpsc::Sender<QueuedTurn>,
210 /// This sink's already-resolved trusty-memory base URL (#2348 reuse).
211 socket: std::path::PathBuf,
212 /// This sink's already-resolved palace id (#2348 reuse).
213 palace: String,
214 /// Whether this sink may bring `palace` into existence (#4638).
215 creation: PalaceCreation,
216 /// (#2425) Where each turn's durability verdict is reported.
217 observer: Arc<dyn MemoryDurabilityObserver>,
218 /// (#2425) Assigns each enqueued turn its `QueuedTurn::sequence`.
219 next_sequence: AtomicU64,
220}
221
222impl TurnMemorySink {
223 /// Construct a sink writing to `palace` at the given (already-resolved)
224 /// `socket`, and spawn its background drain task with the default
225 /// [`QUEUE_CAPACITY`].
226 /// Test: `memory_sink::tests::enqueue_drain_happy_path`.
227 pub fn new(socket: std::path::PathBuf, palace: String, creation: PalaceCreation) -> Self {
228 Self::with_capacity(socket, palace, QUEUE_CAPACITY, creation)
229 }
230
231 /// Same as [`Self::new`], reporting each turn's durability verdict to
232 /// `observer` (#2425).
233 /// Test: `registry_tests::memory_durability_retains_counts_resets_streak_and_warns_at_one_and_three`.
234 pub(crate) fn new_observed(
235 socket: std::path::PathBuf,
236 palace: String,
237 creation: PalaceCreation,
238 observer: Arc<dyn MemoryDurabilityObserver>,
239 ) -> Self {
240 Self::with_capacity_observed(socket, palace, QUEUE_CAPACITY, creation, observer)
241 }
242
243 /// Same as [`Self::new`] with an explicit queue capacity — tests use a
244 /// tiny capacity to exercise the overflow policy cheaply.
245 ///
246 /// Why: `socket` is resolved ONCE by the caller (mirroring
247 /// `catchup::pm_catchup_context`'s own
248 /// `resolve_memory_socket_or_unreachable()` call) rather than
249 /// re-resolved on every enqueued turn — the daemon's bound address does
250 /// not change mid-session, and re-resolving on every turn would add
251 /// discovery-file I/O to the hot drain path for no benefit. Tests inject
252 /// a mock server's URL directly here instead of mutating the
253 /// process-global `TRUSTY_MEMORY_SOCKET` env var (unsafe across parallel
254 /// tests).
255 /// What: spawns [`drain`] as a detached `tokio::spawn`ed task owning the
256 /// receiver half of a `capacity`-bounded channel; returns the sink
257 /// holding only the sender half.
258 /// Test: `memory_sink::tests::enqueue_drops_newest_when_queue_full`.
259 pub fn with_capacity(
260 socket: std::path::PathBuf,
261 palace: String,
262 capacity: usize,
263 creation: PalaceCreation,
264 ) -> Self {
265 Self::with_capacity_observed(
266 socket,
267 palace,
268 capacity,
269 creation,
270 Arc::new(NoopMemoryDurabilityObserver),
271 )
272 }
273
274 /// Same as [`Self::with_capacity`], reporting each turn's durability
275 /// verdict to `observer` (#2425).
276 ///
277 /// Why: the drain task needs its own handle on the observer because it
278 /// outlives no-one but the sink — the sink holds the sender half, so the
279 /// task ends (and releases its `Arc`) when the sink drops.
280 /// What: clones the `Arc` into the spawned [`drain`] and keeps one on the
281 /// sink for [`Self::enqueue`]'s synchronous failure paths.
282 /// Test: `memory_sink::tests::dropping_sink_releases_detached_drain_observer`.
283 pub(crate) fn with_capacity_observed(
284 socket: std::path::PathBuf,
285 palace: String,
286 capacity: usize,
287 creation: PalaceCreation,
288 observer: Arc<dyn MemoryDurabilityObserver>,
289 ) -> Self {
290 let (tx, rx) = mpsc::channel(capacity);
291 tokio::spawn(drain(
292 socket.clone(),
293 palace.clone(),
294 creation,
295 rx,
296 Arc::clone(&observer),
297 ));
298 Self {
299 tx,
300 socket,
301 palace,
302 creation,
303 observer,
304 next_sequence: AtomicU64::new(1),
305 }
306 }
307
308 /// Whether this sink may bring its palace into existence (#4638).
309 ///
310 /// Why: the #4638 bound is a property of the sink, so it must be
311 /// observable to assert on directly rather than inferred from RPC traffic.
312 /// What: returns the [`PalaceCreation`] fixed at construction.
313 /// Test: `registry_tests::memory_sink_for_many_sessions_mint_at_most_one_palace`.
314 pub fn palace_creation(&self) -> PalaceCreation {
315 self.creation
316 }
317
318 /// This sink's already-resolved trusty-memory base URL.
319 ///
320 /// Why: #2348's `recall_session` tool must read from the SAME daemon the
321 /// turn recorder writes into; re-deriving it independently would risk the
322 /// two disagreeing (e.g. after a discovery-file update mid-session) and
323 /// adds a redundant resolution for no benefit.
324 /// What: Returns the URL passed to (or resolved by) [`Self::new`]/
325 /// [`Self::with_capacity`] at construction — fixed for the sink's
326 /// lifetime, mirroring `write_turn`'s own binding.
327 /// Test: `memory_sink::tests::socket_and_palace_expose_construction_args`.
328 pub fn socket(&self) -> &std::path::Path {
329 &self.socket
330 }
331
332 /// This sink's already-resolved palace id.
333 ///
334 /// Why: see [`Self::socket`] — the same reuse rationale applies to the
335 /// palace binding.
336 /// What: Returns the palace passed to [`Self::new`]/[`Self::with_capacity`]
337 /// at construction.
338 /// Test: `memory_sink::tests::socket_and_palace_expose_construction_args`.
339 pub fn palace(&self) -> &str {
340 &self.palace
341 }
342
343 /// Enqueue one turn for durable dual-write, never blocking the caller.
344 ///
345 /// Why: turn recording must NEVER stall or fail a running turn (#2345
346 /// acceptance criteria) — a slow or wedged drain task must not back up
347 /// into the agent loop.
348 /// What: `try_send`s onto the bounded channel. Overflow policy: DROP THE
349 /// NEWEST turn (this call's turn) rather than evicting an
350 /// already-queued older one — the simplest policy `mpsc::Sender::
351 /// try_send` supports directly (no peek/pop-front on the sender side
352 /// without a different channel type), logged via `tracing::warn!` so an
353 /// operator can see it happened. A closed receiver (the drain task
354 /// panicked or was dropped) degrades the same way: logged, dropped, no
355 /// error surfaced to the caller.
356 /// Test: `memory_sink::tests::enqueue_drops_newest_when_queue_full`.
357 pub fn enqueue(
358 &self,
359 session_id: impl Into<String>,
360 prompt: impl Into<String>,
361 response: impl Into<String>,
362 ) {
363 // #2425: the sequence is assigned here, on the ONE path every turn
364 // takes, so the two reporting paths below share one dense ordering.
365 let sequence = self.next_sequence.fetch_add(1, Ordering::Relaxed);
366 let turn = QueuedTurn {
367 sequence,
368 session_id: session_id.into(),
369 prompt: prompt.into(),
370 response: response.into(),
371 };
372 match self.tx.try_send(turn) {
373 Ok(()) => {}
374 Err(mpsc::error::TrySendError::Full(_)) => {
375 warn!(
376 failure_category = "queue_full",
377 tool = "turn_recorder",
378 status = "dropped",
379 "turn_recorder: queue full (capacity reached) — dropping newest turn"
380 );
381 self.observer.observe(MemoryTurnOutcome::Degraded {
382 sequence,
383 category: MemoryFailureCategory::QueueFull,
384 at: Utc::now(),
385 });
386 }
387 Err(mpsc::error::TrySendError::Closed(_)) => {
388 warn!(
389 failure_category = "drain_closed",
390 tool = "turn_recorder",
391 status = "dropped",
392 "turn_recorder: drain task gone — dropping turn"
393 );
394 self.observer.observe(MemoryTurnOutcome::Degraded {
395 sequence,
396 category: MemoryFailureCategory::DrainClosed,
397 at: Utc::now(),
398 });
399 }
400 }
401 }
402}
403
404/// Background drain loop: pop turns off the channel and dual-write each one,
405/// fail-open (see [`write_turn`]), ensuring the target palace exists before
406/// the first write (#2424).
407///
408/// Why: the ensure lives HERE (drain-task-local state) rather than on the
409/// sink struct so it needs no locking — the drain task is the only writer —
410/// and so a failed ensure is naturally retried on the next turn (the flag is
411/// only set on success), covering a daemon that comes up mid-session.
412/// What: on success `palace_ensured` latches true and steady state adds
413/// zero extra RPCs per turn; on failure under [`PalaceCreation::Allowed`] the
414/// turn's writes are still attempted (fail-open — they carry their own
415/// warnings).
416///
417/// (#4638) Under [`PalaceCreation::Forbidden`] a failed ensure means "this
418/// palace does not exist and I am not entitled to create it", so the turn is
419/// DROPPED instead of written: the two writes could not have landed anyway
420/// (`memory_remember` fails `-32603 "palace metadata missing"` against an
421/// absent palace), and skipping them keeps a temp-rooted session down to one
422/// probe RPC per turn instead of three. The ensure is deliberately re-probed
423/// rather than latched-off, so a Forbidden sink whose palace is created
424/// out-of-band mid-session (or whose daemon was merely down for the first
425/// probe) starts recording normally — "the daemon is unreachable" and "the
426/// palace is absent" are not distinguishable from one failed probe, and only
427/// the latter is permanent.
428/// Test: `memory_sink::tests::ensure_palace_creates_missing_palace_once`,
429/// `memory_sink::tests::ensure_palace_skips_create_when_palace_exists`,
430/// `memory_sink::tests::forbidden_creation_never_creates_a_palace`,
431/// `memory_sink::tests::forbidden_creation_still_writes_to_an_existing_palace`.
432async fn drain(
433 socket: std::path::PathBuf,
434 palace: String,
435 creation: PalaceCreation,
436 mut rx: mpsc::Receiver<QueuedTurn>,
437 observer: Arc<dyn MemoryDurabilityObserver>,
438) {
439 let mut palace_ensured = false;
440 while let Some(turn) = rx.recv().await {
441 if !palace_ensured {
442 palace_ensured = ensure_palace(&socket, &palace, creation).await;
443 }
444 // #4638: no palace and no entitlement to make one — the writes below
445 // are guaranteed to fail, so don't issue them.
446 if !palace_ensured && creation == PalaceCreation::Forbidden {
447 debug!(
448 palace = %palace,
449 session_id = %turn.session_id,
450 "turn_recorder: dropping turn — palace absent and auto-create \
451 withheld for an ephemeral project root (#4638)"
452 );
453 observer.observe(MemoryTurnOutcome::Degraded {
454 sequence: turn.sequence,
455 category: MemoryFailureCategory::PalaceEnsure,
456 at: Utc::now(),
457 });
458 continue;
459 }
460 observer.observe(write_turn(&socket, &palace, &turn).await);
461 }
462}
463
464/// Ensure `palace` exists on the target daemon, creating it if missing
465/// (#2424). Returns `true` when the palace is known to exist afterwards.
466///
467/// Why: `memory_remember` does NOT auto-create its palace — against a
468/// missing one it fails `-32603 "palace metadata missing"`, which silently
469/// killed the semantic half of every soak write. Probe-then-create (rather
470/// than unconditional `palace_create`) because trusty-memory's
471/// `handle_palace_create` OVERWRITES `palace.json` for an existing palace
472/// (resetting `created_at`/`description`) — an existing project palace
473/// shared with the PM catch-up digest must not have its metadata clobbered
474/// on every session start.
475/// What: `palace_info` via `tools/call`; on error (the daemon's signal for
476/// "metadata missing" — or any other failure, in which case the create
477/// simply fails too and we stay fail-open), `palace_create` with
478/// `force: true` (the spec-001 documented bypass for app-managed palaces
479/// whose slug does not match the DAEMON's cwd-derived project slug; a no-op
480/// authz gate in default single-tenant mode) via `tools/call`. Never
481/// propagates an error — failure is logged and reported as `false` so the
482/// caller retries on the next turn.
483///
484/// (#4638) `creation` gates the CREATE half only — the probe always runs, so a
485/// [`PalaceCreation::Forbidden`] sink still discovers and uses a palace that
486/// already exists. Returning `false` without attempting a create is what makes
487/// the bound structural: `palace_create` is unreachable from an ephemeral
488/// project root, not merely unlikely.
489/// Test: `memory_sink::tests::ensure_palace_creates_missing_palace_once`,
490/// `memory_sink::tests::ensure_palace_skips_create_when_palace_exists`,
491/// `memory_sink::tests::forbidden_creation_never_creates_a_palace`.
492async fn ensure_palace(socket: &std::path::Path, palace: &str, creation: PalaceCreation) -> bool {
493 if call_tool_wrapped(socket, "palace_info", json!({"palace": palace}))
494 .await
495 .is_ok()
496 {
497 return true;
498 }
499 if creation == PalaceCreation::Forbidden {
500 return false;
501 }
502 let create_params = json!({
503 "name": palace,
504 "force": true,
505 "description": "trusty-code session turn history (auto-created by the turn recorder)",
506 });
507 match call_tool_wrapped(socket, "palace_create", create_params).await {
508 Ok(_) => {
509 info!(palace = %palace, "turn_recorder: created missing palace (#2424)");
510 true
511 }
512 // #2425: the daemon's error text is server-controlled and can be
513 // arbitrarily long or carry a credential-shaped preview of the
514 // rejected content, so the default warning names the failure
515 // CATEGORY instead. See `write_turn` for the same treatment.
516 Err(_error) => {
517 warn!(
518 failure_category = "palace_ensure",
519 tool = "palace_create",
520 status = "rpc_error",
521 "turn_recorder: palace ensure failed (fail-open, will retry next turn)"
522 );
523 false
524 }
525 }
526}
527
528/// Dual-write one turn: `chat_turn_append` (the exact chronological record)
529/// THEN `memory_remember` (the semantic recall surface, #2348).
530///
531/// Why: the exact and semantic representations are independent trusty-memory
532/// endpoints; a mid-outage failure of one must not block the other, so each
533/// call's error is handled separately rather than short-circuiting on the
534/// first failure. (#2424) BOTH calls go through the MCP `tools/call`
535/// envelope (`call_tool_wrapped`) — trusty-memory's direct-dispatch
536/// allowlist (`TOOL_METHODS`) has no `chat_*` entries, so the previous
537/// direct-method dispatch of `chat_turn_append` failed `-32601 Method not
538/// found` on 100% of writes; `memory_remember` IS direct-dispatchable but
539/// uses the same envelope anyway so both halves share one verified shape.
540/// (#2363) `memory_remember` passes `force: true` because
541/// its dedup gate (jaro_winkler >0.92, same-palace, 5-min window) is
542/// documented as hostile to sequential conversational turns — near-duplicate
543/// consecutive turns are the NORMAL case here, not noise; `force: true` also
544/// bypasses the other content-QUALITY gates (blocklist, short-content, noise
545/// pattern). Issue #2520: `force` does NOT bypass secret/credential
546/// detection — a turn whose content looks secret-shaped comes back as an
547/// `Err` from `call_tool_wrapped` (not a `"skipped"` status) and is logged
548/// via the fail-open `Err(e)` arm below, same as any other RPC failure. A
549/// `"status": "skipped"` response (from a gate `force` does NOT bypass, e.g.
550/// a quality/blocklist gate that some OTHER path still applies) is still
551/// checked and warned on so a silently thinned recall surface is at least
552/// observable in logs — (#2424) `call_tool_wrapped` returns the PARSED inner
553/// tool result, so the skipped detection sees the same shape it did under
554/// direct dispatch.
555/// What: never propagates an error — every failure is logged via
556/// `tracing::warn!` and swallowed, matching
557/// `resolve_memory_socket_or_unreachable`'s fail-open contract (mirrored
558/// here, not reused directly, since `socket` is already resolved by the
559/// caller of [`TurnMemorySink::new`]). (#2425) It RETURNS the turn's verdict
560/// rather than propagating anything: `Degraded` with the first failed half's
561/// category if either call failed, `Durable` otherwise. The default warnings
562/// name that category and DELIBERATELY omit the daemon's own error text and
563/// `reason` string, both of which are server-controlled and can quote rejected
564/// content back — including the credential preview #2520's secret gate refused
565/// to store. The daemon's own logs keep that text; this warning does not.
566/// Test: `memory_sink::tests::enqueue_drain_happy_path`,
567/// `memory_sink::tests::write_turn_is_fail_open_on_unreachable_daemon`,
568/// `memory_sink::tests::write_turn_warns_on_skipped_status`,
569/// `memory_sink::tests::partial_dual_write_counts_once_as_failed_turn`,
570/// `memory_sink::tests::default_memory_warnings_redact_server_payloads_in_subprocess`.
571async fn write_turn(
572 socket: &std::path::Path,
573 palace: &str,
574 turn: &QueuedTurn,
575) -> MemoryTurnOutcome {
576 // #2425: the FIRST failure wins the reported category — a turn that lost
577 // both halves is still exactly one degraded turn, not two.
578 let mut failure = None;
579 let append_params = json!({
580 "palace": palace,
581 "session_id": turn.session_id,
582 "prompt": turn.prompt,
583 "response": turn.response,
584 });
585 if let Err(_error) = call_tool_wrapped(socket, "chat_turn_append", append_params).await {
586 failure = Some(MemoryFailureCategory::ChatTurnAppend);
587 warn!(
588 failure_category = "chat_turn_append",
589 tool = "chat_turn_append",
590 status = "rpc_error",
591 "turn_recorder: chat_turn_append failed (fail-open)"
592 );
593 }
594
595 let remember_params = json!({
596 "palace": palace,
597 "text": format!("User: {}\n\nAssistant: {}", turn.prompt, turn.response),
598 "tags": [format!("session:{}", turn.session_id), "turn"],
599 "force": true,
600 });
601 match call_tool_wrapped(socket, "memory_remember", remember_params).await {
602 Ok(result) => {
603 if result.get("status").and_then(|v| v.as_str()) == Some("skipped") {
604 // #2425: `reason` is server-controlled and quotes the rejected
605 // content back — for the secret-detection gate (#2520) that is
606 // a preview of the very credential the gate refused to store.
607 failure.get_or_insert(MemoryFailureCategory::MemoryRememberSkipped);
608 warn!(
609 failure_category = "memory_remember_skipped",
610 tool = "memory_remember",
611 status = "skipped",
612 "turn_recorder: memory_remember returned status=skipped despite force=true \
613 (#2363) — session recall surface may be thinning"
614 );
615 }
616 }
617 Err(_error) => {
618 failure.get_or_insert(MemoryFailureCategory::MemoryRemember);
619 warn!(
620 failure_category = "memory_remember",
621 tool = "memory_remember",
622 status = "rpc_error",
623 "turn_recorder: memory_remember failed (fail-open)"
624 );
625 }
626 }
627
628 match failure {
629 Some(category) => MemoryTurnOutcome::Degraded {
630 sequence: turn.sequence,
631 category,
632 at: Utc::now(),
633 },
634 None => MemoryTurnOutcome::Durable {
635 sequence: turn.sequence,
636 },
637 }
638}
639
640/// Resolve the palace id for a project directory (#2345).
641///
642/// Why: mirrors `trusty_common::catchup`'s own `derive_palace_id_for`
643/// convention exactly, so a session's turns land in the SAME palace
644/// `catchup::pm_catchup_context` reads its digest from — the PM's own catch-up
645/// section and the turn recorder's writes must agree on "which palace is this
646/// project."
647///
648/// This used to answer `"unknown-project"` on any failure. That literal is
649/// SHARED: two projects that both fail resolution get the same id, and
650/// `SessionRegistry::memory_sink_for` grants a durable project root
651/// [`PalaceCreation::Allowed`], so the recorder auto-created one palace under
652/// the placeholder and posted both projects' real prompts and responses into it
653/// (#5811). While the only failure was "no identity at all" that was rare;
654/// routing through `palace_resolve` added three pin-trust failures to the same
655/// branch, so a typo in one committed pin was enough to reach it. The error is
656/// returned instead, and the caller declines to record.
657/// What: delegates to `trusty_common::palace_resolve::resolve_palace` — env
658/// override, then the committed pin, then the git `owner/repo` slug, then the
659/// `parent/dir` slug of the main worktree root.
660/// Test: `memory_sink::tests::derive_palace_id_for_project_falls_back_to_dirname`,
661/// `memory_sink::tests::malformed_pin_is_an_error_not_the_shared_placeholder`.
662pub fn derive_palace_id_for_project(
663 project_dir: &Path,
664) -> Result<String, trusty_common::palace_resolve::PalaceResolveError> {
665 // #5811: this probed the remote itself and called the PURE three-level
666 // core, so a tcode session's turns landed in the derived palace even when
667 // the project committed a pin naming a different one.
668 trusty_common::palace_resolve::resolve_palace(project_dir).map(|resolution| resolution.id)
669}
670
671/// A socket path nothing serves: a dial is refused by the kernel at once.
672const UNREACHABLE_MEMORY_SOCKET: &str = "/nonexistent/trusty-memory/trusty-memory.sock";
673
674/// Resolve the trusty-memory socket the turn recorder and the PM catch-up read
675/// may dial — never the operator's live daemon from a test process (#9139).
676///
677/// Why: a test process inherited the operator's environment, so the recorder
678/// resolved the LIVE daemon's socket and a managed shell's
679/// `TRUSTY_MEMORY_PALACE` named the live palace. The #4638 create bound did not
680/// stop it, because that palace already exists: 2,308 fixture `turn` drawers
681/// landed in it. Test isolation that depends on every caller's environment
682/// fails the first time one caller forgets.
683/// What: outside a test process this is
684/// `trusty_common::memory_rpc::resolve_memory_socket_or_unreachable`. Under
685/// the harness (`trusty_common::test_harness::running_under_test_harness`) it
686/// is `harness_memory_socket` over `TRUSTY_MEMORY_SOCKET`; the data-dir
687/// derivation is never consulted, so the default socket is unreachable.
688/// Test: `memory_sink::tests::harness_admits_only_an_explicit_temp_socket`,
689/// `memory_sink::tests::memory_sink_for_under_the_harness_never_binds_a_live_socket`.
690pub(crate) fn resolve_recorder_socket() -> std::path::PathBuf {
691 static HARNESS_WARNED: std::sync::Once = std::sync::Once::new();
692 if !trusty_common::test_harness::running_under_test_harness() {
693 return trusty_common::memory_rpc::resolve_memory_socket_or_unreachable();
694 }
695 // #9139: a misdetected production run must say why recording stopped.
696 HARNESS_WARNED.call_once(|| {
697 warn!(
698 "turn_recorder: TRUSTY_TEST_HARNESS is set — resolving the memory socket \
699 in test-isolation mode; the live daemon is not dialled (#9139)"
700 );
701 });
702 harness_memory_socket(
703 std::env::var(trusty_common::memory_rpc::TRUSTY_MEMORY_SOCKET_ENV)
704 .ok()
705 .as_deref(),
706 )
707}
708
709/// The socket a test process may dial, given its `TRUSTY_MEMORY_SOCKET` (#9139).
710///
711/// Why: a test's mock daemon binds under a `TempDir`; a live daemon binds in
712/// the operator's data directory, never under a system temp root.
713/// What: an explicit, non-blank path with no `..` component whose parent
714/// directory, once canonicalized (symlinks resolved), is still under a system
715/// temp root is returned unchanged. Anything else — unset, blank, a non-temp
716/// path, a `..` escape, a symlink out of temp, or a parent that cannot be
717/// canonicalized — yields [`UNREACHABLE_MEMORY_SOCKET`], so a failed isolation
718/// fails closed.
719/// Test: `memory_sink::tests::harness_admits_only_an_explicit_temp_socket`.
720pub(crate) fn harness_memory_socket(explicit: Option<&str>) -> std::path::PathBuf {
721 let explicit = explicit
722 .map(str::trim)
723 .filter(|raw| !raw.is_empty())
724 .map(std::path::PathBuf::from);
725 match explicit {
726 Some(socket) if socket_resolves_under_system_temp(&socket) => socket,
727 Some(socket) => {
728 warn!(
729 socket = %socket.display(),
730 "turn_recorder: test process named a memory socket outside a temp \
731 root — refusing it (#9139)"
732 );
733 std::path::PathBuf::from(UNREACHABLE_MEMORY_SOCKET)
734 }
735 None => std::path::PathBuf::from(UNREACHABLE_MEMORY_SOCKET),
736 }
737}
738
739/// Whether `socket` still sits under a system temp root after `..` and
740/// symlinks are resolved (#9139).
741///
742/// Why: a lexical `starts_with` check admits `/tmp/../Users/x/live.sock` and a
743/// temp-dir symlink that points at the operator's data directory.
744/// What: false for any `..` component, or when the parent cannot be
745/// canonicalized; otherwise the canonical parent must pass
746/// `is_under_system_temp`.
747/// Test: `memory_sink::tests::harness_admits_only_an_explicit_temp_socket`.
748fn socket_resolves_under_system_temp(socket: &Path) -> bool {
749 if socket
750 .components()
751 .any(|part| matches!(part, std::path::Component::ParentDir))
752 {
753 return false;
754 }
755 let Some(parent) = socket.parent() else {
756 return false;
757 };
758 parent
759 .canonicalize()
760 .is_ok_and(|real| trusty_common::bin_resolve::is_under_system_temp(&real))
761}
762
763#[cfg(test)]
764#[path = "memory_sink_tests.rs"]
765mod tests;