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
//! Process-global event bus and the lagged-receiver helper for the unified
//! harness event stream (ADR-0005).
//!
//! Why: Threading a `broadcast::Sender<HarnessEvent>` through every code path
//! that might emit telemetry (workflow engine, agent runners, hooks,
//! ctrl) would touch hundreds of function signatures. A `OnceLock` mirrors
//! how `tracing` solves the same problem — emit-from-anywhere with zero
//! overhead when no one is listening.
//! What: Defines the process-global `EVENT_BUS`, a monotonic `SEQ` counter,
//! `bus`/`subscribe`/`publish`/`emit` helpers, the `__OMPM_EVENT__`
//! stderr relay prefix, and a `Lag` notice with `recv_with_lag` so a
//! lagged subscriber is told how many events it skipped and can resume
//! instead of tearing down its stream. A closed channel ends that stream
//! with the terminal `BusClosed` error. The envelope this transports —
//! `HarnessEvent`, `HarnessPayload`, and the lifecycle taxonomy — lives
//! in `trusty_common::control_bus`.
//! Test: `super::tests` covers seq monotonicity, lagged handling against a
//! constructible test bus, and the emit-line formatting helper.
// #6846: the envelope and lifecycle/filter TYPES moved to
// `trusty_common::control_bus`; this file keeps the transport that moves them.
// The in-process channel itself is removed in slice 9 (#6854).
use OnceLock;
use ;
use Utc;
use broadcast;
use ;
/// Stderr line prefix used to relay events from a child process to its parent.
///
/// THE one declaration of this wire marker. `trusty_code::events` and
/// `trusty_agents::events` re-export it rather than declaring their own, and
/// the harness-understanding assets in this crate document this exact value —
/// so the producer, the parent-side parser, and the session manager's
/// instructions cannot drift apart (#5129).
///
/// Why: A harness may spawn workflow / agent work in a child process whose
/// events must still reach the parent's bus. Reusing stderr as the IPC
/// channel (the parent already reads child stderr) avoids inventing a new
/// transport. A stable, unambiguous prefix lets the parent detect relay
/// lines and re-publish them rather than mirroring them to the terminal.
/// What: Match by exact byte prefix; the payload after the space is one JSON
/// object decodable as the emitting crate's event envelope.
/// Test: `super::tests::event_line_prefix_is_stable`,
/// `super::tests::emit_line_has_prefix_and_parses`, and
/// `crate::harness_doc::tests::harness_doc_names_the_relay_prefix`.
// #5129: value is the one tcode and tagent have always written to stderr;
// renaming the producers would break parent/child relay across binary versions.
pub const EVENT_LINE_PREFIX: &str = "__OMPM_EVENT__ ";
/// Broadcast channel capacity for the global bus.
///
/// Why: Event volume is high (every PM thought, every agent line, every tool
/// call). 1024 keeps memory bounded (~256 KB at 256 bytes/event) while
/// tolerating slow subscribers without dropping recent events under
/// typical load. A subscriber that still falls behind receives a `Lag`
/// notice rather than silently losing the stream.
/// What: Used both for the process-global bus and as the default for the
/// test-only constructible bus.
pub const CHANNEL_CAPACITY: usize = 1024;
/// Notice that a subscriber fell behind and skipped `skipped` events.
///
/// Why: `broadcast::Receiver` returns `RecvError::Lagged(n)` and then resumes
/// from the oldest still-buffered event. Silently swallowing that loses
/// the "you missed N events" signal a UI needs to show a gap; tearing the
/// stream down on lag is worse. Surfacing it as a typed value lets
/// subscribers render a gap marker and keep going.
/// What: A thin newtype-ish struct wrapping the skipped count, returned as the
/// `Err` arm of `recv_with_lag`.
/// Test: `super::tests::lagged_receiver_yields_lag_then_resumes`.
/// The channel behind a subscriber is closed: every sender is gone and the
/// buffer is drained.
///
/// Why: `recv_with_lag` used to report this as `Err(())`, which names nothing
/// at the call site and cannot carry a message into a log or an
/// `anyhow` chain. A named unit error carries the same single fact and
/// keeps the public signature off `clippy::result_unit_err`.
/// What: Returned as the outer `Err` arm of `recv_with_lag`. Unlike `Lag`, it
/// is terminal — calling again will not resume the stream, because the
/// process-global `EVENT_BUS` sender only disappears when the whole bus
/// does (in practice this is only reachable on a locally constructed
/// channel, as in the tests).
/// Test: `super::tests::recv_with_lag_reports_closed`.
;
/// Process-global event bus, initialised on first access.
///
/// Why: Emit-from-anywhere telemetry without threading a sender through every
/// signature. First access wins; all later accesses share the same sender.
/// What: `Sender::send` is non-blocking; with no subscribers it returns an
/// error which `publish` silently drops (no listeners is the baseline).
static EVENT_BUS: = new;
/// Process-monotonic sequence source for envelope `seq` assignment.
///
/// Why: Subscribers need a total order over events even when timestamps
/// collide at sub-millisecond resolution. A single atomic counter gives a
/// cheap, lock-free monotonic sequence shared across all emit sites.
/// What: Incremented once per `publish`/`emit`; wraps after 2^64 events
/// (practically never).
static SEQ: AtomicU64 = new;
/// Get (or initialise) the process-global event bus sender.
///
/// Why: Called from any code path that wants to emit. Cheap on the hot path
/// (single atomic load once initialised).
/// What: Returns a clone of the global sender. Receivers are created per
/// subscriber via `subscribe()`.
/// Test: `super::tests::bus_is_singleton`.
/// Subscribe to all future events on the global bus.
///
/// Why: Subscribers (relays, aggregators, future SSE handlers) each need their
/// own `Receiver`; `broadcast::Receiver::recv` takes `&mut self`.
/// What: Returns a fresh `Receiver` that begins receiving events emitted after
/// the call returns.
/// Test: `super::tests::publish_round_trips_through_subscribe`.
/// Allocate the next monotonic sequence number.
///
/// Why: Centralising the counter keeps every emit site assigning sequence
/// numbers from the same source.
/// What: Fetch-adds the global `SEQ` with `Relaxed` ordering (only monotonic
/// uniqueness is required, not cross-field synchronisation).
/// Build a fully-populated `HarnessEvent`, assigning `seq` and `at`.
///
/// Why: `publish` and `emit` both need to stamp the envelope identically; one
/// helper avoids drift between the two paths.
/// What: Allocates the next seq, reads `Utc::now()`, and assembles the envelope.
/// Test: Exercised by `publish_round_trips_through_subscribe` (seq/at present).
/// Publish one event to the global bus (best-effort, never panics).
///
/// Why: Events are telemetry, not control flow. Having no subscribers is the
/// normal baseline, so a send failure is expected and dropped.
/// What: Stamps the envelope (`seq`, `at`) via `make_event`, then sends on the
/// broadcast channel, ignoring `SendError`. Returns the assigned `seq` so
/// callers (and tests) can observe ordering.
/// Test: `super::tests::publish_round_trips_through_subscribe`,
/// `super::tests::seq_is_monotonic`.
/// Publish an event AND emit it on stderr with the `EVENT_LINE_PREFIX` so a
/// parent process can re-broadcast on its own bus.
///
/// Why: Child-process emit sites should not have to know whether they are
/// running standalone or under a parent relay; doing both in one call
/// keeps call sites uniform.
/// What: Builds the envelope once, publishes it for in-process subscribers,
/// then writes one NDJSON line to stderr prefixed with `EVENT_LINE_PREFIX`.
/// Returns the assigned `seq`.
/// Test: `super::tests::emit_line_has_prefix_and_parses` covers the line
/// formatting via the shared `format_event_line` helper.
/// Format a single stderr relay line for `event`, or `None` if it cannot be
/// serialised.
///
/// Why: Splitting the formatting out of `emit` makes the wire shape unit-
/// testable without capturing real stderr.
/// What: Returns `EVENT_LINE_PREFIX` concatenated with the compact JSON of the
/// envelope; `None` only on the (practically impossible) serde failure.
/// Test: `super::tests::emit_line_has_prefix_and_parses`.
/// Receive the next event, translating broadcast lag into a typed `Lag`.
///
/// Why: Raw `broadcast::Receiver::recv` returns `RecvError::Lagged(n)` and then
/// `RecvError::Closed`; a subscriber that wants to keep going needs the
/// lag count surfaced as data, not an opaque error it must re-interpret at
/// every call site. This helper does that translation once.
/// What: On a successful receive returns `Ok(Ok(event))`; on lag returns
/// `Ok(Err(Lag { skipped }))` (the stream is still alive — call again to
/// resume); on a closed channel returns `Err(BusClosed)`.
/// Test: `super::tests::lagged_receiver_yields_lag_then_resumes`,
/// `super::tests::recv_with_lag_reports_closed`.
pub async