Skip to main content

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