trusty_agents_common/events/bus.rs
1//! Process-global event bus, the `HarnessEvent` envelope, and the
2//! lagged-receiver helper for the unified 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. The envelope wraps the per-domain
9//! payload with cross-cutting metadata (source, session, monotonic seq,
10//! timestamp) so any subscriber can order, correlate, and route events
11//! without inspecting the payload.
12//! What: Defines `HarnessPayload` (the domain-tagged inner union),
13//! `HarnessEvent` (the envelope), the process-global `EVENT_BUS`, a
14//! monotonic `SEQ` counter, `bus`/`subscribe`/`publish`/`emit` helpers,
15//! the `__OMPM_EVENT__` stderr relay prefix, and a `Lag` notice with
16//! `recv_with_lag` so a lagged subscriber is told how many events it
17//! skipped and can resume instead of tearing down its stream. A closed
18//! channel ends that stream with the terminal `BusClosed` error.
19//! Test: `super::tests` covers serde round-trips of each payload arm, seq
20//! monotonicity, lagged handling against a constructible test bus, and
21//! the emit-line formatting helper.
22
23use std::sync::OnceLock;
24use std::sync::atomic::{AtomicU64, Ordering};
25
26use chrono::{DateTime, Utc};
27use serde::{Deserialize, Serialize};
28use serde_json::Value;
29use tokio::sync::broadcast;
30
31use super::lifecycle::{HarnessSource, LifecycleEvent};
32
33/// Stderr line prefix used to relay events from a child process to its parent.
34///
35/// THE one declaration of this wire marker. `trusty_code::events` and
36/// `trusty_agents::events` re-export it rather than declaring their own, and
37/// the harness-understanding assets in this crate document this exact value —
38/// so the producer, the parent-side parser, and the session manager's
39/// instructions cannot drift apart (#5129).
40///
41/// Why: A harness may spawn workflow / agent work in a child process whose
42/// events must still reach the parent's bus. Reusing stderr as the IPC
43/// channel (the parent already reads child stderr) avoids inventing a new
44/// transport. A stable, unambiguous prefix lets the parent detect relay
45/// lines and re-publish them rather than mirroring them to the terminal.
46/// What: Match by exact byte prefix; the payload after the space is one JSON
47/// object decodable as the emitting crate's event envelope.
48/// Test: `super::tests::event_line_prefix_is_stable`,
49/// `super::tests::emit_line_has_prefix_and_parses`, and
50/// `crate::harness_doc::tests::harness_doc_names_the_relay_prefix`.
51// #5129: value is the one tcode and tagent have always written to stderr;
52// renaming the producers would break parent/child relay across binary versions.
53pub const EVENT_LINE_PREFIX: &str = "__OMPM_EVENT__ ";
54
55/// Broadcast channel capacity for the global bus.
56///
57/// Why: Event volume is high (every PM thought, every agent line, every tool
58/// call). 1024 keeps memory bounded (~256 KB at 256 bytes/event) while
59/// tolerating slow subscribers without dropping recent events under
60/// typical load. A subscriber that still falls behind receives a `Lag`
61/// notice rather than silently losing the stream.
62/// What: Used both for the process-global bus and as the default for the
63/// test-only constructible bus.
64pub const CHANNEL_CAPACITY: usize = 1024;
65
66/// Domain-tagged inner union carried inside a `HarnessEvent`.
67///
68/// Why: The "adapt, don't fold" decision (ADR-0005): rather than flattening
69/// lifecycle, hook, and keepalive events into one giant enum, we tag by
70/// *domain* so each harness can grow its own payload taxonomy
71/// independently. Hooks in particular are open-ended (arbitrary
72/// tool/event names + JSON data), so they get an untyped `Value` arm
73/// instead of being modelled variant-by-variant.
74/// What: `serde(tag = "domain", content = "event")` produces
75/// `{"domain":"lifecycle","event":{...}}`, `{"domain":"hook","event":
76/// {"kind":...,"data":...}}`, or `{"domain":"ping"}`. `Ping` is the
77/// transport keepalive (promoted out of the lifecycle enum).
78/// Test: `super::tests::payload_*_round_trips` assert the tag shape for each
79/// arm.
80#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
81#[serde(tag = "domain", content = "event", rename_all = "snake_case")]
82pub enum HarnessPayload {
83 /// A structured PM-lifecycle event (session/agent/tool/phase/LLM/...).
84 Lifecycle(LifecycleEvent),
85 /// An open-ended hook event: `kind` names the hook, `data` is its payload.
86 Hook { kind: String, data: Value },
87 /// Transport keepalive so long-lived SSE connections don't time out.
88 Ping,
89}
90
91impl HarnessPayload {
92 /// The domain string for this payload (`"lifecycle"`, `"hook"`, `"ping"`).
93 ///
94 /// Why: `Filter` matches on the domain without serialising the whole
95 /// payload; keeping the mapping here is the single source of truth.
96 /// What: Returns the same string serde uses for the `domain` tag.
97 /// Test: `super::tests::payload_domain_matches_serde_tag`.
98 pub fn domain(&self) -> &'static str {
99 match self {
100 HarnessPayload::Lifecycle(_) => "lifecycle",
101 HarnessPayload::Hook { .. } => "hook",
102 HarnessPayload::Ping => "ping",
103 }
104 }
105}
106
107/// Cross-harness event envelope: metadata + domain-tagged payload.
108///
109/// Why: Subscribers need to order (`seq`), time-stamp (`at`), attribute
110/// (`source`), and correlate (`session`) events uniformly, regardless of
111/// which harness produced them or which domain the payload belongs to.
112/// Carrying that metadata in the envelope keeps the payload taxonomies
113/// free of repeated bookkeeping fields.
114/// What: `source` is the originating harness; `session` is the optional task
115/// correlation key (omitted from JSON when `None`); `seq` is a
116/// process-monotonic counter; `at` is the emit-time UTC timestamp;
117/// `payload` is the domain-tagged union. All fields derive serde.
118/// Test: `super::tests::harness_event_round_trips` and the per-arm payload
119/// tests build full envelopes.
120#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
121pub struct HarnessEvent {
122 /// Which harness produced this event.
123 pub source: HarnessSource,
124 /// Optional task/session correlation key. Omitted from JSON when absent.
125 #[serde(default, skip_serializing_if = "Option::is_none")]
126 pub session: Option<String>,
127 /// Process-monotonic sequence number assigned at publish time.
128 pub seq: u64,
129 /// Emit-time UTC timestamp.
130 pub at: DateTime<Utc>,
131 /// Domain-tagged payload.
132 pub payload: HarnessPayload,
133}
134
135/// Notice that a subscriber fell behind and skipped `skipped` events.
136///
137/// Why: `broadcast::Receiver` returns `RecvError::Lagged(n)` and then resumes
138/// from the oldest still-buffered event. Silently swallowing that loses
139/// the "you missed N events" signal a UI needs to show a gap; tearing the
140/// stream down on lag is worse. Surfacing it as a typed value lets
141/// subscribers render a gap marker and keep going.
142/// What: A thin newtype-ish struct wrapping the skipped count, returned as the
143/// `Err` arm of `recv_with_lag`.
144/// Test: `super::tests::lagged_receiver_yields_lag_then_resumes`.
145#[derive(Debug, Clone, Copy, PartialEq, Eq)]
146pub struct Lag {
147 /// Number of events the receiver skipped past.
148 pub skipped: u64,
149}
150
151/// The channel behind a subscriber is closed: every sender is gone and the
152/// buffer is drained.
153///
154/// Why: `recv_with_lag` used to report this as `Err(())`, which names nothing
155/// at the call site and cannot carry a message into a log or an
156/// `anyhow` chain. A named unit error carries the same single fact and
157/// keeps the public signature off `clippy::result_unit_err`.
158/// What: Returned as the outer `Err` arm of `recv_with_lag`. Unlike `Lag`, it
159/// is terminal — calling again will not resume the stream, because the
160/// process-global `EVENT_BUS` sender only disappears when the whole bus
161/// does (in practice this is only reachable on a locally constructed
162/// channel, as in the tests).
163/// Test: `super::tests::recv_with_lag_reports_closed`.
164#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
165#[error("event channel closed: all senders dropped and the buffer is drained")]
166pub struct BusClosed;
167
168/// Process-global event bus, initialised on first access.
169///
170/// Why: Emit-from-anywhere telemetry without threading a sender through every
171/// signature. First access wins; all later accesses share the same sender.
172/// What: `Sender::send` is non-blocking; with no subscribers it returns an
173/// error which `publish` silently drops (no listeners is the baseline).
174static EVENT_BUS: OnceLock<broadcast::Sender<HarnessEvent>> = OnceLock::new();
175
176/// Process-monotonic sequence source for envelope `seq` assignment.
177///
178/// Why: Subscribers need a total order over events even when timestamps
179/// collide at sub-millisecond resolution. A single atomic counter gives a
180/// cheap, lock-free monotonic sequence shared across all emit sites.
181/// What: Incremented once per `publish`/`emit`; wraps after 2^64 events
182/// (practically never).
183static SEQ: AtomicU64 = AtomicU64::new(0);
184
185/// Get (or initialise) the process-global event bus sender.
186///
187/// Why: Called from any code path that wants to emit. Cheap on the hot path
188/// (single atomic load once initialised).
189/// What: Returns a clone of the global sender. Receivers are created per
190/// subscriber via `subscribe()`.
191/// Test: `super::tests::bus_is_singleton`.
192pub fn bus() -> broadcast::Sender<HarnessEvent> {
193 EVENT_BUS
194 .get_or_init(|| broadcast::channel(CHANNEL_CAPACITY).0)
195 .clone()
196}
197
198/// Subscribe to all future events on the global bus.
199///
200/// Why: Subscribers (relays, aggregators, future SSE handlers) each need their
201/// own `Receiver`; `broadcast::Receiver::recv` takes `&mut self`.
202/// What: Returns a fresh `Receiver` that begins receiving events emitted after
203/// the call returns.
204/// Test: `super::tests::publish_round_trips_through_subscribe`.
205pub fn subscribe() -> broadcast::Receiver<HarnessEvent> {
206 bus().subscribe()
207}
208
209/// Allocate the next monotonic sequence number.
210///
211/// Why: Centralising the counter keeps every emit site assigning sequence
212/// numbers from the same source.
213/// What: Fetch-adds the global `SEQ` with `Relaxed` ordering (only monotonic
214/// uniqueness is required, not cross-field synchronisation).
215fn next_seq() -> u64 {
216 SEQ.fetch_add(1, Ordering::Relaxed)
217}
218
219/// Build a fully-populated `HarnessEvent`, assigning `seq` and `at`.
220///
221/// Why: `publish` and `emit` both need to stamp the envelope identically; one
222/// helper avoids drift between the two paths.
223/// What: Allocates the next seq, reads `Utc::now()`, and assembles the envelope.
224/// Test: Exercised by `publish_round_trips_through_subscribe` (seq/at present).
225fn make_event(
226 source: HarnessSource,
227 session: Option<String>,
228 payload: HarnessPayload,
229) -> HarnessEvent {
230 HarnessEvent {
231 source,
232 session,
233 seq: next_seq(),
234 at: Utc::now(),
235 payload,
236 }
237}
238
239/// Publish one event to the global bus (best-effort, never panics).
240///
241/// Why: Events are telemetry, not control flow. Having no subscribers is the
242/// normal baseline, so a send failure is expected and dropped.
243/// What: Stamps the envelope (`seq`, `at`) via `make_event`, then sends on the
244/// broadcast channel, ignoring `SendError`. Returns the assigned `seq` so
245/// callers (and tests) can observe ordering.
246/// Test: `super::tests::publish_round_trips_through_subscribe`,
247/// `super::tests::seq_is_monotonic`.
248pub fn publish(source: HarnessSource, session: Option<String>, payload: HarnessPayload) -> u64 {
249 let event = make_event(source, session, payload);
250 let seq = event.seq;
251 let _ = bus().send(event);
252 seq
253}
254
255/// Publish an event AND emit it on stderr with the `EVENT_LINE_PREFIX` so a
256/// parent process can re-broadcast on its own bus.
257///
258/// Why: Child-process emit sites should not have to know whether they are
259/// running standalone or under a parent relay; doing both in one call
260/// keeps call sites uniform.
261/// What: Builds the envelope once, publishes it for in-process subscribers,
262/// then writes one NDJSON line to stderr prefixed with `EVENT_LINE_PREFIX`.
263/// Returns the assigned `seq`.
264/// Test: `super::tests::emit_line_has_prefix_and_parses` covers the line
265/// formatting via the shared `format_event_line` helper.
266pub fn emit(source: HarnessSource, session: Option<String>, payload: HarnessPayload) -> u64 {
267 let event = make_event(source, session, payload);
268 let seq = event.seq;
269 let line = format_event_line(&event);
270 let _ = bus().send(event);
271 if let Some(line) = line {
272 eprintln!("{line}");
273 }
274 seq
275}
276
277/// Format a single stderr relay line for `event`, or `None` if it cannot be
278/// serialised.
279///
280/// Why: Splitting the formatting out of `emit` makes the wire shape unit-
281/// testable without capturing real stderr.
282/// What: Returns `EVENT_LINE_PREFIX` concatenated with the compact JSON of the
283/// envelope; `None` only on the (practically impossible) serde failure.
284/// Test: `super::tests::emit_line_has_prefix_and_parses`.
285pub fn format_event_line(event: &HarnessEvent) -> Option<String> {
286 serde_json::to_string(event)
287 .ok()
288 .map(|json| format!("{EVENT_LINE_PREFIX}{json}"))
289}
290
291/// Receive the next event, translating broadcast lag into a typed `Lag`.
292///
293/// Why: Raw `broadcast::Receiver::recv` returns `RecvError::Lagged(n)` and then
294/// `RecvError::Closed`; a subscriber that wants to keep going needs the
295/// lag count surfaced as data, not an opaque error it must re-interpret at
296/// every call site. This helper does that translation once.
297/// What: On a successful receive returns `Ok(Ok(event))`; on lag returns
298/// `Ok(Err(Lag { skipped }))` (the stream is still alive — call again to
299/// resume); on a closed channel returns `Err(BusClosed)`.
300/// Test: `super::tests::lagged_receiver_yields_lag_then_resumes`,
301/// `super::tests::recv_with_lag_reports_closed`.
302pub async fn recv_with_lag(
303 rx: &mut broadcast::Receiver<HarnessEvent>,
304) -> Result<Result<HarnessEvent, Lag>, BusClosed> {
305 match rx.recv().await {
306 Ok(event) => Ok(Ok(event)),
307 Err(broadcast::error::RecvError::Lagged(n)) => Ok(Err(Lag { skipped: n })),
308 Err(broadcast::error::RecvError::Closed) => Err(BusClosed),
309 }
310}