trusty_agents_common/events/bus.rs
1//! Process-global event bus and the lagged-receiver helper for the unified
2//! harness event stream (ADR-0005).
3//!
4//! Why: Threading a `broadcast::Sender<HarnessEvent>` through every code path
5//! that might emit telemetry (workflow engine, agent runners, hooks,
6//! ctrl) would touch hundreds of function signatures. A `OnceLock` mirrors
7//! how `tracing` solves the same problem — emit-from-anywhere with zero
8//! overhead when no one is listening.
9//! What: Defines the process-global `EVENT_BUS`, a monotonic `SEQ` counter,
10//! `bus`/`subscribe`/`publish`/`emit` helpers, the `__OMPM_EVENT__`
11//! stderr relay prefix, and a `Lag` notice with `recv_with_lag` so a
12//! lagged subscriber is told how many events it skipped and can resume
13//! instead of tearing down its stream. A closed channel ends that stream
14//! with the terminal `BusClosed` error. The envelope this transports —
15//! `HarnessEvent`, `HarnessPayload`, and the lifecycle taxonomy — lives
16//! in `trusty_common::control_bus`.
17//! Test: `super::tests` covers seq monotonicity, lagged handling against a
18//! constructible test bus, and the emit-line formatting helper.
19
20// #6846: the envelope and lifecycle/filter TYPES moved to
21// `trusty_common::control_bus`; this file keeps the transport that moves them.
22// The in-process channel itself is removed in slice 9 (#6854).
23
24use std::sync::OnceLock;
25use std::sync::atomic::{AtomicU64, Ordering};
26
27use chrono::Utc;
28use tokio::sync::broadcast;
29use trusty_common::control_bus::{EventId, HarnessEvent, HarnessPayload, HarnessSource};
30
31/// Stderr line prefix used to relay events from a child process to its parent.
32///
33/// THE one declaration of this wire marker. `trusty_code::events` and
34/// `trusty_agents::events` re-export it rather than declaring their own, and
35/// the harness-understanding assets in this crate document this exact value —
36/// so the producer, the parent-side parser, and the session manager's
37/// instructions cannot drift apart (#5129).
38///
39/// Why: A harness may spawn workflow / agent work in a child process whose
40/// events must still reach the parent's bus. Reusing stderr as the IPC
41/// channel (the parent already reads child stderr) avoids inventing a new
42/// transport. A stable, unambiguous prefix lets the parent detect relay
43/// lines and re-publish them rather than mirroring them to the terminal.
44/// What: Match by exact byte prefix; the payload after the space is one JSON
45/// object decodable as the emitting crate's event envelope.
46/// Test: `super::tests::event_line_prefix_is_stable`,
47/// `super::tests::emit_line_has_prefix_and_parses`, and
48/// `crate::harness_doc::tests::harness_doc_names_the_relay_prefix`.
49// #5129: value is the one tcode and tagent have always written to stderr;
50// renaming the producers would break parent/child relay across binary versions.
51pub const EVENT_LINE_PREFIX: &str = "__OMPM_EVENT__ ";
52
53/// Broadcast channel capacity for the global bus.
54///
55/// Why: Event volume is high (every PM thought, every agent line, every tool
56/// call). 1024 keeps memory bounded (~256 KB at 256 bytes/event) while
57/// tolerating slow subscribers without dropping recent events under
58/// typical load. A subscriber that still falls behind receives a `Lag`
59/// notice rather than silently losing the stream.
60/// What: Used both for the process-global bus and as the default for the
61/// test-only constructible bus.
62pub const CHANNEL_CAPACITY: usize = 1024;
63
64/// Notice that a subscriber fell behind and skipped `skipped` events.
65///
66/// Why: `broadcast::Receiver` returns `RecvError::Lagged(n)` and then resumes
67/// from the oldest still-buffered event. Silently swallowing that loses
68/// the "you missed N events" signal a UI needs to show a gap; tearing the
69/// stream down on lag is worse. Surfacing it as a typed value lets
70/// subscribers render a gap marker and keep going.
71/// What: A thin newtype-ish struct wrapping the skipped count, returned as the
72/// `Err` arm of `recv_with_lag`.
73/// Test: `super::tests::lagged_receiver_yields_lag_then_resumes`.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub struct Lag {
76 /// Number of events the receiver skipped past.
77 pub skipped: u64,
78}
79
80/// The channel behind a subscriber is closed: every sender is gone and the
81/// buffer is drained.
82///
83/// Why: `recv_with_lag` used to report this as `Err(())`, which names nothing
84/// at the call site and cannot carry a message into a log or an
85/// `anyhow` chain. A named unit error carries the same single fact and
86/// keeps the public signature off `clippy::result_unit_err`.
87/// What: Returned as the outer `Err` arm of `recv_with_lag`. Unlike `Lag`, it
88/// is terminal — calling again will not resume the stream, because the
89/// process-global `EVENT_BUS` sender only disappears when the whole bus
90/// does (in practice this is only reachable on a locally constructed
91/// channel, as in the tests).
92/// Test: `super::tests::recv_with_lag_reports_closed`.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
94#[error("event channel closed: all senders dropped and the buffer is drained")]
95pub struct BusClosed;
96
97/// Process-global event bus, initialised on first access.
98///
99/// Why: Emit-from-anywhere telemetry without threading a sender through every
100/// signature. First access wins; all later accesses share the same sender.
101/// What: `Sender::send` is non-blocking; with no subscribers it returns an
102/// error which `publish` silently drops (no listeners is the baseline).
103static EVENT_BUS: OnceLock<broadcast::Sender<HarnessEvent>> = OnceLock::new();
104
105/// Process-monotonic sequence source for envelope `seq` assignment.
106///
107/// Why: Subscribers need a total order over events even when timestamps
108/// collide at sub-millisecond resolution. A single atomic counter gives a
109/// cheap, lock-free monotonic sequence shared across all emit sites.
110/// What: Incremented once per `publish`/`emit`; wraps after 2^64 events
111/// (practically never).
112static SEQ: AtomicU64 = AtomicU64::new(0);
113
114/// Get (or initialise) the process-global event bus sender.
115///
116/// Why: Called from any code path that wants to emit. Cheap on the hot path
117/// (single atomic load once initialised).
118/// What: Returns a clone of the global sender. Receivers are created per
119/// subscriber via `subscribe()`.
120/// Test: `super::tests::bus_is_singleton`.
121pub fn bus() -> broadcast::Sender<HarnessEvent> {
122 EVENT_BUS
123 .get_or_init(|| broadcast::channel(CHANNEL_CAPACITY).0)
124 .clone()
125}
126
127/// Subscribe to all future events on the global bus.
128///
129/// Why: Subscribers (relays, aggregators, future SSE handlers) each need their
130/// own `Receiver`; `broadcast::Receiver::recv` takes `&mut self`.
131/// What: Returns a fresh `Receiver` that begins receiving events emitted after
132/// the call returns.
133/// Test: `super::tests::publish_round_trips_through_subscribe`.
134pub fn subscribe() -> broadcast::Receiver<HarnessEvent> {
135 bus().subscribe()
136}
137
138/// Allocate the next monotonic sequence number.
139///
140/// Why: Centralising the counter keeps every emit site assigning sequence
141/// numbers from the same source.
142/// What: Fetch-adds the global `SEQ` with `Relaxed` ordering (only monotonic
143/// uniqueness is required, not cross-field synchronisation).
144fn next_seq() -> u64 {
145 SEQ.fetch_add(1, Ordering::Relaxed)
146}
147
148/// Build a fully-populated `HarnessEvent`, assigning `seq`, `at`, and `id`.
149///
150/// Why: `publish` and `emit` both need to stamp the envelope identically; one
151/// helper avoids drift between the two paths.
152/// What: Allocates the next seq, reads `Utc::now()`, mints a fresh `EventId`
153/// (DOC-73 §3.1 — "minted by the emitting process"), and assembles the
154/// envelope. `parent_id` is `None`: threading real causal context
155/// through this crate's emit sites is DOC-73 §9 Phase 3 / future work
156/// (issue #6847 lands the envelope fields only), so every event this
157/// function builds today is a root.
158/// Test: Exercised by `publish_round_trips_through_subscribe` (seq/at/id
159/// present).
160fn make_event(
161 source: HarnessSource,
162 session: Option<String>,
163 payload: HarnessPayload,
164) -> HarnessEvent {
165 HarnessEvent {
166 source,
167 session,
168 seq: next_seq(),
169 at: Utc::now(),
170 payload,
171 id: EventId::new(),
172 parent_id: None,
173 }
174}
175
176/// Publish one event to the global bus (best-effort, never panics).
177///
178/// Why: Events are telemetry, not control flow. Having no subscribers is the
179/// normal baseline, so a send failure is expected and dropped.
180/// What: Stamps the envelope (`seq`, `at`) via `make_event`, then sends on the
181/// broadcast channel, ignoring `SendError`. Returns the assigned `seq` so
182/// callers (and tests) can observe ordering.
183/// Test: `super::tests::publish_round_trips_through_subscribe`,
184/// `super::tests::seq_is_monotonic`.
185pub fn publish(source: HarnessSource, session: Option<String>, payload: HarnessPayload) -> u64 {
186 let event = make_event(source, session, payload);
187 let seq = event.seq;
188 let _ = bus().send(event);
189 seq
190}
191
192/// Publish an event AND emit it on stderr with the `EVENT_LINE_PREFIX` so a
193/// parent process can re-broadcast on its own bus.
194///
195/// Why: Child-process emit sites should not have to know whether they are
196/// running standalone or under a parent relay; doing both in one call
197/// keeps call sites uniform.
198/// What: Builds the envelope once, publishes it for in-process subscribers,
199/// then writes one NDJSON line to stderr prefixed with `EVENT_LINE_PREFIX`.
200/// Returns the assigned `seq`.
201/// Test: `super::tests::emit_line_has_prefix_and_parses` covers the line
202/// formatting via the shared `format_event_line` helper.
203pub fn emit(source: HarnessSource, session: Option<String>, payload: HarnessPayload) -> u64 {
204 let event = make_event(source, session, payload);
205 let seq = event.seq;
206 let line = format_event_line(&event);
207 let _ = bus().send(event);
208 if let Some(line) = line {
209 eprintln!("{line}");
210 }
211 seq
212}
213
214/// Format a single stderr relay line for `event`, or `None` if it cannot be
215/// serialised.
216///
217/// Why: Splitting the formatting out of `emit` makes the wire shape unit-
218/// testable without capturing real stderr.
219/// What: Returns `EVENT_LINE_PREFIX` concatenated with the compact JSON of the
220/// envelope; `None` only on the (practically impossible) serde failure.
221/// Test: `super::tests::emit_line_has_prefix_and_parses`.
222pub fn format_event_line(event: &HarnessEvent) -> Option<String> {
223 serde_json::to_string(event)
224 .ok()
225 .map(|json| format!("{EVENT_LINE_PREFIX}{json}"))
226}
227
228/// Receive the next event, translating broadcast lag into a typed `Lag`.
229///
230/// Why: Raw `broadcast::Receiver::recv` returns `RecvError::Lagged(n)` and then
231/// `RecvError::Closed`; a subscriber that wants to keep going needs the
232/// lag count surfaced as data, not an opaque error it must re-interpret at
233/// every call site. This helper does that translation once.
234/// What: On a successful receive returns `Ok(Ok(event))`; on lag returns
235/// `Ok(Err(Lag { skipped }))` (the stream is still alive — call again to
236/// resume); on a closed channel returns `Err(BusClosed)`.
237/// Test: `super::tests::lagged_receiver_yields_lag_then_resumes`,
238/// `super::tests::recv_with_lag_reports_closed`.
239pub async fn recv_with_lag(
240 rx: &mut broadcast::Receiver<HarnessEvent>,
241) -> Result<Result<HarnessEvent, Lag>, BusClosed> {
242 match rx.recv().await {
243 Ok(event) => Ok(Ok(event)),
244 Err(broadcast::error::RecvError::Lagged(n)) => Ok(Err(Lag { skipped: n })),
245 Err(broadcast::error::RecvError::Closed) => Err(BusClosed),
246 }
247}