//! Wake-signal writer: notifies the hyperhive harness when an incoming //! matrix event arrives so claude drives a new turn. //! //! Same wire shape as `hive-ag3nt::forge_notify`'s wake: a single JSON //! line written to the hyperhive control socket (`/run/hive/mcp.sock` //! by default) carrying an `AgentRequest::Wake { from, body }`. //! The agent harness's `agent_server` parses it and treats it as a //! `Wake` from the matrix subsystem. //! //! Per mara's call on #548 phase 3: the body is a SHORT TEASER, not //! the full message — the agent then reads the unmarked event via //! the `read_room` MCP tool. Truncation to ~100 chars keeps the wake //! prompt focused (`forge_notify` embeds longer excerpts because the //! agent doesn't have a follow-up read-the-original tool for forge). use std::path::Path; use anyhow::{Context, Result}; use tokio::io::AsyncWriteExt; use tokio::net::UnixStream; /// Max characters of `body` to embed in the wake payload. Shorter than /// `forge_notify`'s 500-byte excerpt because the agent has a follow-up /// `read_room` tool to fetch the full event. pub const WAKE_BODY_TRUNCATE: usize = 100; /// Send an `AgentRequest::Wake { from: "matrix", body }` to the hyperhive /// control socket at `socket`. Best-effort: returns Err on any plumbing /// failure; callers log + ignore so a wake delivery hiccup doesn't tear /// down the matrix sync loop. pub async fn send_wake(socket: &Path, body: impl AsRef) -> Result<()> { let payload = serde_json::json!({ "kind": "wake", "from": "matrix", "body": body.as_ref(), }); let line = format!("{}\n", serde_json::to_string(&payload)?); let mut stream = UnixStream::connect(socket) .await .with_context(|| format!("connect hyperhive socket {}", socket.display()))?; stream .write_all(line.as_bytes()) .await .with_context(|| format!("write wake to {}", socket.display()))?; stream .shutdown() .await .with_context(|| format!("shutdown write to {}", socket.display()))?; Ok(()) } /// Format a wake-message body from a matrix event's sender + room /// canonical alias + body text. Truncates at [`WAKE_BODY_TRUNCATE`] /// chars with an ellipsis. Shape: `[matrix] in : ` /// matches the `forge_notify` `[issue …]` framing convention. #[must_use] pub fn format_wake_body(sender: &str, room: &str, text: &str) -> String { let truncated = truncate_chars(text, WAKE_BODY_TRUNCATE); format!("[matrix] {sender} in {room}: {truncated}") } /// Truncate `s` to `max` Unicode chars, appending `…` when cut. /// Char-based not byte-based so multi-byte content (most chat) doesn't /// get cut mid-codepoint. fn truncate_chars(s: &str, max: usize) -> String { let mut end = s.len(); for (count, (i, _)) in s.char_indices().enumerate() { if count == max { end = i; break; } } if end == s.len() { s.to_owned() } else { format!("{}…", &s[..end]) } } #[cfg(test)] mod tests { use super::*; #[test] fn format_wake_body_short_passes_through() { let body = format_wake_body("@iris:matrix.darkest.space", "#general", "hi all"); assert_eq!( body, "[matrix] @iris:matrix.darkest.space in #general: hi all" ); } #[test] fn format_wake_body_long_truncates_with_ellipsis() { let long = "x".repeat(200); let body = format_wake_body("@iris:m", "#x", &long); assert!(body.contains("xxxxxxx")); assert!(body.ends_with("…")); // Header + truncated body should be well under the absolute // wake-message ceiling (forge_notify uses ~600 bytes; we're // way under that). assert!(body.len() < 200); } #[test] fn truncate_chars_handles_multibyte() { // `ü` is 2 bytes / 1 char. truncating to 3 chars on "üüüüüü" // should yield "üüü…" not "üü\xc3…" (mid-codepoint). let s = "üüüüüü"; let t = truncate_chars(s, 3); assert_eq!(t, "üüü…"); } #[test] fn truncate_chars_no_op_below_limit() { let s = "hi"; assert_eq!(truncate_chars(s, 100), "hi"); } }