openbutler-protocol 0.0.2

The wire contract between the OpenButler daemon and its clients: frame encoding, action envelopes, and the shared state types.
Documentation
//! The event log contract: record schema, levels and the event catalog.
//!
//! The daemon writes one JSON record per line; this module is the typed
//! shape of that record and the registry of event names. Both sides depend
//! on it: the daemon builds a [`LogRecord`] before anything reaches disk,
//! and a client types what it reads without parsing by position.
//!
//! Two rules live here because they are the contract, not the writer:
//!
//! - An event name is `category.action` — lowercase ASCII segments joined
//!   by one dot (`door.first_event_timeout`). The shape is validated, so a
//!   name that does not parse cannot be catalogued or emitted honestly.
//! - The catalog grows without breaking. A client that meets an event name
//!   it does not know still renders the record (level, title, description
//!   carry the meaning); a new catalog entry never requires a client
//!   update.
//!
//! Schema numbers travel in every record. `schema` 0 marks a legacy line
//! written before this module existed (flat fields, no `eventid`); the
//! current shape is [`LOG_SCHEMA`]. Old records stay readable — the
//! reader never requires a future field.

use serde::{Deserialize, Serialize};

/// The record schema this crate writes and understands today.
pub const LOG_SCHEMA: u32 = 1;

/// The five levels, ordered from most to least severe. The ordering is the
/// wire contract: a threshold at `info` lets `error`, `warn` and `info`
/// through and drops `debug` and `trace`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
    /// Something failed.
    Error,
    /// Something looks wrong but the caller continued.
    Warn,
    /// Normal lifecycle news.
    Info,
    /// Detail for diagnosis.
    Debug,
    /// The finest grain: per-step traces for one investigation.
    Trace,
}

impl LogLevel {
    /// The threshold position: lower lets more through.
    pub const fn order(self) -> u8 {
        match self {
            LogLevel::Error => 0,
            LogLevel::Warn => 1,
            LogLevel::Info => 2,
            LogLevel::Debug => 3,
            LogLevel::Trace => 4,
        }
    }

    /// Builds a level from its threshold position.
    pub fn from_order(order: u8) -> Option<Self> {
        match order {
            0 => Some(LogLevel::Error),
            1 => Some(LogLevel::Warn),
            2 => Some(LogLevel::Info),
            3 => Some(LogLevel::Debug),
            4 => Some(LogLevel::Trace),
            _ => None,
        }
    }

    /// The lowercase word the record carries.
    pub const fn as_str(self) -> &'static str {
        match self {
            LogLevel::Error => "error",
            LogLevel::Warn => "warn",
            LogLevel::Info => "info",
            LogLevel::Debug => "debug",
            LogLevel::Trace => "trace",
        }
    }

    /// Parses a level word (the CLI's `--level` values included).
    pub fn parse(value: &str) -> Option<Self> {
        match value {
            "error" => Some(LogLevel::Error),
            "warn" => Some(LogLevel::Warn),
            "info" => Some(LogLevel::Info),
            "debug" => Some(LogLevel::Debug),
            "trace" => Some(LogLevel::Trace),
            _ => None,
        }
    }
}

/// One structured log record — the 12-field schema. `event`, `ts` and
/// `level` are required (the same three the legacy line contract
/// required); every field the new shape added carries a default so a
/// legacy (`schema` 0) flat line still parses. The optional pair
/// (`session`, `extra`) is skipped when empty so a line carries no noise.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct LogRecord {
    /// The record shape number; [`LOG_SCHEMA`] for new records, 0 legacy.
    #[serde(default)]
    pub schema: u32,
    /// The catalogued event name, `category.action`.
    pub event: String,
    /// The record's own id: `log-` plus the registry's random part.
    #[serde(default)]
    pub eventid: String,
    /// Full timestamp with timezone, RFC 3339.
    pub ts: String,
    /// The level this record is written at.
    pub level: LogLevel,
    /// Short human headline.
    #[serde(default)]
    pub title: String,
    /// One sentence saying what happened.
    #[serde(default)]
    pub description: String,
    /// The status or error code (`FirstEventTimeout`), empty when none.
    #[serde(default)]
    pub code: String,
    /// The subsystem category — the segment before the dot in `event`.
    #[serde(default)]
    pub category: String,
    /// The session this record belongs to, when it belongs to one.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub session: Option<String>,
    /// Which product wrote the record (`daemon`, `cli`).
    #[serde(default)]
    pub source: String,
    /// Structured detail; credential-shaped values are redacted before
    /// this map is written.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub extra: Option<serde_json::Map<String, serde_json::Value>>,
}

/// Whether `name` is a valid event name: exactly one dot, two lowercase
/// ASCII segments (`[a-z][a-z0-9_]*`), at most 64 bytes overall.
pub fn is_valid_event_name(name: &str) -> bool {
    if name.is_empty() || name.len() > 64 || name.contains("..") {
        return false;
    }
    let mut segments = name.split('.');
    let (Some(category), Some(action), None) = (segments.next(), segments.next(), segments.next())
    else {
        return false;
    };
    is_segment(category) && is_segment(action)
}

fn is_segment(segment: &str) -> bool {
    let bytes = segment.as_bytes();
    bytes.first().is_some_and(|byte| byte.is_ascii_lowercase())
        && bytes
            .iter()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || *byte == b'_')
}

/// One catalogued event: its name and what it means.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LogEvent {
    /// The `category.action` name.
    pub name: &'static str,
    /// What this event means, for clients that show a legend.
    pub description: &'static str,
}

/// The event catalog. Additive: entries join, existing entries stay, and a
/// client must never need an update to render a name it does not know.
/// The daemon pins the other direction with a test that every catalogued
/// name is actually emitted somewhere in its source.
pub const EVENTS: &[LogEvent] = &[
    // Lifecycle (host).
    LogEvent {
        name: "host.started",
        description: "The daemon process started and holds its entry lock.",
    },
    LogEvent {
        name: "host.stopped",
        description: "The daemon shut down cleanly after draining.",
    },
    LogEvent {
        name: "host.log",
        description: "A lifecycle line the daemon echoes into the log.",
    },
    LogEvent {
        name: "host.listen_refused",
        description: "The remote listener stayed closed, with the reason.",
    },
    // The transport door.
    LogEvent {
        name: "door.first_event_timeout",
        description: "A call got no event before the first-event deadline.",
    },
    LogEvent {
        name: "door.inter_event_timeout",
        description: "A call went quiet for longer than the quiet window.",
    },
    LogEvent {
        name: "door.queue_timeout",
        description: "A queued call waited longer than the queue window.",
    },
    LogEvent {
        name: "door.call_failed",
        description: "A routed call ended with a transport error.",
    },
    // The model process.
    LogEvent {
        name: "sidecar.spawned",
        description: "A model process started and the door went ready.",
    },
    LogEvent {
        name: "sidecar.spawn_failed",
        description: "A model process would not start; stderr tail attached.",
    },
    LogEvent {
        name: "sidecar.exited",
        description: "A model process ended; status recorded when known.",
    },
    // Provider-facing turn outcomes.
    LogEvent {
        name: "provider.turn_failed",
        description: "A turn ended in failure; the error text is attached.",
    },
    LogEvent {
        name: "provider.compact_failed",
        description: "A compaction ended in failure; the error text is attached.",
    },
    // Audit stream (separate append-only file, hash-chained; the
    // operational log never carries these and vice versa).
    LogEvent {
        name: "audit.login",
        description: "A remote login attempt answered; see result (ok, denied, failed).",
    },
    LogEvent {
        name: "audit.admin_created",
        description: "The admin account was created on the host machine.",
    },
    LogEvent {
        name: "audit.key_changed",
        description: "A provider API key was added or removed.",
    },
    LogEvent {
        name: "audit.permissions_changed",
        description: "The approval mode or a permission changed.",
    },
    LogEvent {
        name: "audit.settings_changed",
        description: "A host setting changed (listen target, setup save).",
    },
    LogEvent {
        name: "audit.backup_taken",
        description: "A data-directory snapshot was written.",
    },
    LogEvent {
        name: "audit.autostart_changed",
        description: "The login entry was written or removed.",
    },
    LogEvent {
        name: "audit.pruned",
        description: "Old sessions or ledger rows were pruned.",
    },
    LogEvent {
        name: "audit.refused",
        description: "A connection asked for something its authority does not cover.",
    },
];

/// The catalog entry for `name`, or `None`.
pub fn find_event(name: &str) -> Option<&'static LogEvent> {
    EVENTS.iter().find(|event| event.name == name)
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used)]

    use super::*;
    use serde_json::json;

    #[test]
    fn event_names_are_category_dot_action() {
        for valid in [
            "host.started",
            "door.first_event_timeout",
            "provider.turn_failed",
            "a.b",
        ] {
            assert!(is_valid_event_name(valid), "{valid} must be valid");
        }
        for invalid in [
            "",
            "host",
            "host.",
            ".started",
            "host..started",
            "Host.started",
            "host.started.extra",
            "host.started extra",
            "hoSt.started",
            "1host.started",
            &"x".repeat(65),
        ] {
            assert!(!is_valid_event_name(invalid), "{invalid} must be rejected");
        }
    }

    #[test]
    fn every_catalog_entry_is_a_valid_unique_name() {
        let mut seen = std::collections::HashSet::new();
        for event in EVENTS {
            assert!(
                is_valid_event_name(event.name),
                "{} must be category.action",
                event.name
            );
            assert!(seen.insert(event.name), "{} must be unique", event.name);
            assert!(!event.description.is_empty());
        }
        assert!(!EVENTS.is_empty());
    }

    #[test]
    fn a_full_record_round_trips_through_serde() {
        let record = LogRecord {
            schema: LOG_SCHEMA,
            event: "door.first_event_timeout".to_owned(),
            eventid: "log-8Yq2LxK1vR0pNmT".to_owned(),
            ts: "2026-11-30T18:59:42.119Z".to_owned(),
            level: LogLevel::Error,
            title: "Door waited for a first event".to_owned(),
            description: "No event arrived before the first-event deadline".to_owned(),
            code: "FirstEventTimeout".to_owned(),
            category: "door".to_owned(),
            session: Some("ses-GX3H0HBL7".to_owned()),
            source: "daemon".to_owned(),
            extra: Some(serde_json::Map::from_iter([(
                "door".to_owned(),
                json!("/api/attach"),
            )])),
        };
        let text = serde_json::to_string(&record).unwrap();
        let back: LogRecord = serde_json::from_str(&text).unwrap();
        assert_eq!(back, record);
        let value: serde_json::Value = serde_json::from_str(&text).unwrap();
        assert_eq!(value["schema"], 1);
        assert_eq!(value["level"], "error");
        assert_eq!(value["session"], "ses-GX3H0HBL7");
        assert_eq!(value["extra"]["door"], "/api/attach");
    }

    #[test]
    fn a_legacy_flat_line_still_parses() {
        // What the writer emitted before this module: flat fields, no
        // eventid, no schema. The reader must keep it.
        let legacy = json!({
            "ts": "2026-11-26T09:39:12.000Z",
            "level": "info",
            "event": "host.started",
            "pid": 4242
        });
        let record: LogRecord = serde_json::from_value(legacy).unwrap();
        assert_eq!(record.schema, 0, "no schema field means legacy");
        assert_eq!(record.event, "host.started");
        assert_eq!(record.eventid, "", "legacy lines carry no id");
        assert_eq!(record.source, "");
        assert!(record.extra.is_none());
    }

    #[test]
    fn the_level_order_is_the_wire_contract() {
        assert_eq!(LogLevel::Error.order(), 0);
        assert_eq!(LogLevel::Trace.order(), 4);
        assert!(LogLevel::Error < LogLevel::Warn);
        assert!(LogLevel::Debug < LogLevel::Trace);
        for word in ["error", "warn", "info", "debug", "trace"] {
            let level = LogLevel::parse(word).unwrap();
            assert_eq!(level.as_str(), word);
            assert_eq!(LogLevel::from_order(level.order()), Some(level));
        }
        assert_eq!(LogLevel::parse("verbose"), None);
        assert_eq!(LogLevel::from_order(9), None);
    }
}