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