subc-daemon 0.55.0

Embeddable subc daemon: bootstrap, module supervision, and opaque-byte splice routing.
Documentation
//! The rule for a module's health `summary`, the one plain sentence a person
//! sees in place of the module's operator `detail`.
//!
//! The daemon relays a summary unchanged when it passes the rule and drops it
//! otherwise. Dropping it never affects the rest of the health answer: the
//! status, detail and metrics still count.

use std::{
    collections::HashSet,
    fmt,
    sync::{Mutex, OnceLock},
};

use subc_protocol::session::HEALTH_SUMMARY_MAX_CHARS;
use tracing::warn;

/// Why a health summary broke the rule.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum SummaryProblem {
    /// Empty, or only whitespace.
    Empty,
    /// More than [`HEALTH_SUMMARY_MAX_CHARS`] Unicode scalar values.
    TooLong,
    /// A line break, so it is not one line.
    LineBreak,
    /// A control character other than a line break.
    ControlCharacter,
    /// A `{` or `[`, which is how JSON gets pasted into prose.
    Json,
    /// A backtick anywhere except around one `ck …` command at the end.
    Backtick,
}

impl SummaryProblem {
    fn label(self) -> &'static str {
        match self {
            Self::Empty => "empty",
            Self::TooLong => "too_long",
            Self::LineBreak => "line_break",
            Self::ControlCharacter => "control_character",
            Self::Json => "json",
            Self::Backtick => "backtick",
        }
    }
}

impl fmt::Display for SummaryProblem {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.label())
    }
}

/// Check `summary` against the rule: one plain line of at most
/// [`HEALTH_SUMMARY_MAX_CHARS`] Unicode scalar values, with no control
/// characters, no line breaks and no `{` or `[`. It may end with one `ck …`
/// command in backticks, optionally followed by `.`, `!` or `?`, and holds no
/// other backticks. Returns the first problem found, or `None` when it passes.
pub(crate) fn health_summary_problem(summary: &str) -> Option<SummaryProblem> {
    if summary.trim().is_empty() {
        return Some(SummaryProblem::Empty);
    }
    if summary.chars().count() > HEALTH_SUMMARY_MAX_CHARS {
        return Some(SummaryProblem::TooLong);
    }
    if summary
        .chars()
        .any(|ch| matches!(ch, '\n' | '\r' | '\u{0085}' | '\u{2028}' | '\u{2029}'))
    {
        return Some(SummaryProblem::LineBreak);
    }
    if summary.chars().any(char::is_control) {
        return Some(SummaryProblem::ControlCharacter);
    }
    if summary.contains(['{', '[']) {
        return Some(SummaryProblem::Json);
    }
    if summary.contains('`') && !ends_with_one_ck_command(summary) {
        return Some(SummaryProblem::Backtick);
    }
    None
}

/// Whether the only backticks in `summary` are one pair around a `ck …`
/// command that ends it, allowing one closing `.`, `!` or `?` after it.
fn ends_with_one_ck_command(summary: &str) -> bool {
    let body = summary.strip_suffix(['.', '!', '?']).unwrap_or(summary);
    let Some(before_close) = body.strip_suffix('`') else {
        return false;
    };
    let Some((before, command)) = before_close.rsplit_once('`') else {
        return false;
    };
    !before.contains('`')
        && command
            .strip_prefix("ck ")
            .is_some_and(|rest| !rest.trim().is_empty())
}

/// The summary to store and relay for `module_id`: `summary` itself when it
/// passes [`health_summary_problem`], otherwise `None`. A dropped summary is
/// logged at WARN once per module per distinct problem, without its text,
/// because the text is what broke the rule and may hold anything.
pub(crate) fn relayed_health_summary(module_id: &str, summary: Option<String>) -> Option<String> {
    let summary = summary?;
    let Some(problem) = health_summary_problem(&summary) else {
        return Some(summary);
    };
    if first_report(module_id, problem) {
        warn!(
            module_id,
            problem = %problem,
            chars = summary.chars().count(),
            "dropped a module's health summary that breaks the summary rule; the rest of its health answer still counts"
        );
    }
    None
}

/// Record that `module_id` sent a summary with `problem`, answering whether
/// this is the first time in this daemon's life.
fn first_report(module_id: &str, problem: SummaryProblem) -> bool {
    static REPORTED: OnceLock<Mutex<HashSet<(String, SummaryProblem)>>> = OnceLock::new();
    REPORTED
        .get_or_init(Default::default)
        .lock()
        .unwrap_or_else(|poisoned| poisoned.into_inner())
        .insert((module_id.to_owned(), problem))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::router::test_log::{captured_logs, log_capture};

    #[test]
    fn health_summary_rule_accepts_plain_sentences_and_one_final_ck_command() {
        for summary in [
            "Running normally.",
            "Two logins need signing in again",
            "Backups are paused until the disk has space. Run `ck health engram`.",
            "Sign in again with `ck auth login --provider anthropic`",
            "Sign in again: `ck auth login`!",
            "Grüße, 日本語 and emoji 🚀 count as one character each.",
        ] {
            assert_eq!(health_summary_problem(summary), None, "{summary}");
        }
        let exactly_max = "a".repeat(HEALTH_SUMMARY_MAX_CHARS);
        assert_eq!(health_summary_problem(&exactly_max), None);
        // The limit counts Unicode scalar values, not bytes.
        let multibyte_max = "é".repeat(HEALTH_SUMMARY_MAX_CHARS);
        assert!(multibyte_max.len() > HEALTH_SUMMARY_MAX_CHARS);
        assert_eq!(health_summary_problem(&multibyte_max), None);
    }

    #[test]
    fn health_summary_rule_names_each_problem() {
        let too_long = "a".repeat(HEALTH_SUMMARY_MAX_CHARS + 1);
        for (summary, problem) in [
            ("", SummaryProblem::Empty),
            ("   ", SummaryProblem::Empty),
            (too_long.as_str(), SummaryProblem::TooLong),
            ("First line\nsecond line", SummaryProblem::LineBreak),
            ("Carriage\rreturn", SummaryProblem::LineBreak),
            ("Line\u{2028}separator", SummaryProblem::LineBreak),
            ("Tab\tinside", SummaryProblem::ControlCharacter),
            ("Escape \u{1b}[31m red", SummaryProblem::ControlCharacter),
            ("Bus {\"connected\":true}", SummaryProblem::Json),
            ("Lanes [1, 2] busy", SummaryProblem::Json),
            ("Check the `work` login", SummaryProblem::Backtick),
            ("Run `ck health` then rest.", SummaryProblem::Backtick),
            (
                "Run `ck auth login`. Then `ck health claustrum`.",
                SummaryProblem::Backtick,
            ),
            ("Run `ck-auth login`.", SummaryProblem::Backtick),
            ("Run `ck `.", SummaryProblem::Backtick),
            ("Run `ck auth login", SummaryProblem::Backtick),
            ("Run ``ck health``.", SummaryProblem::Backtick),
        ] {
            assert_eq!(
                health_summary_problem(summary),
                Some(problem),
                "{summary:?}"
            );
        }
    }

    #[test]
    fn relayed_health_summary_keeps_a_passing_summary_unchanged() {
        let summary = "Backups are paused. Run `ck health engram`.".to_string();
        assert_eq!(
            relayed_health_summary("summary-test-pass", Some(summary.clone())),
            Some(summary)
        );
        assert_eq!(relayed_health_summary("summary-test-pass", None), None);
    }

    #[test]
    fn relayed_health_summary_drops_and_logs_each_problem_once_without_text() {
        let (output, _guard) = log_capture(tracing::Level::WARN);
        let module = "summary-test-drop";
        let json = "Bus {\"secret\":1}".to_string();
        let line_break = "First\nsecond".to_string();
        assert_eq!(relayed_health_summary(module, Some(json.clone())), None);
        assert_eq!(relayed_health_summary(module, Some(json.clone())), None);
        assert_eq!(relayed_health_summary(module, Some(line_break)), None);
        // A second module with the same problem is reported on its own.
        assert_eq!(
            relayed_health_summary("summary-test-drop-other", Some(json)),
            None
        );

        let logs = captured_logs(&output);
        let warnings: Vec<_> = logs.lines().filter(|line| line.contains("WARN")).collect();
        assert_eq!(warnings.len(), 3, "{logs}");
        assert_eq!(
            warnings
                .iter()
                .filter(|line| line.contains("module_id=\"summary-test-drop\"")
                    && line.contains("problem=json"))
                .count(),
            1,
            "{logs}"
        );
        assert!(logs.contains("problem=line_break"), "{logs}");
        assert!(
            logs.contains("module_id=\"summary-test-drop-other\""),
            "{logs}"
        );
        assert!(
            !logs.contains("secret"),
            "the dropped text must not be logged: {logs}"
        );
        assert!(
            !logs.contains("First"),
            "the dropped text must not be logged: {logs}"
        );
    }
}