Skip to main content

trusty_code/task/
sink.rs

1//! Concrete `ToolEventSink` forwarding tool-dispatch hooks to
2//! `SessionRegistry::record_tool_*` (#2056).
3//!
4//! Why: #2055 built the emission plumbing; #2056's `agent_loop` extension
5//! built the hook (`agent_loop::ToolEventSink`) that CAN call it. This is the
6//! small piece of glue that actually wires the two together for a specific
7//! session, kept in `task` (the daemon-execution layer) rather than
8//! `agent_loop` (the generic engine) or `session` (which must not depend
9//! upward on the engine) — see `agent_loop::sink`'s module docs for the
10//! layering rationale.
11//! What: [`SessionToolEventSink`] holds an `Arc<SessionRegistry>` and the
12//! target `session_id`; each hook forwards to the matching `record_tool_*`
13//! call, logging (not propagating — the sink trait's methods return `()`)
14//! any failure, which in practice only happens if the session vanished
15//! mid-run (e.g. a race with daemon shutdown).
16//! Test: `task::sink::tests::*`.
17
18use std::sync::Arc;
19
20use async_trait::async_trait;
21
22use crate::agent_loop::{ContextBudgetSnapshot, ToolEventSink};
23use crate::session::SessionRegistry;
24use crate::tools::telemetry::ToolTelemetry;
25
26/// Forwards `AgentLoop` tool-dispatch hooks to a specific session's
27/// `SessionRegistry::record_tool_*` calls (#2056).
28///
29/// Why: the seam that makes a daemon-driven run's tool activity observable
30/// to a `session.attach`ed client, over both the PM's own loop and any
31/// delegated sub-agent loop that shares this same `Arc`.
32/// What: See module docs.
33/// Test: `task::sink::tests::forwards_started_finished_and_error`.
34pub struct SessionToolEventSink {
35    registry: Arc<SessionRegistry>,
36    session_id: String,
37}
38
39impl SessionToolEventSink {
40    /// Build a sink targeting `session_id` on `registry`.
41    pub fn new(registry: Arc<SessionRegistry>, session_id: impl Into<String>) -> Self {
42        Self {
43            registry,
44            session_id: session_id.into(),
45        }
46    }
47}
48
49#[async_trait]
50impl ToolEventSink for SessionToolEventSink {
51    async fn tool_started(
52        &self,
53        agent: &str,
54        agent_id: &str,
55        call_id: &str,
56        tool: &str,
57        args_preview: &str,
58    ) {
59        if let Err(e) = self.registry.record_tool_started(
60            &self.session_id,
61            agent,
62            agent_id,
63            tool,
64            call_id,
65            args_preview,
66        ) {
67            tracing::warn!(session_id = %self.session_id, agent, agent_id, tool, call_id, "record_tool_started failed: {e}");
68        }
69    }
70
71    async fn tool_finished(
72        &self,
73        agent: &str,
74        agent_id: &str,
75        call_id: &str,
76        tool: &str,
77        success: bool,
78        result_preview: &str,
79    ) {
80        if let Err(e) = self.registry.record_tool_finished(
81            &self.session_id,
82            agent,
83            agent_id,
84            tool,
85            call_id,
86            success,
87            result_preview,
88        ) {
89            tracing::warn!(session_id = %self.session_id, agent, agent_id, tool, call_id, "record_tool_finished failed: {e}");
90        }
91    }
92
93    async fn tool_error(
94        &self,
95        agent: &str,
96        agent_id: &str,
97        call_id: &str,
98        tool: &str,
99        error: &str,
100    ) {
101        if let Err(e) =
102            self.registry
103                .record_tool_error(&self.session_id, agent, agent_id, tool, call_id, error)
104        {
105            tracing::warn!(session_id = %self.session_id, agent, agent_id, tool, call_id, "record_tool_error failed: {e}");
106        }
107    }
108
109    /// Fan a tool's structured telemetry out to the matching #UI-Phase-1
110    /// `record_*` call.
111    ///
112    /// Why: the variant-to-record mapping belongs here, in the daemon-glue
113    /// layer, rather than in `agent_loop` (which must not know about
114    /// `SessionRegistry`) or in the tools (which must not know about
115    /// sessions at all).
116    /// What: same log-and-swallow contract as the hooks above — a vanished
117    /// session must never derail a run.
118    /// Test: `tests::forwards_search_and_recall_telemetry`.
119    async fn tool_telemetry(
120        &self,
121        agent: &str,
122        agent_id: &str,
123        call_id: &str,
124        tool: &str,
125        telemetry: &ToolTelemetry,
126    ) {
127        let recorded = match telemetry {
128            ToolTelemetry::Search(t) => {
129                self.registry
130                    .record_search_performed(&self.session_id, agent, agent_id, t)
131            }
132            ToolTelemetry::Recall(t) => {
133                self.registry
134                    .record_memory_recalled(&self.session_id, agent, agent_id, t)
135            }
136        };
137        if let Err(e) = recorded {
138            tracing::warn!(session_id = %self.session_id, agent, agent_id, tool, call_id, "record tool telemetry failed: {e}");
139        }
140    }
141
142    /// Forward the per-turn working-context measurement to this session's
143    /// event stream (epic #2343). Same log-and-swallow contract as the tool
144    /// hooks above: a vanished session must never fault the PM's turn
145    /// boundary — telemetry is not worth failing the work it observes.
146    async fn context_budget(&self, snapshot: &ContextBudgetSnapshot) {
147        if let Err(e) = self
148            .registry
149            .record_context_budget(&self.session_id, snapshot)
150        {
151            tracing::warn!(session_id = %self.session_id, "record_context_budget failed: {e}");
152        }
153    }
154
155    /// Forward one assistant turn's text to this session's event stream
156    /// (tcode streaming epic #3696, Gap A, Slice 1). Same log-and-swallow
157    /// contract as the hooks above: a vanished session must never fault the
158    /// loop that observed the turn.
159    /// Test: `tests::agent_message_reaches_stream_as_delta`.
160    async fn agent_message(
161        &self,
162        agent: &str,
163        agent_id: &str,
164        turn_id: &str,
165        delta: &str,
166        done: bool,
167    ) {
168        if let Err(e) = self.registry.record_agent_message_delta(
169            &self.session_id,
170            agent,
171            agent_id,
172            turn_id,
173            delta,
174            done,
175        ) {
176            tracing::warn!(session_id = %self.session_id, agent, agent_id, turn_id, "record_agent_message_delta failed: {e}");
177        }
178    }
179
180    /// Forward a delegation starting to this session's event stream (#7940).
181    /// Same log-and-swallow contract as the hooks above: a vanished session
182    /// must never fault the delegation it observes.
183    /// Test: `tests::forwards_agent_lifecycle`.
184    async fn agent_spawned(&self, agent: &str, agent_id: &str, task_preview: &str) {
185        if let Err(e) =
186            self.registry
187                .record_agent_spawned(&self.session_id, agent, agent_id, task_preview)
188        {
189            tracing::warn!(session_id = %self.session_id, agent, agent_id, "record_agent_spawned failed: {e}");
190        }
191    }
192
193    /// Forward a delegation finishing normally (#7940). See
194    /// [`Self::agent_spawned`].
195    async fn agent_done(&self, agent: &str, agent_id: &str, status: &str) {
196        if let Err(e) = self
197            .registry
198            .record_agent_done(&self.session_id, agent, agent_id, status)
199        {
200            tracing::warn!(session_id = %self.session_id, agent, agent_id, "record_agent_done failed: {e}");
201        }
202    }
203
204    /// Forward a delegation aborting (#7940). See [`Self::agent_spawned`].
205    async fn agent_failed(&self, agent: &str, agent_id: &str, error: &str) {
206        if let Err(e) = self
207            .registry
208            .record_agent_failed(&self.session_id, agent, agent_id, error)
209        {
210            tracing::warn!(session_id = %self.session_id, agent, agent_id, "record_agent_failed failed: {e}");
211        }
212    }
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218    use tokio::sync::broadcast;
219
220    /// Read the process-global event bus until an envelope matching
221    /// `session_id` arrives (mirrors `session::registry::registry_tests`'
222    /// helper — the global bus is shared across the whole test binary).
223    async fn next_event_for(
224        rx: &mut broadcast::Receiver<crate::events::SessionEventEnvelope>,
225        session_id: &str,
226    ) -> crate::events::SessionEventEnvelope {
227        tokio::time::timeout(std::time::Duration::from_secs(2), async {
228            loop {
229                let envelope = rx.recv().await.expect("event bus closed unexpectedly");
230                if envelope.session_id == session_id {
231                    return envelope;
232                }
233            }
234        })
235        .await
236        .expect("timed out waiting for an event on this session")
237    }
238
239    /// Each hook must forward to the matching `record_tool_*` call and
240    /// publish the corresponding #2055 event kind, carrying the agent it was
241    /// called with (UI Phase 1).
242    #[tokio::test]
243    async fn forwards_started_finished_and_error() {
244        let registry = Arc::new(SessionRegistry::new());
245        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
246        let sink = SessionToolEventSink::new(Arc::clone(&registry), session.id.clone());
247        let mut events = crate::events::subscribe();
248
249        sink.tool_started("pm", "pm-1", "call-1", "bash", "echo hi")
250            .await;
251        let ev = next_event_for(&mut events, &session.id).await;
252        assert_eq!(ev.kind, "tool_started");
253        assert!(matches!(
254            ev.event,
255            crate::events::Event::ToolStarted { agent, agent_id, .. }
256                if agent == "pm" && agent_id == "pm-1"
257        ));
258
259        sink.tool_finished("pm", "pm-1", "call-1", "bash", true, "hi")
260            .await;
261        let ev = next_event_for(&mut events, &session.id).await;
262        assert_eq!(ev.kind, "tool_finished");
263
264        sink.tool_error("pm", "pm-1", "call-1", "bash", "boom")
265            .await;
266        let ev = next_event_for(&mut events, &session.id).await;
267        assert_eq!(ev.kind, "tool_error");
268    }
269
270    /// ONE shared sink instance must attribute events to whichever agent
271    /// calls it (UI Phase 1).
272    ///
273    /// Why: this is the whole reason `agent` is a per-call PARAMETER rather
274    /// than sink state — `task::executor::run_and_record` clones ONE `Arc` of
275    /// this sink into both the PM's loop and the delegated engineer's runner.
276    /// A sink that carried its own agent name could only ever report one of
277    /// them, leaving the two indistinguishable on the stream.
278    #[tokio::test]
279    async fn one_shared_sink_attributes_each_caller_separately() {
280        let registry = Arc::new(SessionRegistry::new());
281        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
282        let sink: Arc<dyn ToolEventSink> = Arc::new(SessionToolEventSink::new(
283            Arc::clone(&registry),
284            session.id.clone(),
285        ));
286        // Two clones of the ONE Arc, exactly as production wires it.
287        let pm_view = Arc::clone(&sink);
288        let engineer_view = Arc::clone(&sink);
289        let mut events = crate::events::subscribe();
290
291        pm_view
292            .tool_started("pm", "pm-session-1", "c1", "delegate_to_agent", "{}")
293            .await;
294        let ev = next_event_for(&mut events, &session.id).await;
295        assert!(matches!(
296            ev.event,
297            crate::events::Event::ToolStarted { agent, agent_id, .. }
298                if agent == "pm" && agent_id == "pm-session-1"
299        ));
300
301        engineer_view
302            .tool_started("python-engineer", "eng-spawn-7", "c2", "bash", "cargo test")
303            .await;
304        let ev = next_event_for(&mut events, &session.id).await;
305        assert!(
306            matches!(ev.event, crate::events::Event::ToolStarted { agent, agent_id, .. }
307                if agent == "python-engineer" && agent_id == "eng-spawn-7"),
308            "a shared sink must report the CALLER's agent AND agent_id, not one fixed pair \
309             (DOC-39 AC-13)"
310        );
311    }
312
313    /// `tool_telemetry` must fan each variant out to its matching structured
314    /// event (UI Phase 1).
315    #[tokio::test]
316    async fn forwards_search_and_recall_telemetry() {
317        let registry = Arc::new(SessionRegistry::new());
318        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
319        let sink = SessionToolEventSink::new(Arc::clone(&registry), session.id.clone());
320        let mut events = crate::events::subscribe();
321
322        sink.tool_telemetry(
323            "python-engineer",
324            "eng-1",
325            "c1",
326            "search_code",
327            &ToolTelemetry::Search(crate::tools::SearchTelemetry {
328                lane: "lexical".to_string(),
329                query: "q".to_string(),
330                hit_count: Some(2),
331                hits: vec![],
332                latency_ms: 5,
333            }),
334        )
335        .await;
336        let ev = next_event_for(&mut events, &session.id).await;
337        assert_eq!(ev.kind, "search_performed");
338        assert!(
339            matches!(ev.event, crate::events::Event::SearchPerformed { agent, agent_id, lane, .. }
340                if agent == "python-engineer" && agent_id == "eng-1" && lane == "lexical")
341        );
342
343        sink.tool_telemetry(
344            "pm",
345            "pm-1",
346            "c2",
347            "recall_session",
348            &ToolTelemetry::Recall(crate::tools::RecallTelemetry {
349                query: "q".to_string(),
350                results: vec![crate::events::RecalledMemory {
351                    score: 0.4,
352                    injected: false,
353                    text: "held back".to_string(),
354                    run_id: None,
355                }],
356            }),
357        )
358        .await;
359        let ev = next_event_for(&mut events, &session.id).await;
360        assert_eq!(ev.kind, "memory_recalled");
361        assert!(matches!(
362            ev.event,
363            crate::events::Event::MemoryRecalled { agent, agent_id, .. }
364                if agent == "pm" && agent_id == "pm-1"
365        ));
366    }
367
368    /// Hooks against an unknown session must not panic (they log and
369    /// swallow the `session_not_found` error — the sink trait is `()`-only).
370    #[tokio::test]
371    async fn unknown_session_does_not_panic() {
372        let registry = Arc::new(SessionRegistry::new());
373        let sink = SessionToolEventSink::new(registry, "does-not-exist".to_string());
374        sink.tool_started("pm", "pm-1", "c", "bash", "x").await;
375        sink.tool_finished("pm", "pm-1", "c", "bash", true, "x")
376            .await;
377        sink.tool_error("pm", "pm-1", "c", "bash", "x").await;
378        sink.tool_telemetry(
379            "pm",
380            "pm-1",
381            "c",
382            "search_code",
383            &ToolTelemetry::Search(crate::tools::SearchTelemetry {
384                lane: "semantic".to_string(),
385                query: "q".to_string(),
386                hit_count: None,
387                hits: vec![],
388                latency_ms: 1,
389            }),
390        )
391        .await;
392        sink.context_budget(&budget_snapshot()).await;
393        sink.agent_message("pm", "pm-1", "turn-1", "x", true).await;
394        sink.agent_spawned("engineer", "eng-1", "t").await;
395        sink.agent_done("engineer", "eng-1", "success").await;
396        sink.agent_failed("engineer", "eng-1", "boom").await;
397    }
398
399    /// The three delegation-lifecycle hooks must each reach the session's
400    /// event stream as their matching event kind (#7940) — the brackets a
401    /// TUI renders a delegation block from.
402    #[tokio::test]
403    async fn forwards_agent_lifecycle() {
404        let registry = Arc::new(SessionRegistry::new());
405        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
406        let sink = SessionToolEventSink::new(Arc::clone(&registry), session.id.clone());
407        let mut events = crate::events::subscribe();
408
409        sink.agent_spawned("engineer", "eng-1", "build the thing")
410            .await;
411        let ev = next_event_for(&mut events, &session.id).await;
412        assert_eq!(ev.kind, "agent_spawned");
413        assert!(matches!(
414            ev.event,
415            crate::events::Event::AgentSpawned { agent, agent_id, task_preview, .. }
416                if agent == "engineer" && agent_id == "eng-1"
417                    && task_preview == "build the thing"
418        ));
419
420        sink.agent_done("engineer", "eng-1", "success").await;
421        let ev = next_event_for(&mut events, &session.id).await;
422        assert_eq!(ev.kind, "agent_done");
423        assert!(matches!(
424            ev.event,
425            crate::events::Event::AgentDone { agent_id, status, .. }
426                if agent_id == "eng-1" && status == "success"
427        ));
428
429        sink.agent_failed("engineer", "eng-2", "turn cap exceeded")
430            .await;
431        let ev = next_event_for(&mut events, &session.id).await;
432        assert_eq!(ev.kind, "agent_failed");
433        assert!(matches!(
434            ev.event,
435            crate::events::Event::AgentFailed { agent_id, error, .. }
436                if agent_id == "eng-2" && error == "turn cap exceeded"
437        ));
438    }
439
440    /// A representative budget snapshot for the sink tests.
441    fn budget_snapshot() -> ContextBudgetSnapshot {
442        ContextBudgetSnapshot {
443            context_window: 200_000,
444            overhead_tokens: 50_000,
445            overhead_cap_tokens: 80_000,
446            working_context_pct: 75,
447            overhead_pct: 25,
448            within_budget: true,
449            fired: false,
450            rounds: 1,
451        }
452    }
453
454    /// The `context_budget` hook must reach the session's event stream as a
455    /// `context_budget` event carrying the measured figures (epic #2343).
456    ///
457    /// Why: this is the last link in the chain that makes the Infinite
458    /// Sessions guarantee renderable — `agent_loop` measures it, this sink is
459    /// what binds it to a session and publishes it.
460    #[tokio::test]
461    async fn forwards_context_budget() {
462        let registry = Arc::new(SessionRegistry::new());
463        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
464        let sink = SessionToolEventSink::new(Arc::clone(&registry), session.id.clone());
465        let mut events = crate::events::subscribe();
466
467        sink.context_budget(&budget_snapshot()).await;
468
469        let ev = next_event_for(&mut events, &session.id).await;
470        assert_eq!(ev.kind, "context_budget");
471        assert!(matches!(
472            ev.event,
473            crate::events::Event::ContextBudget { working_context_pct, overhead_tokens, .. }
474                if working_context_pct == 75 && overhead_tokens == 50_000
475        ));
476    }
477
478    /// The `agent_message` hook must reach the session's event stream as an
479    /// `agent_message_delta` event carrying the caller's attribution and
480    /// text (tcode streaming epic #3696, Gap A, Slice 1).
481    #[tokio::test]
482    async fn agent_message_reaches_stream_as_delta() {
483        let registry = Arc::new(SessionRegistry::new());
484        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
485        let sink = SessionToolEventSink::new(Arc::clone(&registry), session.id.clone());
486        let mut events = crate::events::subscribe();
487
488        sink.agent_message("pm", "pm-1", "turn-1", "hello there", true)
489            .await;
490
491        let ev = next_event_for(&mut events, &session.id).await;
492        assert_eq!(ev.kind, "agent_message_delta");
493        assert!(matches!(
494            ev.event,
495            crate::events::Event::AgentMessageDelta { agent, agent_id, turn_id, delta, done, .. }
496                if agent == "pm" && agent_id == "pm-1" && turn_id == "turn-1"
497                    && delta == "hello there" && done
498        ));
499    }
500}