trusty_code/events.rs
1//! Process-wide event bus for real-time UI streaming (#192 Phase B; #2055
2//! formalises the session-attach envelope on top of it).
3//!
4//! Why: The 2-second stderr polling model from #149 is slow, lossy, and only
5//! handles workflow phase transitions. The UI needs immediate feedback on
6//! every PM thinking turn, every sub-agent message, every tool call — across
7//! both the in-process Axum server path AND the subprocess workflow path.
8//! A `tokio::sync::broadcast` channel exposed via a process-global `OnceLock`
9//! lets any code path emit events without threading the bus through dozens of
10//! function signatures, while SSE subscribers fan out to all browsers.
11//!
12//! #2055 adds [`SessionEventEnvelope`](crate::events::SessionEventEnvelope): every event the `session.attach`
13//! protocol (#2054) cares about is session-scoped, so the bus now carries the
14//! ENVELOPE (`session_id`, a per-session monotonic `seq`, a UTC timestamp,
15//! and the tagged [`Event`] payload) rather than a bare `Event`. This is the
16//! same "envelope wraps a domain-tagged payload" shape as
17//! `trusty-agents-common`'s `HarnessEvent`/`HarnessPayload` convention, with
18//! two deliberate divergences (documented on the struct itself): `seq` is
19//! PER-SESSION here (not process-global) because the session-attach
20//! replay->live continuity this ticket requires is scoped to one session's
21//! stream, and the payload stays a flat `#[serde(tag = "type")]` enum (not a
22//! nested `{domain, event}` wrapper) because #2054 already shipped that wire
23//! shape and rewriting it would break the shipped `session.attach` contract.
24//! `session::registry::SessionRegistry` is the sole assigner of `seq`
25//! (see its `record` method) since it already owns the per-session ring
26//! buffer this must stay consistent with.
27//!
28//! What: Defines the `Event` enum (the tagged payload), `SessionEventEnvelope`
29//! (the wire envelope), a process-global `EVENT_BUS` initialised lazily from
30//! any thread carrying envelopes, helpers to publish and subscribe, and a
31//! `__OMPM_EVENT__ <json>\n` stderr-relay protocol so events emitted by
32//! `--workflow` subprocesses can be re-broadcast by the parent API server.
33//! Test: see `events_tests` (sibling file, `#[cfg(test)]`) — `events::publish`
34//! round-trips through `subscribe()`, `kind()` is pinned against the serde tag
35//! for every variant, and the relay prefix is stable so the parent stderr
36//! reader can detect and re-publish.
37//!
38//! [`Event`]: crate::events::Event
39
40use std::sync::OnceLock;
41
42use chrono::{DateTime, Utc};
43use serde::{Deserialize, Serialize};
44use tokio::sync::broadcast;
45
46/// Stderr line prefix used to relay events from a workflow subprocess to its
47/// parent API server. The parent reads stderr line-by-line; lines starting
48/// with this prefix are parsed as `Event` JSON and re-published on the
49/// parent's event bus instead of being mirrored to terminal stderr.
50///
51/// Why: Workflow phase + agent telemetry must reach the API server even
52/// though the workflow runs in a child process. Reusing the same stderr
53/// channel that already carries `__OMPM_PROGRESS__` (the legacy 2s-poll
54/// path) avoids inventing yet another IPC mechanism.
55/// What: Match by exact byte prefix; payload after the space is one JSON
56/// object decodable as `Event`. Re-exported, not declared — the marker is a
57/// cross-crate wire format, so it has exactly one declaration, in
58/// `trusty_agents_common::events`, which the harness-understanding assets
59/// document and the session-manager prompt is built from.
60/// Test: `events_tests::event_line_prefix_is_stable` and
61/// `events_tests::sm_harness_doc_documents_the_prefix_tcode_emits`.
62// #5129: a second copy here is what let the documented marker drift off the
63// emitted one; a re-export makes that divergence impossible to write.
64pub use trusty_agents_common::events::EVENT_LINE_PREFIX;
65
66/// Capacity of the broadcast channel. Larger than `bus`'s 256 because event
67/// volume is much higher (every PM thought, every agent line). 1024 keeps
68/// memory bounded (~256KB at 256 bytes/event) while tolerating slow SSE
69/// subscribers without dropping recent events under typical load.
70const CHANNEL_CAPACITY: usize = 1024;
71
72/// The `agent` attribution value used when a tool event's `AgentLoop` was
73/// never told which agent it is running as (UI Phase 1).
74///
75/// Why: attribution is a builder opt-in (`AgentLoop::with_agent`), so a loop
76/// built by a caller that predates it — or by a test — still has to emit
77/// SOMETHING. An explicit, documented sentinel is strictly better than an
78/// empty string, which a UI would render as a blank agent chip and could not
79/// tell apart from a genuine empty name. Every PRODUCTION construction site
80/// sets a real name, so this value appearing in a live stream is a wiring
81/// bug worth seeing rather than hiding.
82/// What: the literal `"unknown"`; joins against nothing in the agent-keyed
83/// taxonomy, which is the point.
84/// Test: `agent_loop::tests::sink_events::unattributed_loop_emits_unknown_agent`.
85pub const UNATTRIBUTED_AGENT: &str = "unknown";
86
87/// The `agent_id` attribution value used when a tool event's `AgentLoop` was
88/// never told a stable per-spawn id (DOC-39 AC-13.1/13.2).
89///
90/// Why: mirrors [`UNATTRIBUTED_AGENT`] — a loop built before
91/// `AgentLoop::with_agent_id` existed (or a test double) still has to emit
92/// SOMETHING for `agent_id`, and reusing the same sentinel text keeps a
93/// grep/dashboard treating "unattributed" consistently across both fields
94/// rather than inventing a second magic string with no behavioural
95/// difference.
96/// What: the literal `"unknown"` — identical to [`UNATTRIBUTED_AGENT`], kept
97/// as its own named constant purely so call sites document which fallback
98/// they mean.
99/// Test: `agent_loop::tests::sink_events::unattributed_loop_emits_unknown_agent`.
100pub const UNATTRIBUTED_AGENT_ID: &str = "unknown";
101
102/// One memory recalled by `recall_session`, with the flag that says whether
103/// it actually reached the model (UI Phase 1; `text`/`run_id` added for
104/// DOC-39 Slice C — the "what memory drove this / what was held back"
105/// context-construction debugging view).
106///
107/// Why: see [`Event::MemoryRecalled`] — `injected` is the whole point of the
108/// event. `score` rides along because the UI renders it beside the memory
109/// ("41% · held"), and re-deriving it client-side is impossible: it is the
110/// memory daemon's own relevance score. Before DOC-39 Slice C, `text` was
111/// dropped at this exact boundary: `tools::recall_session::render_results`
112/// always had the recalled content in hand (it is what gets rendered/token-
113/// budgeted), but only the score and injected flag escaped into telemetry —
114/// so a held-back memory could be COUNTED but never READ by the UI, which
115/// defeats the "what was held back" debugging surface's entire point.
116/// What: `score` is trusty-memory's relevance score for the query, verbatim.
117/// `injected` is `true` when the tool's rendered result text included this
118/// result whole, `false` when its token budget dropped it. `text` is the
119/// recalled memory's raw content (untruncated — the same string
120/// `render_results` reads from `content`), empty string when the source
121/// entry carried no readable content rather than panicking. `run_id` is the
122/// originating run/session identifier the daemon result was tagged with,
123/// when the daemon's response carries one; `None` when absent (the current
124/// `trusty-memory` `memory_recall` response shape does not yet emit this
125/// field — see `docs/specs/trusty-code-harness-ui.md` §5.3 — so `None` is
126/// the expected value today, not a parsing failure). Both new fields are
127/// `#[serde(default)]` so a ring-buffer/transcript entry recorded before this
128/// ticket still deserializes.
129/// Test: `recalled_memory_round_trips_through_json`,
130/// `tools::recall_session::tests::telemetry_carries_recalled_text_and_run_id`.
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
132pub struct RecalledMemory {
133 /// trusty-memory's relevance score for this result, as returned.
134 pub score: f64,
135 /// Whether this result entered the model's context (`false` = recalled
136 /// but held back by the tool's token budget).
137 pub injected: bool,
138 /// The recalled memory's raw text content (DOC-39 Slice C). Empty string
139 /// when the source entry carried no readable `content`.
140 #[serde(default)]
141 pub text: String,
142 /// The originating run/session id the daemon tagged this result with, if
143 /// any (DOC-39 Slice C). `None` when the daemon response carries no such
144 /// field — see the struct docs.
145 #[serde(default)]
146 pub run_id: Option<String>,
147}
148
149/// One search hit's path and relevance score, as parsed from a
150/// `search_code` call's underlying trusty-search response (UI "what drove
151/// this" search-audit detail — DOC-39 Slice B).
152///
153/// Why: [`Event::SearchPerformed`]'s `hit_count` tells the UI HOW MANY files
154/// a search touched but not WHICH ones — the audit trail's whole point is
155/// tracing a change back to the exact files that surfaced it, and a bare
156/// count cannot answer "was it this file". `tools::trusty_search` already
157/// walks every hit out of the raw MCP response once to COUNT it; this struct
158/// carries the same per-hit path/score it already has in hand from that SAME
159/// walk, so no second parse pass is needed.
160/// What: `path` is the hit's index-relative path when the lane reports one,
161/// falling back to its absolute path otherwise (see
162/// `tools::trusty_search::parse_search_hits` for exactly which JSON key is
163/// read per lane). `score` is the lane's relevance score reinterpreted as
164/// `f64` (matches `serde_json::Value::as_f64`'s own numeric representation,
165/// regardless of the daemon's internal `f32`/`f64`); it defaults to `0.0`
166/// for lanes (e.g. `grep`) whose hits carry no score at all — a real hit
167/// that is merely unscored, never fabricated data.
168/// Test: `search_hit_round_trips_through_json`.
169#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
170pub struct SearchHit {
171 /// The hit's path, as reported by the trusty-search lane that served it.
172 pub path: String,
173 /// The lane's relevance score for this hit, or `0.0` when the lane
174 /// reports no score (e.g. `grep`).
175 pub score: f64,
176}
177
178/// Real-time event types streamed to UI clients (browser, future Tauri).
179///
180/// Why: A single tagged enum keeps wire-format evolution tractable —
181/// `serde(tag = "type")` produces `{"type":"agent_message", ...}` so the UI
182/// can pattern-match on type and the back-end can grow new variants without
183/// breaking older clients (unknown variants degrade to "ignored event").
184/// What: Variants cover the full PM lifecycle plus a `Ping` keepalive so SSE
185/// connections don't time out behind reverse proxies. `session_id` correlates
186/// events to a specific task; the UI filters by session when scoped to a
187/// task view.
188/// Test: `event_serializes_with_type_tag` asserts the wire shape for one
189/// variant; `Event::Ping` round-trips for the keepalive path.
190#[derive(Debug, Clone, Serialize, Deserialize)]
191#[serde(tag = "type", rename_all = "snake_case")]
192pub enum Event {
193 // -- Session lifecycle --
194 SessionStarted {
195 session_id: String,
196 project: String,
197 },
198 SessionDone {
199 session_id: String,
200 status: String,
201 },
202 SessionCancelled {
203 session_id: String,
204 },
205 /// A session's lifecycle status changed (#2054 session-attach protocol).
206 ///
207 /// Why: `SessionStarted`/`SessionDone`/`SessionCancelled` cover the two
208 /// endpoints of a session's life, but the daemon-owned `Session` model
209 /// (vision spec Axiom 4) also transitions through intermediate states
210 /// (e.g. `created` -> `running`) that a freshly-`session.attach`ed
211 /// client should see. This variant is the generic "status is now X"
212 /// signal `crate::session::registry::SessionRegistry` emits on every
213 /// transition, including the two endpoints (so a client that attaches
214 /// mid-stream sees a uniform status trail rather than mixing this
215 /// variant with the older ones).
216 /// What: `status` is a lowercase string matching
217 /// `session::model::SessionStatus`'s serde representation (`"created"`,
218 /// `"running"`, `"cancelled"`, `"finished"`, `"failed"`).
219 /// Test: `session::registry::tests::create_publishes_started_and_status_events`.
220 SessionStatusChanged {
221 session_id: String,
222 status: String,
223 },
224 /// Input was received for a session via `session.send` (#2054).
225 ///
226 /// Why: distinct from `AgentMessage` (sub-agent -> PM activity) —
227 /// this is the client -> daemon direction. Emitting it is what makes
228 /// `session.send` observably reach a freshly-`session.attach`ed client
229 /// in M1, ahead of any real agent-loop wiring (`task.*`, #2056).
230 /// What: `input` is the raw string the caller passed to `session.send`.
231 /// Test: `session::registry::tests::send_publishes_input_event`.
232 SessionInput {
233 session_id: String,
234 input: String,
235 },
236
237 // -- Tool lifecycle (#2055 taxonomy; emitted by #2056's agent loop) --
238 /// A tool invocation began. Distinct from the older `ToolCalled` (which
239 /// has no started/finished/error distinction or call-correlation id, and
240 /// predates the session-attach protocol) — this is the tcode
241 /// session.attach taxonomy's tool-lifecycle kind.
242 ///
243 /// Why: `call_id` correlates this with the matching `ToolFinished`/
244 /// `ToolError` when a session runs multiple tool calls in sequence or
245 /// concurrently. `agent` (UI Phase 1) is the attribution key: without it
246 /// a client can only guess WHICH agent made a call by interleaving this
247 /// stream with `AgentSpawned`/`AgentDone` ordering, which breaks the
248 /// moment the PM and a delegated engineer have overlapping calls. It is
249 /// the agent NAME (not a synthetic id) so it joins directly against the
250 /// pre-existing `LlmRequested`/`LlmResponded.agent_name` and
251 /// `AgentSpawned`/`AgentDone`/`PmDelegating.agent` keys — see
252 /// [`UNATTRIBUTED_AGENT`] for the fallback when a loop runs unattributed.
253 /// (DOC-39 AC-13.1/13.2) `agent` alone cannot distinguish two
254 /// concurrently-delegated sub-agents sharing one name (e.g. two
255 /// `python-engineer` delegations) — `agent_id` is the STABLE per-spawn
256 /// id minted once per delegation
257 /// (`runner::in_process::InProcessAgentRunner::run_pipeline`) that a
258 /// client must key correlation off instead; `agent` remains the
259 /// human-readable label.
260 /// What: `args_preview` is truncated via `preview()` before emission.
261 /// Test: `session::registry::registry_tests::record_tool_started_publishes_event`.
262 ToolStarted {
263 session_id: String,
264 agent: String,
265 /// (DOC-39 AC-13) stable per-spawn id — see the variant's own docs
266 /// above. `#[serde(default)]` so a transcript recorded before this
267 /// field existed still deserializes (decoding to `""`, not
268 /// [`UNATTRIBUTED_AGENT_ID`]'s sentinel text).
269 #[serde(default)]
270 agent_id: String,
271 tool: String,
272 call_id: String,
273 args_preview: String,
274 },
275 /// A tool invocation completed (success or failure signalled by `success`,
276 /// not a separate error variant — use `ToolError` for exceptional
277 /// failures the caller wants to narrate distinctly, e.g. a timeout).
278 /// `agent` attributes the call — see [`Event::ToolStarted`]. `agent_id`
279 /// (DOC-39 AC-13) is the same per-spawn stable id.
280 ToolFinished {
281 session_id: String,
282 agent: String,
283 #[serde(default)]
284 agent_id: String,
285 tool: String,
286 call_id: String,
287 success: bool,
288 result_preview: String,
289 },
290 /// A tool invocation raised an exceptional error (as opposed to
291 /// completing with `success: false`) — e.g. the tool process crashed or
292 /// timed out rather than returning a normal failure result.
293 /// `agent` attributes the call — see [`Event::ToolStarted`]. `agent_id`
294 /// (DOC-39 AC-13) is the same per-spawn stable id.
295 ToolError {
296 session_id: String,
297 agent: String,
298 #[serde(default)]
299 agent_id: String,
300 tool: String,
301 call_id: String,
302 error: String,
303 },
304
305 // -- Structured retrieval telemetry (UI Phase 1) --
306 /// A `search_code` call resolved to a concrete trusty-search lane and
307 /// returned `hit_count` hits (each with its `path`/`score` in `hits`) in
308 /// `latency_ms` (UI Phase 1; `hits` added DOC-39 Slice B).
309 ///
310 /// Why: `ToolStarted`/`ToolFinished` carry only TRUNCATED STRING
311 /// PREVIEWS of a search's arguments and rendered result text. The UI's
312 /// core bet is that a change is explained by the searches and memories
313 /// that drove it — which needs the search's real routed lane, its hit
314 /// count, and its cost as DATA, not as a prefix of prose the UI would
315 /// have to re-parse. Emitted ALONGSIDE (never instead of) the generic
316 /// tool events, so every existing consumer is unaffected. `hits` extends
317 /// this the same way: the search-audit UI needs to know WHICH files a
318 /// search touched, not just how many.
319 /// What: `lane` is the lane trusty-search ACTUALLY served, which is not
320 /// always the mode the model asked for: a `semantic`/`symbol` query that
321 /// hits a still-building index transparently retries on the lexical lane
322 /// (issue #2783), and that degraded reality is reported as
323 /// `lane: "lexical"` — see `tools::trusty_search`'s `SearchLane`.
324 /// `hit_count` is `None` when the lane served results whose shape this
325 /// crate could not count (never a silent zero, which would read as "no
326 /// hits"); `hits` is `[]` in that same uncountable case. Both come from
327 /// the SAME parse of the tool's response — see
328 /// `tools::trusty_search::parse_search_hits`. `latency_ms` measures the
329 /// whole tool call, retry included.
330 /// Test: `session::registry::registry_tests::record_search_performed_publishes_event`,
331 /// `tools::trusty_search_tests::resolved_lane_reports_lexical_when_the_retry_served_it`,
332 /// `search_hit_round_trips_through_json`.
333 SearchPerformed {
334 session_id: String,
335 agent: String,
336 /// (DOC-39 AC-13) the dispatching agent's stable per-spawn id — see
337 /// `Event::ToolStarted`'s docs. `#[serde(default)]` for the same
338 /// old-transcript-compatibility reason.
339 #[serde(default)]
340 agent_id: String,
341 lane: String,
342 query: String,
343 hit_count: Option<usize>,
344 /// Per-hit path + score, in the order the lane returned them
345 /// (DOC-39 Slice B). `#[serde(default)]` — absent on any transcript
346 /// recorded before this field existed, mirroring `agent_id`'s
347 /// old-transcript-compatibility contract.
348 #[serde(default)]
349 hits: Vec<SearchHit>,
350 latency_ms: u64,
351 },
352 /// A `recall_session` call recalled `results` from durable memory, each
353 /// flagged with whether it actually ENTERED the model's context
354 /// (UI Phase 1).
355 ///
356 /// Why: the differentiating UI surface distinguishes memories that were
357 /// injected into context from ones that were recalled but HELD BACK —
358 /// rendered as e.g. "PKCE required… 41% · held" next to the injected
359 /// ones. `recall_session` has always known both the scores and which
360 /// results its token budget dropped, but that knowledge died inside the
361 /// tool's rendered text. This is the event that lets it out.
362 /// What: `results` is ordered highest-score-first (the order the daemon
363 /// returned and the tool preserved). `injected: false` means EXACTLY
364 /// "recalled but not entered into context" — the tool drops WHOLE
365 /// lowest-scored results to fit its token budget, so a held-back result
366 /// is one the model never saw.
367 /// Test: `session::registry::registry_tests::record_memory_recalled_publishes_event`,
368 /// `tools::recall_session::tests::telemetry_marks_budget_dropped_results_held_back`.
369 MemoryRecalled {
370 session_id: String,
371 agent: String,
372 /// (DOC-39 AC-13) the dispatching agent's stable per-spawn id — see
373 /// `Event::ToolStarted`'s docs. `#[serde(default)]` for the same
374 /// old-transcript-compatibility reason.
375 #[serde(default)]
376 agent_id: String,
377 query: String,
378 results: Vec<RecalledMemory>,
379 },
380
381 // -- Diagnostics / progress / generic message (#2055 taxonomy) --
382 /// A structured log line scoped to a session, for operators/UIs that
383 /// want daemon-side diagnostics without parsing stderr.
384 Log {
385 session_id: String,
386 /// `"debug"` | `"info"` | `"warn"` | `"error"`.
387 level: String,
388 message: String,
389 },
390 /// A coarse progress update for a long-running session operation.
391 /// `percent` is `None` when progress isn't quantifiable (e.g. "still
392 /// searching") — the UI falls back to an indeterminate spinner.
393 Progress {
394 session_id: String,
395 message: String,
396 percent: Option<f32>,
397 },
398 /// A generic, freeform session-scoped message that doesn't fit any more
399 /// specific kind — the taxonomy's catch-all, used sparingly.
400 Message {
401 session_id: String,
402 text: String,
403 },
404
405 // -- PM activity --
406 PmThinking {
407 session_id: String,
408 text: String,
409 },
410 PmDelegating {
411 session_id: String,
412 agent: String,
413 task_preview: String,
414 },
415
416 // -- Agent activity --
417 /// (DOC-39 AC-13) not yet emitted by any production call site — reserved
418 /// for a future agent-lifecycle producer. `agent_id` is defined now so
419 /// that producer never has to retrofit it onto an already-shipped wire
420 /// shape.
421 AgentSpawned {
422 session_id: String,
423 agent: String,
424 #[serde(default)]
425 agent_id: String,
426 },
427 AgentMessage {
428 session_id: String,
429 agent: String,
430 text: String,
431 },
432 /// A streamed chunk of one assistant turn's text (tcode streaming epic
433 /// #3696 Slice 0 — contract only, no producer/consumer wired yet).
434 ///
435 /// Why: [`Event::AgentMessage`] carries a turn's full text as a single
436 /// atomic event, which is fine for a batch-completed turn but cannot
437 /// represent a turn arriving incrementally — the UI has nothing to render
438 /// until the whole turn lands. This variant lets a producer emit the SAME
439 /// turn as a sequence of deltas correlated by `turn_id`, with two
440 /// intentionally-supported shapes: Gap A (a harness that only exposes a
441 /// turn's full text once it is done) emits ONE delta carrying the whole
442 /// turn text with `done: true`; Gap B (a harness with real token-level
443 /// streaming) emits many small deltas with `done: false` followed by one
444 /// final `done: true` marker. Consumers must handle both without special-
445 /// casing which shape a given session uses. `agent_id` mirrors
446 /// [`Event::AgentSpawned`]'s rationale — `agent` alone cannot disambiguate
447 /// two concurrently-delegated sub-agents sharing one name — and this
448 /// codebase runs sub-agents concurrently (`AgentLoop`/`InProcessAgentRunner`
449 /// delegation), so `turn_id` scoping is a correctness requirement, not a
450 /// nicety: see `turn_id`'s own note below.
451 /// What: `turn_id` is opaque and MUST be unique within a session across
452 /// ALL agents, INCLUDING two agents streaming concurrently — a UUID or a
453 /// session-global monotonic counter satisfies this; a per-agent-local
454 /// counter (e.g. each `AgentLoop` restarting its own turn counter from 0)
455 /// does NOT, and would let two concurrently-streaming agents collide on
456 /// the same `turn_id` and interleave into one bubble. Consumers SHOULD
457 /// therefore group/concatenate deltas by the tuple `(agent_id, turn_id)`,
458 /// not `turn_id` alone, as defensive practice against a producer that
459 /// gets this id-scoping requirement wrong — reconstructing one turn's
460 /// text is "concatenate `delta` in arrival order for one `(agent_id,
461 /// turn_id)` key". `done: false` means more deltas for this key are
462 /// coming; `done: true` means this turn's bubble is complete and no
463 /// further deltas for this key will arrive. `agent_id` is
464 /// `#[serde(default)]` so a transcript recorded before this field existed
465 /// still deserializes (decoding to `""`).
466 /// Test: `agent_message_delta_round_trips_through_json`,
467 /// `agent_message_delta_full_text_in_one_delta_round_trips` (Gap A shape).
468 AgentMessageDelta {
469 session_id: String,
470 agent: String,
471 #[serde(default)]
472 agent_id: String,
473 turn_id: String,
474 delta: String,
475 done: bool,
476 },
477 /// (DOC-39 AC-13) see [`Event::AgentSpawned`]'s note — not yet emitted.
478 AgentDone {
479 session_id: String,
480 agent: String,
481 #[serde(default)]
482 agent_id: String,
483 status: String,
484 },
485 /// (DOC-39 AC-13) see [`Event::AgentSpawned`]'s note — not yet emitted.
486 AgentFailed {
487 session_id: String,
488 agent: String,
489 #[serde(default)]
490 agent_id: String,
491 error: String,
492 },
493
494 // -- Tool calls --
495 ToolCalled {
496 session_id: String,
497 tool: String,
498 preview: String,
499 },
500 ToolResult {
501 session_id: String,
502 tool: String,
503 preview: String,
504 },
505
506 // -- AST analysis --
507 /// Emitted when an AST-native tool performs a structural code operation
508 /// (symbol lookup, edit, insert, import, validation, patch apply, or
509 /// project pre-indexing). Surfaces in the REPL's thinking-step display
510 /// so users can see structural analysis happening in real time.
511 ///
512 /// Why: AST-native tools replace whole-file rewrites with surgical edits.
513 /// Without dedicated telemetry the user only sees opaque `ToolCalled`
514 /// events and loses the narrative of "indexed project → looked up symbol
515 /// → staged edit → applied patch". This event makes the AST narrative
516 /// visible.
517 /// What: `op` is a short label (`index`, `lookup`, `edit`, `insert`,
518 /// `import`, `validate`, `patch`); `detail` is a human-readable
519 /// substring (e.g. "42 symbols from src/" or "fn parse_args in main.rs").
520 /// Test: `ast_operation_round_trips_through_subscribe` round-trips one
521 /// variant through the bus.
522 AstOperation {
523 session_id: String,
524 op: String,
525 detail: String,
526 },
527
528 // -- Phase (workflow) --
529 PhaseStarted {
530 session_id: String,
531 phase: String,
532 },
533 PhaseDone {
534 session_id: String,
535 phase: String,
536 status: String,
537 },
538 /// #196: a phase was skipped because the active persona opts out of it.
539 ///
540 /// Why: Operators and the UI need visibility when persona-aware skipping
541 /// changes the executed workflow shape (e.g. `[hacker]` skipping QA).
542 /// Without this event the run looks like phases silently disappeared.
543 /// What: Carries the phase name and the persona that triggered the skip.
544 PhaseSkipped {
545 session_id: String,
546 phase: String,
547 persona: String,
548 },
549
550 // -- Persona (workflow) --
551 /// #196: emitted once per workflow run when a persona is detected from the
552 /// task text. Lets the UI surface "running in \[hacker\] mode" before any
553 /// phases execute, so users immediately see why the pipeline shape may
554 /// differ from the default.
555 PersonaDetected {
556 session_id: String,
557 persona: String,
558 },
559
560 // -- LLM call lifecycle (#199) --
561 /// Emitted just before any LLM chat-completion HTTP call leaves the
562 /// process. Pairs with `LlmResponded` so consumers can compute latency
563 /// independently and surface in-flight calls in the UI.
564 ///
565 /// Why: Operators debugging slow runs need to see WHICH model is in flight
566 /// at any moment, not just retroactively in totals. `prompt_tokens` is
567 /// optional because we don't always know the prompt size up front.
568 /// What: `agent_name` may be empty for top-level PM calls; `model` is the
569 /// resolved provider/model string sent on the wire.
570 LlmRequested {
571 session_id: String,
572 agent_name: String,
573 model: String,
574 prompt_tokens: Option<u32>,
575 },
576
577 /// Emitted after every LLM chat-completion HTTP call returns successfully.
578 /// Carries the wall-clock latency so the UI can render "model X took Yms"
579 /// badges without waiting for end-of-run perf aggregation.
580 LlmResponded {
581 session_id: String,
582 agent_name: String,
583 model: String,
584 completion_tokens: Option<u32>,
585 latency_ms: u64,
586 },
587
588 /// Emitted when an agent's actual work loop begins — distinct from
589 /// `AgentSpawned`, which fires when the subprocess is kicked off.
590 /// `AgentStarted` fires AFTER the spawn handshake (or at the start of an
591 /// in-process runner loop) so the UI can show "spawning…" vs. "running"
592 /// states. `runner_type` is one of "subprocess", "claude-code", "inline".
593 /// (DOC-39 AC-13) `agent_id` — see [`Event::AgentSpawned`]'s note; not yet
594 /// emitted by any production call site.
595 AgentStarted {
596 session_id: String,
597 agent_name: String,
598 #[serde(default)]
599 agent_id: String,
600 runner_type: String,
601 },
602
603 /// Emitted when an agent produces its final result before returning to
604 /// the PM. Lets the UI render "agent X returned a Y-word report" badges
605 /// without parsing the result body.
606 ///
607 /// Why: A coarse signal of agent productivity that complements
608 /// `AgentDone`. `word_count` is a cheap whitespace-split count; status
609 /// mirrors the agent's IPC status field ("success" or "error").
610 ReportGenerated {
611 session_id: String,
612 agent_name: String,
613 word_count: usize,
614 status: String,
615 },
616
617 /// Emitted when a session recap is generated after N completed tasks (#371).
618 /// Carries the session ID, a one-line prose summary, and structured table rows.
619 /// Consumed by TUI (renders `※ recap:` banner) and SSE → GUI (RecapPanel).
620 RecapGenerated {
621 session_id: String,
622 /// One-line prose summary, e.g. "Fixed a bug where X. Y is now deployed."
623 summary: String,
624 /// Structured rows for the recap table: [(step_label, result_text)]
625 table_rows: Vec<(String, String)>,
626 },
627
628 // -- Search-index readiness (#2784 follow-up: UI Phase-1) --
629 /// The project's trusty-search index readiness, probed once at task start.
630 ///
631 /// Why: cold-indexing a large repo has a real semantic warm-up window —
632 /// lexical (BM25) is queryable in seconds while semantic embedding can stay
633 /// `InProgress` for minutes. During that window a search returns EMPTY, and
634 /// an empty result is indistinguishable from "this index is fully ready and
635 /// the code genuinely isn't here" — two states that mean OPPOSITE things.
636 /// `trusty_common::search_readiness` already computes this per-lane, but
637 /// only ever logged it to stderr, so no UI (and no consumer of the daemon
638 /// API at all) could see it. This variant is that value escaping.
639 /// `state` is the field that resolves the ambiguity: a UI must NOT render
640 /// "no results found" while `state == "warming"`, and a `"unavailable"`
641 /// index means an empty search is likewise not evidence of absence.
642 /// What: `state` is the single coarse discriminant — `"ready"` (the
643 /// semantic lane is queryable; an empty search IS evidence of absence),
644 /// `"warming"` (at least the semantic lane is still building; an empty
645 /// search is NOT evidence of absence), or `"unavailable"` (the probe found
646 /// no reachable daemon / no derivable index id — likewise not evidence of
647 /// absence). It keys off `IndexReadiness::semantic_search_ready`, the
648 /// module's canonical "is a search trustworthy yet" predicate, rather than
649 /// requiring all three lanes — the graph/KG lane is legitimately absent on
650 /// many indexes (`TRUSTY_NO_KG`), and gating `"ready"` on it would report
651 /// `"warming"` forever. The per-lane `lexical_ready`/`semantic_ready`/
652 /// `graph_ready` flags ship alongside so a UI can still render each lane
653 /// individually. `index_id`/`lifecycle_status`/`chunk_count` are `None`
654 /// exactly when `state == "unavailable"` (nothing was probed). `summary` is
655 /// the same human-readable line the stderr log carries.
656 /// (DOC-39 §5.6 Slice D) This event is EMITTED ONCE, at task start — a
657 /// client that attaches after it fired sees nothing. `session.get_readiness`
658 /// is the query counterpart: it returns the last-recorded
659 /// [`IndexReadinessSnapshot`] (this variant's fields, minus `session_id`)
660 /// for late attachers, so "what is readiness right now" doesn't depend on
661 /// having been subscribed at the right moment.
662 /// Test: `session::registry::registry_tests::record_index_readiness_*`,
663 /// `session::registry::registry_tests::warming_index_is_distinguishable_from_ready_with_zero_hits`.
664 IndexReadiness {
665 session_id: String,
666 /// `"ready"` | `"warming"` | `"unavailable"` — see the variant docs.
667 state: String,
668 index_id: Option<String>,
669 lifecycle_status: Option<String>,
670 chunk_count: Option<u64>,
671 lexical_ready: bool,
672 semantic_ready: bool,
673 graph_ready: bool,
674 summary: String,
675 },
676
677 // -- Working-context budget (epic #2343 "Infinite Sessions"; UI Phase-1) --
678 /// The working-context budget after one cadence/enforcement turn boundary.
679 ///
680 /// Why: the Infinite Sessions guarantee — working context >= 60% of the
681 /// model's window, session overhead <= 40%, at ALL times — is what makes
682 /// "the workstream never ends" true. `agent_loop::cadence` recomputed that
683 /// budget every single turn and then DISCARDED the result: `CadenceOutcome`
684 /// was documented "for observability/tests" and observability never
685 /// consumed it. Nothing could render the guarantee it enforces. This
686 /// variant is that already-computed value escaping, so a UI can show a live
687 /// context-budget indicator instead of the user flying blind into a
688 /// compaction.
689 /// What: `overhead_tokens` is the REAL measured `estimate_total_tokens` of
690 /// the model-facing transcript after enforcement settled (not a
691 /// projection); `overhead_cap_tokens` is the hard cap
692 /// (`context_window * max_overhead_fraction_pct / 100`); `working_context_pct`
693 /// and `overhead_pct` are the two derived percentages a budget meter renders
694 /// (they sum to 100). `within_budget` is `false` only on cadence's one
695 /// documented floor — pinned/system/user content alone exceeds the cap.
696 /// `compaction_fired` marks the turns where history was actually
697 /// compressed: that content was removed from the model-facing CONTEXT, never
698 /// from the durable record (the summary left in its place points at
699 /// `recall_session`), which is the distinction a UI should make legible
700 /// rather than rendering compaction as data loss. `compaction_rounds`
701 /// counts the cadence round plus every continuous-enforcement round.
702 /// Emitted ONLY by the PM's persistent-session loop — cadence is PM-only by
703 /// construction (`AgentLoopConfig.cadence` defaults `None`), so a delegated
704 /// engineer loop never emits this.
705 /// Test: `agent_loop::tests::cadence_emits_context_budget_snapshot`,
706 /// `agent_loop::tests::no_context_budget_event_when_cadence_disabled`.
707 ContextBudget {
708 session_id: String,
709 context_window_tokens: usize,
710 overhead_tokens: usize,
711 overhead_cap_tokens: usize,
712 /// Percentage of the window left for real work. The Infinite Sessions
713 /// guarantee is that this stays >= 60.
714 working_context_pct: u8,
715 /// Percentage of the window consumed by session overhead (<= 40).
716 overhead_pct: u8,
717 within_budget: bool,
718 compaction_fired: bool,
719 compaction_rounds: usize,
720 },
721
722 // -- Session<->workstream binding (DOC-48 §4/§5.3, issue #3298) --
723 /// A session was just bound to a workstream — either the ambient default
724 /// target (§4.2: `session.create`/`task.run` called with no explicit
725 /// `workstream_id` while a workstream is active) or an explicit
726 /// `workstream_id` param (§4.1). `session::protocol::create` and
727 /// `task::protocol::task_run` are the sole emitters, each exactly once
728 /// per newly-minted session that resolves a binding — a session's
729 /// binding is immutable thereafter (§4.1), so this can never fire twice
730 /// for the same `session_id`.
731 ///
732 /// Why: DOC-48 §5.3's event table lists `SessionAdded` as part of the
733 /// minimal Phase 1A/1B set so a client observing
734 /// `GET /workstreams/{id}/events` learns a new session joined the
735 /// workstream. Session-scoped (unlike `WorkstreamActivationChanged`/
736 /// `WorkstreamStateInferred` above) — published via
737 /// `SessionRegistry::record`, so it flows through the SAME per-session
738 /// ring buffer and live bus every other session event does. This is
739 /// exactly why `crate::workstreams::sse::aggregate_live`'s dynamic
740 /// per-event membership re-check (module docs) needs no change to pick
741 /// it up: by the time this event is recorded, the binding write into
742 /// [`crate::workstreams::store::WorkstreamStore`] has already completed,
743 /// so the session is already a member of `workstream_id`'s `session_ids`
744 /// when the aggregation route re-checks membership for this event.
745 /// What: `workstream_id` and `session_id` are both carried (unlike
746 /// §5.3's literal `{session_id, binding_time}` table, widened per this
747 /// ticket's scope note so a client subscribed to one workstream's
748 /// aggregate stream — which tags every forwarded event with its source
749 /// `session_id` already — can also learn WHICH workstream without a
750 /// second round trip); `binding_time` is the UTC instant the binding was
751 /// persisted.
752 /// Test: `session::protocol::workstream_binding_tests::create_binds_ambient_active_workstream`,
753 /// `session::protocol::workstream_binding_tests::create_binds_explicit_workstream_overriding_ambient`,
754 /// `task::protocol::tests::task_run_binds_ambient_active_workstream_and_publishes_session_added`.
755 SessionAdded {
756 session_id: String,
757 workstream_id: String,
758 binding_time: DateTime<Utc>,
759 },
760
761 /// A bound session's activity signal changed — currently fired whenever
762 /// `SessionRegistry::set_run_outcome` records a completed run's turns
763 /// (the natural "a turn just happened" hook; #2056's `task::executor`
764 /// calls it once per finished execution).
765 ///
766 /// Why: DOC-48 §5.3's event table lists this alongside `SessionAdded` so
767 /// a workstream observer can track which of its bound sessions are
768 /// live/recently-active without polling `session.status` per id. Emitted
769 /// ONLY for workstream-BOUND sessions (`Session.workstream_id` set):
770 /// this is a workstream-taxonomy event (§5.3 defines it in that set),
771 /// an unbound session has no workstream observer to serve — and the M1
772 /// cutline e2e contract (`tests/m1_cutline_e2e.rs`) freezes the exact
773 /// event-kind sequence a plain, workstream-less session emits, so
774 /// firing this unconditionally would (and, in PR #3354's first cut,
775 /// did) break that frozen baseline for every existing client on both
776 /// transports. See `SessionRegistry::set_run_outcome`'s docs for the
777 /// gate.
778 /// What: `last_turn_at` is the UTC instant this update was recorded;
779 /// `has_running_task` mirrors `SessionRegistry::is_executing` at that
780 /// same instant (`true` while `set_run_outcome`'s caller — `run_task`'s
781 /// executor — still holds the execution slot when this fires; #2056's
782 /// call order means this is realistically always `false` in practice
783 /// today, since the executor clears its execution slot only AFTER
784 /// `set_run_outcome` returns — carried anyway so a future caller with a
785 /// genuinely mid-run activity signal has a field to set it on without a
786 /// schema change).
787 /// Test: `session::registry_tests::set_run_outcome_publishes_activity_update_when_workstream_bound`,
788 /// `session::registry_tests::set_run_outcome_stays_silent_for_unbound_session`.
789 SessionActivityUpdate {
790 session_id: String,
791 last_turn_at: DateTime<Utc>,
792 has_running_task: bool,
793 },
794
795 // -- Workstream lifecycle (DOC-48 §5.3/§6.3, issue #3297) --
796 /// The daemon-wide active workstream changed: `workstream.activate`
797 /// switched to a different workstream (or activated one from no prior
798 /// active workstream), or `workstream.deactivate` cleared the pointer
799 /// with no successor (`crate::workstreams::activation::{activate,
800 /// deactivate}` are the sole emitters — see their docs).
801 ///
802 /// Why: DOC-48 AC-3.3 requires every client observing a workstream to
803 /// learn when the active workstream changes, including a workstream that
804 /// was active learning it just got DEACTIVATED (so it can stop treating
805 /// itself as the ambient default target, §4.2) — not just clients of the
806 /// newly-active one. `crate::events::Event` was, until now, exhaustively
807 /// session-scoped (every variant but `Ping` carries a `session_id`); this
808 /// is a genuinely DAEMON-scoped signal with no owning session, so it
809 /// reuses the SAME global broadcast bus (the one mechanism already wired
810 /// to every live SSE subscriber) rather than standing up a second,
811 /// parallel channel purely to carry one event type — the aggregation
812 /// route (`crate::workstreams::sse::aggregate_live`) already subscribes
813 /// to this bus for its per-session fan-out, so no extra subscription is
814 /// needed to also observe this variant.
815 /// What: `new_active_id` is `Some(id)` for both a fresh activation (no
816 /// prior active workstream) and a force-switch; `None` exactly when
817 /// `workstream.deactivate` cleared the pointer with no successor — this
818 /// widens DOC-48 §5.3's literal `{new_active_id: UUID, prior_id?}` table
819 /// (which only anticipates a switch always landing on a new active
820 /// workstream) to also cover deactivation, a case the table's shape
821 /// otherwise cannot express. `prior_id` is the workstream that was active
822 /// immediately before this change, `None` when there wasn't one. Emitted
823 /// only when the persisted active pointer ACTUALLY changed — not on an
824 /// idempotent re-activation of the already-active workstream, nor on a
825 /// deactivate of a non-active workstream (both are true no-ops).
826 /// Not session-scoped: `Event::session_id()` returns `None` for this
827 /// variant, same as `Event::Ping`.
828 /// Test: `workstreams::activation_tests::activate_with_no_prior_active_publishes_activation_changed`,
829 /// `workstreams::activation_tests::activate_with_force_publishes_activation_changed_with_prior`,
830 /// `workstreams::activation_tests::activate_already_active_does_not_publish`,
831 /// `workstreams::activation_tests::deactivate_active_publishes_activation_changed`,
832 /// `workstreams::activation_tests::deactivate_non_active_does_not_publish`.
833 WorkstreamActivationChanged {
834 new_active_id: Option<String>,
835 prior_id: Option<String>,
836 },
837
838 /// A workstream's computed state (DOC-48 §2.2: `active | idle | closed`)
839 /// actually transitioned — fired by `workstream.activate`/`deactivate`
840 /// (`crate::workstreams::activation`) and `workstream.close`
841 /// (`crate::workstreams::protocol::close`) whenever they change it.
842 ///
843 /// Why: DOC-48 §5.3's event table lists this alongside
844 /// `WorkstreamActivationChanged` as part of the minimal Phase 1A set — a
845 /// client observing one workstream via `GET /workstreams/{id}/events`
846 /// needs to learn its OWN state changed (e.g. it was closed) even when no
847 /// bound session emitted anything, the same gap `WorkstreamActivationChanged`
848 /// fills for the daemon-wide active pointer.
849 /// What: `workstream_id` names which workstream transitioned; `state` is
850 /// its NEW state as a lowercase string (`"active"` | `"idle"` |
851 /// `"closed"`) — deliberately a plain string rather than
852 /// `crate::workstreams::WorkstreamState` so this module stays
853 /// domain-decoupled, matching `Event::IndexReadiness`/
854 /// `SessionStatusChanged`'s existing "state as a plain string"
855 /// convention. `reason` is a short human-readable cause (e.g.
856 /// `"activated"`, `"activated (force-switch)"`, `"deactivated"`,
857 /// `"closed"`).
858 /// Not session-scoped — grouped with `WorkstreamActivationChanged` and
859 /// `Ping` in `session_id()`.
860 /// Test: `workstreams::activation_tests::activate_with_no_prior_active_publishes_state_inferred`,
861 /// `workstreams::activation_tests::activate_with_force_publishes_state_inferred_for_both`,
862 /// `workstreams::activation_tests::deactivate_active_publishes_state_inferred_idle`,
863 /// `workstreams::protocol_tests::close_publishes_state_inferred`.
864 WorkstreamStateInferred {
865 workstream_id: String,
866 state: String,
867 reason: String,
868 },
869
870 // -- Keepalive --
871 Ping,
872}
873
874/// A cached snapshot of the `Event::IndexReadiness` payload (DOC-39 §5.6
875/// Slice D — `session.get_readiness` query RPC).
876///
877/// Why: `Event::IndexReadiness` above is emitted exactly once, at task start
878/// — a fire-once event, not a queryable value. A UI client that attaches to
879/// a session AFTER that one-time probe fired has no way to ask "what is the
880/// readiness state right now"; it can only ever see events that arrive while
881/// it happens to be subscribed. This struct is the field-for-field twin of
882/// `Event::IndexReadiness`'s payload (deliberately excluding `session_id`,
883/// which is contextual to the cache slot it lives in, not the event) so
884/// `SessionRegistry` can cache the last-recorded probe per session and
885/// `session.get_readiness` can hand it back verbatim to a late-attaching
886/// client — one shape for both the streamed event and the query response,
887/// with no independent field-naming to drift out of sync.
888/// What: every field name and type matches the corresponding field on
889/// `Event::IndexReadiness` exactly. `SessionRegistry::record_index_readiness`
890/// builds one of these first and derives the `Event::IndexReadiness` it
891/// publishes from it, so the two can never disagree.
892/// Test: `session::registry_tests::record_index_readiness_caches_snapshot_for_late_query`,
893/// `session::protocol_readiness::tests::get_readiness_returns_probed_snapshot_after_recording`.
894#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
895pub struct IndexReadinessSnapshot {
896 /// `"ready"` | `"warming"` | `"unavailable"` — see `Event::IndexReadiness`.
897 pub state: String,
898 pub index_id: Option<String>,
899 pub lifecycle_status: Option<String>,
900 pub chunk_count: Option<u64>,
901 pub lexical_ready: bool,
902 pub semantic_ready: bool,
903 pub graph_ready: bool,
904 pub summary: String,
905}
906
907/// A cached snapshot of the `Event::ContextBudget` payload (issue #3015 —
908/// `session.get_context_budget` query RPC; surfaced by PR #3014's GUI status
909/// bar, which renders "budget: unavailable" waiting for exactly this API).
910///
911/// Why: `Event::ContextBudget` above is a per-turn STREAM value, not a
912/// queryable one — a client that attaches (or reconnects) between turns has
913/// no way to ask "what is the working-context budget right now"; it can only
914/// ever see events that arrive while it happens to be subscribed. This is
915/// the field-for-field twin of `Event::ContextBudget`'s payload (deliberately
916/// excluding `session_id`, contextual to the cache slot it lives in) so
917/// `SessionRegistry` can cache the last-recorded measurement per session and
918/// `session.get_context_budget` can hand it back verbatim to a
919/// late-attaching client — mirrors [`IndexReadinessSnapshot`] exactly.
920/// What: every field name and type matches the corresponding field on
921/// `Event::ContextBudget` exactly. `SessionRegistry::record_context_budget`
922/// builds one of these first and derives the `Event::ContextBudget` it
923/// publishes from it, so the two can never disagree. All-`Copy` (unlike
924/// `IndexReadinessSnapshot`) since every field is a primitive.
925/// Test: `session::registry_tests::record_context_budget_caches_snapshot_for_late_query`,
926/// `session::protocol_budget::tests::get_context_budget_returns_recorded_snapshot_after_recording`.
927///
928/// (issue #3868) `lifetime_compaction_alarm_count` is additive and, unlike
929/// every other field here, has NO twin on `Event::ContextBudget` — it is
930/// deliberately absent from the per-turn stream. Why: the stream event is
931/// derived once, at the moment a turn's cadence measurement lands, from
932/// values the caller already computed; the alarm count instead needs a
933/// `File::open` + line-scan of `agent_loop::telemetry`'s durable,
934/// cross-session alarm log, which is too expensive to pay on the EVERY-TURN
935/// write path (`record_context_budget`, called once per cadence tick). It is
936/// therefore read fresh only in `SessionRegistry::get_context_budget` — the
937/// actual RPC query path, called once per client poll — which overwrites
938/// the field on the cached snapshot right before returning it; the copy
939/// `record_context_budget` stores is a `0` placeholder never observed by a
940/// caller. This also means a session that never fires threshold compaction
941/// still gets an accurate count reflecting fires from ANY session on this
942/// machine, not a stale per-session value baked in at some earlier turn. It
943/// answers "has threshold compaction EVER fired under cadence, cumulative
944/// across every session on this machine" — a fact with no natural
945/// single-turn "stream" moment to attach to.
946#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
947pub struct ContextBudgetSnapshot {
948 pub context_window_tokens: usize,
949 pub overhead_tokens: usize,
950 pub overhead_cap_tokens: usize,
951 pub working_context_pct: u8,
952 pub overhead_pct: u8,
953 pub within_budget: bool,
954 pub compaction_fired: bool,
955 pub compaction_rounds: usize,
956 /// (#3868) Lifetime, cross-session count of `cadence: Some(_)`
957 /// threshold-compaction fires — epic #2343's never-event alarm, made
958 /// durable and reachable from the ONE RPC that's already the front door
959 /// for budget state (`session.get_context_budget`) instead of requiring
960 /// a second `session.get_transcript` call.
961 pub lifetime_compaction_alarm_count: u64,
962 /// (issues #3912, #3948) This SESSION's lowest `working_context_pct`
963 /// across every cadence measurement `SessionRegistry` has recorded for
964 /// it — `None` until the first measurement lands. It exists because the
965 /// load-realistic compression soak (epic #3866) proved the single
966 /// most-recent snapshot above (`working_context_pct`) can read 98-99%
967 /// while the same session dipped to 48-60% moments earlier; a coarse
968 /// poll reliably misses the turn where the floor was lowest.
969 ///
970 /// (#3948) Unlike `lifetime_compaction_alarm_count` above, this is NOT
971 /// read fresh from a durable log at query time. It is folded in
972 /// incrementally by `SessionRegistry::record_context_budget` and lives
973 /// as long as the session does, which means the value is scoped to the
974 /// running daemon: a restart drops the session itself, so the RPC
975 /// answers `session_not_found` rather than a reset floor. Offline
976 /// history stays in `compression.jsonl`, readable via
977 /// `agent_loop::telemetry::session_working_context_floor`; that reader
978 /// aggregates a different sample set (only turns that did compaction
979 /// work, plus threshold fires), so its floor and this one can differ.
980 pub working_context_pct_low_water_mark: Option<u8>,
981 /// (issues #3912, #3948) How many cadence measurements
982 /// `working_context_pct_low_water_mark` was computed over for this
983 /// session — lets a consumer distinguish "no samples yet" (`None` above)
984 /// from "exactly one, possibly unrepresentative, sample". Counts live
985 /// measurements, not durable JSONL rows.
986 pub working_context_pct_sample_count: usize,
987 /// (issue #3911) Lifetime, cross-session count of a cadence-level
988 /// 60%-floor breach (`CadenceOutcome::within_budget == false` after
989 /// `cadence::enforce_budget` exhausted every eligible entry) — the
990 /// backstop's own alarm, mirroring `lifetime_compaction_alarm_count`
991 /// exactly but keyed to the cadence mechanism's OWN floor guarantee
992 /// rather than the mechanically-independent threshold compactor's
993 /// separate 75%-of-window trigger (see
994 /// `agent_loop::telemetry::record_cadence_floor_breach`'s docs for why
995 /// the two alarms cannot be the same counter). Same "placeholder `0` on
996 /// the write path, real read on the query path" pattern.
997 pub lifetime_cadence_floor_breach_count: u64,
998}
999
1000/// One row in a session's RETAINED search/recall audit trail (issue #3072;
1001/// backs `session.get_search_audit` / `GET /sessions/{id}/search-audit` —
1002/// DOC-39 §4.7's Search tab (10d) and the #3027 8b monitor card).
1003///
1004/// Why: [`Event::SearchPerformed`]/[`Event::MemoryRecalled`] are emitted only
1005/// on the SSE stream, so a client that attaches after either fired — or never
1006/// opens an SSE connection at all, per DOC-39 §2.1's thin-REST-client
1007/// constraint — has no way to see search/recall history. This is the
1008/// per-record projection `SessionRegistry::push_search_audit`
1009/// (`session::registry_search_audit`) appends to `SessionEntry::search_audit`
1010/// from the SAME call `record_search_performed`/`record_memory_recalled`
1011/// already makes to emit the live event, so the retained list and the SSE
1012/// stream can never disagree about what happened. Retention is capped at
1013/// `session::registry_search_audit::SEARCH_AUDIT_CAP` records, oldest
1014/// dropped first — mirrors the ring buffer's own eviction policy, so a
1015/// long-running session's memory use stays bounded.
1016/// What: `#[serde(tag = "kind", rename_all = "snake_case")]` — `Search`
1017/// mirrors [`Event::SearchPerformed`]'s `lane`/`query`/`hit_count`/
1018/// `latency_ms` fields verbatim; per-hit path/score detail is deliberately
1019/// NOT retained here (`hit_count` already answers "how many" — carrying
1020/// every hit for up to `SEARCH_AUDIT_CAP` records would be unbounded per-hit
1021/// growth this audit trail does not need). `Recall` mirrors
1022/// [`Event::MemoryRecalled`]'s `query`, plus `result_count`/`injected_count`
1023/// folded from `results` (the recalled TEXT itself is likewise not retained,
1024/// same rationale). Both variants carry `agent`/`agent_id` (DOC-39 AC-13
1025/// attribution) and `at` — the wall-clock time the record was appended,
1026/// generated here because neither source event carries its own timestamp,
1027/// giving DOC-39 AC-7.2's "age" column something to compute from.
1028/// Test: `session::registry_search_audit::tests::*`.
1029#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
1030#[serde(tag = "kind", rename_all = "snake_case")]
1031pub enum SearchAuditRecord {
1032 Search {
1033 agent: String,
1034 agent_id: String,
1035 lane: String,
1036 query: String,
1037 hit_count: Option<usize>,
1038 latency_ms: u64,
1039 at: DateTime<Utc>,
1040 },
1041 Recall {
1042 agent: String,
1043 agent_id: String,
1044 query: String,
1045 result_count: usize,
1046 injected_count: usize,
1047 at: DateTime<Utc>,
1048 },
1049}
1050
1051impl Event {
1052 /// Return the event's `session_id` if it has one. Used by the SSE
1053 /// handler to filter the broadcast stream to a single task subscription.
1054 ///
1055 /// Why: Variants without a session (currently just `Ping`) must always
1056 /// pass the filter — losing keepalives would defeat their purpose.
1057 /// What: Returns `Some(&str)` for variants that carry a session, `None`
1058 /// for keepalives. The SSE filter treats `None` as "always include".
1059 pub fn session_id(&self) -> Option<&str> {
1060 match self {
1061 Event::SessionStarted { session_id, .. }
1062 | Event::SessionDone { session_id, .. }
1063 | Event::SessionCancelled { session_id }
1064 | Event::SessionStatusChanged { session_id, .. }
1065 | Event::SessionInput { session_id, .. }
1066 | Event::ToolStarted { session_id, .. }
1067 | Event::ToolFinished { session_id, .. }
1068 | Event::ToolError { session_id, .. }
1069 | Event::SearchPerformed { session_id, .. }
1070 | Event::MemoryRecalled { session_id, .. }
1071 | Event::Log { session_id, .. }
1072 | Event::Progress { session_id, .. }
1073 | Event::Message { session_id, .. }
1074 | Event::PmThinking { session_id, .. }
1075 | Event::PmDelegating { session_id, .. }
1076 | Event::AgentSpawned { session_id, .. }
1077 | Event::AgentMessage { session_id, .. }
1078 | Event::AgentMessageDelta { session_id, .. }
1079 | Event::AgentDone { session_id, .. }
1080 | Event::AgentFailed { session_id, .. }
1081 | Event::ToolCalled { session_id, .. }
1082 | Event::ToolResult { session_id, .. }
1083 | Event::AstOperation { session_id, .. }
1084 | Event::PhaseStarted { session_id, .. }
1085 | Event::PhaseDone { session_id, .. }
1086 | Event::PhaseSkipped { session_id, .. }
1087 | Event::PersonaDetected { session_id, .. }
1088 | Event::LlmRequested { session_id, .. }
1089 | Event::LlmResponded { session_id, .. }
1090 | Event::AgentStarted { session_id, .. }
1091 | Event::ReportGenerated { session_id, .. }
1092 | Event::RecapGenerated { session_id, .. }
1093 | Event::IndexReadiness { session_id, .. }
1094 | Event::ContextBudget { session_id, .. }
1095 | Event::SessionAdded { session_id, .. }
1096 | Event::SessionActivityUpdate { session_id, .. } => Some(session_id),
1097 Event::WorkstreamActivationChanged { .. }
1098 | Event::WorkstreamStateInferred { .. }
1099 | Event::Ping => None,
1100 }
1101 }
1102
1103 /// The stable `kind` string for this event — identical to the serde
1104 /// `"type"` tag `#[serde(tag = "type", rename_all = "snake_case")]`
1105 /// produces on the wire.
1106 ///
1107 /// Why (#2055): `SessionEventEnvelope` carries `kind` as a top-level
1108 /// field (vision spec's envelope requirement) so a client can filter/
1109 /// route on it without parsing into the nested `event` payload. Hand-
1110 /// written rather than derived from serde reflection (no such API exists
1111 /// without an extra dependency) — `kind_matches_serde_tag_for_every_variant`
1112 /// guards the two from drifting apart.
1113 /// What: Returns the exact snake_case tag string for every variant.
1114 /// Test: `kind_matches_serde_tag_for_every_variant`.
1115 pub fn kind(&self) -> &'static str {
1116 match self {
1117 Event::SessionStarted { .. } => "session_started",
1118 Event::SessionDone { .. } => "session_done",
1119 Event::SessionCancelled { .. } => "session_cancelled",
1120 Event::SessionStatusChanged { .. } => "session_status_changed",
1121 Event::SessionInput { .. } => "session_input",
1122 Event::ToolStarted { .. } => "tool_started",
1123 Event::ToolFinished { .. } => "tool_finished",
1124 Event::ToolError { .. } => "tool_error",
1125 Event::SearchPerformed { .. } => "search_performed",
1126 Event::MemoryRecalled { .. } => "memory_recalled",
1127 Event::Log { .. } => "log",
1128 Event::Progress { .. } => "progress",
1129 Event::Message { .. } => "message",
1130 Event::PmThinking { .. } => "pm_thinking",
1131 Event::PmDelegating { .. } => "pm_delegating",
1132 Event::AgentSpawned { .. } => "agent_spawned",
1133 Event::AgentMessage { .. } => "agent_message",
1134 Event::AgentMessageDelta { .. } => "agent_message_delta",
1135 Event::AgentDone { .. } => "agent_done",
1136 Event::AgentFailed { .. } => "agent_failed",
1137 Event::ToolCalled { .. } => "tool_called",
1138 Event::ToolResult { .. } => "tool_result",
1139 Event::AstOperation { .. } => "ast_operation",
1140 Event::PhaseStarted { .. } => "phase_started",
1141 Event::PhaseDone { .. } => "phase_done",
1142 Event::PhaseSkipped { .. } => "phase_skipped",
1143 Event::PersonaDetected { .. } => "persona_detected",
1144 Event::LlmRequested { .. } => "llm_requested",
1145 Event::LlmResponded { .. } => "llm_responded",
1146 Event::AgentStarted { .. } => "agent_started",
1147 Event::ReportGenerated { .. } => "report_generated",
1148 Event::RecapGenerated { .. } => "recap_generated",
1149 Event::IndexReadiness { .. } => "index_readiness",
1150 Event::ContextBudget { .. } => "context_budget",
1151 Event::SessionAdded { .. } => "session_added",
1152 Event::SessionActivityUpdate { .. } => "session_activity_update",
1153 Event::WorkstreamActivationChanged { .. } => "workstream_activation_changed",
1154 Event::WorkstreamStateInferred { .. } => "workstream_state_inferred",
1155 Event::Ping => "ping",
1156 }
1157 }
1158}
1159
1160/// The stable, sequenced wire envelope for one session's event (#2055).
1161///
1162/// Why: `session.attach`'s ring-buffer replay and every live notification
1163/// thereafter (both STDIO `session.event` notifications and the HTTP
1164/// `GET /sessions/{id}/events` SSE stream) need the SAME shape so a client
1165/// can detect gaps and stitch replay -> live into one ordered stream. See
1166/// the module docs for how this aligns with / diverges from
1167/// `trusty-agents-common`'s `HarnessEvent` convention.
1168/// What: `session_id` (always present — every event this daemon emits is
1169/// session-scoped), `seq` (per-session monotonic, assigned by
1170/// `session::registry::SessionRegistry::record`, starting at 1), `at` (UTC
1171/// emit timestamp), `kind` (== `event.kind()`, duplicated at the top level
1172/// for cheap client-side filtering), and `event` (the full tagged payload).
1173/// Test: `session_event_envelope_round_trips_through_json`.
1174#[derive(Debug, Clone, Serialize, Deserialize)]
1175pub struct SessionEventEnvelope {
1176 pub session_id: String,
1177 pub seq: u64,
1178 pub at: DateTime<Utc>,
1179 pub kind: String,
1180 pub event: Event,
1181}
1182
1183impl SessionEventEnvelope {
1184 /// Build an envelope for `event`, computing `kind` from
1185 /// [`Event::kind`].
1186 ///
1187 /// Why: the one place `kind` is derived from `event`, so the two can
1188 /// never be constructed out of sync.
1189 /// What: `session_id`/`seq`/`at` are supplied by the caller (the
1190 /// registry, which owns the per-session sequence counter); `kind` is
1191 /// computed here.
1192 /// Test: `session_event_envelope_round_trips_through_json`.
1193 pub fn new(session_id: String, seq: u64, at: DateTime<Utc>, event: Event) -> Self {
1194 let kind = event.kind().to_string();
1195 Self {
1196 session_id,
1197 seq,
1198 at,
1199 kind,
1200 event,
1201 }
1202 }
1203}
1204
1205/// Process-global event bus, initialised on first access.
1206///
1207/// Why: Threading a `broadcast::Sender<SessionEventEnvelope>` through every
1208/// code path that might want to emit telemetry (workflow engine, agent
1209/// runners, ctrl) would touch hundreds of function signatures. A `OnceLock`
1210/// mirrors how `tracing` solves the same problem — emit-from-anywhere with
1211/// zero overhead when no one is listening. Carries the full envelope
1212/// (#2055), not a bare `Event`, since every current producer
1213/// (`session::registry::SessionRegistry`) and every current consumer (the
1214/// STDIO forwarder, the HTTP SSE route) is session-scoped and needs `seq`/
1215/// `at`/`kind` alongside the payload — see the module docs for the
1216/// `HarnessEvent` alignment/divergence rationale.
1217/// What: `Sender::send` is non-blocking; when there are no subscribers it
1218/// returns an error which we silently drop (events without listeners are
1219/// the expected baseline).
1220static EVENT_BUS: OnceLock<broadcast::Sender<SessionEventEnvelope>> = OnceLock::new();
1221
1222/// Get (or initialise) the process-global event bus sender.
1223///
1224/// Why: Called from any code path that wants to emit. First call wins; all
1225/// subsequent calls receive the same `Sender`. Cheap (single atomic load on
1226/// the hot path).
1227/// What: Returns a clone of the global sender. The receiver half is created
1228/// per subscriber via `subscribe()`.
1229/// Test: `bus_is_singleton` confirms repeated calls return the same channel.
1230pub fn bus() -> broadcast::Sender<SessionEventEnvelope> {
1231 EVENT_BUS
1232 .get_or_init(|| broadcast::channel(CHANNEL_CAPACITY).0)
1233 .clone()
1234}
1235
1236/// Subscribe to all future events on the global bus.
1237///
1238/// Why: SSE handlers + tests both need a fresh receiver without sharing one.
1239/// `broadcast::Receiver::recv` is `&mut self` so each subscriber owns one.
1240/// What: Returns a new `Receiver` that begins receiving events emitted after
1241/// the call returns. Lagged subscribers receive `RecvError::Lagged(n)` and
1242/// can resume.
1243pub fn subscribe() -> broadcast::Receiver<SessionEventEnvelope> {
1244 bus().subscribe()
1245}
1246
1247/// Publish one envelope to the bus (best-effort, never panics).
1248///
1249/// Why: Most callers don't care whether anyone is listening — events are
1250/// telemetry, not control flow. Failures (no subscribers) are normal. The
1251/// envelope (not a bare `Event`) is the unit of publication so `seq`/`at`
1252/// travel with the payload to every subscriber, including a client that
1253/// only just attached.
1254/// What: Sends the envelope on the broadcast channel, ignoring `SendError`.
1255/// Test: `publish_round_trips_through_subscribe`.
1256pub fn publish(envelope: SessionEventEnvelope) {
1257 let _ = bus().send(envelope);
1258}
1259
1260/// Publish an envelope AND emit it on stderr with the `__OMPM_EVENT__` prefix
1261/// so a parent process can re-broadcast on its own bus.
1262///
1263/// Why: Workflow runs spawn as `tcode --workflow ...` subprocesses of the
1264/// API server (`api/server.rs::run_task`). Events emitted inside that child
1265/// reach the parent's bus only via the existing stderr stream. This helper
1266/// does both in one call so emit sites don't have to know whether they're
1267/// running as a child.
1268/// What: Calls `publish(envelope.clone())` for in-process subscribers, then
1269/// writes one NDJSON line to stderr prefixed with `__OMPM_EVENT__ `. The
1270/// parent's stderr reader (in `api::server::run_task`) detects the prefix
1271/// and re-publishes on its own bus.
1272/// Test: `events_tests::sm_harness_doc_documents_the_prefix_tcode_emits`
1273/// covers the wire line via `format_event_line`; the stderr write itself is
1274/// exercised by the workflow integration path.
1275pub fn emit(envelope: SessionEventEnvelope) {
1276 let line = format_event_line(&envelope);
1277 publish(envelope);
1278 if let Some(line) = line {
1279 eprintln!("{line}");
1280 }
1281}
1282
1283/// Format the single stderr relay line `emit` writes for `envelope`, or `None`
1284/// if it cannot be serialised.
1285///
1286/// Why: the relay line is a cross-process wire format, and the session
1287/// manager's harness-understanding doc tells an operator which prefix to look
1288/// for. Splitting formatting out of `emit` lets a test compare the REAL
1289/// emitted line against that doc instead of against a copy of the literal —
1290/// the divergence #5129 recorded was invisible precisely because every test
1291/// pinned a constant to itself.
1292/// What: returns `EVENT_LINE_PREFIX` concatenated with the compact JSON of the
1293/// envelope; `None` only on the (practically impossible) serde failure.
1294/// Test: `events_tests::sm_harness_doc_documents_the_prefix_tcode_emits`.
1295pub fn format_event_line(envelope: &SessionEventEnvelope) -> Option<String> {
1296 serde_json::to_string(envelope)
1297 .ok()
1298 .map(|json| format!("{EVENT_LINE_PREFIX}{json}"))
1299}
1300
1301/// Truncate a string to at most `max` characters, appending an ellipsis
1302/// marker when truncation occurred. Operates on chars (not bytes) so
1303/// multi-byte characters are not split.
1304///
1305/// Why: Event payloads should be human-readable previews; raw multi-KB
1306/// agent outputs would saturate the broadcast channel and overwhelm the SSE
1307/// stream. Centralising preview construction keeps emit sites tidy.
1308/// What: Returns `s` unchanged when shorter than `max`; otherwise returns
1309/// the first `max` chars plus a Unicode horizontal ellipsis.
1310pub fn preview(s: &str, max: usize) -> String {
1311 if s.chars().count() <= max {
1312 return s.to_string();
1313 }
1314 let mut out: String = s.chars().take(max).collect();
1315 out.push('\u{2026}');
1316 out
1317}
1318
1319#[cfg(test)]
1320#[path = "events_tests.rs"]
1321mod tests;