Skip to main content

openbutler_protocol/
eventlog.rs

1//! The event log contract: record schema, levels and the event catalog.
2//!
3//! The daemon writes one JSON record per line; this module is the typed
4//! shape of that record and the registry of event names. Both sides depend
5//! on it: the daemon builds a [`LogRecord`] before anything reaches disk,
6//! and a client types what it reads without parsing by position.
7//!
8//! Two rules live here because they are the contract, not the writer:
9//!
10//! - An event name is `category.action` — lowercase ASCII segments joined
11//!   by one dot (`door.first_event_timeout`). The shape is validated, so a
12//!   name that does not parse cannot be catalogued or emitted honestly.
13//! - The catalog grows without breaking. A client that meets an event name
14//!   it does not know still renders the record (level, title, description
15//!   carry the meaning); a new catalog entry never requires a client
16//!   update.
17//!
18//! Schema numbers travel in every record. `schema` 0 marks a legacy line
19//! written before this module existed (flat fields, no `eventid`); the
20//! current shape is [`LOG_SCHEMA`]. Old records stay readable — the
21//! reader never requires a future field.
22
23use serde::{Deserialize, Serialize};
24
25/// The record schema this crate writes and understands today.
26pub const LOG_SCHEMA: u32 = 1;
27
28/// The five levels, ordered from most to least severe. The ordering is the
29/// wire contract: a threshold at `info` lets `error`, `warn` and `info`
30/// through and drops `debug` and `trace`.
31#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
32#[serde(rename_all = "lowercase")]
33pub enum LogLevel {
34    /// Something failed.
35    Error,
36    /// Something looks wrong but the caller continued.
37    Warn,
38    /// Normal lifecycle news.
39    Info,
40    /// Detail for diagnosis.
41    Debug,
42    /// The finest grain: per-step traces for one investigation.
43    Trace,
44}
45
46impl LogLevel {
47    /// The threshold position: lower lets more through.
48    pub const fn order(self) -> u8 {
49        match self {
50            LogLevel::Error => 0,
51            LogLevel::Warn => 1,
52            LogLevel::Info => 2,
53            LogLevel::Debug => 3,
54            LogLevel::Trace => 4,
55        }
56    }
57
58    /// Builds a level from its threshold position.
59    pub fn from_order(order: u8) -> Option<Self> {
60        match order {
61            0 => Some(LogLevel::Error),
62            1 => Some(LogLevel::Warn),
63            2 => Some(LogLevel::Info),
64            3 => Some(LogLevel::Debug),
65            4 => Some(LogLevel::Trace),
66            _ => None,
67        }
68    }
69
70    /// The lowercase word the record carries.
71    pub const fn as_str(self) -> &'static str {
72        match self {
73            LogLevel::Error => "error",
74            LogLevel::Warn => "warn",
75            LogLevel::Info => "info",
76            LogLevel::Debug => "debug",
77            LogLevel::Trace => "trace",
78        }
79    }
80
81    /// Parses a level word (the CLI's `--level` values included).
82    pub fn parse(value: &str) -> Option<Self> {
83        match value {
84            "error" => Some(LogLevel::Error),
85            "warn" => Some(LogLevel::Warn),
86            "info" => Some(LogLevel::Info),
87            "debug" => Some(LogLevel::Debug),
88            "trace" => Some(LogLevel::Trace),
89            _ => None,
90        }
91    }
92}
93
94/// One structured log record — the 12-field schema. `event`, `ts` and
95/// `level` are required (the same three the legacy line contract
96/// required); every field the new shape added carries a default so a
97/// legacy (`schema` 0) flat line still parses. The optional pair
98/// (`session`, `extra`) is skipped when empty so a line carries no noise.
99#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
100pub struct LogRecord {
101    /// The record shape number; [`LOG_SCHEMA`] for new records, 0 legacy.
102    #[serde(default)]
103    pub schema: u32,
104    /// The catalogued event name, `category.action`.
105    pub event: String,
106    /// The record's own id: `log-` plus the registry's random part.
107    #[serde(default)]
108    pub eventid: String,
109    /// Full timestamp with timezone, RFC 3339.
110    pub ts: String,
111    /// The level this record is written at.
112    pub level: LogLevel,
113    /// Short human headline.
114    #[serde(default)]
115    pub title: String,
116    /// One sentence saying what happened.
117    #[serde(default)]
118    pub description: String,
119    /// The status or error code (`FirstEventTimeout`), empty when none.
120    #[serde(default)]
121    pub code: String,
122    /// The subsystem category — the segment before the dot in `event`.
123    #[serde(default)]
124    pub category: String,
125    /// The session this record belongs to, when it belongs to one.
126    #[serde(default, skip_serializing_if = "Option::is_none")]
127    pub session: Option<String>,
128    /// Which product wrote the record (`daemon`, `cli`).
129    #[serde(default)]
130    pub source: String,
131    /// Structured detail; credential-shaped values are redacted before
132    /// this map is written.
133    #[serde(default, skip_serializing_if = "Option::is_none")]
134    pub extra: Option<serde_json::Map<String, serde_json::Value>>,
135}
136
137/// Whether `name` is a valid event name: exactly one dot, two lowercase
138/// ASCII segments (`[a-z][a-z0-9_]*`), at most 64 bytes overall.
139pub fn is_valid_event_name(name: &str) -> bool {
140    if name.is_empty() || name.len() > 64 || name.contains("..") {
141        return false;
142    }
143    let mut segments = name.split('.');
144    let (Some(category), Some(action), None) = (segments.next(), segments.next(), segments.next())
145    else {
146        return false;
147    };
148    is_segment(category) && is_segment(action)
149}
150
151fn is_segment(segment: &str) -> bool {
152    let bytes = segment.as_bytes();
153    bytes.first().is_some_and(|byte| byte.is_ascii_lowercase())
154        && bytes
155            .iter()
156            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'_')
157}
158
159/// One catalogued event: its name and what it means.
160#[derive(Debug, Clone, Copy, PartialEq, Eq)]
161pub struct LogEvent {
162    /// The `category.action` name.
163    pub name: &'static str,
164    /// What this event means, for clients that show a legend.
165    pub description: &'static str,
166}
167
168/// The event catalog. Additive: entries join, existing entries stay, and a
169/// client must never need an update to render a name it does not know.
170/// The daemon pins the other direction with a test that every catalogued
171/// name is actually emitted somewhere in its source.
172pub const EVENTS: &[LogEvent] = &[
173    // Lifecycle (host).
174    LogEvent {
175        name: "host.started",
176        description: "The daemon process started and holds its entry lock.",
177    },
178    LogEvent {
179        name: "host.stopped",
180        description: "The daemon shut down cleanly after draining.",
181    },
182    LogEvent {
183        name: "host.log",
184        description: "A lifecycle line the daemon echoes into the log.",
185    },
186    LogEvent {
187        name: "host.listen_refused",
188        description: "The remote listener stayed closed, with the reason.",
189    },
190    // The transport door.
191    LogEvent {
192        name: "door.first_event_timeout",
193        description: "A call got no event before the first-event deadline.",
194    },
195    LogEvent {
196        name: "door.inter_event_timeout",
197        description: "A call went quiet for longer than the quiet window.",
198    },
199    LogEvent {
200        name: "door.queue_timeout",
201        description: "A queued call waited longer than the queue window.",
202    },
203    LogEvent {
204        name: "door.call_failed",
205        description: "A routed call ended with a transport error.",
206    },
207    // The model process.
208    LogEvent {
209        name: "sidecar.spawned",
210        description: "A model process started and the door went ready.",
211    },
212    LogEvent {
213        name: "sidecar.spawn_failed",
214        description: "A model process would not start; stderr tail attached.",
215    },
216    LogEvent {
217        name: "sidecar.exited",
218        description: "A model process ended; status recorded when known.",
219    },
220    // Provider-facing turn outcomes.
221    LogEvent {
222        name: "provider.turn_failed",
223        description: "A turn ended in failure; the error text is attached.",
224    },
225    LogEvent {
226        name: "provider.compact_failed",
227        description: "A compaction ended in failure; the error text is attached.",
228    },
229    // Audit stream (separate append-only file, hash-chained; the
230    // operational log never carries these and vice versa).
231    LogEvent {
232        name: "audit.login",
233        description: "A remote login attempt answered; see result (ok, denied, failed).",
234    },
235    LogEvent {
236        name: "audit.admin_created",
237        description: "The admin account was created on the host machine.",
238    },
239    LogEvent {
240        name: "audit.key_changed",
241        description: "A provider API key was added or removed.",
242    },
243    LogEvent {
244        name: "audit.permissions_changed",
245        description: "The approval mode or a permission changed.",
246    },
247    LogEvent {
248        name: "audit.settings_changed",
249        description: "A host setting changed (listen target, setup save).",
250    },
251    LogEvent {
252        name: "audit.backup_taken",
253        description: "A data-directory snapshot was written.",
254    },
255    LogEvent {
256        name: "audit.autostart_changed",
257        description: "The login entry was written or removed.",
258    },
259    LogEvent {
260        name: "audit.pruned",
261        description: "Old sessions or ledger rows were pruned.",
262    },
263    LogEvent {
264        name: "audit.refused",
265        description: "A connection asked for something its authority does not cover.",
266    },
267];
268
269/// The catalog entry for `name`, or `None`.
270pub fn find_event(name: &str) -> Option<&'static LogEvent> {
271    EVENTS.iter().find(|event| event.name == name)
272}
273
274#[cfg(test)]
275mod tests {
276    #![allow(clippy::unwrap_used, clippy::expect_used)]
277
278    use super::*;
279    use serde_json::json;
280
281    #[test]
282    fn event_names_are_category_dot_action() {
283        for valid in [
284            "host.started",
285            "door.first_event_timeout",
286            "provider.turn_failed",
287            "a.b",
288        ] {
289            assert!(is_valid_event_name(valid), "{valid} must be valid");
290        }
291        for invalid in [
292            "",
293            "host",
294            "host.",
295            ".started",
296            "host..started",
297            "Host.started",
298            "host.started.extra",
299            "host.started extra",
300            "hoSt.started",
301            "1host.started",
302            &"x".repeat(65),
303        ] {
304            assert!(!is_valid_event_name(invalid), "{invalid} must be rejected");
305        }
306    }
307
308    #[test]
309    fn every_catalog_entry_is_a_valid_unique_name() {
310        let mut seen = std::collections::HashSet::new();
311        for event in EVENTS {
312            assert!(
313                is_valid_event_name(event.name),
314                "{} must be category.action",
315                event.name
316            );
317            assert!(seen.insert(event.name), "{} must be unique", event.name);
318            assert!(!event.description.is_empty());
319        }
320        assert!(!EVENTS.is_empty());
321    }
322
323    #[test]
324    fn a_full_record_round_trips_through_serde() {
325        let record = LogRecord {
326            schema: LOG_SCHEMA,
327            event: "door.first_event_timeout".to_owned(),
328            eventid: "log-8Yq2LxK1vR0pNmT".to_owned(),
329            ts: "2026-11-30T18:59:42.119Z".to_owned(),
330            level: LogLevel::Error,
331            title: "Door waited for a first event".to_owned(),
332            description: "No event arrived before the first-event deadline".to_owned(),
333            code: "FirstEventTimeout".to_owned(),
334            category: "door".to_owned(),
335            session: Some("ses-GX3H0HBL7".to_owned()),
336            source: "daemon".to_owned(),
337            extra: Some(serde_json::Map::from_iter([(
338                "door".to_owned(),
339                json!("/api/attach"),
340            )])),
341        };
342        let text = serde_json::to_string(&record).unwrap();
343        let back: LogRecord = serde_json::from_str(&text).unwrap();
344        assert_eq!(back, record);
345        let value: serde_json::Value = serde_json::from_str(&text).unwrap();
346        assert_eq!(value["schema"], 1);
347        assert_eq!(value["level"], "error");
348        assert_eq!(value["session"], "ses-GX3H0HBL7");
349        assert_eq!(value["extra"]["door"], "/api/attach");
350    }
351
352    #[test]
353    fn a_legacy_flat_line_still_parses() {
354        // What the writer emitted before this module: flat fields, no
355        // eventid, no schema. The reader must keep it.
356        let legacy = json!({
357            "ts": "2026-11-26T09:39:12.000Z",
358            "level": "info",
359            "event": "host.started",
360            "pid": 4242
361        });
362        let record: LogRecord = serde_json::from_value(legacy).unwrap();
363        assert_eq!(record.schema, 0, "no schema field means legacy");
364        assert_eq!(record.event, "host.started");
365        assert_eq!(record.eventid, "", "legacy lines carry no id");
366        assert_eq!(record.source, "");
367        assert!(record.extra.is_none());
368    }
369
370    #[test]
371    fn the_level_order_is_the_wire_contract() {
372        assert_eq!(LogLevel::Error.order(), 0);
373        assert_eq!(LogLevel::Trace.order(), 4);
374        assert!(LogLevel::Error < LogLevel::Warn);
375        assert!(LogLevel::Debug < LogLevel::Trace);
376        for word in ["error", "warn", "info", "debug", "trace"] {
377            let level = LogLevel::parse(word).unwrap();
378            assert_eq!(level.as_str(), word);
379            assert_eq!(LogLevel::from_order(level.order()), Some(level));
380        }
381        assert_eq!(LogLevel::parse("verbose"), None);
382        assert_eq!(LogLevel::from_order(9), None);
383    }
384}