trusty-code 0.8.2

Per-project Claude-Code-compatible MPM orchestration harness (bin: tcode) — an original coding harness, tracked under epic #2052.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! Concrete `ToolEventSink` forwarding tool-dispatch hooks to
//! `SessionRegistry::record_tool_*` (#2056).
//!
//! Why: #2055 built the emission plumbing; #2056's `agent_loop` extension
//! built the hook (`agent_loop::ToolEventSink`) that CAN call it. This is the
//! small piece of glue that actually wires the two together for a specific
//! session, kept in `task` (the daemon-execution layer) rather than
//! `agent_loop` (the generic engine) or `session` (which must not depend
//! upward on the engine) — see `agent_loop::sink`'s module docs for the
//! layering rationale.
//! What: [`SessionToolEventSink`] holds an `Arc<SessionRegistry>` and the
//! target `session_id`; each hook forwards to the matching `record_tool_*`
//! call, logging (not propagating — the sink trait's methods return `()`)
//! any failure, which in practice only happens if the session vanished
//! mid-run (e.g. a race with daemon shutdown).
//! Test: `task::sink::tests::*`.

use std::sync::Arc;

use async_trait::async_trait;

use crate::agent_loop::{ContextBudgetSnapshot, ToolEventSink};
use crate::session::SessionRegistry;
use crate::tools::telemetry::ToolTelemetry;

/// Forwards `AgentLoop` tool-dispatch hooks to a specific session's
/// `SessionRegistry::record_tool_*` calls (#2056).
///
/// Why: the seam that makes a daemon-driven run's tool activity observable
/// to a `session.attach`ed client, over both the PM's own loop and any
/// delegated sub-agent loop that shares this same `Arc`.
/// What: See module docs.
/// Test: `task::sink::tests::forwards_started_finished_and_error`.
pub struct SessionToolEventSink {
    registry: Arc<SessionRegistry>,
    session_id: String,
}

impl SessionToolEventSink {
    /// Build a sink targeting `session_id` on `registry`.
    pub fn new(registry: Arc<SessionRegistry>, session_id: impl Into<String>) -> Self {
        Self {
            registry,
            session_id: session_id.into(),
        }
    }
}

#[async_trait]
impl ToolEventSink for SessionToolEventSink {
    async fn tool_started(
        &self,
        agent: &str,
        agent_id: &str,
        call_id: &str,
        tool: &str,
        args_preview: &str,
    ) {
        if let Err(e) = self.registry.record_tool_started(
            &self.session_id,
            agent,
            agent_id,
            tool,
            call_id,
            args_preview,
        ) {
            tracing::warn!(session_id = %self.session_id, agent, agent_id, tool, call_id, "record_tool_started failed: {e}");
        }
    }

    async fn tool_finished(
        &self,
        agent: &str,
        agent_id: &str,
        call_id: &str,
        tool: &str,
        success: bool,
        result_preview: &str,
    ) {
        if let Err(e) = self.registry.record_tool_finished(
            &self.session_id,
            agent,
            agent_id,
            tool,
            call_id,
            success,
            result_preview,
        ) {
            tracing::warn!(session_id = %self.session_id, agent, agent_id, tool, call_id, "record_tool_finished failed: {e}");
        }
    }

    async fn tool_error(
        &self,
        agent: &str,
        agent_id: &str,
        call_id: &str,
        tool: &str,
        error: &str,
    ) {
        if let Err(e) =
            self.registry
                .record_tool_error(&self.session_id, agent, agent_id, tool, call_id, error)
        {
            tracing::warn!(session_id = %self.session_id, agent, agent_id, tool, call_id, "record_tool_error failed: {e}");
        }
    }

    /// Fan a tool's structured telemetry out to the matching #UI-Phase-1
    /// `record_*` call.
    ///
    /// Why: the variant-to-record mapping belongs here, in the daemon-glue
    /// layer, rather than in `agent_loop` (which must not know about
    /// `SessionRegistry`) or in the tools (which must not know about
    /// sessions at all).
    /// What: same log-and-swallow contract as the hooks above — a vanished
    /// session must never derail a run.
    /// Test: `tests::forwards_search_and_recall_telemetry`.
    async fn tool_telemetry(
        &self,
        agent: &str,
        agent_id: &str,
        call_id: &str,
        tool: &str,
        telemetry: &ToolTelemetry,
    ) {
        let recorded = match telemetry {
            ToolTelemetry::Search(t) => {
                self.registry
                    .record_search_performed(&self.session_id, agent, agent_id, t)
            }
            ToolTelemetry::Recall(t) => {
                self.registry
                    .record_memory_recalled(&self.session_id, agent, agent_id, t)
            }
        };
        if let Err(e) = recorded {
            tracing::warn!(session_id = %self.session_id, agent, agent_id, tool, call_id, "record tool telemetry failed: {e}");
        }
    }

    /// Forward the per-turn working-context measurement to this session's
    /// event stream (epic #2343). Same log-and-swallow contract as the tool
    /// hooks above: a vanished session must never fault the PM's turn
    /// boundary — telemetry is not worth failing the work it observes.
    async fn context_budget(&self, snapshot: &ContextBudgetSnapshot) {
        if let Err(e) = self
            .registry
            .record_context_budget(&self.session_id, snapshot)
        {
            tracing::warn!(session_id = %self.session_id, "record_context_budget failed: {e}");
        }
    }

    /// Forward one assistant turn's text to this session's event stream
    /// (tcode streaming epic #3696, Gap A, Slice 1). Same log-and-swallow
    /// contract as the hooks above: a vanished session must never fault the
    /// loop that observed the turn.
    /// Test: `tests::agent_message_reaches_stream_as_delta`.
    async fn agent_message(
        &self,
        agent: &str,
        agent_id: &str,
        turn_id: &str,
        delta: &str,
        done: bool,
    ) {
        if let Err(e) = self.registry.record_agent_message_delta(
            &self.session_id,
            agent,
            agent_id,
            turn_id,
            delta,
            done,
        ) {
            tracing::warn!(session_id = %self.session_id, agent, agent_id, turn_id, "record_agent_message_delta failed: {e}");
        }
    }

    /// Forward a delegation starting to this session's event stream (#7940).
    /// Same log-and-swallow contract as the hooks above: a vanished session
    /// must never fault the delegation it observes.
    /// Test: `tests::forwards_agent_lifecycle`.
    async fn agent_spawned(&self, agent: &str, agent_id: &str, task_preview: &str) {
        if let Err(e) =
            self.registry
                .record_agent_spawned(&self.session_id, agent, agent_id, task_preview)
        {
            tracing::warn!(session_id = %self.session_id, agent, agent_id, "record_agent_spawned failed: {e}");
        }
    }

    /// Forward a delegation finishing normally (#7940). See
    /// [`Self::agent_spawned`].
    async fn agent_done(&self, agent: &str, agent_id: &str, status: &str) {
        if let Err(e) = self
            .registry
            .record_agent_done(&self.session_id, agent, agent_id, status)
        {
            tracing::warn!(session_id = %self.session_id, agent, agent_id, "record_agent_done failed: {e}");
        }
    }

    /// Forward a delegation aborting (#7940). See [`Self::agent_spawned`].
    async fn agent_failed(&self, agent: &str, agent_id: &str, error: &str) {
        if let Err(e) = self
            .registry
            .record_agent_failed(&self.session_id, agent, agent_id, error)
        {
            tracing::warn!(session_id = %self.session_id, agent, agent_id, "record_agent_failed failed: {e}");
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::sync::broadcast;

    /// Read the process-global event bus until an envelope matching
    /// `session_id` arrives (mirrors `session::registry::registry_tests`'
    /// helper — the global bus is shared across the whole test binary).
    async fn next_event_for(
        rx: &mut broadcast::Receiver<crate::events::SessionEventEnvelope>,
        session_id: &str,
    ) -> crate::events::SessionEventEnvelope {
        tokio::time::timeout(std::time::Duration::from_secs(2), async {
            loop {
                let envelope = rx.recv().await.expect("event bus closed unexpectedly");
                if envelope.session_id == session_id {
                    return envelope;
                }
            }
        })
        .await
        .expect("timed out waiting for an event on this session")
    }

    /// Each hook must forward to the matching `record_tool_*` call and
    /// publish the corresponding #2055 event kind, carrying the agent it was
    /// called with (UI Phase 1).
    #[tokio::test]
    async fn forwards_started_finished_and_error() {
        let registry = Arc::new(SessionRegistry::new());
        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
        let sink = SessionToolEventSink::new(Arc::clone(&registry), session.id.clone());
        let mut events = crate::events::subscribe();

        sink.tool_started("pm", "pm-1", "call-1", "bash", "echo hi")
            .await;
        let ev = next_event_for(&mut events, &session.id).await;
        assert_eq!(ev.kind, "tool_started");
        assert!(matches!(
            ev.event,
            crate::events::Event::ToolStarted { agent, agent_id, .. }
                if agent == "pm" && agent_id == "pm-1"
        ));

        sink.tool_finished("pm", "pm-1", "call-1", "bash", true, "hi")
            .await;
        let ev = next_event_for(&mut events, &session.id).await;
        assert_eq!(ev.kind, "tool_finished");

        sink.tool_error("pm", "pm-1", "call-1", "bash", "boom")
            .await;
        let ev = next_event_for(&mut events, &session.id).await;
        assert_eq!(ev.kind, "tool_error");
    }

    /// ONE shared sink instance must attribute events to whichever agent
    /// calls it (UI Phase 1).
    ///
    /// Why: this is the whole reason `agent` is a per-call PARAMETER rather
    /// than sink state — `task::executor::run_and_record` clones ONE `Arc` of
    /// this sink into both the PM's loop and the delegated engineer's runner.
    /// A sink that carried its own agent name could only ever report one of
    /// them, leaving the two indistinguishable on the stream.
    #[tokio::test]
    async fn one_shared_sink_attributes_each_caller_separately() {
        let registry = Arc::new(SessionRegistry::new());
        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
        let sink: Arc<dyn ToolEventSink> = Arc::new(SessionToolEventSink::new(
            Arc::clone(&registry),
            session.id.clone(),
        ));
        // Two clones of the ONE Arc, exactly as production wires it.
        let pm_view = Arc::clone(&sink);
        let engineer_view = Arc::clone(&sink);
        let mut events = crate::events::subscribe();

        pm_view
            .tool_started("pm", "pm-session-1", "c1", "delegate_to_agent", "{}")
            .await;
        let ev = next_event_for(&mut events, &session.id).await;
        assert!(matches!(
            ev.event,
            crate::events::Event::ToolStarted { agent, agent_id, .. }
                if agent == "pm" && agent_id == "pm-session-1"
        ));

        engineer_view
            .tool_started("python-engineer", "eng-spawn-7", "c2", "bash", "cargo test")
            .await;
        let ev = next_event_for(&mut events, &session.id).await;
        assert!(
            matches!(ev.event, crate::events::Event::ToolStarted { agent, agent_id, .. }
                if agent == "python-engineer" && agent_id == "eng-spawn-7"),
            "a shared sink must report the CALLER's agent AND agent_id, not one fixed pair \
             (DOC-39 AC-13)"
        );
    }

    /// `tool_telemetry` must fan each variant out to its matching structured
    /// event (UI Phase 1).
    #[tokio::test]
    async fn forwards_search_and_recall_telemetry() {
        let registry = Arc::new(SessionRegistry::new());
        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
        let sink = SessionToolEventSink::new(Arc::clone(&registry), session.id.clone());
        let mut events = crate::events::subscribe();

        sink.tool_telemetry(
            "python-engineer",
            "eng-1",
            "c1",
            "search_code",
            &ToolTelemetry::Search(crate::tools::SearchTelemetry {
                lane: "lexical".to_string(),
                query: "q".to_string(),
                hit_count: Some(2),
                hits: vec![],
                latency_ms: 5,
            }),
        )
        .await;
        let ev = next_event_for(&mut events, &session.id).await;
        assert_eq!(ev.kind, "search_performed");
        assert!(
            matches!(ev.event, crate::events::Event::SearchPerformed { agent, agent_id, lane, .. }
                if agent == "python-engineer" && agent_id == "eng-1" && lane == "lexical")
        );

        sink.tool_telemetry(
            "pm",
            "pm-1",
            "c2",
            "recall_session",
            &ToolTelemetry::Recall(crate::tools::RecallTelemetry {
                query: "q".to_string(),
                results: vec![crate::events::RecalledMemory {
                    score: 0.4,
                    injected: false,
                    text: "held back".to_string(),
                    run_id: None,
                }],
            }),
        )
        .await;
        let ev = next_event_for(&mut events, &session.id).await;
        assert_eq!(ev.kind, "memory_recalled");
        assert!(matches!(
            ev.event,
            crate::events::Event::MemoryRecalled { agent, agent_id, .. }
                if agent == "pm" && agent_id == "pm-1"
        ));
    }

    /// Hooks against an unknown session must not panic (they log and
    /// swallow the `session_not_found` error — the sink trait is `()`-only).
    #[tokio::test]
    async fn unknown_session_does_not_panic() {
        let registry = Arc::new(SessionRegistry::new());
        let sink = SessionToolEventSink::new(registry, "does-not-exist".to_string());
        sink.tool_started("pm", "pm-1", "c", "bash", "x").await;
        sink.tool_finished("pm", "pm-1", "c", "bash", true, "x")
            .await;
        sink.tool_error("pm", "pm-1", "c", "bash", "x").await;
        sink.tool_telemetry(
            "pm",
            "pm-1",
            "c",
            "search_code",
            &ToolTelemetry::Search(crate::tools::SearchTelemetry {
                lane: "semantic".to_string(),
                query: "q".to_string(),
                hit_count: None,
                hits: vec![],
                latency_ms: 1,
            }),
        )
        .await;
        sink.context_budget(&budget_snapshot()).await;
        sink.agent_message("pm", "pm-1", "turn-1", "x", true).await;
        sink.agent_spawned("engineer", "eng-1", "t").await;
        sink.agent_done("engineer", "eng-1", "success").await;
        sink.agent_failed("engineer", "eng-1", "boom").await;
    }

    /// The three delegation-lifecycle hooks must each reach the session's
    /// event stream as their matching event kind (#7940) — the brackets a
    /// TUI renders a delegation block from.
    #[tokio::test]
    async fn forwards_agent_lifecycle() {
        let registry = Arc::new(SessionRegistry::new());
        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
        let sink = SessionToolEventSink::new(Arc::clone(&registry), session.id.clone());
        let mut events = crate::events::subscribe();

        sink.agent_spawned("engineer", "eng-1", "build the thing")
            .await;
        let ev = next_event_for(&mut events, &session.id).await;
        assert_eq!(ev.kind, "agent_spawned");
        assert!(matches!(
            ev.event,
            crate::events::Event::AgentSpawned { agent, agent_id, task_preview, .. }
                if agent == "engineer" && agent_id == "eng-1"
                    && task_preview == "build the thing"
        ));

        sink.agent_done("engineer", "eng-1", "success").await;
        let ev = next_event_for(&mut events, &session.id).await;
        assert_eq!(ev.kind, "agent_done");
        assert!(matches!(
            ev.event,
            crate::events::Event::AgentDone { agent_id, status, .. }
                if agent_id == "eng-1" && status == "success"
        ));

        sink.agent_failed("engineer", "eng-2", "turn cap exceeded")
            .await;
        let ev = next_event_for(&mut events, &session.id).await;
        assert_eq!(ev.kind, "agent_failed");
        assert!(matches!(
            ev.event,
            crate::events::Event::AgentFailed { agent_id, error, .. }
                if agent_id == "eng-2" && error == "turn cap exceeded"
        ));
    }

    /// A representative budget snapshot for the sink tests.
    fn budget_snapshot() -> ContextBudgetSnapshot {
        ContextBudgetSnapshot {
            context_window: 200_000,
            overhead_tokens: 50_000,
            overhead_cap_tokens: 80_000,
            working_context_pct: 75,
            overhead_pct: 25,
            within_budget: true,
            fired: false,
            rounds: 1,
        }
    }

    /// The `context_budget` hook must reach the session's event stream as a
    /// `context_budget` event carrying the measured figures (epic #2343).
    ///
    /// Why: this is the last link in the chain that makes the Infinite
    /// Sessions guarantee renderable — `agent_loop` measures it, this sink is
    /// what binds it to a session and publishes it.
    #[tokio::test]
    async fn forwards_context_budget() {
        let registry = Arc::new(SessionRegistry::new());
        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
        let sink = SessionToolEventSink::new(Arc::clone(&registry), session.id.clone());
        let mut events = crate::events::subscribe();

        sink.context_budget(&budget_snapshot()).await;

        let ev = next_event_for(&mut events, &session.id).await;
        assert_eq!(ev.kind, "context_budget");
        assert!(matches!(
            ev.event,
            crate::events::Event::ContextBudget { working_context_pct, overhead_tokens, .. }
                if working_context_pct == 75 && overhead_tokens == 50_000
        ));
    }

    /// The `agent_message` hook must reach the session's event stream as an
    /// `agent_message_delta` event carrying the caller's attribution and
    /// text (tcode streaming epic #3696, Gap A, Slice 1).
    #[tokio::test]
    async fn agent_message_reaches_stream_as_delta() {
        let registry = Arc::new(SessionRegistry::new());
        let session = registry.create("t".to_string(), None, crate::binding::ProjectBinding::None);
        let sink = SessionToolEventSink::new(Arc::clone(&registry), session.id.clone());
        let mut events = crate::events::subscribe();

        sink.agent_message("pm", "pm-1", "turn-1", "hello there", true)
            .await;

        let ev = next_event_for(&mut events, &session.id).await;
        assert_eq!(ev.kind, "agent_message_delta");
        assert!(matches!(
            ev.event,
            crate::events::Event::AgentMessageDelta { agent, agent_id, turn_id, delta, done, .. }
                if agent == "pm" && agent_id == "pm-1" && turn_id == "turn-1"
                    && delta == "hello there" && done
        ));
    }
}