trusty_code/session/registry_events.rs
1//! `SessionRegistry`'s #2055 tool/log/progress/message event-recording
2//! plumbing. Split out of `registry.rs` (#2344) purely to keep that
3//! production file under the crate's 500-SLOC cap as the #2344
4//! persistent-transcript methods grew it past the limit — this is a child
5//! module of `registry` (declared via `#[path = ...] mod events;`), so it
6//! shares full access to `SessionRegistry`'s private `lock`/`record` helpers
7//! exactly as if these methods were still defined in that file.
8//!
9//! Why: gives the agent loop a stable, already-wired call for each #2055
10//! event kind without it needing to touch the ring buffer, sequencing, or
11//! bus directly.
12//! What: `record_tool_started`/`record_tool_finished`/`record_tool_error`/
13//! `record_log`/`record_progress`/`record_message`, plus the shared
14//! `ensure_exists` existence guard they all call before recording.
15//! Test: `registry_tests::record_tool_started_publishes_event`,
16//! `registry_tests::record_tool_finished_publishes_event`,
17//! `registry_tests::record_tool_error_publishes_event`,
18//! `registry_tests::record_log_publishes_event`,
19//! `registry_tests::record_progress_publishes_event`,
20//! `registry_tests::record_message_publishes_event`.
21
22use serde::Serialize;
23
24use super::*;
25use crate::tools::telemetry::{RecallTelemetry, SearchTelemetry};
26
27use crate::events::{ContextBudgetSnapshot, IndexReadinessSnapshot};
28
29/// `Event::IndexReadiness.state` when the semantic lane is queryable — an
30/// empty search result IS evidence of absence.
31const READINESS_STATE_READY: &str = "ready";
32/// `Event::IndexReadiness.state` while a lane is still building — an empty
33/// search result is NOT evidence of absence.
34const READINESS_STATE_WARMING: &str = "warming";
35/// `Event::IndexReadiness.state` when no index could be probed at all (no
36/// daemon / no derivable id) — likewise not evidence of absence.
37const READINESS_STATE_UNAVAILABLE: &str = "unavailable";
38
39/// `session.get_readiness`'s response payload (DOC-39 §5.6 Slice D).
40///
41/// Why: a session's readiness is a single cached value, not a collection —
42/// `session.get_goals`'s "empty array means nothing yet" convention doesn't
43/// fit here, and a bare `Option` serialising to `null` would be exactly the
44/// kind of untyped "nothing yet" signal the design explicitly rules out (a
45/// consumer can't tell "never probed" from "probed, and every field happens
46/// to be absent" without a discriminant). This is a thin, tagged wrapper
47/// around [`IndexReadinessSnapshot`] — the SAME struct
48/// `SessionRegistry::record_index_readiness` caches and `Event::IndexReadiness`
49/// derives from — so the query and event surfaces can never independently
50/// drift on field names.
51/// What: `#[serde(tag = "status")]` (internally tagged, matching `Event`'s own
52/// `tag = "type"` convention) so the wire shape is
53/// `{"status":"probed","state":...,"index_id":...,...}` for a session with a
54/// recorded snapshot, or `{"status":"never_probed"}` for one with none.
55/// Test: `registry_tests::record_index_readiness_caches_snapshot_for_late_query`,
56/// `protocol_readiness::tests::get_readiness_never_probed_session_returns_never_probed`.
57#[derive(Debug, Clone, Serialize)]
58#[serde(tag = "status", rename_all = "snake_case")]
59pub enum ReadinessQuery {
60 /// A probe has landed for this session; wraps the last-recorded snapshot.
61 Probed(IndexReadinessSnapshot),
62 /// No `record_index_readiness` call has ever landed for this session.
63 NeverProbed,
64}
65
66/// `session.get_context_budget`'s response payload (issue #3015).
67///
68/// Why: a session's working-context budget is a single cached value, not a
69/// collection — the same "typed nothing-yet, never a bare `null`" rationale
70/// as [`ReadinessQuery`] applies verbatim: a consumer must be able to tell
71/// "no turn has completed yet" from "a turn completed and every field
72/// happens to be zero" without a discriminant.
73/// What: `#[serde(tag = "status", rename_all = "snake_case")]` so the wire
74/// shape is `{"status":"recorded", ...snapshot fields}` for a session with a
75/// cached measurement, or `{"status":"never_recorded"}` for one with none.
76/// Test: `registry_tests::record_context_budget_caches_snapshot_for_late_query`,
77/// `protocol_budget::tests::get_context_budget_never_recorded_session_returns_never_recorded`.
78#[derive(Debug, Clone, Copy, Serialize)]
79#[serde(tag = "status", rename_all = "snake_case")]
80pub enum ContextBudgetQuery {
81 /// A turn has completed for this session; wraps the last-recorded
82 /// snapshot.
83 Recorded(ContextBudgetSnapshot),
84 /// No `record_context_budget` call has ever landed for this session.
85 NeverRecorded,
86}
87
88impl SessionRegistry {
89 /// Record a project's trusty-search index readiness (issue #2784's
90 /// UI Phase-1 follow-up).
91 ///
92 /// Why: `trusty_common::search_readiness` already probes this per lane and
93 /// then only logged it to stderr, where no API consumer could reach it.
94 /// The UI is a thin client over this daemon — anything it renders must
95 /// arrive as an event — so a warming index was structurally unrenderable.
96 /// Critically, this is what lets a consumer tell a COLD index from a READY
97 /// one with genuinely zero hits: both return an empty search, but they mean
98 /// opposite things, and conflating them is exactly what makes a model
99 /// conclude "nothing there" and hand-explore to the wrong target.
100 /// What: takes the probe's `Option<IndexReadiness>` — `None` (fail-open: no
101 /// daemon, undrivable id, HTTP error) maps to `state: "unavailable"` with
102 /// every lane `false` and no index fields, which is itself the useful
103 /// signal rather than something to swallow. `Some` maps to `"ready"` when
104 /// `semantic_search_ready()` and `"warming"` otherwise, carrying the
105 /// per-lane flags through verbatim. Errors with `session_not_found` if `id`
106 /// is unknown.
107 /// (DOC-39 §5.6 Slice D) Also caches the resulting [`IndexReadinessSnapshot`]
108 /// on the session (last-writer-wins), so a client that attaches AFTER this
109 /// one-time event fires can still retrieve it via
110 /// [`Self::get_readiness`]/`session.get_readiness`.
111 /// Test: `registry_tests::record_index_readiness_warming_publishes_event`,
112 /// `registry_tests::record_index_readiness_ready_publishes_event`,
113 /// `registry_tests::record_index_readiness_unavailable_publishes_event`,
114 /// `registry_tests::record_index_readiness_caches_snapshot_for_late_query`.
115 pub fn record_index_readiness(
116 &self,
117 id: &str,
118 readiness: Option<&trusty_common::search_readiness::IndexReadiness>,
119 summary: &str,
120 ) -> Result<(), RpcError> {
121 self.ensure_exists(id)?;
122 let snapshot = match readiness {
123 Some(r) => IndexReadinessSnapshot {
124 state: if r.semantic_search_ready() {
125 READINESS_STATE_READY
126 } else {
127 READINESS_STATE_WARMING
128 }
129 .to_string(),
130 index_id: Some(r.index_id.clone()),
131 lifecycle_status: Some(r.lifecycle_status.clone()),
132 chunk_count: Some(r.chunk_count),
133 lexical_ready: r.lexical_ready,
134 semantic_ready: r.semantic_ready,
135 graph_ready: r.graph_ready,
136 summary: summary.to_string(),
137 },
138 None => IndexReadinessSnapshot {
139 state: READINESS_STATE_UNAVAILABLE.to_string(),
140 index_id: None,
141 lifecycle_status: None,
142 chunk_count: None,
143 lexical_ready: false,
144 semantic_ready: false,
145 graph_ready: false,
146 summary: summary.to_string(),
147 },
148 };
149 {
150 let mut sessions = self.lock();
151 if let Some(entry) = sessions.get_mut(id) {
152 entry.readiness = Some(snapshot.clone());
153 }
154 }
155 self.record(
156 id,
157 Event::IndexReadiness {
158 session_id: id.to_string(),
159 state: snapshot.state,
160 index_id: snapshot.index_id,
161 lifecycle_status: snapshot.lifecycle_status,
162 chunk_count: snapshot.chunk_count,
163 lexical_ready: snapshot.lexical_ready,
164 semantic_ready: snapshot.semantic_ready,
165 graph_ready: snapshot.graph_ready,
166 summary: snapshot.summary,
167 },
168 );
169 Ok(())
170 }
171
172 /// `session.get_readiness`: return the last-recorded index-readiness
173 /// probe for a session, for clients that attach after the one-time
174 /// `Event::IndexReadiness` already fired (DOC-39 §5.6 Slice D).
175 ///
176 /// Why: [`Self::record_index_readiness`] emits its event exactly once, at
177 /// task start (see `run_task::ensure_project_indexed_in_background`'s
178 /// call site in `task::executor`). A UI that connects even a moment later
179 /// has no query surface to ask "what is the readiness state right now" —
180 /// only a stream it may have missed. This is that query surface.
181 /// What: `Err(session_not_found)` if `id` is unknown. Otherwise
182 /// [`ReadinessQuery::Probed`] wrapping the cached [`IndexReadinessSnapshot`]
183 /// if a probe has ever landed for this session, or
184 /// [`ReadinessQuery::NeverProbed`] — a distinct, clearly-typed state,
185 /// never a bare `null` — if no `record_index_readiness` call has happened
186 /// yet (e.g. a projectless session, or one queried before its background
187 /// indexing probe completes).
188 /// Test: `registry_tests::record_index_readiness_caches_snapshot_for_late_query`,
189 /// `protocol_readiness::tests::get_readiness_never_probed_session_returns_never_probed`,
190 /// `registry_tests::get_readiness_unknown_session_errors`.
191 pub fn get_readiness(&self, id: &str) -> Result<ReadinessQuery, RpcError> {
192 self.ensure_exists(id)?;
193 Ok(self
194 .lock()
195 .get(id)
196 .and_then(|e| e.readiness.clone())
197 .map(ReadinessQuery::Probed)
198 .unwrap_or(ReadinessQuery::NeverProbed))
199 }
200
201 /// Record one turn's working-context budget measurement (epic #2343;
202 /// caches the snapshot for late queries as of issue #3015).
203 ///
204 /// Why: the Infinite Sessions guarantee (working context >= 60%, session
205 /// overhead <= 40%) is enforced every single turn and was visible to
206 /// nothing — `CadenceOutcome` was computed and dropped. This is the
207 /// emission plumbing that lets `task::SessionToolEventSink` forward the
208 /// measurement to a `session.attach`ed UI's budget indicator. (issue
209 /// #3015) Also caches the resulting [`ContextBudgetSnapshot`] on the
210 /// session (last-writer-wins), mirroring [`Self::record_index_readiness`],
211 /// so a client that attaches or reconnects AFTER a turn's event already
212 /// fired can still retrieve it via [`Self::get_context_budget`]/
213 /// `session.get_context_budget` — the API PR #3014's GUI status bar
214 /// polls instead of leaving "budget: unavailable" permanently.
215 /// What: maps the caller's `agent_loop::ContextBudgetSnapshot` field-for-
216 /// field onto a cached [`ContextBudgetSnapshot`] first, then derives
217 /// `Event::ContextBudget` from that cached value so the two can never
218 /// disagree; every value is already computed by the caller, so this adds
219 /// no arithmetic of its own. Errors with `session_not_found` if `id` is
220 /// unknown.
221 /// (#3868) `lifetime_compaction_alarm_count` is stored as a `0`
222 /// placeholder here — this method runs on the EVERY-TURN write path
223 /// (`AgentLoop::maybe_cadence_compress` forwards to it once per cadence
224 /// tick), so a `File::open` + line-scan here would pay the durable-log
225 /// read cost once per turn per session. [`Self::get_context_budget`]
226 /// (the actual RPC query path — called far less often, once per client
227 /// poll) overwrites this field with a fresh read before returning, so no
228 /// caller ever observes the placeholder.
229 /// (#3948) The session's working-context floor takes the opposite route:
230 /// it is folded in HERE, under the same lock that stores the snapshot,
231 /// because a `min` over one `u8` costs nothing per turn while the query
232 /// path's alternative — rescanning the multi-session
233 /// `compression.jsonl` — grows with the machine's whole compression
234 /// history.
235 /// Test: `registry_tests::record_context_budget_publishes_event`,
236 /// `registry_tests::record_context_budget_caches_snapshot_for_late_query`,
237 /// `registry_tests::context_floor_tracks_every_measurement`,
238 /// `registry_tests::context_floor_is_session_scoped`.
239 pub fn record_context_budget(
240 &self,
241 id: &str,
242 measurement: &crate::agent_loop::ContextBudgetSnapshot,
243 ) -> Result<(), RpcError> {
244 self.ensure_exists(id)?;
245 let mut snapshot = ContextBudgetSnapshot {
246 context_window_tokens: measurement.context_window,
247 overhead_tokens: measurement.overhead_tokens,
248 overhead_cap_tokens: measurement.overhead_cap_tokens,
249 working_context_pct: measurement.working_context_pct,
250 overhead_pct: measurement.overhead_pct,
251 within_budget: measurement.within_budget,
252 compaction_fired: measurement.fired,
253 compaction_rounds: measurement.rounds,
254 // (#3868) Placeholder — see doc note above. Never observed: only
255 // `get_context_budget` reads this field back out, and it always
256 // overwrites it first.
257 lifetime_compaction_alarm_count: 0,
258 // (#3948) Overwritten from this entry's retained floor under the
259 // registry lock below, before the snapshot is stored.
260 working_context_pct_low_water_mark: None,
261 working_context_pct_sample_count: 0,
262 // (#3911) Same placeholder contract as
263 // `lifetime_compaction_alarm_count` above.
264 lifetime_cadence_floor_breach_count: 0,
265 };
266 {
267 let mut sessions = self.lock();
268 if let Some(entry) = sessions.get_mut(id) {
269 entry.context_floor.record(measurement.working_context_pct);
270 snapshot.working_context_pct_low_water_mark = entry.context_floor.low_water_mark;
271 snapshot.working_context_pct_sample_count = entry.context_floor.sample_count;
272 entry.context_budget = Some(snapshot);
273 }
274 }
275 self.record(
276 id,
277 Event::ContextBudget {
278 session_id: id.to_string(),
279 context_window_tokens: snapshot.context_window_tokens,
280 overhead_tokens: snapshot.overhead_tokens,
281 overhead_cap_tokens: snapshot.overhead_cap_tokens,
282 working_context_pct: snapshot.working_context_pct,
283 overhead_pct: snapshot.overhead_pct,
284 within_budget: snapshot.within_budget,
285 compaction_fired: snapshot.compaction_fired,
286 compaction_rounds: snapshot.compaction_rounds,
287 },
288 );
289 Ok(())
290 }
291
292 /// `session.get_context_budget`: return the last-recorded working-context
293 /// budget measurement for a session, for clients that attach after the
294 /// per-turn `Event::ContextBudget` already fired (issue #3015).
295 ///
296 /// Why: [`Self::record_context_budget`] emits its event once per PM turn
297 /// boundary — a client that attaches (or reconnects) between turns has no
298 /// query surface to ask "what is the budget right now", only a stream it
299 /// may have missed. This is that query surface, the exact counterpart to
300 /// [`Self::get_readiness`].
301 /// What: `Err(session_not_found)` if `id` is unknown. Otherwise
302 /// [`ContextBudgetQuery::Recorded`] wrapping the cached
303 /// [`ContextBudgetSnapshot`] if a turn has ever completed for this
304 /// session, or [`ContextBudgetQuery::NeverRecorded`] — a distinct,
305 /// clearly-typed state, never a bare `null` — if no
306 /// `record_context_budget` call has happened yet (e.g. a session queried
307 /// before its first PM turn completes, or a delegated sub-agent session,
308 /// which never emits cadence budget events at all).
309 /// (#3868) `lifetime_compaction_alarm_count` is read fresh from the
310 /// durable, cross-session alarm log HERE — the query path, called once
311 /// per client poll — rather than in [`Self::record_context_budget`] (the
312 /// every-turn write path), so the `File::open` + line-scan cost is paid
313 /// once per query, not once per turn per session. This is also why the
314 /// count reflects fires from ANY session on this machine, not just this
315 /// one: it is derived from a shared log, not a per-session cache.
316 /// (#3948) `working_context_pct_low_water_mark`/
317 /// `working_context_pct_sample_count` are read from the state
318 /// [`Self::record_context_budget`] retains per session, NOT from
319 /// `compression.jsonl`. This query used to call
320 /// `telemetry::session_working_context_floor`, which reopens and reparses
321 /// the machine-wide compression log on every poll; that function is
322 /// unchanged and remains the offline-history reader, but no live query
323 /// path calls it. The two answers are not identical, and the difference
324 /// is deliberate: the live floor samples EVERY cadence tick, while the
325 /// log only carries a percentage for turns where compaction work
326 /// happened (`rounds > 0`) plus threshold-compaction fires, which
327 /// `record_context_budget` never sees. So the live floor is over a
328 /// per-turn superset of this session's cadence measurements, and
329 /// `working_context_pct_sample_count` counts cadence measurements rather
330 /// than durable rows.
331 /// Test: `registry_tests::record_context_budget_caches_snapshot_for_late_query`,
332 /// `protocol_budget::tests::get_context_budget_never_recorded_session_returns_never_recorded`,
333 /// `registry_tests::get_context_budget_unknown_session_errors`,
334 /// `protocol_budget::tests::get_context_budget_reflects_lifetime_compaction_alarm_count`,
335 /// `protocol_budget::tests::get_context_budget_reflects_working_context_floor`,
336 /// `registry_tests::context_budget_query_does_not_open_compression_log`,
337 /// `registry_tests::context_floor_after_restart_is_absent_not_wrong`.
338 pub fn get_context_budget(&self, id: &str) -> Result<ContextBudgetQuery, RpcError> {
339 self.ensure_exists(id)?;
340 let cached = self.lock().get(id).and_then(|entry| {
341 entry.context_budget.map(|mut snapshot| {
342 snapshot.working_context_pct_low_water_mark = entry.context_floor.low_water_mark;
343 snapshot.working_context_pct_sample_count = entry.context_floor.sample_count;
344 snapshot
345 })
346 });
347 Ok(cached
348 .map(|mut snapshot| {
349 let data_dir = crate::agent_loop::telemetry::default_data_dir();
350 snapshot.lifetime_compaction_alarm_count =
351 crate::agent_loop::telemetry::lifetime_compaction_alarm_count(&data_dir);
352 snapshot.lifetime_cadence_floor_breach_count =
353 crate::agent_loop::telemetry::lifetime_cadence_floor_breach_count(&data_dir);
354 ContextBudgetQuery::Recorded(snapshot)
355 })
356 .unwrap_or(ContextBudgetQuery::NeverRecorded))
357 }
358
359 /// Record a tool invocation starting (#2055 emission plumbing for
360 /// #2056's agent loop).
361 ///
362 /// Why: gives the future agent loop a stable, already-wired call for
363 /// `ToolStarted` without it needing to touch the ring buffer, sequencing,
364 /// or bus directly.
365 /// What: errors with `session_not_found` if `id` is unknown; `args_preview`
366 /// is truncated via `crate::events::preview` before emission so a large
367 /// argument payload can't blow the ring buffer / wire size. `agent`
368 /// (UI Phase 1) is the dispatching agent's name — see
369 /// [`crate::events::Event::ToolStarted`]. `agent_id` (DOC-39 AC-13) is
370 /// that same agent's stable per-spawn id.
371 /// Test: `registry_tests::record_tool_started_publishes_event`.
372 pub fn record_tool_started(
373 &self,
374 id: &str,
375 agent: &str,
376 agent_id: &str,
377 tool: &str,
378 call_id: &str,
379 args: &str,
380 ) -> Result<(), RpcError> {
381 self.ensure_exists(id)?;
382 self.record(
383 id,
384 Event::ToolStarted {
385 session_id: id.to_string(),
386 agent: agent.to_string(),
387 agent_id: agent_id.to_string(),
388 tool: tool.to_string(),
389 call_id: call_id.to_string(),
390 args_preview: crate::events::preview(args, 500),
391 },
392 );
393 Ok(())
394 }
395
396 /// Record a tool invocation finishing (#2055 emission plumbing for
397 /// #2056's agent loop). See [`Self::record_tool_started`].
398 /// Test: `registry_tests::record_tool_finished_publishes_event`.
399 /// (DOC-39 AC-13) `agent_id` pushed this past clippy's
400 /// `too_many_arguments` gate; every parameter is a plain, independent
401 /// piece of the event and none pair naturally into a sub-struct, so the
402 /// attribute is the pragmatic choice here (mirrors
403 /// `serve::transport::run_loop`'s same allowance).
404 #[allow(clippy::too_many_arguments)]
405 pub fn record_tool_finished(
406 &self,
407 id: &str,
408 agent: &str,
409 agent_id: &str,
410 tool: &str,
411 call_id: &str,
412 success: bool,
413 result: &str,
414 ) -> Result<(), RpcError> {
415 self.ensure_exists(id)?;
416 self.record(
417 id,
418 Event::ToolFinished {
419 session_id: id.to_string(),
420 agent: agent.to_string(),
421 agent_id: agent_id.to_string(),
422 tool: tool.to_string(),
423 call_id: call_id.to_string(),
424 success,
425 result_preview: crate::events::preview(result, 500),
426 },
427 );
428 Ok(())
429 }
430
431 /// Record a tool invocation raising an exceptional error (#2055 emission
432 /// plumbing for #2056's agent loop). See [`Self::record_tool_started`].
433 /// Test: `registry_tests::record_tool_error_publishes_event`.
434 pub fn record_tool_error(
435 &self,
436 id: &str,
437 agent: &str,
438 agent_id: &str,
439 tool: &str,
440 call_id: &str,
441 error: &str,
442 ) -> Result<(), RpcError> {
443 self.ensure_exists(id)?;
444 self.record(
445 id,
446 Event::ToolError {
447 session_id: id.to_string(),
448 agent: agent.to_string(),
449 agent_id: agent_id.to_string(),
450 tool: tool.to_string(),
451 call_id: call_id.to_string(),
452 error: error.to_string(),
453 },
454 );
455 Ok(())
456 }
457
458 /// Record a `search_code` call's real lane + hit count + per-hit
459 /// path/score + latency (UI Phase 1; `hits` added DOC-39 Slice B). See
460 /// [`crate::events::Event::SearchPerformed`].
461 ///
462 /// Why: emitted ALONGSIDE the generic tool events so the UI can trace a
463 /// change back to the searches that drove it without re-parsing prose.
464 /// What: same existence guard + ring-buffer/sequencing path as every
465 /// other `record_*`, so a structured event replays on `session.attach`
466 /// exactly like the generic ones.
467 /// Test: `registry_tests::record_search_performed_publishes_event`,
468 /// `registry_search_audit::tests::get_search_audit_returns_records_after_recording`.
469 pub fn record_search_performed(
470 &self,
471 id: &str,
472 agent: &str,
473 agent_id: &str,
474 telemetry: &SearchTelemetry,
475 ) -> Result<(), RpcError> {
476 self.ensure_exists(id)?;
477 // (issue #3072) Append to the retained audit trail BEFORE emitting
478 // the SSE event, mirroring `record_context_budget`'s cache-then-emit
479 // ordering — a client that queries `session.get_search_audit` right
480 // after observing this event on the stream is guaranteed to see it.
481 self.push_search_audit(
482 id,
483 crate::events::SearchAuditRecord::Search {
484 agent: agent.to_string(),
485 agent_id: agent_id.to_string(),
486 lane: telemetry.lane.clone(),
487 query: telemetry.query.clone(),
488 hit_count: telemetry.hit_count,
489 latency_ms: telemetry.latency_ms,
490 at: Utc::now(),
491 },
492 );
493 self.record(
494 id,
495 Event::SearchPerformed {
496 session_id: id.to_string(),
497 agent: agent.to_string(),
498 agent_id: agent_id.to_string(),
499 lane: telemetry.lane.clone(),
500 query: telemetry.query.clone(),
501 hit_count: telemetry.hit_count,
502 hits: telemetry.hits.clone(),
503 latency_ms: telemetry.latency_ms,
504 },
505 );
506 Ok(())
507 }
508
509 /// Record a `recall_session` call's results and which ones entered
510 /// context (UI Phase 1). See [`crate::events::Event::MemoryRecalled`].
511 ///
512 /// Why: the `injected` flag is the UI's differentiating surface —
513 /// injected memories vs ones recalled and held back.
514 /// What: as [`Self::record_search_performed`].
515 /// Test: `registry_tests::record_memory_recalled_publishes_event`,
516 /// `registry_search_audit::tests::get_search_audit_returns_records_after_recording`.
517 pub fn record_memory_recalled(
518 &self,
519 id: &str,
520 agent: &str,
521 agent_id: &str,
522 telemetry: &RecallTelemetry,
523 ) -> Result<(), RpcError> {
524 self.ensure_exists(id)?;
525 // (issue #3072) Append to the retained audit trail BEFORE emitting
526 // the SSE event — see `record_search_performed`'s matching comment.
527 self.push_search_audit(
528 id,
529 crate::events::SearchAuditRecord::Recall {
530 agent: agent.to_string(),
531 agent_id: agent_id.to_string(),
532 query: telemetry.query.clone(),
533 result_count: telemetry.results.len(),
534 injected_count: telemetry.results.iter().filter(|r| r.injected).count(),
535 at: Utc::now(),
536 },
537 );
538 self.record(
539 id,
540 Event::MemoryRecalled {
541 session_id: id.to_string(),
542 agent: agent.to_string(),
543 agent_id: agent_id.to_string(),
544 query: telemetry.query.clone(),
545 results: telemetry.results.clone(),
546 },
547 );
548 Ok(())
549 }
550
551 /// Record a session-scoped diagnostic log line (#2055 emission plumbing).
552 /// Test: `registry_tests::record_log_publishes_event`.
553 pub fn record_log(&self, id: &str, level: &str, message: &str) -> Result<(), RpcError> {
554 self.ensure_exists(id)?;
555 self.record(
556 id,
557 Event::Log {
558 session_id: id.to_string(),
559 level: level.to_string(),
560 message: message.to_string(),
561 },
562 );
563 Ok(())
564 }
565
566 /// Record a coarse progress update (#2055 emission plumbing).
567 /// Test: `registry_tests::record_progress_publishes_event`.
568 pub fn record_progress(
569 &self,
570 id: &str,
571 message: &str,
572 percent: Option<f32>,
573 ) -> Result<(), RpcError> {
574 self.ensure_exists(id)?;
575 self.record(
576 id,
577 Event::Progress {
578 session_id: id.to_string(),
579 message: message.to_string(),
580 percent,
581 },
582 );
583 Ok(())
584 }
585
586 /// Record a generic freeform session message (#2055 emission plumbing).
587 /// Test: `registry_tests::record_message_publishes_event`.
588 pub fn record_message(&self, id: &str, text: &str) -> Result<(), RpcError> {
589 self.ensure_exists(id)?;
590 self.record(
591 id,
592 Event::Message {
593 session_id: id.to_string(),
594 text: text.to_string(),
595 },
596 );
597 Ok(())
598 }
599
600 /// Record one assistant turn's text as an `AgentMessageDelta` (tcode
601 /// streaming epic #3696, Gap A, Slice 1). See
602 /// [`crate::events::Event::AgentMessageDelta`] for the `turn_id`
603 /// uniqueness requirement and the `(agent_id, turn_id)` grouping contract.
604 /// Test: `registry_tests::record_agent_message_delta_publishes_event`.
605 pub fn record_agent_message_delta(
606 &self,
607 id: &str,
608 agent: &str,
609 agent_id: &str,
610 turn_id: &str,
611 delta: &str,
612 done: bool,
613 ) -> Result<(), RpcError> {
614 self.ensure_exists(id)?;
615 self.record(
616 id,
617 Event::AgentMessageDelta {
618 session_id: id.to_string(),
619 agent: agent.to_string(),
620 agent_id: agent_id.to_string(),
621 turn_id: turn_id.to_string(),
622 delta: delta.to_string(),
623 done,
624 },
625 );
626 Ok(())
627 }
628
629 /// Return `Ok(())` if `id` exists, `Err(session_not_found)` otherwise.
630 ///
631 /// Why: every `record_*` plumbing method needs the same existence guard
632 /// before recording; centralising it keeps each one a two-line body.
633 fn ensure_exists(&self, id: &str) -> Result<(), RpcError> {
634 if self.lock().contains_key(id) {
635 Ok(())
636 } else {
637 Err(RpcError::session_not_found(id))
638 }
639 }
640}