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
//! Process-global event bus, the `HarnessEvent` envelope, 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. The envelope wraps the per-domain
//! payload with cross-cutting metadata (source, session, monotonic seq,
//! timestamp) so any subscriber can order, correlate, and route events
//! without inspecting the payload.
//! What: Defines `HarnessPayload` (the domain-tagged inner union),
//! `HarnessEvent` (the envelope), the process-global `EVENT_BUS`, a
//! monotonic `SEQ` counter, `bus`/`subscribe`/`publish`/`emit` helpers,
//! the `__HARNESS_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.
//! Test: `super::tests` covers serde round-trips of each payload arm, seq
//! monotonicity, lagged handling against a constructible test bus, and
//! the emit-line formatting helper.
use OnceLock;
use ;
use ;
use ;
use Value;
use broadcast;
use ;
/// Stderr line prefix used to relay events from a child process to its parent.
///
/// 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 `HarnessEvent`.
/// Test: `super::tests::event_line_prefix_is_stable` and
/// `super::tests::emit_line_has_prefix_and_parses`.
pub const EVENT_LINE_PREFIX: &str = "__HARNESS_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;
/// Domain-tagged inner union carried inside a `HarnessEvent`.
///
/// Why: The "adapt, don't fold" decision (ADR-0005): rather than flattening
/// lifecycle, hook, and keepalive events into one giant enum, we tag by
/// *domain* so each harness can grow its own payload taxonomy
/// independently. Hooks in particular are open-ended (arbitrary
/// tool/event names + JSON data), so they get an untyped `Value` arm
/// instead of being modelled variant-by-variant.
/// What: `serde(tag = "domain", content = "event")` produces
/// `{"domain":"lifecycle","event":{...}}`, `{"domain":"hook","event":
/// {"kind":...,"data":...}}`, or `{"domain":"ping"}`. `Ping` is the
/// transport keepalive (promoted out of the lifecycle enum).
/// Test: `super::tests::payload_*_round_trips` assert the tag shape for each
/// arm.
/// Cross-harness event envelope: metadata + domain-tagged payload.
///
/// Why: Subscribers need to order (`seq`), time-stamp (`at`), attribute
/// (`source`), and correlate (`session`) events uniformly, regardless of
/// which harness produced them or which domain the payload belongs to.
/// Carrying that metadata in the envelope keeps the payload taxonomies
/// free of repeated bookkeeping fields.
/// What: `source` is the originating harness; `session` is the optional task
/// correlation key (omitted from JSON when `None`); `seq` is a
/// process-monotonic counter; `at` is the emit-time UTC timestamp;
/// `payload` is the domain-tagged union. All fields derive serde.
/// Test: `super::tests::harness_event_round_trips` and the per-arm payload
/// tests build full envelopes.
/// 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`.
/// 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(())`.
/// Test: `super::tests::lagged_receiver_yields_lag_then_resumes`.
pub async