interplane.Get Omega
Read in your language

aienos.com

Source of www.aienos.com, served from my own hardware

Brought by drakestapleton

branch main Branches Tags History

aienos.com / crates / hive-feed / src / tests.rs

625 lines · 53422 bytes Raw Blame History
1use super::*;
2use serde_json::json;
3use std::{fs, io::Write, sync::atomic::{AtomicU64, Ordering}};
4
5fn collector() -> Collector { let mut c = Collector::new(vec![7;32],1000); c.ensure("private-root","private-root",None,"Root",2000); c }
6/// A per-run salt: the identifiers only need to be stable within one test.
7fn run_salt() -> Vec<u8> { std::process::id().to_le_bytes().repeat(8) }
8fn 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}}) }
9#[test] fn only_final_agent_text_is_published_never_human_messages() {
10 let mut c = collector();
11 c.event("private-root",&message("user","user",json!([{"type":"text","text":"Hello Drake"}]),1001),2000);
12 c.event("private-root",&message("user","agent",json!([{"type":"text","text":"injected assignment"}]),1002),2000);
13 c.event("private-root",&message("developer","",json!([{"type":"text","text":"guest note"}]),1002),2000);
14 c.event("private-root",&message("assistant","",json!([{"type":"text","text":"historical"}]),999),2000);
15 let mut narration = message("assistant","",json!([{"type":"text","text":"Narration before a tool call"},{"type":"toolCall","name":"read"}]),1003);
16 narration["message"]["stopReason"] = json!("toolUse"); c.event("private-root",&narration,2000);
17 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);
18 c.ensure("private-root/Child","private-root",Some("private-root"),"Child",2000);
19 c.event("private-root/Child",&message("user","user",json!([{"type":"text","text":"child assignment"}]),1005),2000);
20 assert_eq!(c.interactions.len(),1); assert_eq!(c.interactions[0].role,"assistant"); assert_eq!(c.interactions[0].text,"Public answer");
21}
22#[test] fn an_agent_quoting_drake_is_published_as_written() {
23 let mut c = collector();
24 let drake = "Please take my chat logs off the website. I've changed my mind. I would like just to show the actual chat.";
25 // Drake, 2026-11-14: "everything I am doing is public". The human message itself
26 // is never a published record, but an agent reply that quotes it is not cut.
27 c.event("private-root",&message("user","user",json!([{"type":"text","text":drake}]),999),2000);
28 c.ensure("private-root/Worker","private-root",Some("private-root"),"Worker",2000);
29 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);
30 assert_eq!(c.interactions.len(),1);
31 let text = &c.interactions[0].text;
32 assert!(text.contains("chat logs off the website") && text.contains("I removed human messages"), "{text}");
33 c.event("private-root",&message("assistant","",json!([{"type":"text","text":format!("> {drake}")}]),1002),2000);
34 assert_eq!(c.interactions.len(),2, "a reply that is only a quote is still a reply");
35}
36#[test] fn every_published_source_field_is_filtered_before_truncation() {
37 // The canary runs from character 3,992 to 4,005, across the 4,000-character reply
38 // bound, so cutting before redacting would publish part of it; the label fields are
39 // cut at 180 in any case.
40 let secret = format!("{}filler. password=s3cret-canary", "ordinary words ".repeat(265));
41 let mut c = collector();
42 c.ensure("private-root/Child","private-root",Some("private-root"),&secret,2000);
43 for event in [
44 json!({"type":"title","title":secret}),
45 json!({"type":"session_init","agent":secret,"resolvedModel":secret,"task":"TASK_CANARY","systemPrompt":"SYSTEM_CANARY"}),
46 json!({"type":"model_usage","model":secret,"provider":secret}),
47 json!({"type":"custom","customType":"tool_execution_start","data":{"toolCallId":"PRIVATE_ID","toolName":secret,"intent":secret,"args":{"token":"ARGS_CANARY"}}}),
48 message("assistant","",json!([{"type":"text","text":secret}]),1001),
49 ] { c.event("private-root/Child",&event,2000); }
50 let output = serde_json::to_string(&c.nodes.values().map(|n| &n.public).collect::<Vec<_>>()).unwrap();
51 for needle in ["s3cret-canary","TASK_CANARY","SYSTEM_CANARY","PRIVATE_ID","ARGS_CANARY","private-root"] { assert!(!output.contains(needle),"{needle}"); }
52 assert_eq!(c.interactions.len(),1);
53 // Redacted in the full string, then cut to the 4,000-character bound.
54 assert!(!c.interactions[0].text.contains("s3cret-canary") && c.interactions[0].text.chars().count() <= 4000);
55 let start = secret.find("s3cret-canary").unwrap();
56 assert!(start < 4000 && start + "s3cret-canary".len() > 4000, "the canary must cross the bound");
57 let short = "ordinary words password=s3cret-canary";
58 c.event("private-root/Child",&message("assistant","",json!([{"type":"text","text":short}]),1002),2000);
59 assert_eq!(c.interactions[1].text, format!("ordinary words {}",crate::privacy::SECRET));
60}
61#[test] fn labeled_cli_credentials_never_enter_public_interactions() {
62 let mut c = collector();
63 c.event("private-root",&message("assistant","",json!([{"type":"text","text":"example --api-key 'abcdef1234567890'"}]),1002),2000);
64 assert_eq!(c.interactions[0].text, format!("example --api-key '{}'",crate::privacy::SECRET), "labeled credentials are redacted");
65 c.event("private-root",&message("assistant","",json!([{"type":"text","text":"Run example --output public/report.txt"}]),1003),2000);
66 assert_eq!(c.interactions[1].text,"Run example --output public/report.txt", "ordinary CLI flags remain publishable");
67}
68#[test] fn grandchildren_pending_terminal_and_long_running_tool() {
69 let mut c = collector();
70 c.event("private-root",&json!({"type":"message","timestamp":2000,"message":{"role":"toolResult","toolName":"task","details":{"progress":[{"id":"Parent","agent":"task","status":"pending","assignment":"DO_NOT_PUBLISH"}]}}}),2000);
71 c.event("private-root/Parent",&json!({"type":"message","timestamp":2001,"message":{"role":"toolResult","toolName":"task","details":{"progress":[{"id":"Parent.Child","agent":"reviewer","status":"running"}]}}}),2001);
72 let parent = c.id("private-root/Parent"); assert_eq!(c.nodes["private-root/Parent.Child"].public.parent_id.as_deref(),Some(parent.as_str()));
73 c.event("private-root/Parent.Child",&json!({"type":"custom","timestamp":2002,"customType":"tool_execution_start","data":{"toolCallId":"t","toolName":"bash","intent":"Running long operation","startedAt":2002}}),2002);
74 assert_eq!(c.nodes["private-root/Parent.Child"].public.activity_state,"running");
75 c.event("private-root/Parent.Child",&json!({"type":"message","timestamp":999999,"message":{"role":"assistant","content":[{"type":"text","text":"Still waiting"}]}}),999999);
76 assert_eq!(c.nodes["private-root/Parent.Child"].public.status,"working");
77 c.event("private-root/Parent",&json!({"type":"custom_message","customType":"async-result","timestamp":1000000,"details":{"jobs":[{"type":"task","agentId":"Parent.Child","status":"completed"}]}}),1000000);
78 assert_eq!(c.nodes["private-root/Parent.Child"].public.status,"completed");
79 c.event("private-root",&json!({"type":"custom_message","customType":"async-result","timestamp":1000001,"details":{"jobs":[{"type":"task","agentId":"NoFile","status":"failed"}]}}),1000001);
80 assert_eq!(c.nodes["private-root/NoFile"].public.status,"failed");
81}
82struct Fixture { dir: PathBuf, hosts: PathBuf, sessions: PathBuf, root: PathBuf }
83impl Fixture {
84 fn new() -> Self {
85 static COUNT: AtomicU64 = AtomicU64::new(0);
86 let dir = std::env::temp_dir().join(format!("hive-feed-{}-{}",std::process::id(),COUNT.fetch_add(1,Ordering::Relaxed)));
87 let sessions = dir.join("sessions"); fs::create_dir_all(sessions.join("cwd")).unwrap();
88 let hosts = dir.join("hosts.json");
89 fs::write(&hosts,json!({"version":1,"hosts":[{"sessionId":"private-root","sessionName":"Live coding","pid":1234567,"model":{"provider":"openai-codex","id":"gpt-6-astra"},"startedAt":1000,"busy":true,"inputRequired":false}]}).to_string()).unwrap();
90 let root = sessions.join("cwd/date_private-root.jsonl");
91 fs::write(&root,format!("{}\n",json!({"type":"session","timestamp":1000}))).unwrap();
92 Self { dir,hosts,sessions,root }
93 }
94 fn append(&self, value: Value) { let mut f=fs::OpenOptions::new().append(true).open(&self.root).unwrap(); writeln!(f,"{value}").unwrap(); }
95}
96impl Drop for Fixture { fn drop(&mut self) { let _ = fs::remove_dir_all(&self.dir); } }
97#[test] fn failures_and_disappearance_are_not_completion() {
98 let f=Fixture::new(); let mut c=Collector::new(vec![8;32],1000);
99 f.append(json!({"type":"custom","customType":"tool_execution_start","timestamp":1001,"data":{"toolCallId":"t","toolName":"bash","intent":"Running operation","startedAt":1001}}));
100 let feed=c.poll(&f.sessions,Some(&f.hosts),2000); assert_eq!(feed.agents[0].status,"working");
101 let feed=c.poll(&f.sessions,Some(&f.hosts),100000); assert_eq!(feed.agents[0].activity_state,"running");
102 fs::write(&f.hosts,"malformed").unwrap(); let feed=c.poll(&f.sessions,Some(&f.hosts),100001);
103 assert_eq!(feed.agents.len(),1); assert_eq!(feed.agents[0].status,"unknown"); assert!(!feed.coverage.complete); assert!(feed.coverage.notice.contains("source gaps"));
104 fs::write(&f.hosts,"{\"version\":1,\"hosts\":[]}").unwrap(); let feed=c.poll(&f.sessions,Some(&f.hosts),100002); assert_eq!(feed.agents[0].status,"unknown");
105}
106#[test] fn terminal_history_not_resurrected_and_root_busy_is_authoritative() {
107 let f=Fixture::new(); let child=f.root.with_extension("").join("Child.jsonl"); fs::create_dir_all(child.parent().unwrap()).unwrap();
108 fs::write(child,format!("{}\n{}\n",json!({"type":"session_init","timestamp":1000,"agent":"task","resolvedModel":"anthropic/claude-opus-5-5"}),json!({"type":"custom","timestamp":1001,"customType":"tool_execution_start","data":{"toolName":"read","toolCallId":"t","startedAt":1001}}))).unwrap();
109 f.append(json!({"type":"custom_message","customType":"async-result","timestamp":2000,"details":{"jobs":[{"type":"task","agentId":"Child","status":"completed"}]}}));
110 f.append(json!({"type":"custom","customType":"session_exit","timestamp":2001,"data":{"kind":"normal"}}));
111 let mut c=Collector::new(vec![8;32],5000); let feed=c.poll(&f.sessions,Some(&f.hosts),200000);
112 assert_eq!(feed.agents.len(),1); assert_eq!(feed.agents[0].status,"working");
113 assert_eq!(c.poll(&f.sessions,Some(&f.hosts),201000).agents.len(),1);
114}
115#[test] fn interaction_bound_and_stable_opaque_identity() {
116 let mut c=collector();
117 for i in 0..110 { c.event("private-root",&message("assistant","",json!([{"type":"text","text":"Public response"}]),1000+i),2000); }
118 assert_eq!(c.interactions.len(),100); assert!(!c.id("private-root").contains("private-root"));
119 assert_eq!(c.id("private-root"),collector().id("private-root"));
120 assert_ne!(c.id("private-root"),Collector::new(vec![9;32],0).id("private-root"));
121}
122
123#[test] fn missing_child_becomes_unknown_without_refreshing_observation() {
124 let f=Fixture::new(); let child=f.root.with_extension("").join("Child.jsonl"); fs::create_dir_all(child.parent().unwrap()).unwrap();
125 let data=format!("{}\n{}\n",json!({"type":"session_init","timestamp":1000,"agent":"task","resolvedModel":"anthropic/claude-opus-5-5"}),json!({"type":"custom","timestamp":1001,"customType":"tool_execution_start","data":{"toolName":"read","toolCallId":"t","startedAt":1001}}));
126 fs::write(&child,&data).unwrap();
127 let mut c=Collector::new(vec![8;32],5000); let initial=c.poll(&f.sessions,Some(&f.hosts),2000);
128 let id=c.id("private-root/Child"); let before=initial.agents.iter().find(|a| a.id==id).unwrap().observed_at.clone();
129 fs::remove_file(&child).unwrap();
130 let snapshot=c.poll(&f.sessions,Some(&f.hosts),3000); let node=snapshot.agents.iter().find(|a| a.id==id).unwrap();
131 assert_eq!(node.status,"unknown"); assert_eq!(node.activity_state,"unknown"); assert_eq!(node.observed_at,before);
132 fs::write(&child,&data).unwrap();
133 let snapshot=c.poll(&f.sessions,Some(&f.hosts),4000); let node=snapshot.agents.iter().find(|a| a.id==id).unwrap();
134 assert_eq!(node.status,"working"); assert_eq!(node.activity_state,"running");
135}
136
137#[test] fn flood_protection_is_balanced_across_agents() {
138 let mut c=collector();
139 c.ensure("private-root/Quiet","private-root",Some("private-root"),"Quiet",2000);
140 c.event("private-root/Quiet",&message("assistant","",json!([{"type":"text","text":"Ship the observatory"}]),1000),2000);
141 for i in 0..300 { c.event("private-root",&message("assistant","",json!([{"type":"text","text":format!("Reply {i}")}]),1001+i),2000); }
142 assert_eq!(c.interactions.len(),100);
143 let quiet = c.id("private-root/Quiet");
144 let kept: Vec<_> = c.interactions.iter().filter(|m| m.agent_id==quiet).collect();
145 assert_eq!(kept.len(),1,"a quiet agent's reply must not be evicted by a busy agent's flood");
146 assert_eq!(kept[0].text,"Ship the observatory");
147}
148
149#[test] fn interaction_bound_uses_event_time_not_scan_order() {
150 let mut c=collector();
151 for i in (0..150).rev() { c.event("private-root",&message("assistant","",json!([{"type":"text","text":"Public response"}]),1000+i),2000); }
152 assert_eq!(c.interactions.len(),100);
153 assert_eq!(c.interactions.front().unwrap().at,timestamp(1050));
154 assert_eq!(c.interactions.back().unwrap().at,timestamp(1149));
155}
156
157#[test] fn root_fields_and_unknown_fields_cannot_bypass_boundary() {
158 let f=Fixture::new();
159 fs::write(&f.hosts,json!({"version":1,"hosts":[{"sessionId":"private-root","sessionName":"password=CANARY9xyz","pid":987654321,"cwd":"/home/PRIVATE_PERSON/path","instanceId":"PRIVATE_INSTANCE","token":"UNKNOWN_CANARY","model":{"provider":"password=CANARY9xyz","id":"password=CANARY9xyz"},"startedAt":1000,"busy":true}]}).to_string()).unwrap();
160 let mut c=Collector::new(vec![8;32],5000);
161 let output=serde_json::to_string(&c.poll(&f.sessions,Some(&f.hosts),2000)).unwrap();
162 for needle in ["CANARY","987654321","PRIVATE_PERSON","PRIVATE_INSTANCE","private-root"] { assert!(!output.contains(needle),"{needle}"); }
163}
164
165#[test] fn interactions_keep_message_model_not_current_node_model() {
166 let mut c=collector();
167 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);
168 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);
169 c.event("private-root",&message("user","user",json!([{"type":"text","text":"Hello"}]),1003),2000);
170 assert_eq!(c.interactions[0].provider,"anthropic"); assert_eq!(c.interactions[0].model,"claude-opus-5-5");
171 assert_eq!(c.interactions[1].provider,"openai-codex"); assert_eq!(c.interactions[1].model,"gpt-6-astra");
172 assert_eq!(c.interactions.len(),2, "the human message is never published");
173 c.event("private-root",&json!({"type":"message","timestamp":1004,"message":{"role":"assistant","stopReason":"stop","provider":"password=CANARY9xyz","model":"password=CANARY9xyz","content":[{"type":"text","text":"Safe reply"}]}}),2000);
174 assert!(!serde_json::to_string(&c.interactions).unwrap().contains("CANARY"));
175}
176
177#[test] fn assignment_summary_whitelist_tracks_child_without_publishing_payload() {
178 let mut c=collector();
179 let args=json!({"context":"CONTEXT_CANARY","other":"OTHER_CANARY","tasks":[
180 {"name":"Parent","solutionSpace":"Implement orbital motion controls","task":"TASK_CANARY","other":"CHILD_CANARY"},
181 {"name":"Rejected","solutionSpace":format!("{} password=CANARY9xyz","ordinary words ".repeat(100)),"task":"ASSIGNMENT_CANARY"}
182 ]});
183 c.event("private-root",&message("assistant","",json!([{"type":"toolCall","name":"task","arguments":args}]),1001),2000);
184 assert!(!c.nodes.contains_key("private-root/Parent"));
185 c.event("private-root",&json!({"type":"message","timestamp":1002,"message":{"role":"toolResult","toolName":"task","details":{"progress":[{"id":"Parent","agent":"task","status":"pending"},{"id":"Rejected","agent":"task","status":"pending"}]}}}),2000);
186 assert_eq!(c.nodes["private-root/Parent"].public.task,"Implement orbital motion controls");
187 let redacted = &c.nodes["private-root/Rejected"].public.task;
188 assert!(redacted.starts_with("ordinary words") && !redacted.contains("CANARY9xyz"), "{redacted}");
189 c.event("private-root/Parent",&json!({"type":"title","title":""}),2000);
190 c.event("private-root/Parent",&json!({"type":"title","title":"Parent"}),2000);
191 assert_eq!(c.nodes["private-root/Parent"].public.task,"Implement orbital motion controls");
192 c.event("private-root/Parent",&json!({"type":"custom","customType":"tool_execution_start","timestamp":1003,"data":{"toolName":"task","toolCallId":"t","args":{"context":"NESTED_CONTEXT_CANARY","tasks":[{"name":"Child","solutionSpace":"Check reduced motion behavior","task":"NESTED_TASK_CANARY"}]}}}),2000);
193 c.event("private-root/Parent",&json!({"type":"message","timestamp":1004,"message":{"role":"toolResult","toolName":"task","details":{"progress":[{"id":"Parent.Child","agent":"reviewer","status":"pending"}]}}}),2000);
194 assert_eq!(c.nodes["private-root/Parent.Child"].public.task,"Check reduced motion behavior");
195 let output=serde_json::to_string(&c.nodes.values().map(|n| &n.public).collect::<Vec<_>>()).unwrap();
196 assert!(!output.contains("CANARY")); assert!(c.interactions.is_empty());
197}
198
199#[test] fn claude_and_codex_transcripts_publish_final_replies_only() {
200 let f=Fixture::new();
201 let now=chrono::Utc::now().timestamp_millis();
202 let at=|ms: i64| timestamp(now-ms);
203 let claude=f.dir.join("claude/projects/-home-person"); fs::create_dir_all(claude.join("session/subagents")).unwrap();
204 let drake="Please take my chat logs off the website and only show what the agents say back to me.";
205 let lines=[
206 json!({"type":"user","timestamp":at(9000),"uuid":"u1","message":{"role":"user","content":drake}}),
207 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"}]}}),
208 json!({"type":"user","timestamp":at(7500),"uuid":"u2","message":{"role":"user","content":[{"type":"tool_result","content":"TOOL_RESULT_CANARY"}]}}),
209 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"}]}}),
210 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.")}]}}),
211 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"}]}}),
212 ];
213 fs::write(claude.join("session.jsonl"),lines.iter().map(|l| format!("{l}\n")).collect::<String>()).unwrap();
214 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();
215 let codex=f.dir.join("codex/sessions/2026/10/27"); fs::create_dir_all(&codex).unwrap();
216 let lines=[
217 json!({"type":"session_meta","timestamp":at(9000),"payload":{"id":"x","model_provider":"openai"}}),
218 json!({"type":"turn_context","timestamp":at(9000),"payload":{"model":"gpt-6-astra"}}),
219 json!({"type":"event_msg","timestamp":at(8800),"payload":{"type":"user_message","message":"CODEX_HUMAN_CANARY please rebuild the hive page"}}),
220 json!({"type":"event_msg","timestamp":at(8500),"payload":{"type":"agent_message","message":"CODEX_NARRATION_CANARY"}}),
221 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."}}),
222 ];
223 fs::write(codex.join("rollout-x.jsonl"),lines.iter().map(|l| format!("{l}\n")).collect::<String>()).unwrap();
224 let mut c=Collector::new(run_salt(),0).with_transcripts(source::Transcript::Claude,f.dir.join("claude/projects")).with_transcripts(source::Transcript::Codex,f.dir.join("codex/sessions"));
225 let feed=c.poll(&f.sessions,Some(&f.hosts),now);
226 let output=serde_json::to_string(&feed).unwrap();
227 for needle in ["CANARY","-home-person","rollout"] { assert!(!output.contains(needle),"{needle} in {output}"); }
228 assert_eq!(feed.interactions.len(),2,"{output}");
229 assert!(feed.interactions.iter().all(|i| i.role=="assistant"));
230 let claude_reply=feed.interactions.iter().find(|i| i.runtime=="Claude Code").unwrap();
231 assert!(claude_reply.text.contains("chat logs off the website") && claude_reply.text.contains("agent replies only"),"{}",claude_reply.text);
232 assert_eq!((claude_reply.provider.as_str(),claude_reply.model.as_str()),("anthropic","claude-opus-5-5"));
233 let codex_reply=feed.interactions.iter().find(|i| i.runtime=="Codex").unwrap();
234 assert_eq!(codex_reply.text,"Rebuilt the hive page and ran the checks.");
235 assert_eq!((codex_reply.provider.as_str(),codex_reply.model.as_str()),("openai","gpt-6-astra"));
236 assert!(feed.agents.iter().any(|a| a.runtime=="Claude Code") && feed.agents.iter().any(|a| a.runtime=="Codex"));
237 // A second poll re-reads nothing and publishes nothing twice.
238 assert_eq!(c.poll(&f.sessions,Some(&f.hosts),now+1000).interactions.len(),2);
239}
240
241#[test] fn prompt_derived_titles_are_never_published_but_summaries_are_as_written() {
242 let f=Fixture::new();
243 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();
244 let drake="Separate the two subscription plans before the launch and tell me which one pays.";
245 f.append(json!({"type":"title","timestamp":1001,"title":"TITLE_CANARY separate plans"}));
246 f.append(json!({"type":"message","timestamp":1002,"message":{"role":"user","attribution":"user","content":[{"type":"text","text":drake}]}}));
247 f.append(json!({"type":"message","timestamp":1003,"message":{"role":"assistant","stopReason":"toolUse","content":[{"type":"toolCall","name":"task","arguments":{"tasks":[
248 {"name":"Quoter","solutionSpace":drake.to_string()},
249 {"name":"Plain","solutionSpace":"one fix: split the billing table"}]}}]}}));
250 f.append(json!({"type":"custom","customType":"tool_execution_start","timestamp":1004,"data":{"toolCallId":"t","toolName":"bash","intent":drake,"startedAt":1004}}));
251 let mut c=Collector::new(run_salt(),1000);
252 c.ensure("private-root/Quoter","private-root",Some("private-root"),"Quoter",1005);
253 c.ensure("private-root/Plain","private-root",Some("private-root"),"Plain",1005);
254 let output=serde_json::to_string(&c.poll(&f.sessions,Some(&f.hosts),2000)).unwrap();
255 assert!(!output.contains("CANARY"),"{output}");
256 assert!(output.contains("one fix: split the billing table") && output.contains("which one pays"),"{output}");
257 assert_eq!(c.nodes["private-root"].public.name,"Coding session");
258 assert_eq!(c.nodes["private-root"].public.activity,format!("bash: {drake}"));
259}
260#[test] fn usage_limit_is_the_stated_idle_reason_and_lifts() {
261 let at = 1_793_000_000_000i64;
262 let mut c = Collector::new(vec![7;32],1000); c.ensure("private-root","private-root",None,"Root",at);
263 // A side job (caption) hitting a limit does not stop the agent: never claimed. This first record is
264 // the real OMP shape (model_usage, seen 73 times in 10 days); the next one exercises the purpose guard.
265 c.event("private-root",&json!({"type":"model_usage","timestamp":at,"purpose":"job-caption","stopReason":"error","errorMessage":"You have hit your ChatGPT usage limit (promax plan). Try again in ~7796 min."}),at);
266 assert_eq!(c.nodes["private-root"].limit, None);
267 // The same side job written as an assistant message must not count either.
268 let mut side = message("assistant","",json!([]),at);
269 side["purpose"] = json!("job-caption"); side["message"]["stopReason"] = json!("error"); side["message"]["errorMessage"] = json!("You have hit your ChatGPT usage limit (promax plan). Try again in ~7796 min.");
270 c.event("private-root",&side,at);
271 assert_eq!(c.nodes["private-root"].limit, None);
272 // The agent's own turn failing on the limit is the reason it is idle.
273 let mut failed = message("assistant","",json!([]),at);
274 failed["message"]["stopReason"] = json!("error"); failed["message"]["errorMessage"] = json!("You have hit your ChatGPT usage limit (promax plan). Try again in ~90 min.");
275 c.event("private-root",&failed,at);
276 let feed = serde_json::to_value(c.poll(Path::new("/nonexistent-hive-sessions"),None,at + 1000)).unwrap();
277 let id = c.nodes["private-root"].public.id.clone(); let root = feed["agents"].as_array().unwrap().iter().find(|a| a["id"] == id.as_str()).unwrap().clone();
278 assert_eq!(root["activity"], format!("Idle: provider usage limit reached; the provider says it resets about {} 09:03 UTC", crate::privacy::SECRET));
279 assert_eq!(root["status"], "idle");
280 assert!(!root["activity"].as_str().unwrap().contains("promax"), "the raw error text is never published");
281 // A later successful turn clears it.
282 c.event("private-root",&message("assistant","",json!([{"type":"text","text":"back"}]),at + 2000),at + 2000);
283 assert_eq!(c.nodes["private-root"].limit, None);
284}
285#[test] fn usage_limit_past_its_reset_is_no_longer_claimed() {
286 let mut c = collector();
287 let n = c.nodes.get_mut("private-root").unwrap();
288 n.limit = Some(Limit { stop: Stop::Usage, until: Some(5000), source: LimitSource::Turn });
289 n.public.activity = stop_sentence(&n.limit.unwrap());
290 let feed = serde_json::to_value(c.poll(Path::new("/nonexistent-hive-sessions"),None,6000)).unwrap();
291 let id = c.nodes["private-root"].public.id.clone(); let root = feed["agents"].as_array().unwrap().iter().find(|a| a["id"] == id.as_str()).unwrap().clone();
292 assert_eq!(root["activity"], "No action observed"); assert_eq!(c.nodes["private-root"].limit, None);
293 // A running tool, or any activity that is not the limit sentence, stays.
294 let mut c = collector();
295 let n = c.nodes.get_mut("private-root").unwrap();
296 n.limit = Some(Limit { stop: Stop::Usage, until: Some(5000), source: LimitSource::Turn });
297 n.public.activity = "bash: Running operation".into(); n.public.activity_state = "running".into();
298 let feed = serde_json::to_value(c.poll(Path::new("/nonexistent-hive-sessions"),None,6000)).unwrap();
299 let id = c.nodes["private-root"].public.id.clone(); let root = feed["agents"].as_array().unwrap().iter().find(|a| a["id"] == id.as_str()).unwrap().clone();
300 assert_eq!(root["activity"], "bash: Running operation"); assert_eq!(c.nodes["private-root"].limit, None);
301}
302#[test] fn an_expired_limit_leaves_a_busy_hosts_running_tool_alone() {
303 let f = Fixture::new();
304 f.append(json!({"type":"custom","customType":"tool_execution_start","timestamp":1_002_000,"data":{"toolCallId":"t","toolName":"bash","intent":"Running operation","startedAt":1_002_000}}));
305 f.append(json!({"type":"message","timestamp":1_002_000,"message":{"role":"assistant","stopReason":"error","errorMessage":"You have hit your usage limit. Try again in 1 sec.","content":[]}}));
306 let mut c = Collector::new(vec![8;32],1000);
307 let before = c.poll(&f.sessions,Some(&f.hosts),1_002_500);
308 assert_eq!(before.agents[0].activity, "bash: Running operation");
309 assert_eq!(before.agents[0].activity_state, "running");
310 let after = c.poll(&f.sessions,Some(&f.hosts),1_003_001);
311 assert_eq!(after.agents[0].activity, "bash: Running operation");
312 assert_eq!(after.agents[0].activity_state, "running");
313 assert_eq!(after.agents[0].status, "working");
314 assert_eq!(c.nodes["private-root"].limit, None);
315}
316#[test] fn an_expired_limit_sentence_clears_while_the_host_is_busy() {
317 let f = Fixture::new();
318 let host = |busy: bool| json!({"version":1,"hosts":[{"sessionId":"private-root","sessionName":"Live coding","pid":1234567,"model":{"provider":"openai-codex","id":"gpt-6-astra"},"startedAt":1000,"busy":busy,"inputRequired":false}]});
319 fs::write(&f.hosts, host(false).to_string()).unwrap();
320 f.append(json!({"type":"message","timestamp":8_000_000,"message":{"role":"assistant","stopReason":"error","errorMessage":"You have hit your usage limit. Try again in 1 sec.","content":[]}}));
321 let mut c = Collector::new(vec![8;32],1000);
322 let shown = c.poll(&f.sessions, Some(&f.hosts), 8_000_200);
323 assert!(shown.agents[0].activity.starts_with(USAGE_PREFIX), "{}", shown.agents[0].activity);
324 assert_eq!(c.nodes["private-root"].limit.as_ref().and_then(|l| l.until), Some(8_001_000));
325 fs::write(&f.hosts, host(true).to_string()).unwrap();
326 let crossed = c.poll(&f.sessions, Some(&f.hosts), 8_001_001);
327 assert_eq!(crossed.agents[0].activity, "No action observed");
328 assert_eq!(c.nodes["private-root"].limit, None);
329 fs::write(&f.hosts, host(false).to_string()).unwrap();
330 let later = c.poll(&f.sessions, Some(&f.hosts), 8_001_800);
331 assert_eq!(later.agents[0].activity, "No action observed");
332}
333#[test] fn a_codex_count_under_the_limit_clears_the_idle_sentence() {
334 let f = Fixture::new();
335 let now = chrono::Utc::now().timestamp_millis();
336 let limit_at = now - 60_000;
337 let codex = f.dir.join("codex/sessions/2026/11/15"); fs::create_dir_all(&codex).unwrap();
338 let resets = now / 1000 + 3_600;
339 let count = |percent: f64, at: i64| json!({"type":"event_msg","timestamp":at,"payload":{"type":"token_count","rate_limits":{"primary":{"used_percent":percent,"window_minutes":300,"resets_at":resets},"secondary":null,"rate_limit_reached_type":null}}});
340 let path = codex.join("rollout-x.jsonl");
341 let lines = [
342 count(100.0, limit_at),
343 json!({"type":"event_msg","timestamp":now,"payload":{"type":"user_message","message":"Are you still there?"}}),
344 ];
345 fs::write(&path, lines.iter().map(|l| format!("{l}\n")).collect::<String>()).unwrap();
346 let mut c = Collector::new(run_salt(),0).with_transcripts(source::Transcript::Codex, f.dir.join("codex/sessions"));
347 let codex_agent = |feed: &Feed| feed.agents.iter().find(|a| a.runtime == "Codex").unwrap().activity.clone();
348 assert!(codex_agent(&c.poll(&f.sessions, Some(&f.hosts), now)).starts_with(USAGE_PREFIX));
349 let mut file = fs::OpenOptions::new().append(true).open(&path).unwrap();
350 writeln!(file, "{}", count(100.0, now + 400)).unwrap();
351 assert!(codex_agent(&c.poll(&f.sessions, Some(&f.hosts), now + 500)).starts_with(USAGE_PREFIX));
352 writeln!(file, "{}", count(40.0, now + 600)).unwrap();
353 let cleared = codex_agent(&c.poll(&f.sessions, Some(&f.hosts), now + 1000));
354 assert!(!cleared.starts_with(USAGE_PREFIX), "{cleared}");
355}
356#[test] fn codex_and_claude_limit_records() {
357 assert_eq!(codex_limit(&json!({"primary":{"used_percent":69.0,"window_minutes":10080,"resets_at":1795149329},"secondary":null,"rate_limit_reached_type":null})), None);
358 assert_eq!(codex_limit(&json!({"primary":{"used_percent":100.0,"window_minutes":300,"resets_at":1795149329},"rate_limit_reached_type":null})), Some(Limit { stop: Stop::Usage, until: Some(1_795_149_329_000), source: LimitSource::TokenWindow }));
359 assert_eq!(codex_limit(&json!({"primary":null,"secondary":null,"rate_limit_reached_type":"workspace_member_usage_limit_reached"})), Some(Limit { stop: Stop::Usage, until: None, source: LimitSource::TokenWindow }));
360 assert_eq!(classify("Claude AI usage limit reached|1795149329", 0).and_then(|l| l.until), Some(1_795_149_329_000));
361 assert_eq!(classify("You have hit your usage limit. Try again in 4 hours and 31 minutes.", 0).and_then(|l| l.until), Some((4 * 60 + 31) * 60_000));
362 assert_eq!(classify("You have hit your ChatGPT usage limit (promax plan). Try again in ~90 min.", 10).and_then(|l| l.until), Some(10 + 90 * 60_000));
363 assert_eq!(classify("usage limit. Try again in 99999999999999999 min", 0).and_then(|l| l.until), None, "an overflowing wait is not a reset time");
364 assert_eq!(classify("usage limit. Try again in 5 fortnights", 0).and_then(|l| l.until), None);
365 assert_eq!(classify("The model is currently at capacity due to high demand.", 0).map(|l| l.stop), Some(Stop::Capacity));
366 assert_eq!(classify("Request was aborted", 0), None);
367 assert_eq!(classify("Interrupted by user", 0), None);
368}
369#[test] fn the_page_rings_key_on_the_published_sentence_prefixes() {
370 let page = include_str!("../../../om/hive-page/hive-js.om");
371 for (prefix, limit) in [(USAGE_PREFIX, Limit { stop: Stop::Usage, until: None, source: LimitSource::Turn }), (USAGE_PREFIX, Limit { stop: Stop::Usage, until: Some(0), source: LimitSource::Turn }), (CAPACITY_PREFIX, Limit { stop: Stop::Capacity, until: None, source: LimitSource::Turn })] {
372 assert!(stop_sentence(&limit).starts_with(prefix));
373 assert!(page.contains(&format!("startsWith('{prefix}')")), "hive-js.om must ring on {prefix:?}");
374 }
375}
376#[test] fn newer_activity_than_the_limit_is_not_overridden() {
377 let f = Fixture::new();
378 fs::write(&f.hosts, json!({"version":1,"hosts":[{"sessionId":"private-root","sessionName":"Live coding","pid":1234567,"model":{"provider":"openai-codex","id":"gpt-6-astra"},"startedAt":1000,"busy":false,"inputRequired":false}]}).to_string()).unwrap();
379 f.append(json!({"type":"custom","customType":"tool_execution_start","timestamp":3000,"data":{"toolCallId":"t","toolName":"read","intent":"file","startedAt":3000}}));
380 f.append(json!({"type":"message","timestamp":3000,"message":{"role":"assistant","stopReason":"error","errorMessage":"You have hit your usage limit. Try again in 90 min.","content":[]}}));
381 let mut c = Collector::new(vec![8;32],1000);
382 let feed = c.poll(&f.sessions, Some(&f.hosts), 4000);
383 assert_eq!(feed.agents[0].activity, "read: file");
384 // A fresh file time is not an action. The sentence still replaces the line.
385 let mut c = collector();
386 let n = c.nodes.get_mut("private-root").unwrap();
387 n.limit = Some(Limit { stop: Stop::Usage, until: None, source: LimitSource::Turn }); n.public.updated_at = Some(timestamp(90_000)); n.public.activity = "read: file".into();
388 let id = c.nodes["private-root"].public.id.clone();
389 let feed = serde_json::to_value(c.poll(Path::new("/nonexistent-hive-sessions"),None,4000)).unwrap();
390 let root = feed["agents"].as_array().unwrap().iter().find(|a| a["id"] == id.as_str()).unwrap().clone();
391 assert!(root["activity"].as_str().unwrap().starts_with(USAGE_PREFIX), "{}", root["activity"]);
392}
393#[test] fn a_human_line_does_not_hide_a_provider_usage_limit() {
394 let f = Fixture::new();
395 let now = chrono::Utc::now().timestamp_millis();
396 let limit_at = now - 60_000;
397 let claude = f.dir.join("claude/projects/-home-person"); fs::create_dir_all(&claude).unwrap();
398 let lines = [
399 json!({"type":"assistant","timestamp":limit_at,"uuid":"a1","isApiErrorMessage":true,"error":"rate_limit","message":{"role":"assistant","content":[{"type":"text","text":"You have hit your usage limit. Try again in 90 min."}]}}),
400 json!({"type":"user","timestamp":now,"uuid":"u1","message":{"role":"user","content":"Are you still there?"}}),
401 ];
402 let claude_path = claude.join("session.jsonl");
403 fs::write(&claude_path, lines.iter().map(|l| format!("{l}\n")).collect::<String>()).unwrap();
404 let codex = f.dir.join("codex/sessions/2026/11/15"); fs::create_dir_all(&codex).unwrap();
405 let resets = now / 1000 + 3_600;
406 let lines = [
407 json!({"type":"event_msg","timestamp":limit_at,"payload":{"type":"token_count","rate_limits":{"primary":{"used_percent":100.0,"window_minutes":300,"resets_at":resets},"secondary":null,"rate_limit_reached_type":null}}}),
408 json!({"type":"event_msg","timestamp":now,"payload":{"type":"user_message","message":"Are you still there?"}}),
409 ];
410 let codex_path = codex.join("rollout-x.jsonl");
411 fs::write(&codex_path, lines.iter().map(|l| format!("{l}\n")).collect::<String>()).unwrap();
412 let mut c = Collector::new(run_salt(),0).with_transcripts(source::Transcript::Claude,f.dir.join("claude/projects")).with_transcripts(source::Transcript::Codex,f.dir.join("codex/sessions"));
413 let feed = c.poll(&f.sessions,Some(&f.hosts),now);
414 for runtime in ["Claude Code","Codex"] {
415 let agent = feed.agents.iter().find(|a| a.runtime==runtime).unwrap_or_else(|| panic!("no {runtime}"));
416 assert!(agent.activity.starts_with(USAGE_PREFIX), "{runtime} {}", agent.activity);
417 assert_eq!(agent.status, "idle", "{runtime} {}", agent.status);
418 }
419 let mut claude_file = fs::OpenOptions::new().append(true).open(&claude_path).unwrap();
420 writeln!(claude_file, "{}", json!({"type":"assistant","timestamp":now+500,"uuid":"a2","message":{"role":"assistant","model":"claude-opus-5-5","stop_reason":"end_turn","content":[{"type":"text","text":"Back to work."}]}})).unwrap();
421 let mut codex_file = fs::OpenOptions::new().append(true).open(&codex_path).unwrap();
422 writeln!(codex_file, "{}", json!({"type":"event_msg","timestamp":now+500,"payload":{"type":"task_complete","turn_id":"t1","last_agent_message":"Back to work."}})).unwrap();
423 let feed = c.poll(&f.sessions,Some(&f.hosts),now+1000);
424 for runtime in ["Claude Code","Codex"] {
425 let agent = feed.agents.iter().find(|a| a.runtime==runtime).unwrap();
426 assert!(!agent.activity.starts_with(USAGE_PREFIX), "{runtime} still {}", agent.activity);
427 }
428 assert!(c.nodes.values().filter(|n| n.public.runtime=="Claude Code" || n.public.runtime=="Codex").all(|n| n.limit.is_none()));
429}
430fn idle_host(path: &std::path::Path) {
431 fs::write(path, json!({"version":1,"hosts":[{"sessionId":"private-root","sessionName":"Live coding","pid":1234567,"model":{"provider":"openai-codex","id":"gpt-6-astra"},"startedAt":1000,"busy":false,"inputRequired":false}]}).to_string()).unwrap();
432}
433/// Mutant: status working hides the sentence, so a worker that never left "working" stays silent.
434#[test] fn a_working_worker_with_no_running_tool_shows_the_limit() {
435 let f = Fixture::new();
436 let dir = f.root.with_extension(""); fs::create_dir_all(&dir).unwrap();
437 let error = json!({"type":"message","timestamp":8_000_000,"message":{"role":"assistant","stopReason":"error","errorMessage":"You have hit your usage limit. Try again in 90 min.","content":[]}});
438 fs::write(dir.join("Worker.jsonl"), format!("{}\n{}\n", json!({"type":"session_init","timestamp":8_000_000,"agent":"task","resolvedModel":"openai/gpt-6"}), error)).unwrap();
439 fs::write(dir.join("Runner.jsonl"), format!("{}\n{}\n{}\n", json!({"type":"session_init","timestamp":8_000_000,"agent":"task","resolvedModel":"openai/gpt-6"}), json!({"type":"custom","customType":"tool_execution_start","timestamp":8_000_000,"data":{"toolCallId":"t","toolName":"bash","intent":"Running operation","startedAt":8_000_000}}), error)).unwrap();
440 f.append(error);
441 let mut c = Collector::new(vec![8;32],1000);
442 let feed = c.poll(&f.sessions, Some(&f.hosts), 8_000_200);
443 let output = serde_json::to_string(&feed).unwrap();
444 assert!(!output.contains("Try again in 90 min") && !output.contains("promax"), "{output}");
445 let worker = feed.agents.iter().find(|a| a.id == c.id("private-root/Worker")).unwrap();
446 assert!(worker.activity.starts_with(USAGE_PREFIX), "{}", worker.activity);
447 assert_eq!(worker.status, "idle");
448 let runner = feed.agents.iter().find(|a| a.id == c.id("private-root/Runner")).unwrap();
449 assert_eq!(runner.activity, "bash: Running operation");
450 assert_eq!(runner.status, "working");
451 let host = feed.agents.iter().find(|a| a.id == c.id("private-root")).unwrap();
452 assert!(!host.activity.starts_with(USAGE_PREFIX), "host busy hides the sentence: {}", host.activity);
453 assert_eq!(host.status, "working");
454}
455/// Mutant: an under-100 token_count clears every limit, including capacity.
456#[test] fn an_under_100_token_count_does_not_retire_capacity() {
457 let f = Fixture::new();
458 let now = chrono::Utc::now().timestamp_millis();
459 let codex = f.dir.join("codex/sessions/2026/11/15"); fs::create_dir_all(&codex).unwrap();
460 let path = codex.join("rollout-x.jsonl");
461 let lines = [
462 json!({"type":"event_msg","timestamp":now-60_000,"payload":{"type":"error","message":"The model is currently at capacity due to high demand."}}),
463 json!({"type":"event_msg","timestamp":now,"payload":{"type":"user_message","message":"Are you still there?"}}),
464 ];
465 fs::write(&path, lines.iter().map(|l| format!("{l}\n")).collect::<String>()).unwrap();
466 let mut c = Collector::new(run_salt(),0).with_transcripts(source::Transcript::Codex, f.dir.join("codex/sessions"));
467 let activity = |feed: &Feed| feed.agents.iter().find(|a| a.runtime == "Codex").unwrap().activity.clone();
468 let shown = c.poll(&f.sessions, Some(&f.hosts), now);
469 assert!(activity(&shown).starts_with(CAPACITY_PREFIX), "{}", activity(&shown));
470 assert!(!serde_json::to_string(&shown).unwrap().contains("high demand"));
471 assert!(!serde_json::to_string(&shown).unwrap().contains("Are you still there"));
472 let mut file = fs::OpenOptions::new().append(true).open(&path).unwrap();
473 writeln!(file, "{}", json!({"type":"event_msg","timestamp":now+400,"payload":{"type":"token_count","rate_limits":{"primary":{"used_percent":40.0,"window_minutes":300,"resets_at":now/1000+3600},"secondary":null,"rate_limit_reached_type":null}}})).unwrap();
474 let kept = activity(&c.poll(&f.sessions, Some(&f.hosts), now+500));
475 assert!(kept.starts_with(CAPACITY_PREFIX), "{kept}");
476 writeln!(file, "{}", json!({"type":"event_msg","timestamp":now+800,"payload":{"type":"task_complete","turn_id":"t1","last_agent_message":"Back to work."}})).unwrap();
477 let lifted = activity(&c.poll(&f.sessions, Some(&f.hosts), now+1000));
478 assert!(!lifted.starts_with(CAPACITY_PREFIX), "{lifted}");
479}
480/// Mutant: drop `&& transcript` in `shown` and this fails. The tool is still in the map, and the file is not.
481#[test] fn a_missing_transcript_is_not_a_running_tool() {
482 let f = Fixture::new();
483 idle_host(&f.hosts);
484 f.append(json!({"type":"custom","customType":"tool_execution_start","timestamp":1_000_000,"data":{"toolCallId":"t","toolName":"bash","intent":"Running operation","startedAt":1_000_000}}));
485 f.append(json!({"type":"message","timestamp":1_000_000,"message":{"role":"assistant","stopReason":"error","errorMessage":"You have hit your usage limit. Try again in 1 sec.","content":[]}}));
486 let mut c = Collector::new(vec![8;32],1000);
487 let running = c.poll(&f.sessions, Some(&f.hosts), 1_000_400);
488 assert_eq!(running.agents[0].activity, "bash: Running operation");
489 fs::remove_file(&f.root).unwrap();
490 let stale = c.poll(&f.sessions, Some(&f.hosts), 1_000_800);
491 assert!(!c.nodes["private-root"].tools.is_empty(), "the tool record is still in the map");
492 assert!(stale.agents[0].activity.starts_with(USAGE_PREFIX), "{}", stale.agents[0].activity);
493 assert_eq!(stale.agents[0].status, "idle");
494 let later = c.poll(&f.sessions, Some(&f.hosts), 1_001_001);
495 assert!(!later.agents[0].activity.starts_with(USAGE_PREFIX), "{}", later.agents[0].activity);
496 assert_eq!(c.nodes["private-root"].limit, None);
497}
498fn running_bash(f: &Fixture) {
499 f.append(json!({"type":"custom","customType":"tool_execution_start","timestamp":8_000_000,"data":{"toolCallId":"t","toolName":"bash","intent":"Running operation","startedAt":8_000_000}}));
500 f.append(json!({"type":"message","timestamp":8_000_000,"message":{"role":"assistant","stopReason":"error","errorMessage":"You have hit your usage limit. Try again in 90 min.","content":[]}}));
501}
502/// Mutant: a returning file at the same inode and length is not reread, so activity_state stays unknown and the sentence wins.
503#[test] fn a_renamed_transcript_publishes_its_running_tool_again() {
504 let f = Fixture::new();
505 idle_host(&f.hosts);
506 running_bash(&f);
507 let mut c = Collector::new(vec![8;32],1000);
508 assert_eq!(c.poll(&f.sessions, Some(&f.hosts), 8_000_200).agents[0].activity, "bash: Running operation");
509 let away = f.dir.join("held.jsonl");
510 fs::rename(&f.root, &away).unwrap();
511 let gone = c.poll(&f.sessions, Some(&f.hosts), 8_000_400);
512 assert!(gone.agents[0].activity.starts_with(USAGE_PREFIX), "{}", gone.agents[0].activity);
513 assert!(!c.nodes["private-root"].tools.is_empty());
514 fs::rename(&away, &f.root).unwrap();
515 let back = c.poll(&f.sessions, Some(&f.hosts), 8_000_600);
516 assert_eq!(back.agents[0].activity, "bash: Running operation");
517 assert_eq!(back.agents[0].activity_state, "running");
518}
519/// Mutant: skip `forget` for a missing path. The rewrite keeps the cursor's old identity and length, so nothing is reread.
520#[test] fn a_rewritten_transcript_with_the_same_cursor_identity_is_reread() {
521 let f = Fixture::new();
522 idle_host(&f.hosts);
523 running_bash(&f);
524 let mut c = Collector::new(vec![8;32],1000);
525 assert_eq!(c.poll(&f.sessions, Some(&f.hosts), 8_000_200).agents[0].activity, "bash: Running operation");
526 let identity = c.cursors[&f.root].stored_identity().unwrap();
527 let bytes = fs::read(&f.root).unwrap();
528 fs::remove_file(&f.root).unwrap();
529 let gone = c.poll(&f.sessions, Some(&f.hosts), 8_000_400);
530 assert!(gone.agents[0].activity.starts_with(USAGE_PREFIX), "{}", gone.agents[0].activity);
531 assert!(c.cursors[&f.root].stored_identity().is_none());
532 fs::write(&f.root, bytes).unwrap();
533 c.cursors.get_mut(&f.root).unwrap().pretend_identity(identity);
534 let back = c.poll(&f.sessions, Some(&f.hosts), 8_000_600);
535 assert_eq!(back.agents[0].activity, "bash: Running operation");
536 assert_eq!(back.agents[0].activity_state, "running");
537}
538/// Mutant: a 100% token_count overwrites a Turn capacity record, and the next under-100 count clears it.
539#[test] fn a_full_token_window_does_not_replace_turn_capacity() {
540 let f = Fixture::new();
541 let now = chrono::Utc::now().timestamp_millis();
542 let codex = f.dir.join("codex/sessions/2026/11/15"); fs::create_dir_all(&codex).unwrap();
543 let path = codex.join("rollout-x.jsonl");
544 let resets = now / 1000 + 3_600;
545 let count = |percent: f64, at: i64| json!({"type":"event_msg","timestamp":at,"payload":{"type":"token_count","rate_limits":{"primary":{"used_percent":percent,"window_minutes":300,"resets_at":resets},"secondary":null,"rate_limit_reached_type":null}}});
546 let lines = [
547 json!({"type":"event_msg","timestamp":now-60_000,"payload":{"type":"error","message":"The model is currently at capacity due to high demand."}}),
548 json!({"type":"event_msg","timestamp":now,"payload":{"type":"user_message","message":"Are you still there?"}}),
549 ];
550 fs::write(&path, lines.iter().map(|l| format!("{l}\n")).collect::<String>()).unwrap();
551 let mut c = Collector::new(run_salt(),0).with_transcripts(source::Transcript::Codex, f.dir.join("codex/sessions"));
552 let activity = |feed: &Feed| feed.agents.iter().find(|a| a.runtime == "Codex").unwrap().activity.clone();
553 let shown = c.poll(&f.sessions, Some(&f.hosts), now);
554 assert!(activity(&shown).starts_with(CAPACITY_PREFIX), "{}", activity(&shown));
555 assert!(!serde_json::to_string(&shown).unwrap().contains("high demand"));
556 assert!(!serde_json::to_string(&shown).unwrap().contains("Are you still there"));
557 let mut file = fs::OpenOptions::new().append(true).open(&path).unwrap();
558 writeln!(file, "{}", count(100.0, now + 400)).unwrap();
559 let full = c.poll(&f.sessions, Some(&f.hosts), now + 500);
560 assert!(activity(&full).starts_with(CAPACITY_PREFIX), "{}", activity(&full));
561 let limit = c.nodes.values().find(|n| n.public.runtime == "Codex").unwrap().limit.unwrap();
562 assert_eq!(limit.stop, Stop::Capacity);
563 assert_eq!(limit.source, LimitSource::Turn);
564 writeln!(file, "{}", count(40.0, now + 600)).unwrap();
565 let under = activity(&c.poll(&f.sessions, Some(&f.hosts), now + 700));
566 assert!(under.starts_with(CAPACITY_PREFIX), "{under}");
567 writeln!(file, "{}", json!({"type":"event_msg","timestamp":now+800,"payload":{"type":"task_complete","turn_id":"t1","last_agent_message":"Back to work."}})).unwrap();
568 let lifted = activity(&c.poll(&f.sessions, Some(&f.hosts), now + 1000));
569 assert!(!lifted.starts_with(CAPACITY_PREFIX), "{lifted}");
570 assert!(c.nodes.values().filter(|n| n.public.runtime == "Codex").all(|n| n.limit.is_none()));
571}
572#[test] fn agent_replies_are_public_by_default() {
573 let mut c = Collector::new(vec![7;32],1000); c.ensure("private-root","private-root",None,"Root",2000);
574 c.event("private-root",&message("assistant","",json!([{"type":"text","text":"The hive page is rebuilt and the checks passed"}]),1004),2000);
575 assert_eq!(c.interactions.len(), 1, "agent replies are public by default");
576 assert!(c.interactions[0].text.contains("The hive page is rebuilt and the checks passed"), "{}", c.interactions[0].text);
577 c.event("private-root",&message("user","user",json!([{"type":"text","text":"a person wrote this and it must stay off the page"}]),1005),2000);
578 assert_eq!(c.interactions.len(), 1, "a person's own message stays unpublished");
579}
580#[test] fn a_key_crossing_the_reply_bound_is_withheld_whole() {
581 let mut c = collector();
582 let key = "ghp_FAKE0123456789abcdefFAKE0123456789";
583 let reply = format!("{} {key} end", "x".repeat(3990));
584 c.event("private-root",&message("assistant","",json!([{"type":"text","text":reply}]),1004),2000);
585 let text = &c.interactions[0].text;
586 assert!(!text.contains("ghp_"), "{text}");
587 // The bound falls inside the marker, so the reply ends before it.
588 assert_eq!(text, &"x".repeat(3990));
589}
590#[test] fn replies_are_public_by_default_and_hold_turns_them_off() {
591 let reply = "Your email to someone@example.net is in Drafts; key sk-ant-api03-FAKEplantedKEY0123456789 rotated";
592 let mut c = Collector::new(vec![7;32],1000); c.ensure("private-root","private-root",None,"Root",2000);
593 c.event("private-root",&message("assistant","",json!([{"type":"text","text":reply}]),1004),2000);
594 assert_eq!(c.interactions.len(),1, "replies are public by default");
595 let text = &c.interactions[0].text;
596 assert_eq!(text, &format!("Your email to {} is in Drafts; key {} rotated", crate::privacy::EMAIL, crate::privacy::SECRET));
597 let mut held = Collector::new(vec![7;32],1000).with_replies(false); held.ensure("private-root","private-root",None,"Root",2000);
598 held.event("private-root",&message("assistant","",json!([{"type":"text","text":reply}]),1004),2000);
599 assert!(held.interactions.is_empty(), "--hold-replies keeps reply text off the feed");
600}
601#[test] fn idle_sentences_and_the_universe_title_withhold_a_planted_key_and_email() {
602 let key = "sk-ant-api03-FAKEplantedKEY0123456789";
603 let mail = "someone@example.net";
604 let at = 1_793_000_000_000i64;
605 let mut c = Collector::new(vec![7;32],1000);
606 c.ensure("private-root","private-root",None,&format!("worker {key} {mail}"),at);
607 let mut failed = message("assistant","",json!([]),at);
608 failed["message"]["stopReason"] = json!("error");
609 failed["message"]["errorMessage"] = json!(format!("You have hit your usage limit. Try again in 90 min. {key} {mail}"));
610 c.event("private-root",&failed,at);
611 let feed = c.poll(Path::new("/nonexistent-hive-sessions"),None,at + 1000);
612 let output = serde_json::to_string(&feed).unwrap();
613 assert!(!output.contains(key) && !output.contains(mail), "{output}");
614 let agent = feed.agents.iter().find(|a| a.id == c.id("private-root")).unwrap();
615 assert!(agent.activity.starts_with(USAGE_PREFIX), "{}", agent.activity);
616 assert!(agent.activity.contains(crate::privacy::SECRET), "{}", agent.activity);
617 let raw = stop_sentence(c.nodes["private-root"].limit.as_ref().unwrap());
618 assert_ne!(screened_sentence(c.nodes["private-root"].limit.as_ref().unwrap(), PathMutant::None), raw);
619 assert_eq!(screened_sentence(c.nodes["private-root"].limit.as_ref().unwrap(), PathMutant::SentenceSkip), raw);
620 let title = universe_title(&format!("worker {key}"), "idle", &format!("{raw} {mail}"), PathMutant::None);
621 assert!(!title.contains(key) && !title.contains(mail), "{title}");
622 let leaked = universe_title(&format!("worker {key}"), "idle", &format!("{raw} {mail}"), PathMutant::UniverseSkip);
623 assert!(leaked.contains(key) && leaked.contains(mail), "{leaked}");
624 assert_ne!(title, leaked);
625}