From fa18ca52fd635623a13c93979c20b27abf1dde6e Mon Sep 17 00:00:00 2001 From: Drake Stapleton Date: Mon, 26 Oct 2026 20:21:18 -0500 Subject: [PATCH 1/4] hive: publish agent responses only, never human messages Drake asked that his own chat messages come off the site. The collector now publishes only an agent's final reply at the end of a turn (OMP, Claude Code and Codex transcripts), screens it for emails, secrets, paths, hosts and private repo names, and withholds any span an agent quotes from a recent human message. Prompt-derived titles are no longer published. The edge receiver refuses a whole snapshot that carries any non-assistant record and keeps the previous one; the Omega renderer refuses the same. The page now reads "What the agents are saying, live". Signed-off-by: Drake Stapleton --- crates/hive-feed/src/bin/hive-receive.rs | 18 +- crates/hive-feed/src/feed.rs | 169 ++++++++++++++++--- crates/hive-feed/src/main.rs | 22 ++- crates/hive-feed/src/privacy.rs | 73 +++++++- crates/hive-feed/src/quotes.rs | 105 ++++++++++++ crates/hive-feed/src/source.rs | 29 ++++ crates/hive-feed/src/tests.rs | 115 +++++++++++-- crates/site-builder/src/components/follow.rs | 4 +- crates/site-builder/src/components/hive.rs | 2 +- crates/site-builder/src/seo.rs | 2 +- om/hive-page/hive.om | 8 +- om/hive-page/main.html | 10 +- om/hive-page/main.html.sha256 | 2 +- om/hive-render/hive-render | Bin 40256 -> 40264 bytes om/hive-render/hive-render.sha256 | 2 +- om/hive-render/render.om | 10 +- om/hive-render/render.om.sha256 | 2 +- om/hive-render/test-receive.py | 14 +- om/hive-render/test-render.py | 13 ++ public/assets/hive.css | 1 - 20 files changed, 529 insertions(+), 72 deletions(-) create mode 100644 crates/hive-feed/src/quotes.rs diff --git a/crates/hive-feed/src/bin/hive-receive.rs b/crates/hive-feed/src/bin/hive-receive.rs index b833596a..64ed102c 100644 --- a/crates/hive-feed/src/bin/hive-receive.rs +++ b/crates/hive-feed/src/bin/hive-receive.rs @@ -79,7 +79,9 @@ fn validate(v: &Value) -> Result<(), ()> { object(m, &["id", "agent_id", "role", "text", "at", "runtime", "provider", "model"])?; if !message_ids.insert(ident(&m["id"])?) { return Err(()); } ident(&m["agent_id"])?; - if !["drake", "assistant"].contains(&text(&m["role"], 20)?) { return Err(()); } + // Agent replies only. A human message (drake, user, guest or any other + // role) refuses the whole snapshot, so the previous one stays served. + if text(&m["role"], 20)? != "assistant" { return Err(()); } text(&m["text"], 16000)?; for key in ["runtime", "provider", "model"] { text(&m[key], LABEL_MAX)?; } stamp(&m["at"], false)?; @@ -202,6 +204,20 @@ mod tests { assert!(validate(&snapshot).is_err()); } #[test] + fn any_human_record_refuses_the_whole_snapshot() { + let reply = serde_json::json!({"id":"m1","agent_id":"a1","role":"assistant","text":"Agent reply","at":"2026-10-25T20:00:00Z","runtime":"OMP","provider":"unknown","model":"unknown"}); + let mut snapshot = empty(); + snapshot["interactions"] = serde_json::json!([reply.clone()]); + assert!(validate(&snapshot).is_ok()); + for role in ["drake", "user", "guest", "human", "developer", "Drake", "assistant "] { + let mut human = reply.clone(); + human["id"] = "m2".into(); human["role"] = role.into(); human["text"] = "Human message".into(); + snapshot["interactions"] = serde_json::json!([reply.clone(), human]); + assert!(validate(&snapshot).is_err(), "{role}"); + assert!(canonical(format!("{snapshot}\n").as_bytes()).is_err(), "{role}"); + } + } + #[test] fn accepts_the_collector_maximum_label_length() { let mut snapshot = empty(); let agent = serde_json::json!({"id":"a1","parent_id":null,"name":"x".repeat(LABEL_MAX),"runtime":"OMP","provider":"unknown","model":"unknown","role":"root","task":"t","status":"working","activity":"","activity_state":"unknown","started_at":null,"updated_at":null,"observed_at":"2026-10-25T20:00:00Z"}); diff --git a/crates/hive-feed/src/feed.rs b/crates/hive-feed/src/feed.rs index 360c3132..b14a7161 100644 --- a/crates/hive-feed/src/feed.rs +++ b/crates/hive-feed/src/feed.rs @@ -1,4 +1,4 @@ -use crate::{privacy::{label, public_text}, source::{self, Cursor}}; +use crate::{privacy::{label, public_text}, quotes::Quotes, source::{self, Cursor}}; use chrono::{DateTime, SecondsFormat, Utc}; use hmac::{Hmac, Mac}; use serde::Serialize; @@ -10,6 +10,16 @@ pub fn timestamp(ms: i64) -> String { DateTime::::from_timestamp_millis(ms) pub fn milliseconds(value: &Value) -> Option { value.as_i64().or_else(|| value.as_str().and_then(|s| DateTime::parse_from_rfc3339(s).ok()).map(|t| t.timestamp_millis())) } fn text<'a>(v: &'a Value, key: &str) -> &'a str { v[key].as_str().unwrap_or("") } fn safe_date(v: &Value) -> Option { milliseconds(v).map(timestamp) } +/// Text parts only: tool calls, tool results, images and reasoning are never joined. +fn joined_text(content: &Value) -> String { + if let Some(s) = content.as_str() { return s.to_owned(); } + let mut joined = String::new(); + for part in content.as_array().into_iter().flatten() { + if !matches!(text(part,"type"), "text" | "input_text" | "output_text") { continue; } + if let Some(t) = part["text"].as_str() { if !joined.is_empty() { joined.push('\n'); } joined.push_str(t); } + } + joined +} #[derive(Clone, Serialize)] pub struct Agent { @@ -17,6 +27,10 @@ pub struct Agent { pub provider: String, pub model: String, pub role: String, pub task: String, pub status: String, pub activity: String, pub activity_state: String, pub started_at: Option, pub updated_at: Option, pub observed_at: String, } +/// Claude Code and Codex transcript directories are listed this often, and a +/// transcript counts as a live session while written within the active window. +const TRANSCRIPT_RESCAN_MS: i64 = 10_000; +const TRANSCRIPT_ACTIVE_MS: i64 = 15 * 60_000; /// The receiver, the client validator and this collector share one window size. const INTERACTION_WINDOW: usize = 100; #[derive(Clone, Serialize)] @@ -25,13 +39,19 @@ pub struct Interaction { pub id: String, pub agent_id: String, pub role: String, pub struct Coverage { label: &'static str, roots: usize, agents: usize, complete: bool, notice: String } #[derive(Serialize)] pub struct Feed { schema_version: u8, generated_at: String, sequence: String, poll_ms: u32, stale_after_ms: u32, coverage: Coverage, agents: Vec, interactions: Vec } -struct Node { public: Agent, root: String, seen: i64, terminal: Option, tools: BTreeMap, placeholder: bool, unavailable: Option<(String,String)>, has_summary: bool } +struct Node { public: Agent, root: String, seen: i64, terminal: Option, tools: BTreeMap, placeholder: bool, unavailable: Option<(String,String)> } pub struct Collector { salt: Vec, since: i64, sequence: u64, nodes: BTreeMap, cursors: HashMap, interactions: VecDeque, seen_events: HashSet, known_hosts: HashMap, task_summaries: HashMap, + /// Recent human messages per session root, private, used only for quote elision. + quotes: HashMap, + /// Claude Code and Codex transcript directories, observed while recently written. + transcripts: Vec<(source::Transcript, PathBuf)>, active_transcripts: Vec<(source::Transcript, PathBuf, i64)>, transcript_scan: Option, } impl Collector { - pub fn new(salt: Vec, since: i64) -> Self { Self { salt, since, sequence: 0, nodes: BTreeMap::new(), cursors: HashMap::new(), interactions: VecDeque::new(), seen_events: HashSet::new(), known_hosts: HashMap::new(), task_summaries: HashMap::new() } } + pub fn new(salt: Vec, since: i64) -> Self { Self { salt, since, sequence: 0, nodes: BTreeMap::new(), cursors: HashMap::new(), interactions: VecDeque::new(), seen_events: HashSet::new(), known_hosts: HashMap::new(), task_summaries: HashMap::new(), quotes: HashMap::new(), transcripts: Vec::new(), active_transcripts: Vec::new(), transcript_scan: None } } + /// Also observe Claude Code or Codex transcripts under `dir`. + pub fn with_transcripts(mut self, kind: source::Transcript, dir: PathBuf) -> Self { self.transcripts.push((kind,dir)); self } fn id(&self, private: &str) -> String { let mut mac = Hmac::::new_from_slice(&self.salt).expect("HMAC accepts any key length"); mac.update(private.as_bytes()); let digest = mac.finalize().into_bytes(); let mut out = String::from("h"); @@ -41,7 +61,7 @@ impl Collector { if self.nodes.contains_key(key) { return; } let id = self.id(key); let parent_id = parent.map(|p| self.id(p)); let summary = self.task_summaries.get(key); - self.nodes.insert(key.to_owned(), Node { public: Agent { id, parent_id, name: label(name, "Agent"), runtime: "OMP".into(), provider: "unknown".into(), model: "unknown".into(), role: if parent.is_some() { "worker" } else { "root" }.into(), task: summary.cloned().unwrap_or_else(|| label(name, "Task label withheld")), status: "unknown".into(), activity: "No action observed".into(), activity_state: "unknown".into(), started_at: None, updated_at: None, observed_at: timestamp(now) }, root: root.to_owned(), seen: now, terminal: None, tools: BTreeMap::new(), placeholder: true, unavailable: None, has_summary: summary.is_some() }); + self.nodes.insert(key.to_owned(), Node { public: Agent { id, parent_id, name: label(name, "Agent"), runtime: "OMP".into(), provider: "unknown".into(), model: "unknown".into(), role: if parent.is_some() { "worker" } else { "root" }.into(), task: summary.cloned().unwrap_or_else(|| label(name, "Task label withheld")), status: "unknown".into(), activity: "No action observed".into(), activity_state: "unknown".into(), started_at: None, updated_at: None, observed_at: timestamp(now) }, root: root.to_owned(), seen: now, terminal: None, tools: BTreeMap::new(), placeholder: true, unavailable: None }); } fn model(node: &mut Node, raw: &str, provider: Option<&str>) { let (p,m) = if let Some(p) = provider { (p,raw) } else { raw.split_once('/').unwrap_or(("unknown",raw)) }; @@ -57,15 +77,21 @@ impl Collector { if name.trim().is_empty() { continue; } // This is the sole public assignment-summary field. Never use task, // context or any other tool argument as a display fallback. - let Some(summary) = public_text(text(task,"solutionSpace"),180) else { continue; }; + // Agent-written, but it can quote the human verbatim: a summary + // that repeats a recent human message is withheld whole. + let Some(summary) = public_text(text(task,"solutionSpace"),180).filter(|s| !self.quotes_human(root,s)) else { continue; }; let key = Self::child_key(root,parent,name); if let Some(node) = self.nodes.get_mut(&key) { - node.public.task = summary.clone(); node.has_summary = true; + node.public.task = summary.clone(); } // Do not create a live worker merely because a spawn was requested. self.task_summaries.insert(key,summary); } } + /// True when `text` repeats a recent human message from session `root`. + fn quotes_human(&self, root: &str, text: &str) -> bool { + self.quotes.get(root).is_some_and(|q| q.elide(text).as_deref() != Some(text)) + } fn terminal(&mut self, key: &str, status: &str, now: i64) { if let Some(node) = self.nodes.get_mut(key) { node.public.status = status.into(); node.public.activity_state = "finished".into(); node.tools.clear(); node.terminal = Some(now); @@ -78,7 +104,8 @@ impl Collector { let event_time = milliseconds(&value["timestamp"]).unwrap_or(now); if let Some(node) = self.nodes.get_mut(key) { node.placeholder = false; - if kind == "title" && !node.has_summary && !text(value,"title").trim().is_empty() { node.public.task = label(text(value,"title"), "Task label withheld"); } + // Session titles ("title" events, host sessionName) are generated from + // the human's first prompt, so they are never published. if kind == "session" { node.public.started_at = at.clone(); } if kind == "session_init" { node.public.role = label(text(value,"agent"), "worker"); @@ -91,7 +118,9 @@ impl Collector { } if custom == "tool_execution_start" { let d = &value["data"]; let tool = label(text(d,"toolName"), "tool"); - let action = public_text(text(d,"intent"), 180).map(|i| format!("{tool}: {i}")).unwrap_or(tool); + let action = public_text(text(d,"intent"), 180).map(|i| format!("{tool}: {i}")).unwrap_or_else(|| tool.clone()); + let quoted = self.quotes.get(&root).is_some_and(|q| q.elide(&action).as_deref() != Some(action.as_str())); + let action = if quoted { tool } else { action }; let date = safe_date(&d["startedAt"]).or(at.clone()); node.tools.insert(text(d,"toolCallId").to_owned(), (action.clone(), date.clone().unwrap_or_default())); node.public.activity = action; node.public.activity_state = "running".into(); node.public.status = "working".into(); node.public.updated_at = date; node.terminal = None; @@ -153,27 +182,91 @@ impl Collector { } } } - // Attribution is a strict provenance boundary, not a heuristic on visible text. - let direct_user = role == "user" && key == root && m["attribution"] == "user"; - if role != "assistant" && !direct_user { return; } + // Human text is never published. It is kept privately, per session, only + // so that an agent reply quoting it can be elided. Every human-side role + // counts: Drake, collaboration guests, developer and custom injections. + if role != "assistant" && role != "toolResult" && (key == root || m["attribution"] == "user") { + let human = joined_text(&m["content"]); + if !human.is_empty() { self.quotes.entry(root.clone()).or_default().add(&human); } + } + // Only the final text of a completed turn is a reply; narration before + // tool calls, tool output and reasoning stay unpublished. + if role != "assistant" || text(m,"stopReason") != "stop" { return; } let Some(time) = milliseconds(&m["timestamp"]).or_else(|| milliseconds(&value["timestamp"])) else { return; }; - if time < self.since { return; } - let Some(parts) = m["content"].as_array() else { return; }; - let mut joined = String::new(); - for part in parts { if part["type"] == "text" { if let Some(t) = part["text"].as_str() { if !joined.is_empty() { joined.push('\n'); } joined.push_str(t); } } } - let Some(public) = public_text(&joined,4000) else { return; }; - let eid = self.id(&format!("interaction:{key}:{}:{time}:{joined}", text(value,"id"))); + let joined = joined_text(&m["content"]); + let seed = format!("interaction:{key}:{}:{time}:{joined}", text(value,"id")); + self.publish(key, &root, &joined, time, &seed, "OMP", label(text(m,"provider"),"unknown"), label(text(m,"model"),"unknown")); + } + /// Publish one agent reply after quote elision and the privacy screen. The + /// public role is always "assistant"; no other role is ever emitted. + #[allow(clippy::too_many_arguments)] + fn publish(&mut self, key: &str, root: &str, reply: &str, time: i64, seed: &str, runtime: &str, provider: String, model: String) { + if time < self.since || reply.trim().is_empty() { return; } + let elided = match self.quotes.get(root) { Some(q) => q.elide(reply), None => Some(reply.to_owned()) }; + let Some(public) = elided.and_then(|r| public_text(&r,4000)) else { return; }; + let eid = self.id(seed); if !self.seen_events.insert(eid.clone()) { return; } - self.interactions.push_back(Interaction { id: eid, agent_id: self.id(key), role: if direct_user { "drake" } else { "assistant" }.into(), text: public, at: timestamp(time), runtime: "OMP".into(), provider: if direct_user { "unknown".into() } else { label(text(m,"provider"),"unknown") }, model: if direct_user { "unknown".into() } else { label(text(m,"model"),"unknown") } }); + self.interactions.push_back(Interaction { id: eid, agent_id: self.id(key), role: "assistant".into(), text: public, at: timestamp(time), runtime: runtime.into(), provider, model }); self.interactions.make_contiguous().sort_by(|a,b| a.at.cmp(&b.at).then(a.id.cmp(&b.id))); - // Drake's own messages are the scarce signal here; agent replies would - // otherwise fill the whole window within minutes. Evict the oldest agent - // reply first, and only drop Drake's once no replies remain to evict. + // Flood protection balanced across agents: one busy agent must not push + // every other agent out of the window. Evict the oldest reply of the + // agent holding the most replies. while self.interactions.len() > INTERACTION_WINDOW { - let victim = self.interactions.iter().position(|m| m.role != "drake").unwrap_or(0); + let mut counts: HashMap<&str,usize> = HashMap::new(); + for i in &self.interactions { *counts.entry(i.agent_id.as_str()).or_default() += 1; } + let most = counts.values().copied().max().unwrap_or(0); + let victim = self.interactions.iter().position(|i| counts[i.agent_id.as_str()] == most).unwrap_or(0); if let Some(old) = self.interactions.remove(victim) { self.seen_events.remove(&old.id); } } } + fn read_transcript(&mut self, kind: source::Transcript, key: &str, path: &Path, now: i64) -> bool { + let cursor = self.cursors.entry(path.to_owned()).or_default(); + let Ok(values) = cursor.read(path) else { return false; }; + if let Some(n) = self.nodes.get_mut(key) { n.placeholder = false; } + for value in values { + match kind { source::Transcript::Claude => self.claude_event(key,&value), source::Transcript::Codex => self.codex_event(key,&value,now) } + } + true + } + /// Claude Code: human prompts are `user` entries with text content (tool + /// results excluded); a reply is the text of an `assistant` entry whose + /// message ended the turn (`stop_reason` `end_turn`). Sidechains are skipped. + fn claude_event(&mut self, key: &str, value: &Value) { + if value["isSidechain"] == true { return; } + let m = &value["message"]; + match text(value,"type") { + "user" => { + let human = joined_text(&m["content"]); + if !human.is_empty() { self.quotes.entry(key.to_owned()).or_default().add(&human); } + } + "assistant" => { + if let Some(n) = self.nodes.get_mut(key) { if let Some(model) = m["model"].as_str() { Self::model(n,model,Some("anthropic")); } } + if text(m,"stop_reason") != "end_turn" { return; } + let Some(time) = milliseconds(&value["timestamp"]) else { return; }; + let seed = format!("interaction:{key}:{}", text(value,"uuid")); + self.publish(key,key,&joined_text(&m["content"]),time,&seed,"Claude Code","anthropic".into(),label(text(m,"model"),"unknown")); + } + _ => {} + } + } + /// Codex: human prompts are `user_message` events and user response items; + /// a reply is `task_complete.last_agent_message`, the final text of a turn. + fn codex_event(&mut self, key: &str, value: &Value, _now: i64) { + let p = &value["payload"]; + match (text(value,"type"), text(p,"type")) { + ("session_meta", _) => if let Some(n) = self.nodes.get_mut(key) { n.public.provider = label(text(p,"model_provider"),"unknown"); }, + ("turn_context", _) => if let Some(n) = self.nodes.get_mut(key) { n.public.model = label(text(p,"model"),"unknown"); }, + ("event_msg", "user_message") => { let human = text(p,"message"); if !human.is_empty() { self.quotes.entry(key.to_owned()).or_default().add(human); } } + ("response_item", "message") if text(p,"role") != "assistant" => { let human = joined_text(&p["content"]); if !human.is_empty() { self.quotes.entry(key.to_owned()).or_default().add(&human); } } + ("event_msg", "task_complete") => { + let Some(time) = milliseconds(&value["timestamp"]) else { return; }; + let (provider,model) = self.nodes.get(key).map(|n| (n.public.provider.clone(),n.public.model.clone())).unwrap_or_else(|| ("unknown".into(),"unknown".into())); + let seed = format!("interaction:{key}:{time}:{}", text(p,"turn_id")); + self.publish(key,key,text(p,"last_agent_message"),time,&seed,"Codex",provider,model); + } + _ => {} + } + } fn read_node(&mut self, key: &str, path: &Path, now: i64) -> bool { let terminal = self.nodes.get(key).and_then(|n| n.terminal.map(|t| (t,n.public.status.clone()))); let cursor = self.cursors.entry(path.to_owned()).or_default(); @@ -204,7 +297,7 @@ impl Collector { observed.insert(key.to_owned()); if let Some(pid) = host["pid"].as_u64() { host_pids.insert(pid as u32,key.to_owned()); } let n = self.nodes.get_mut(key).unwrap(); n.seen = now; n.terminal = None; - n.public.task = label(text(host,"sessionName"), "Task label withheld"); n.public.name = n.public.task.clone(); + n.public.task = "Coding session".into(); n.public.name = n.public.task.clone(); n.public.started_at = safe_date(&host["startedAt"]); Self::model(n,text(&host["model"],"id"),host["model"]["provider"].as_str()); n.public.status = if host["inputRequired"] == true { "waiting" } else { match host["busy"].as_bool() { Some(true) => "working", Some(false) => "idle", None => "unknown" } }.into(); @@ -258,6 +351,34 @@ impl Collector { }, Err(_) => faults += 1, } } + // Claude Code and Codex sessions are observed through their own + // transcripts while those are being written. Only final replies publish. + if !self.transcripts.is_empty() { + if self.transcript_scan.is_none_or(|t| now - t >= TRANSCRIPT_RESCAN_MS) { + self.transcript_scan = Some(now); + let mut active = Vec::new(); + for (kind,dir) in &self.transcripts { + match source::recent_transcripts(*kind,dir,now,TRANSCRIPT_ACTIVE_MS) { + Ok(found) => active.extend(found.into_iter().map(|(p,m)| (*kind,p,m))), + Err(_) => faults += 1, + } + } + self.active_transcripts = active; + } + for (kind,path,_) in self.active_transcripts.clone() { + let key = format!("{}:{}", kind.runtime(), path.display()); + self.ensure(&key,&key,None,&format!("{} session", kind.runtime()),now); + if let Some(n) = self.nodes.get_mut(&key) { n.public.runtime = kind.runtime().into(); n.public.role = "transcript-observed session".into(); } + if !self.read_transcript(kind,&key,&path,now) { faults += 1; continue; } + observed.insert(key.clone()); roots.insert(key.clone()); + let modified = std::fs::metadata(&path).ok().and_then(|m| m.modified().ok()).and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok()).map(|d| d.as_millis() as i64); + if let Some(n) = self.nodes.get_mut(&key) { + n.seen = now; + n.public.status = if modified.is_some_and(|m| now - m < 60_000) { "working" } else { "unknown" }.into(); + n.public.updated_at = modified.map(timestamp); + } + } + } for (key,node) in &mut self.nodes { if observed.contains(key) { node.public.observed_at = timestamp(now); @@ -285,7 +406,7 @@ impl Collector { let mut interactions: Vec<_> = self.interactions.iter().cloned().collect(); interactions.sort_by(|a,b| a.at.cmp(&b.at)); Feed { schema_version: 1, generated_at: timestamp(now), sequence: self.id(&format!("snapshot:{now}:{}",self.sequence)), poll_ms: 1000, stale_after_ms: 15000, coverage: Coverage { label: "Observed live coding sessions", roots: agents.iter().filter(|a| a.parent_id.is_none()).count(), agents: agents.len(), complete: false, - notice: format!("OMP collaboration trees and recognized live coding processes. Process-only workers have limited metadata. Other runtimes and disconnected sessions may be unobserved. {faults} source gaps this snapshot. Disappearance is unknown, not completion.") }, agents, interactions } + notice: format!("OMP collaboration trees, Claude Code and Codex transcripts being written, and recognized live coding processes. Only agents' final replies are published; human messages never are. Process-only workers have limited metadata. Other runtimes and disconnected sessions may be unobserved. {faults} source gaps this snapshot. Disappearance is unknown, not completion.") }, agents, interactions } } } diff --git a/crates/hive-feed/src/main.rs b/crates/hive-feed/src/main.rs index 54c4b0b7..85e439cf 100644 --- a/crates/hive-feed/src/main.rs +++ b/crates/hive-feed/src/main.rs @@ -1,21 +1,23 @@ mod feed; mod privacy; +mod quotes; mod source; use chrono::{DateTime, Utc}; use std::{fs::{self, File, OpenOptions}, io::{self, Read, Write}, os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt}, path::{Path, PathBuf}, time::{Duration, Instant}}; -struct Options { once: bool, out: PathBuf, sessions: PathBuf, hosts: Option, since: i64, salt: PathBuf } +struct Options { once: bool, out: PathBuf, sessions: PathBuf, hosts: Option, since: i64, salt: PathBuf, claude: PathBuf, codex: PathBuf, private_repos: PathBuf } fn options() -> Result { let home = std::env::var_os("HOME").map(PathBuf::from).ok_or("HOME is unavailable")?; - let mut opts = Options { once: false, out: PathBuf::new(), sessions: home.join(".omp/agent/sessions"), hosts: None, since: Utc::now().timestamp_millis(), salt: home.join(".local/state/hive-feed/salt") }; + let mut opts = Options { once: false, out: PathBuf::new(), sessions: home.join(".omp/agent/sessions"), hosts: None, since: Utc::now().timestamp_millis(), salt: home.join(".local/state/hive-feed/salt"), claude: home.join(".claude/projects"), codex: home.join(".codex/sessions"), private_repos: home.join(".local/state/aienos-hive/private-repos.tsv") }; let mut args = std::env::args().skip(1); while let Some(arg) = args.next() { if arg == "--once" { opts.once = true; continue; } - if arg == "--help" { println!("hive-feed [--once] --out PATH [--sessions DIR] [--hosts-file PATH] [--since RFC3339] [--salt PATH]\nDefault: poll every second. Conversation starts at startup unless --since is supplied. Keep --salt private and persistent. No raw transcript, arguments or source errors are logged."); std::process::exit(0); } + if arg == "--help" { println!("hive-feed [--once] --out PATH [--sessions DIR] [--claude DIR] [--codex DIR] [--private-repos PATH] [--hosts-file PATH] [--since RFC3339] [--salt PATH]\nDefault: poll every second. Conversation starts at startup unless --since is supplied. Only agents' final replies are published, never human messages. --private-repos lists one private repository per line as NAME or NAMEprivate-NN. Keep --salt and --private-repos private. No raw transcript, arguments or source errors are logged."); std::process::exit(0); } let value = args.next().ok_or("missing option value")?; match arg.as_str() { "--out" => opts.out = value.into(), "--sessions" => opts.sessions = value.into(), "--hosts-file" => opts.hosts = Some(value.into()), "--salt" => opts.salt = value.into(), + "--claude" => opts.claude = value.into(), "--codex" => opts.codex = value.into(), "--private-repos" => opts.private_repos = value.into(), "--since" => opts.since = DateTime::parse_from_rfc3339(&value).map_err(|_| "invalid --since timestamp")?.timestamp_millis(), _ => return Err("unknown option"), } @@ -37,6 +39,16 @@ fn salt(path: &Path) -> io::Result> { }, Err(e) => Err(e), } } +/// Private repository names, one per line, optionally followed by a tab and the +/// anonymised id they publish as. A missing file means no private names are known. +fn private_repos(path: &Path) -> io::Result)>> { + let text = match fs::read_to_string(path) { Ok(t) => t, Err(e) if e.kind() == io::ErrorKind::NotFound => return Ok(Vec::new()), Err(e) => return Err(e) }; + Ok(text.lines().map(str::trim).filter(|l| !l.is_empty() && !l.starts_with('#')).map(|l| match l.split_once('\t') { + Some((name, id)) if !id.trim().is_empty() => (name.trim().to_owned(), Some(id.trim().to_owned())), + Some((name, _)) => (name.trim().to_owned(), None), + None => (l.to_owned(), None), + }).collect()) +} fn publish(path: &Path, bytes: &[u8]) -> io::Result<()> { if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) { fs::create_dir_all(parent)?; } let tmp = path.with_extension(format!("hive-{}.tmp",std::process::id())); @@ -49,7 +61,11 @@ fn publish(path: &Path, bytes: &[u8]) -> io::Result<()> { fn run() -> Result<(), &'static str> { let opts = options()?; let key = salt(&opts.salt).map_err(|_| "private salt unavailable or unsafe")?; + privacy::set_private_repos(private_repos(&opts.private_repos).map_err(|_| "private repository list unreadable")?); let mut collector = feed::Collector::new(key,opts.since); + if opts.hosts.is_none() { + collector = collector.with_transcripts(source::Transcript::Claude, opts.claude).with_transcripts(source::Transcript::Codex, opts.codex); + } loop { let start = Instant::now(); let snapshot = collector.poll(&opts.sessions,opts.hosts.as_deref(),Utc::now().timestamp_millis()); diff --git a/crates/hive-feed/src/privacy.rs b/crates/hive-feed/src/privacy.rs index 2512b2a9..9e9d7a6b 100644 --- a/crates/hive-feed/src/privacy.rs +++ b/crates/hive-feed/src/privacy.rs @@ -1,8 +1,8 @@ //! One publication boundary for every source-controlled string. Inspect before truncating. use regex::Regex; -use std::sync::LazyLock; +use std::sync::{LazyLock, OnceLock}; -struct Rules { secrets: Regex, cli_flags: Regex, paths: Regex, hosts: Regex, ipv4: Regex, ipv6: Regex, context: Regex, token: Regex } +struct Rules { secrets: Regex, cli_flags: Regex, paths: Regex, hosts: Regex, ipv4: Regex, ipv6: Regex, context: Regex, token: Regex, email: Regex, vault: Regex, secret_names: Regex } static RULES: LazyLock = LazyLock::new(|| Rules { secrets: Regex::new(r#"(?ix)(-----BEGIN\s+(?:[A-Z]+\s+)*PRIVATE\s+KEY|\b(?:bearer|basic)\s+[a-z0-9+/=_-]+|\b(?:[a-z0-9]+[_-])*(?:password|passwd|secret|api[_\x20-]?key|private[_\x20-]?key|access[_\x20-]?token|auth(?:orization)?|cookie|token|session[_\x20-]?(?:key|token|id))["\x27]?\s*(?::|=|\bis\b)\s*\S+|\b(?:sk-|ghp_|github_pat_|gho_|xox[baprs]-|AKIA)[a-z0-9_-]+|\beyJ[a-z0-9_-]+\.[a-z0-9_-]+\.[a-z0-9_-]+|(?:omp|ssh|agent|proc|history|local|memory|xd|skill|file|artifact|security|mcp)://|(?:https?|wss?)://[^\s<>]+[?\#][^\s<>]+|[a-z][a-z0-9+.-]*://[^\s/@]+:[^\s/@]+@|https?://(?:localhost|127\.|10\.|192\.168\.|\[))"#).unwrap(), // Command-line options often separate the credential from its label @@ -19,8 +19,52 @@ static RULES: LazyLock = LazyLock::new(|| Rules { ipv6: Regex::new(r"(?i)\[?[0-9a-f]{0,4}(?::[0-9a-f]{0,4}){2,7}\]?").unwrap(), context: Regex::new(r"(?i)<\s*/?\s*[a-z][a-z0-9_-]*(?:\s[^>]*|\s*)>|\[system[- ](?:reminder|notice)\]|\[Wait interrupted|^\s* } +static PRIVATE_REPOS: OnceLock> = OnceLock::new(); + +/// Install the private repository list once at startup. Each entry is a name and +/// an optional anonymised id; names without an id publish as `[private repo]`. +pub fn set_private_repos(entries: Vec<(String, Option)>) { + let _ = PRIVATE_REPOS.set(compile_repos(entries)); +} +fn compile_repos(entries: Vec<(String, Option)>) -> Option { + let mut names: Vec<_> = entries.iter().map(|(n, _)| n.to_ascii_lowercase()).filter(|n| !n.is_empty()).collect(); + if names.is_empty() { return None; } + names.sort_by_key(|n| std::cmp::Reverse(n.len())); + let alternation = names.iter().map(|n| regex::escape(n)).collect::>().join("|"); + let pattern = Regex::new(&format!("(?i)(?:aien-dev/)?(?:{alternation})")).ok()?; + let replacement = entries.into_iter().map(|(n, id)| (n.to_ascii_lowercase(), id.unwrap_or_else(|| "[private repo]".to_owned()))).collect(); + Some(PrivateRepos { pattern, replacement }) +} +fn redact_repos(text: &str, repos: &PrivateRepos) -> String { + let word = |c: char| c.is_ascii_alphanumeric() || c == '_' || c == '-'; + let mut out = String::with_capacity(text.len()); + let mut at = 0; + for m in repos.pattern.find_iter(text) { + let before = text[..m.start()].chars().next_back(); + let mut after = text[m.end()..].chars(); + let next = after.next(); + // Whole names only: omega-learn must not match inside omega-learning or a.omega-learn. + let joined_after = next.is_some_and(word) || (next == Some('.') && after.next().is_some_and(|c| c.is_ascii_alphanumeric())); + if before.is_some_and(|c| word(c) || c == '.') || joined_after { continue; } + let name = m.as_str().to_ascii_lowercase(); + let name = name.strip_prefix("aien-dev/").unwrap_or(&name); + let Some(public) = repos.replacement.get(name) else { continue; }; + out.push_str(&text[at..m.start()]); out.push_str(public); at = m.end(); + } + out.push_str(&text[at..]); + out +} + pub fn public_text(input: &str, limit: usize) -> Option { let r = &*RULES; // Reject the entire original, including content beyond the display bound. @@ -33,7 +77,11 @@ pub fn public_text(input: &str, limit: usize) -> Option { let mixed = s.bytes().any(|b| b.is_ascii_digit()) && s.bytes().any(|b| b.is_ascii_alphabetic()); if (mixed && entropy > 3.5) || entropy > 4.2 || (s.len() >= 32 && s.bytes().all(|b| b.is_ascii_hexdigit())) { return None; } } - let text = r.paths.replace_all(input, |caps: ®ex::Captures<'_>| format!("{}[private path]", &caps[1])); + let text = r.email.replace_all(input, "[email withheld]"); + let text = r.vault.replace_all(&text, "atlas-vault [secret withheld]"); + let text = r.secret_names.replace_all(&text, "[secret name withheld]"); + let text = match PRIVATE_REPOS.get() { Some(Some(repos)) => redact_repos(&text, repos), _ => text.into_owned() }; + let text = r.paths.replace_all(&text, |caps: ®ex::Captures<'_>| format!("{}[private path]", &caps[1])); let text = r.hosts.replace_all(&text, "[private host]"); // Every IPv4 literal is masked, public or not: a home or office address is // itself private detail, and nothing published here needs an address. @@ -52,6 +100,25 @@ pub fn public_text(input: &str, limit: usize) -> Option { if text.is_empty() { None } else { Some(text.chars().take(limit).collect()) } } +#[cfg(test)] +mod agent_reply_tests { + use super::*; + #[test] fn redacts_email_addresses() { + let value = public_text("I sent the note to first.last+tag@example.ac.uk and copied drake@aienos.com.", 4000).unwrap(); + assert!(!value.contains('@') && value.contains("[email withheld]"), "{value}"); + } + #[test] fn redacts_vault_and_secret_names() { + let value = public_text("I read it with atlas-vault get ZENODO_TOKEN, then exported SANDBOX_SSH_KEY and named deepseek-api-key in the notes.", 4000).unwrap(); + for needle in ["ZENODO", "SANDBOX", "deepseek"] { assert!(!value.contains(needle), "{needle} in {value}"); } + assert!(public_text("The model used 400 tokens and a key frame.", 4000).unwrap().contains("400 tokens and a key frame")); + } + #[test] fn private_repo_names_use_the_local_mapping() { + let repos = compile_repos(vec![("aien-math".into(), Some("private-03".into())), ("omega-learn".into(), None)]).unwrap(); + let value = redact_repos("Merged aien-dev/aien-math#12 and omega-learn; kept aien-math-oracle-work, omega-learning and aienos.com.", &repos); + assert_eq!(value, "Merged private-03#12 and [private repo]; kept aien-math-oracle-work, omega-learning and aienos.com."); + } +} + pub fn label(input: &str, fallback: &str) -> String { public_text(input, 180).unwrap_or_else(|| fallback.to_owned()) } #[cfg(test)] diff --git a/crates/hive-feed/src/quotes.rs b/crates/hive-feed/src/quotes.rs new file mode 100644 index 00000000..51ea38cd --- /dev/null +++ b/crates/hive-feed/src/quotes.rs @@ -0,0 +1,105 @@ +//! Agent replies often quote the human they answer. Human text is never +//! published, so any span of an agent reply that repeats a recent human message +//! from the same session is withheld before the reply reaches the privacy screen. +//! +//! Matching ignores case, spacing, punctuation and quote markup: both sides are +//! reduced to their letters and digits, and a span matches when at least +//! `WINDOW` consecutive letters or digits appear in a human message. `WINDOW` +//! letters or digits are roughly 40 characters of ordinary prose. +use std::{collections::{HashSet, VecDeque}, hash::{DefaultHasher, Hash, Hasher}}; + +pub const WINDOW: usize = 32; +/// Human messages kept per session for matching. +const KEEP: usize = 200; +/// Letters and digits kept per human message for matching. +const MESSAGE_CHARS: usize = 65536; +/// A reply with fewer letters or digits left after elision is dropped. +const MIN_LEFT: usize = 16; +pub const WITHHELD: &str = "[quoted human message withheld]"; + +/// Letters and digits, lowercased, each with the byte range of its source char. +fn normalized(text: &str) -> Vec<(char, usize, usize)> { + let mut out = Vec::new(); + for (start, c) in text.char_indices() { + if !c.is_alphanumeric() { continue; } + let end = start + c.len_utf8(); + for lower in c.to_lowercase() { out.push((lower, start, end)); } + } + out +} +fn shingle(chars: &[(char, usize, usize)]) -> u64 { + let mut h = DefaultHasher::new(); + for (c, _, _) in chars { c.hash(&mut h); } + h.finish() +} + +#[derive(Default)] +pub struct Quotes { messages: VecDeque>, shingles: HashSet } +impl Quotes { + pub fn add(&mut self, human: &str) { + let mut chars = normalized(human); + chars.truncate(MESSAGE_CHARS); + if chars.len() < WINDOW { return; } + let hashes: Vec = chars.windows(WINDOW).map(shingle).collect(); + self.shingles.extend(hashes.iter().copied()); + self.messages.push_back(hashes); + if self.messages.len() > KEEP { + self.messages.pop_front(); + self.shingles = self.messages.iter().flatten().copied().collect(); + } + } + /// The reply with every quoted human span replaced, or None when too little + /// of the agent's own text remains to be worth publishing. + pub fn elide(&self, reply: &str) -> Option { + let chars = normalized(reply); + let mut spans: Vec<(usize, usize)> = Vec::new(); + if !self.shingles.is_empty() && chars.len() >= WINDOW { + for (i, window) in chars.windows(WINDOW).enumerate() { + if !self.shingles.contains(&shingle(window)) { continue; } + let (start, end) = (chars[i].1, chars[i + WINDOW - 1].2); + match spans.last_mut() { Some(last) if start <= last.1 => last.1 = last.1.max(end), _ => spans.push((start, end)) } + } + } + if spans.is_empty() { return Some(reply.to_owned()); } + let mut out = String::with_capacity(reply.len()); + let mut at = 0; + for (start, end) in spans { out.push_str(&reply[at..start]); out.push_str(WITHHELD); at = end; } + out.push_str(&reply[at..]); + let left = normalized(&out.replace(WITHHELD, "")).len(); + (left >= MIN_LEFT).then_some(out) + } +} + +#[cfg(test)] +mod tests { + use super::*; + const HUMAN: &str = "Please take my chat logs off the website. I've changed my mind."; + #[test] fn elides_a_verbatim_quote_and_keeps_the_agents_own_text() { + let mut q = Quotes::default(); q.add(HUMAN); + let reply = format!("You asked: \"{HUMAN}\" I removed every human message from the public feed and kept agent replies."); + let out = q.elide(&reply).unwrap(); + assert!(!out.contains("chat logs off the website"), "{out}"); + assert!(out.contains(WITHHELD) && out.contains("I removed every human message"), "{out}"); + } + #[test] fn matching_ignores_case_spacing_and_blockquote_markup() { + let mut q = Quotes::default(); q.add(HUMAN); + let reply = "> PLEASE take my chat\n> logs off the website.\n\nDone: the receiver now refuses human records, and the page shows agents only."; + let out = q.elide(reply).unwrap(); + assert!(!out.to_lowercase().contains("logs off the"), "{out}"); + } + #[test] fn short_overlaps_and_unrelated_text_survive() { + let mut q = Quotes::default(); q.add(HUMAN); + let reply = "I changed my mind about the cache layout and rebuilt the website index."; + assert_eq!(q.elide(reply).as_deref(), Some(reply)); + } + #[test] fn a_reply_that_is_only_a_quote_is_dropped() { + let mut q = Quotes::default(); q.add(HUMAN); + assert!(q.elide(&format!("\"{HUMAN}\" Okay.")).is_none()); + } + #[test] fn old_messages_age_out() { + let mut q = Quotes::default(); q.add(HUMAN); + for i in 0..KEEP { q.add(&format!("filler message number {i:04} with enough letters to count as human text")); } + let reply = format!("{HUMAN} and some agent words after it to keep"); + assert_eq!(q.elide(&reply).as_deref(), Some(reply.as_str())); + } +} diff --git a/crates/hive-feed/src/source.rs b/crates/hive-feed/src/source.rs index d73183c9..eebfc28f 100644 --- a/crates/hive-feed/src/source.rs +++ b/crates/hive-feed/src/source.rs @@ -128,6 +128,35 @@ pub fn nearest_parent(mut pid: u32, known: &std::collections::HashMap &'static str { match self { Self::Claude => "Claude Code", Self::Codex => "Codex" } } +} +/// Top-level session transcripts written within `window_ms` of `now_ms`, with +/// their modification time. Claude Code keeps `projects//.jsonl` +/// (subagent sidechains live deeper and are skipped); Codex keeps +/// `sessions/YYYY/MM/DD/rollout-*.jsonl`. A missing directory is no transcripts. +pub fn recent_transcripts(kind: Transcript, base: &Path, now_ms: i64, window_ms: i64) -> io::Result> { + let depth = match kind { Transcript::Claude => 1, Transcript::Codex => 3 }; + let mut result = Vec::new(); + if !base.exists() { return Ok(result); } + let mut dirs = vec![(base.to_owned(),0)]; + while let Some((dir,level)) = dirs.pop() { + for entry in fs::read_dir(&dir)? { + let entry = entry?; let kind_of = entry.file_type()?; + if kind_of.is_dir() && level < depth { dirs.push((entry.path(),level + 1)); continue; } + if !kind_of.is_file() || level != depth || entry.path().extension().is_none_or(|e| e != "jsonl") { continue; } + let Ok(meta) = entry.metadata() else { continue; }; + let modified = meta.mtime() * 1000 + meta.mtime_nsec() / 1_000_000; + if now_ms - modified <= window_ms { result.push((entry.path(),modified)); } + } + } + result.sort(); + Ok(result) +} + #[cfg(test)] mod tests { use super::*; diff --git a/crates/hive-feed/src/tests.rs b/crates/hive-feed/src/tests.rs index 971351bf..31e915cc 100644 --- a/crates/hive-feed/src/tests.rs +++ b/crates/hive-feed/src/tests.rs @@ -3,16 +3,33 @@ use serde_json::json; use std::{fs, io::Write, sync::atomic::{AtomicU64, Ordering}}; fn collector() -> Collector { let mut c = Collector::new(vec![7;32],1000); c.ensure("private-root","private-root",None,"Root",2000); c } -fn message(role: &str, attribution: &str, content: Value, at: i64) -> Value { json!({"type":"message","id":format!("{role}-{at}"),"timestamp":at,"message":{"role":role,"attribution":attribution,"timestamp":at,"content":content}}) } -#[test] fn explicit_conversation_whitelist_and_cutoff() { +fn message(role: &str, attribution: &str, content: Value, at: i64) -> Value { json!({"type":"message","id":format!("{role}-{at}"),"timestamp":at,"message":{"role":role,"attribution":attribution,"timestamp":at,"stopReason":if role == "assistant" { "stop" } else { "" },"content":content}}) } +#[test] fn only_final_agent_text_is_published_never_human_messages() { let mut c = collector(); c.event("private-root",&message("user","user",json!([{"type":"text","text":"Hello Drake"}]),1001),2000); c.event("private-root",&message("user","agent",json!([{"type":"text","text":"injected assignment"}]),1002),2000); - c.event("private-root",&message("user","user",json!([{"type":"text","text":"historical"}]),999),2000); - c.event("private-root",&message("assistant","",json!([{"type":"thinking","thinking":"HIDDEN_CANARY"},{"type":"text","text":"Public answer"},{"type":"providerPayload","text":"PROVIDER_CANARY"},{"type":"toolCall","text":"TOOL_CANARY"}]),1003),2000); + c.event("private-root",&message("developer","",json!([{"type":"text","text":"guest note"}]),1002),2000); + c.event("private-root",&message("assistant","",json!([{"type":"text","text":"historical"}]),999),2000); + let mut narration = message("assistant","",json!([{"type":"text","text":"Narration before a tool call"},{"type":"toolCall","name":"read"}]),1003); + narration["message"]["stopReason"] = json!("toolUse"); c.event("private-root",&narration,2000); + c.event("private-root",&message("assistant","",json!([{"type":"thinking","thinking":"HIDDEN_CANARY"},{"type":"text","text":"Public answer"},{"type":"providerPayload","text":"PROVIDER_CANARY"},{"type":"toolCall","text":"TOOL_CANARY"}]),1004),2000); c.ensure("private-root/Child","private-root",Some("private-root"),"Child",2000); - c.event("private-root/Child",&message("user","user",json!([{"type":"text","text":"child assignment"}]),1004),2000); - assert_eq!(c.interactions.len(),2); assert_eq!(c.interactions[0].role,"drake"); assert_eq!(c.interactions[1].text,"Public answer"); + c.event("private-root/Child",&message("user","user",json!([{"type":"text","text":"child assignment"}]),1005),2000); + assert_eq!(c.interactions.len(),1); assert_eq!(c.interactions[0].role,"assistant"); assert_eq!(c.interactions[0].text,"Public answer"); +} +#[test] fn an_agent_quoting_drake_is_elided() { + let mut c = collector(); + let drake = "Please take my chat logs off the website. I've changed my mind. I would like just to show the actual chat."; + // The human message predates the publication cutoff; it is still remembered for elision. + c.event("private-root",&message("user","user",json!([{"type":"text","text":drake}]),999),2000); + c.ensure("private-root/Worker","private-root",Some("private-root"),"Worker",2000); + c.event("private-root/Worker",&message("assistant","",json!([{"type":"text","text":format!("Drake wrote: \"{drake}\"\n\nI removed human messages from the feed; the receiver now refuses them.")}]),1001),2000); + assert_eq!(c.interactions.len(),1); + let text = &c.interactions[0].text; + assert!(!text.contains("chat logs off the website") && !text.contains("actual chat"), "{text}"); + assert!(text.contains(crate::quotes::WITHHELD) && text.contains("I removed human messages"), "{text}"); + c.event("private-root",&message("assistant","",json!([{"type":"text","text":format!("> {drake}")}]),1002),2000); + assert_eq!(c.interactions.len(),1, "a reply that is only a quote is dropped"); } #[test] fn every_published_source_field_is_filtered_before_truncation() { let secret = format!("{} password=secret-canary", "ordinary words ".repeat(400)); @@ -31,10 +48,9 @@ fn message(role: &str, attribution: &str, content: Value, at: i64) -> Value { js } #[test] fn labeled_cli_credentials_never_enter_public_interactions() { let mut c = collector(); - c.event("private-root",&message("user","user",json!([{"type":"text","text":"Run example --password hunter22"}]),1001),2000); c.event("private-root",&message("assistant","",json!([{"type":"text","text":"example --api-key 'abcdef1234567890'"}]),1002),2000); assert!(c.interactions.is_empty(), "labeled credentials must not be published"); - c.event("private-root",&message("user","user",json!([{"type":"text","text":"Run example --output public/report.txt"}]),1003),2000); + c.event("private-root",&message("assistant","",json!([{"type":"text","text":"Run example --output public/report.txt"}]),1003),2000); assert_eq!(c.interactions.len(),1, "ordinary CLI flags remain publishable"); } #[test] fn grandchildren_pending_terminal_and_long_running_tool() { @@ -106,15 +122,16 @@ impl Drop for Fixture { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.di assert_eq!(node.status,"working"); assert_eq!(node.activity_state,"running"); } -#[test] fn drake_messages_survive_an_agent_flood() { +#[test] fn flood_protection_is_balanced_across_agents() { let mut c=collector(); - c.event("private-root",&message("user","user",json!([{"type":"text","text":"Ship the observatory"}]),1000),2000); + c.ensure("private-root/Quiet","private-root",Some("private-root"),"Quiet",2000); + c.event("private-root/Quiet",&message("assistant","",json!([{"type":"text","text":"Ship the observatory"}]),1000),2000); for i in 0..300 { c.event("private-root",&message("assistant","",json!([{"type":"text","text":format!("Reply {i}")}]),1001+i),2000); } assert_eq!(c.interactions.len(),100); - let drake: Vec<_> = c.interactions.iter().filter(|m| m.role=="drake").collect(); - assert_eq!(drake.len(),1,"the one authorized Drake message must not be evicted by replies"); - assert_eq!(drake[0].text,"Ship the observatory"); - assert!(c.interactions.front().unwrap().role=="drake" || c.interactions.iter().any(|m| m.role=="drake")); + let quiet = c.id("private-root/Quiet"); + let kept: Vec<_> = c.interactions.iter().filter(|m| m.agent_id==quiet).collect(); + assert_eq!(kept.len(),1,"a quiet agent's reply must not be evicted by a busy agent's flood"); + assert_eq!(kept[0].text,"Ship the observatory"); } #[test] fn interaction_bound_uses_event_time_not_scan_order() { @@ -135,13 +152,13 @@ impl Drop for Fixture { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.di #[test] fn interactions_keep_message_model_not_current_node_model() { let mut c=collector(); - c.event("private-root",&json!({"type":"message","timestamp":1001,"message":{"role":"assistant","provider":"anthropic","model":"claude-opus-5-5","content":[{"type":"text","text":"First reply"}]}}),2000); - c.event("private-root",&json!({"type":"message","timestamp":1002,"message":{"role":"assistant","provider":"openai-codex","model":"gpt-6-astra","content":[{"type":"text","text":"Second reply"}]}}),2000); + c.event("private-root",&json!({"type":"message","timestamp":1001,"message":{"role":"assistant","stopReason":"stop","provider":"anthropic","model":"claude-opus-5-5","content":[{"type":"text","text":"First reply"}]}}),2000); + c.event("private-root",&json!({"type":"message","timestamp":1002,"message":{"role":"assistant","stopReason":"stop","provider":"openai-codex","model":"gpt-6-astra","content":[{"type":"text","text":"Second reply"}]}}),2000); c.event("private-root",&message("user","user",json!([{"type":"text","text":"Hello"}]),1003),2000); assert_eq!(c.interactions[0].provider,"anthropic"); assert_eq!(c.interactions[0].model,"claude-opus-5-5"); assert_eq!(c.interactions[1].provider,"openai-codex"); assert_eq!(c.interactions[1].model,"gpt-6-astra"); - assert_eq!(c.interactions[2].model,"unknown"); - c.event("private-root",&json!({"type":"message","timestamp":1004,"message":{"role":"assistant","provider":"password=PROVIDER_CANARY","model":"password=MODEL_CANARY","content":[{"type":"text","text":"Safe reply"}]}}),2000); + assert_eq!(c.interactions.len(),2, "the human message is never published"); + c.event("private-root",&json!({"type":"message","timestamp":1004,"message":{"role":"assistant","stopReason":"stop","provider":"password=PROVIDER_CANARY","model":"password=MODEL_CANARY","content":[{"type":"text","text":"Safe reply"}]}}),2000); assert!(!serde_json::to_string(&c.interactions).unwrap().contains("CANARY")); } @@ -165,3 +182,65 @@ impl Drop for Fixture { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.di let output=serde_json::to_string(&c.nodes.values().map(|n| &n.public).collect::>()).unwrap(); assert!(!output.contains("CANARY")); assert!(c.interactions.is_empty()); } + +#[test] fn claude_and_codex_transcripts_publish_final_replies_only() { + let f=Fixture::new(); + let now=chrono::Utc::now().timestamp_millis(); + let at=|ms: i64| timestamp(now-ms); + let claude=f.dir.join("claude/projects/-home-person"); fs::create_dir_all(claude.join("session/subagents")).unwrap(); + let drake="Please take my chat logs off the website and only show what the agents say back to me."; + let lines=[ + json!({"type":"user","timestamp":at(9000),"uuid":"u1","message":{"role":"user","content":drake}}), + json!({"type":"assistant","timestamp":at(8000),"uuid":"a1","message":{"id":"m1","role":"assistant","model":"claude-opus-5-5","stop_reason":"tool_use","content":[{"type":"text","text":"CLAUDE_NARRATION_CANARY"}]}}), + json!({"type":"user","timestamp":at(7500),"uuid":"u2","message":{"role":"user","content":[{"type":"tool_result","content":"TOOL_RESULT_CANARY"}]}}), + json!({"type":"assistant","timestamp":at(7000),"uuid":"a2","message":{"id":"m2","role":"assistant","model":"claude-opus-5-5","stop_reason":"end_turn","content":[{"type":"thinking","thinking":"THINKING_CANARY"}]}}), + json!({"type":"assistant","timestamp":at(7000),"uuid":"a3","message":{"id":"m2","role":"assistant","model":"claude-opus-5-5","stop_reason":"end_turn","content":[{"type":"text","text":format!("You said \"{drake}\" and the feed now shows agent replies only.")}]}}), + json!({"type":"assistant","isSidechain":true,"timestamp":at(6000),"uuid":"a4","message":{"id":"m3","role":"assistant","stop_reason":"end_turn","content":[{"type":"text","text":"SIDECHAIN_CANARY"}]}}), + ]; + fs::write(claude.join("session.jsonl"),lines.iter().map(|l| format!("{l}\n")).collect::()).unwrap(); + fs::write(claude.join("session/subagents/agent.jsonl"),format!("{}\n",json!({"type":"assistant","timestamp":at(5000),"uuid":"s","message":{"role":"assistant","stop_reason":"end_turn","content":[{"type":"text","text":"SUBAGENT_CANARY"}]}}))).unwrap(); + let codex=f.dir.join("codex/sessions/2026/10/27"); fs::create_dir_all(&codex).unwrap(); + let lines=[ + json!({"type":"session_meta","timestamp":at(9000),"payload":{"id":"x","model_provider":"openai"}}), + json!({"type":"turn_context","timestamp":at(9000),"payload":{"model":"gpt-6-astra"}}), + json!({"type":"event_msg","timestamp":at(8800),"payload":{"type":"user_message","message":"CODEX_HUMAN_CANARY please rebuild the hive page"}}), + json!({"type":"event_msg","timestamp":at(8500),"payload":{"type":"agent_message","message":"CODEX_NARRATION_CANARY"}}), + json!({"type":"event_msg","timestamp":at(8000),"payload":{"type":"task_complete","turn_id":"t1","last_agent_message":"Rebuilt the hive page and ran the checks."}}), + ]; + fs::write(codex.join("rollout-x.jsonl"),lines.iter().map(|l| format!("{l}\n")).collect::()).unwrap(); + let mut c=Collector::new(vec![8;32],0).with_transcripts(source::Transcript::Claude,f.dir.join("claude/projects")).with_transcripts(source::Transcript::Codex,f.dir.join("codex/sessions")); + let feed=c.poll(&f.sessions,Some(&f.hosts),now); + let output=serde_json::to_string(&feed).unwrap(); + for needle in ["CANARY","chat logs off the website","-home-person","rollout"] { assert!(!output.contains(needle),"{needle} in {output}"); } + assert_eq!(feed.interactions.len(),2,"{output}"); + assert!(feed.interactions.iter().all(|i| i.role=="assistant")); + let claude_reply=feed.interactions.iter().find(|i| i.runtime=="Claude Code").unwrap(); + assert!(claude_reply.text.contains(crate::quotes::WITHHELD) && claude_reply.text.contains("agent replies only"),"{}",claude_reply.text); + assert_eq!((claude_reply.provider.as_str(),claude_reply.model.as_str()),("anthropic","claude-opus-5-5")); + let codex_reply=feed.interactions.iter().find(|i| i.runtime=="Codex").unwrap(); + assert_eq!(codex_reply.text,"Rebuilt the hive page and ran the checks."); + assert_eq!((codex_reply.provider.as_str(),codex_reply.model.as_str()),("openai","gpt-6-astra")); + assert!(feed.agents.iter().any(|a| a.runtime=="Claude Code") && feed.agents.iter().any(|a| a.runtime=="Codex")); + // A second poll re-reads nothing and publishes nothing twice. + assert_eq!(c.poll(&f.sessions,Some(&f.hosts),now+1000).interactions.len(),2); +} + +#[test] fn prompt_derived_titles_and_quoting_summaries_are_never_published() { + let f=Fixture::new(); + fs::write(&f.hosts,json!({"version":1,"hosts":[{"sessionId":"private-root","sessionName":"SESSION_NAME_CANARY plans for launch","pid":1234567,"model":{"provider":"openai-codex","id":"gpt-6-astra"},"startedAt":1000,"busy":true}]}).to_string()).unwrap(); + let drake="Separate the two subscription plans before the launch and tell me which one pays."; + f.append(json!({"type":"title","timestamp":1001,"title":"TITLE_CANARY separate plans"})); + f.append(json!({"type":"message","timestamp":1002,"message":{"role":"user","attribution":"user","content":[{"type":"text","text":drake}]}})); + f.append(json!({"type":"message","timestamp":1003,"message":{"role":"assistant","stopReason":"toolUse","content":[{"type":"toolCall","name":"task","arguments":{"tasks":[ + {"name":"Quoter","solutionSpace":format!("{drake}")}, + {"name":"Plain","solutionSpace":"one fix: split the billing table"}]}}]}})); + f.append(json!({"type":"custom","customType":"tool_execution_start","timestamp":1004,"data":{"toolCallId":"t","toolName":"bash","intent":drake,"startedAt":1004}})); + let mut c=Collector::new(vec![8;32],1000); + c.ensure("private-root/Quoter","private-root",Some("private-root"),"Quoter",1005); + c.ensure("private-root/Plain","private-root",Some("private-root"),"Plain",1005); + let output=serde_json::to_string(&c.poll(&f.sessions,Some(&f.hosts),2000)).unwrap(); + for needle in ["CANARY","subscription plans","which one pays"] { assert!(!output.contains(needle),"{needle} in {output}"); } + assert!(output.contains("one fix: split the billing table")); + assert_eq!(c.nodes["private-root"].public.name,"Coding session"); + assert_eq!(c.nodes["private-root"].public.activity,"bash"); +} diff --git a/crates/site-builder/src/components/follow.rs b/crates/site-builder/src/components/follow.rs index 4f4b56f9..fe192c81 100644 --- a/crates/site-builder/src/components/follow.rs +++ b/crates/site-builder/src/components/follow.rs @@ -19,8 +19,8 @@ pub fn render_follow() -> Markup { "Learning to code with AI? You are welcome here. " a href="/learn/" style="color: var(--text-primary); text-decoration: underline;" { "Start with a practical working method" } ", then " - a href="/hive/" style="color: var(--text-primary); text-decoration: underline;" { "watch Drake and the agents in Hive" } - ": the instructions, the models, the corrections, and the work as it happens." + a href="/hive/" style="color: var(--text-primary); text-decoration: underline;" { "watch the agents in Hive" } + ": the models, the corrections, and the work as it happens." } div style="display: flex; gap: 12px; flex-wrap: wrap; justify-content: center;" { a href="https://github.com/aien-dev" target="_blank" rel="noopener noreferrer" style="background: var(--accent-green); color: var(--bg-base); border-radius: 4px; padding: 12px 22px; font-family: var(--font-mono); font-size: 13px; font-weight: 700;" { diff --git a/crates/site-builder/src/components/hive.rs b/crates/site-builder/src/components/hive.rs index 4ed98925..2a8e3119 100644 --- a/crates/site-builder/src/components/hive.rs +++ b/crates/site-builder/src/components/hive.rs @@ -9,7 +9,7 @@ use maud::{html, Markup, PreEscaped}; pub const TITLE: &str = "The Hive | AienOS"; -pub const DESCRIPTION: &str = "Watch Drake and the Aien coding agents work in public: real missions, nested agents, exact models and live conversations. Learn how to build with AI."; +pub const DESCRIPTION: &str = "Watch the Aien coding agents work in public: real missions, nested agents, exact models and what the agents are saying, live. Learn how to build with AI."; pub const URL: &str = "https://www.aienos.com/hive/"; pub const SOURCE: &str = "https://github.com/aien-dev/aienos.com/blob/main/crates/site-builder/src/components/hive.rs"; diff --git a/crates/site-builder/src/seo.rs b/crates/site-builder/src/seo.rs index 843adbb4..06a4540c 100644 --- a/crates/site-builder/src/seo.rs +++ b/crates/site-builder/src/seo.rs @@ -92,7 +92,7 @@ pub const PAGES: &[PageInfo] = &[ PageInfo { path: "/cudaplusplus/", name: "CUDA++", what: "CUDA++ is the GPU half of Omega: everything CUDA gives you plus the motor, for the NVIDIA GPUs people already own, with no NVIDIA user-space software (Apache-2.0 with LLVM exception, aien-dev/CUDApp). What it is for, the path from program to chip with whose code runs at each step, how I did it, CUDA's pain points and the swap down to the kernel driver.", section: Section::Machine, kind: Kind::Page, image: "/og-machine.png", published: "2026-10-22", doi: None }, PageInfo { path: "/now/", name: "Now", what: "The live coordination ledger: what every agent is doing right now, what is settled with evidence, what waits on the operator. Rebuilt whenever the ledger changes.", section: Section::Machine, kind: Kind::Live, image: "/og-now.png", published: "2026-10-19", doi: None }, PageInfo { path: "/dash/", name: "Dashboard", what: "One screen: model quota left on every account the agents run on, the Spark's pulse, open work, and which model each role uses. Rebuilt with the ledger.", section: Section::Machine, kind: Kind::Live, image: "/og-now.png", published: "2026-10-26", doi: None }, - PageInfo { path: "/hive/", name: "Hive", what: "Watch Drake build with coding agents: live missions, nested subagents, exact models and public conversations, with source freshness and failures visible.", section: Section::Start, kind: Kind::Live, image: "/og-now.png", published: "2026-10-25", doi: None }, + PageInfo { path: "/hive/", name: "Hive", what: "Watch coding agents work in public: live missions, nested subagents, exact models and the agents' own replies, with source freshness and failures visible.", section: Section::Start, kind: Kind::Live, image: "/og-now.png", published: "2026-10-25", doi: None }, PageInfo { path: "/aien/", name: "Talk to Aien", what: "Chat with Aien, Drake's AI (formerly Allen), on the live model on a DGX Spark: speed measured from the stream, questions about Omega, and small HTML or Omega programs that run sandboxed in your browser. Conversations are not stored.", section: Section::Start, kind: Kind::Live, image: "/og-now.png", published: "2026-10-26", doi: None }, PageInfo { path: "/alpha/", name: "Sovereign Intelligence", what: "Sovereign Intelligence, built on AienOS. The Omega installer, hardware and evidence boundaries, source and a reversible way back. The local Aien experience is coming in the next update.", section: Section::Start, kind: Kind::Page, image: "/og.png", published: "2026-10-26", doi: None }, PageInfo { path: "/lab/", name: "Omega Lab", what: "Write a data-parallel kernel in Omega beside the same kernel in CUDA C, run it in your browser as WebAssembly checked against JavaScript, compile edits on a DGX Spark, and see every back end and every GPU result that has and has not run.", section: Section::Start, kind: Kind::Page, image: "/og.png", published: "2026-10-27", doi: None }, diff --git a/om/hive-page/hive.om b/om/hive-page/hive.om index f96e5438..d53b33fe 100644 --- a/om/hive-page/hive.om +++ b/om/hive-page/hive.om @@ -98,15 +98,15 @@ note The emitted style block also carries the wiring, inside a prefers-reduced-m note behind the native motion checkbox, so with motion off elements keep their base state: note one representative frame, the two holes at a visible separation, no merged hole, no ripple. -text meta "

|01 / Signal|

|Source and freshness|

|This page reads the edge-rendered public board. It never assumes it can see every agent.|

|
|

|02 / Missions|

|Current missions|

|One disclosure per branch. A status describes the agent's reported state, not a measure of progress.|

|
|

|03 / Manifest|

|Selected mission|

|Runtime observations, not GitHub receipts or proof that a task succeeded.|

|
|

|04 / Conversations|

|Drake and the agents|

|Direct messages from Drake and agents public replies, in time order, inside one publication window. Hidden reasoning, tool payloads and automatic context are not conversations.||

|" +text meta "

|01 / Signal|

|Source and freshness|

|This page reads the edge-rendered public board. It never assumes it can see every agent.|

|
|

|02 / Missions|

|Current missions|

|One disclosure per branch. A status describes the agent's reported state, not a measure of progress.|

|
|

|03 / Manifest|

|Selected mission|

|Runtime observations, not GitHub receipts or proof that a task succeeded.|

|
|

|04 / Agent responses|

|What the agents are saying, live|

|Each agent's final reply at the end of a turn, in time order, inside one publication window. Human messages are never published, and text an agent quotes from one is withheld. Hidden reasoning, tool payloads and automatic context are not shown.||

|" text noteend "

\n" text lineend "\n" -text page1a "
\n\n\n
\n" +text page1a "
\n\n\n
\n" -text page1b "

An open observatory, written in Omega

\n

The hive.

\n

Drake. A constellation of agents. Real work, unfolding in the open.

\n

Watch Drake and the agents build, question, get things wrong and try again. You do not need to know how any of this works to begin.

\nLearn to build with AI\n
\n\n
\n" +text page1b "

An open observatory, written in Omega

\n

The hive.

\n

Drake. A constellation of agents. Real work, unfolding in the open.

\n

Watch the agents build, question, get things wrong and try again. You do not need to know how any of this works to begin.

\nLearn to build with AI\n
\n\n
\n" text sig1 "
\n
\n
Source snapshot
\n
Browser received
\n
\n
\n

Connecting to the observatory

\n

A browser clock is not evidence of a live source.

\n
\n
\n" @@ -122,7 +122,7 @@ text man2 "\n" text chat1 "
\n\n\n
\n

\n

No published live message for this view yet.

\n" -text chat2 "
    \n

    This is work in progress, including mistakes and failures. Public messages are not verified project outcomes.

    \n" +text chat2 "
      \n

      This is work in progress, including mistakes and failures. Agent replies are not verified project outcomes.

      \n" text page2 "
      \n\n\n" diff --git a/om/hive-page/main.html b/om/hive-page/main.html index 14fd1a2a..2c0cb054 100644 --- a/om/hive-page/main.html +++ b/om/hive-page/main.html @@ -4,13 +4,13 @@ Signal Missions Manifest -Conversations +Agent responses

      An open observatory, written in Omega

      The hive.

      Drake. A constellation of agents. Real work, unfolding in the open.

      -

      Watch Drake and the agents build, question, get things wrong and try again. You do not need to know how any of this works to begin.

      +

      Watch the agents build, question, get things wrong and try again. You do not need to know how any of this works to begin.

      Learn to build with AI
      -

      04 / Conversations

      Drake and the agents

      Direct messages from Drake and agents public replies, in time order, inside one publication window. Hidden reasoning, tool payloads and automatic context are not conversations.

      +

      04 / Agent responses

      What the agents are saying, live

      Each agent's final reply at the end of a turn, in time order, inside one publication window. Human messages are never published, and text an agent quotes from one is withheld. Hidden reasoning, tool payloads and automatic context are not shown.

      No published live message for this view yet.

      -
        -

        This is work in progress, including mistakes and failures. Public messages are not verified project outcomes.

        +
          +

          This is work in progress, including mistakes and failures. Agent replies are not verified project outcomes.