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
181#[cfg(test)]
182mod tests {
183    use super::*;
184    use tokio::sync::broadcast;
185
186    /// Read the process-global event bus until an envelope matching
187    /// `session_id` arrives (mirrors `session::registry::registry_tests`'
188    /// helper — the global bus is shared across the whole test binary).
189    async fn next_event_for(
190        rx: &mut broadcast::Receiver<crate::events::SessionEventEnvelope>,
191        session_id: &str,
192    ) -> crate::events::SessionEventEnvelope {
193        tokio::time::timeout(std::time::Duration::from_secs(2), async {
194            loop {
195                let envelope = rx.recv().await.expect("event bus closed unexpectedly");
196                if envelope.session_id == session_id {
197                    return envelope;
198                }
199            }
200        })
201        .await
202        .expect("timed out waiting for an event on this session")
203    }
204
205    /// Each hook must forward to the matching `record_tool_*` call and
206    /// publish the corresponding #2055 event kind, carrying the agent it was
207    /// called with (UI Phase 1).
208    #[tokio::test]
209    async fn forwards_started_finished_and_error() {
210        let registry = Arc::new(SessionRegistry::new());
211        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
212        let sink = SessionToolEventSink::new(Arc::clone(&registry), session.id.clone());
213        let mut events = crate::events::subscribe();
214
215        sink.tool_started("pm", "pm-1", "call-1", "bash", "echo hi")
216            .await;
217        let ev = next_event_for(&mut events, &session.id).await;
218        assert_eq!(ev.kind, "tool_started");
219        assert!(matches!(
220            ev.event,
221            crate::events::Event::ToolStarted { agent, agent_id, .. }
222                if agent == "pm" && agent_id == "pm-1"
223        ));
224
225        sink.tool_finished("pm", "pm-1", "call-1", "bash", true, "hi")
226            .await;
227        let ev = next_event_for(&mut events, &session.id).await;
228        assert_eq!(ev.kind, "tool_finished");
229
230        sink.tool_error("pm", "pm-1", "call-1", "bash", "boom")
231            .await;
232        let ev = next_event_for(&mut events, &session.id).await;
233        assert_eq!(ev.kind, "tool_error");
234    }
235
236    /// ONE shared sink instance must attribute events to whichever agent
237    /// calls it (UI Phase 1).
238    ///
239    /// Why: this is the whole reason `agent` is a per-call PARAMETER rather
240    /// than sink state — `task::executor::run_and_record` clones ONE `Arc` of
241    /// this sink into both the PM's loop and the delegated engineer's runner.
242    /// A sink that carried its own agent name could only ever report one of
243    /// them, leaving the two indistinguishable on the stream.
244    #[tokio::test]
245    async fn one_shared_sink_attributes_each_caller_separately() {
246        let registry = Arc::new(SessionRegistry::new());
247        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
248        let sink: Arc<dyn ToolEventSink> = Arc::new(SessionToolEventSink::new(
249            Arc::clone(&registry),
250            session.id.clone(),
251        ));
252        // Two clones of the ONE Arc, exactly as production wires it.
253        let pm_view = Arc::clone(&sink);
254        let engineer_view = Arc::clone(&sink);
255        let mut events = crate::events::subscribe();
256
257        pm_view
258            .tool_started("pm", "pm-session-1", "c1", "delegate_to_agent", "{}")
259            .await;
260        let ev = next_event_for(&mut events, &session.id).await;
261        assert!(matches!(
262            ev.event,
263            crate::events::Event::ToolStarted { agent, agent_id, .. }
264                if agent == "pm" && agent_id == "pm-session-1"
265        ));
266
267        engineer_view
268            .tool_started("python-engineer", "eng-spawn-7", "c2", "bash", "cargo test")
269            .await;
270        let ev = next_event_for(&mut events, &session.id).await;
271        assert!(
272            matches!(ev.event, crate::events::Event::ToolStarted { agent, agent_id, .. }
273                if agent == "python-engineer" && agent_id == "eng-spawn-7"),
274            "a shared sink must report the CALLER's agent AND agent_id, not one fixed pair \
275             (DOC-39 AC-13)"
276        );
277    }
278
279    /// `tool_telemetry` must fan each variant out to its matching structured
280    /// event (UI Phase 1).
281    #[tokio::test]
282    async fn forwards_search_and_recall_telemetry() {
283        let registry = Arc::new(SessionRegistry::new());
284        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
285        let sink = SessionToolEventSink::new(Arc::clone(&registry), session.id.clone());
286        let mut events = crate::events::subscribe();
287
288        sink.tool_telemetry(
289            "python-engineer",
290            "eng-1",
291            "c1",
292            "search_code",
293            &ToolTelemetry::Search(crate::tools::SearchTelemetry {
294                lane: "lexical".to_string(),
295                query: "q".to_string(),
296                hit_count: Some(2),
297                hits: vec![],
298                latency_ms: 5,
299            }),
300        )
301        .await;
302        let ev = next_event_for(&mut events, &session.id).await;
303        assert_eq!(ev.kind, "search_performed");
304        assert!(
305            matches!(ev.event, crate::events::Event::SearchPerformed { agent, agent_id, lane, .. }
306                if agent == "python-engineer" && agent_id == "eng-1" && lane == "lexical")
307        );
308
309        sink.tool_telemetry(
310            "pm",
311            "pm-1",
312            "c2",
313            "recall_session",
314            &ToolTelemetry::Recall(crate::tools::RecallTelemetry {
315                query: "q".to_string(),
316                results: vec![crate::events::RecalledMemory {
317                    score: 0.4,
318                    injected: false,
319                    text: "held back".to_string(),
320                    run_id: None,
321                }],
322            }),
323        )
324        .await;
325        let ev = next_event_for(&mut events, &session.id).await;
326        assert_eq!(ev.kind, "memory_recalled");
327        assert!(matches!(
328            ev.event,
329            crate::events::Event::MemoryRecalled { agent, agent_id, .. }
330                if agent == "pm" && agent_id == "pm-1"
331        ));
332    }
333
334    /// Hooks against an unknown session must not panic (they log and
335    /// swallow the `session_not_found` error — the sink trait is `()`-only).
336    #[tokio::test]
337    async fn unknown_session_does_not_panic() {
338        let registry = Arc::new(SessionRegistry::new());
339        let sink = SessionToolEventSink::new(registry, "does-not-exist".to_string());
340        sink.tool_started("pm", "pm-1", "c", "bash", "x").await;
341        sink.tool_finished("pm", "pm-1", "c", "bash", true, "x")
342            .await;
343        sink.tool_error("pm", "pm-1", "c", "bash", "x").await;
344        sink.tool_telemetry(
345            "pm",
346            "pm-1",
347            "c",
348            "search_code",
349            &ToolTelemetry::Search(crate::tools::SearchTelemetry {
350                lane: "semantic".to_string(),
351                query: "q".to_string(),
352                hit_count: None,
353                hits: vec![],
354                latency_ms: 1,
355            }),
356        )
357        .await;
358        sink.context_budget(&budget_snapshot()).await;
359        sink.agent_message("pm", "pm-1", "turn-1", "x", true).await;
360    }
361
362    /// A representative budget snapshot for the sink tests.
363    fn budget_snapshot() -> ContextBudgetSnapshot {
364        ContextBudgetSnapshot {
365            context_window: 200_000,
366            overhead_tokens: 50_000,
367            overhead_cap_tokens: 80_000,
368            working_context_pct: 75,
369            overhead_pct: 25,
370            within_budget: true,
371            fired: false,
372            rounds: 1,
373        }
374    }
375
376    /// The `context_budget` hook must reach the session's event stream as a
377    /// `context_budget` event carrying the measured figures (epic #2343).
378    ///
379    /// Why: this is the last link in the chain that makes the Infinite
380    /// Sessions guarantee renderable — `agent_loop` measures it, this sink is
381    /// what binds it to a session and publishes it.
382    #[tokio::test]
383    async fn forwards_context_budget() {
384        let registry = Arc::new(SessionRegistry::new());
385        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
386        let sink = SessionToolEventSink::new(Arc::clone(&registry), session.id.clone());
387        let mut events = crate::events::subscribe();
388
389        sink.context_budget(&budget_snapshot()).await;
390
391        let ev = next_event_for(&mut events, &session.id).await;
392        assert_eq!(ev.kind, "context_budget");
393        assert!(matches!(
394            ev.event,
395            crate::events::Event::ContextBudget { working_context_pct, overhead_tokens, .. }
396                if working_context_pct == 75 && overhead_tokens == 50_000
397        ));
398    }
399
400    /// The `agent_message` hook must reach the session's event stream as an
401    /// `agent_message_delta` event carrying the caller's attribution and
402    /// text (tcode streaming epic #3696, Gap A, Slice 1).
403    #[tokio::test]
404    async fn agent_message_reaches_stream_as_delta() {
405        let registry = Arc::new(SessionRegistry::new());
406        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
407        let sink = SessionToolEventSink::new(Arc::clone(&registry), session.id.clone());
408        let mut events = crate::events::subscribe();
409
410        sink.agent_message("pm", "pm-1", "turn-1", "hello there", true)
411            .await;
412
413        let ev = next_event_for(&mut events, &session.id).await;
414        assert_eq!(ev.kind, "agent_message_delta");
415        assert!(matches!(
416            ev.event,
417            crate::events::Event::AgentMessageDelta { agent, agent_id, turn_id, delta, done, .. }
418                if agent == "pm" && agent_id == "pm-1" && turn_id == "turn-1"
419                    && delta == "hello there" && done
420        ));
421    }
422}