From b103a0b28cd626af1539c47b0d8e706ed7b86b5c Mon Sep 17 00:00:00 2001 From: i2cjak Date: Tue, 24 Nov 2026 20:28:07 -0500 Subject: [PATCH] mailroom: route triage-end completions, guarantee fallback tell, deduplicate per thread --- native/host/src/bots/mail/done.rs | 426 ++++++++++++++++++++++++-- native/host/src/bots/mail/escalate.rs | 90 +++++- native/host/src/bots/mail/gate.rs | 16 +- native/host/src/bots/mail/owner.rs | 10 +- native/host/src/bots/mail/route.rs | 2 - native/host/src/bots/mail/run.rs | 29 +- native/host/src/bots/rpc.rs | 4 +- native/host/src/bots/tests/triage.rs | 197 ++++++++++++ 8 files changed, 718 insertions(+), 56 deletions(-) diff --git a/native/host/src/bots/mail/done.rs b/native/host/src/bots/mail/done.rs index a6a6c70b69..dc2ea5e32e 100644 --- a/native/host/src/bots/mail/done.rs +++ b/native/host/src/bots/mail/done.rs @@ -12,15 +12,98 @@ use std::sync::Arc; /// Done.window: seconds a batch stays open after its first finish pub const WINDOW: u64 = 60; +/// Done.fallback: seconds after a finish is admitted (or a lane starts) before an untold completion gets a plain fallback tell +pub const FALLBACK_AFTER: u64 = 120; +/// Historical `triage-end:` mail older than this (from un-claimed backlog) is claimed and dropped without telling +pub const TRIAGE_END_STALE_SECS: u64 = 7200; +/// Cooldown between repeated `triage-end:` completion tells for the same thread (seconds). +pub const COOLDOWN: u64 = 1800; fn set(k: String, v: &str, at: u64) -> Value { json!({"$":"SettingSet","key":k,"value":v,"at":at}) } pub fn batch_key(bot: &str) -> String { format!("mail.private.done.batch.{bot}") } pub fn due_key(bot: &str) -> String { format!("mail.private.done.due.{bot}") } +pub fn pending_key(bot: &str) -> String { format!("mail.private.done.pending.{bot}") } +pub fn told_at_key(bot: &str, thread: &str) -> String { format!("mail.private.done.told.{bot}.{thread}") } +pub fn fallback_at_key(bot: &str, thread: &str) -> String { format!("mail.private.done.fallback.{bot}.{thread}") } fn item_key(input: &str) -> String { format!("mail.private.done.item.{input}") } /// the plain digest a done lane owes, kept until it tells (`said`) or the hub posts it pub fn lane_key(lane: &str) -> String { format!("mail.private.done.lane.{lane}") } fn said_key(lane: &str) -> String { format!("mail.private.said.{lane}") } fn handed_key(lane: &str) -> String { format!("mail.private.handed.{lane}") } +/// Extract `` from `triage-end::` or an imported `owner:[uid,origin,"triage-end::"]`. +pub fn triage_end_thread_of_id(mail_id: &str) -> Option { + let raw = if let Some(r) = mail_id.strip_prefix("triage-end:") { + r.to_string() + } else if let Some(arr) = mail_id.strip_prefix("owner:") { + let v: Vec = serde_json::from_str(arr).ok()?; + v.get(2).and_then(|s| s.strip_prefix("triage-end:"))?.to_string() + } else { + return None; + }; + let th = raw.rsplit_once(':').map(|(t, _)| t).unwrap_or(&raw); + (!th.is_empty()).then(|| th.to_string()) +} +/// Extract `` from a `triage-end:` mail id (local or owner-imported). +pub fn triage_end_thread(mail_id: &str) -> Option { triage_end_thread_of_id(mail_id) } +/// Parse a `triage-end:` completed report: returns `(thread, title)` only when the status is `completed`. +fn triage_end_completed(m: &super::Hdr, text: &str) -> Option<(String, String)> { + let extracted = triage_end_thread(&m.id)?; + let thread = if m.id.starts_with("owner:") { + m.from.strip_prefix("thread:").filter(|t| !t.is_empty()).map(str::to_string).unwrap_or(extracted) + } else { + extracted + }; + let first = text.lines().next().filter(|l| !l.is_empty()).unwrap_or(&m.head); + let rest = first.strip_prefix("Thread completed:")?.trim(); + let title = if rest.starts_with("backplane://") { + String::new() + } else if let Some(i) = rest.rfind(" (backplane://") { + rest[..i].trim().to_string() + } else { + rest.to_string() + }; + Some((thread, title)) +} +fn contains_id(text: &str, id: &str) -> bool { + if id.is_empty() { return false } + let is_id_char = |c: char| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '~'); + for (idx, _) in text.match_indices(id) { + let before_ok = text[..idx].chars().next_back().map_or(true, |c| !is_id_char(c)); + let after_ok = text[idx + id.len()..].chars().next().map_or(true, |c| !is_id_char(c)); + if before_ok && after_ok { return true } + } + false +} +/// Extract up to `max_lines` non-empty cleaned lines, truncated to `max_chars`. +pub fn first_lines(text: &str, max_lines: usize, max_chars: usize) -> String { + if max_lines == 0 || max_chars == 0 { return String::new() } + let mut lines: Vec = vec![]; + for raw in text.lines() { + let cleaned = raw.trim().trim_start_matches(['#', '*', '-', '>', ' ']).trim().replace('\t', " "); + if !cleaned.is_empty() { + lines.push(cleaned); + if lines.len() >= max_lines { break } + } + } + let joined = lines.join("\n"); + if joined.chars().count() > max_chars { + format!("{}…", take_chars(&joined, max_chars.saturating_sub(1))) + } else { + joined + } +} +/// Plain fallback tell for a completion that went untold past `FALLBACK_AFTER`: title, link, and first lines of reply. +pub fn fallback_text(title: &str, reply: &str, thread: &str) -> String { + let title = if title.trim().is_empty() { thread } else { title.trim() }; + let link = ref_uri("thread", thread); + let preview = first_lines(reply, 3, 300); + if preview.is_empty() { + format!("Finished: {title} ({link})") + } else { + format!("Finished: {title} ({link})\n{preview}") + } +} + /// Done.report: the launcher's report of a launched thread whose turn completed (`launch::note` with `word` "completed"): (thread, title). /// "waits for an answer", "failed", "was interrupted" and "needs the person" are not finishes. pub fn done_report(text: &str) -> Option<(String, String)> { @@ -52,34 +135,144 @@ pub fn digest(xs: &[Value]) -> String { pub fn running_build() -> String { std::env::current_exe().ok().and_then(|p| p.parent().and_then(|d| d.file_name()).map(|n| n.to_string_lossy().to_string())).filter(|n| n.matches('-').count() >= 2).unwrap_or_default() } -const DONE_HEAD: &str = "[Private mailroom: launched threads ended a turn. Each item below is a launched thread (often a lead) that ended a turn; most turn-ends are progress, not news. The person's rules in (pref.fewer-progress-notes among them) rule here: speak only when something landed on main, was released for them to try, a non-PR deliverable/user-requested thread actually finished (local firmware build, CAD/PDF render, hardware BOM, local analysis/task with no PR/commit/release ref), or something needs their decision, approval or answer. Never use completed for intermediate progress turns of recurring software leads. For each item, thread_read it if unsure. If one is material, call tell_person ONCE with the key given below, its kind (landed, release, completed or needs_you) and its ref (owner/repo#N merged, commit:owner/repo@sha, release:owner/repo@tag published, thread: local or ~ completed, ask: open: the hub verifies it and refuses a tell without one): one short plain line per material item, what landed and whether it is in their running build, what deliverable/task finished, or exactly what they must decide. If nothing is material, end silently with no tell: that is the right outcome. Never tell \"nothing landed\", \"nothing to try\", \"still waiting\", \"in review\", \"queued\" or \"rebased\": the hub refuses it. Landings, releases and completed deliverables are collected and reach the person at most every 30 minutes; needs_you goes at once.]\n"; +const DONE_HEAD: &str = "[Private mailroom: threads ended a turn. Each item below is a thread (launched or user-requested) that ended a turn; most recurring-lead turn-ends are progress, not news. The person's rules in (pref.fewer-progress-notes among them) rule here: speak only when something landed on main, was released for them to try, a non-PR deliverable/user-requested thread actually finished (local firmware build, CAD/PDF render, hardware BOM, local analysis/task with no PR/commit/release ref), or something needs their decision, approval or answer. Never use completed for intermediate progress turns of recurring software leads. For each item, thread_read it if unsure. If one is material, call tell_person ONCE with the key given below, its kind (landed, release, completed or needs_you) and its ref (owner/repo#N merged, commit:owner/repo@sha, release:owner/repo@tag published, thread: local or ~ completed, ask: open: the hub verifies it and refuses a tell without one): one short plain line per material item, what landed and whether it is in their running build, what deliverable/task finished, or exactly what they must decide. If nothing is material, end silently with no tell: that is the right outcome. Never tell \"nothing landed\", \"nothing to try\", \"still waiting\", \"in review\", \"queued\" or \"rebased\": the hub refuses it. Landings, releases and completed deliverables are collected and reach the person at most every 30 minutes; needs_you goes at once.]\n"; impl<'a> Ctx<'a> { - /// Done.admit (Mail.route, the owner's inbound launch report of a finish): the report joins the batch instead of a triage run; its ticket is claimed so the - /// outbox walk does not route it again + /// Done.admit (Mail.route, the owner's inbound launch or `triage-end:` completion): the report joins the batch instead of a triage run; + /// its ticket is claimed so the outbox walk does not route it again, and repeated completions of the same thread are deduplicated. pub fn done_admit(&mut self, body: &Body, bot: &str) -> Option { - let m = &body.mail; if m.kind != "launch" { return None } - if !self.setting(&item_key(&m.id), "").is_empty() { return Some(Step::none()) } - let (thread, title) = done_report(&body.text).or_else(|| done_report(&m.head))?; - // Gate.quiet: a turn-end that opens with no-change words and asks nothing is no finish: no lane, nothing told - if super::gate::quiet_report(&summary(&body.text)) { + let m = &body.mail; + let (thread, title, source) = if m.kind == "launch" { + let (th, ti) = done_report(&body.text).or_else(|| done_report(&m.head))?; + (th, ti, "launch") + } else if triage_end_thread(&m.id).is_some() { + let Some((th, ti)) = triage_end_completed(m, &body.text) else { + let mut cs = self.owner_claim(&m.id); + if self.setting(&item_key(&m.id), "").is_empty() { cs.push(set(item_key(&m.id), "ignored", self.now)); } + self.replay(&cs); + return Some(Step { cs, outs: vec![] }); + }; + if m.at >= 1_700_000_000 && self.now.saturating_sub(m.at) > TRIAGE_END_STALE_SECS { + let mut cs = self.owner_claim(&m.id); + if self.setting(&item_key(&m.id), "").is_empty() { cs.push(set(item_key(&m.id), "stale", self.now)); } + self.replay(&cs); + return Some(Step { cs, outs: vec![] }); + } + (th, ti, "triage-end") + } else { + return None; + }; + if !self.setting(&item_key(&m.id), "").is_empty() { + let cs = self.owner_claim(&m.id); + self.replay(&cs); + return Some(Step { cs, outs: vec![] }); + } + // Gate.quiet: a launched thread's turn-end that opens with no-change words and asks nothing is no finish: no lane, nothing told + if source == "launch" && super::gate::quiet_report(&summary(&body.text)) { let mut cs = self.owner_claim(&m.id); cs.push(set(item_key(&m.id), "quiet", self.now)); self.replay(&cs); return Some(Step { cs, outs: vec![] }) } - let mut xs = items(&self.setting(&batch_key(bot), "[]")); let title = if title.is_empty() { self.th(&thread).title } else { title }; - xs.push(json!({"input":m.id,"conv":m.conv,"thread":thread,"title":title,"summary":summary(&body.text),"at":self.now})); + let body_reply = body.text.split_once('\n').map(|(_, r)| r).unwrap_or("").trim(); + let reply = if !body_reply.is_empty() { + body_reply + } else { + self.f.last.get(&thread).map(|l| l.0.as_str()).unwrap_or("") + }; + let sum = first_lines(reply, 1, 200); + let preview = first_lines(reply, 3, 300); + + let mut xs = items(&self.setting(&batch_key(bot), "[]")); + let mut pend = items(&self.setting(&pending_key(bot), "[]")); + if let Some(existing) = xs.iter_mut().find(|i| i["thread"] == thread.as_str()) { + if let Some(o) = existing.as_object_mut() { + if !title.is_empty() { o.insert("title".into(), json!(title)); } + if !sum.is_empty() { o.insert("summary".into(), json!(sum)); } + o.insert("at".into(), json!(self.now)); + } + let mut pend_changed = false; + for p in &mut pend { + if p["thread"] == thread.as_str() { + if let Some(o) = p.as_object_mut() { + if !title.is_empty() { o.insert("title".into(), json!(title)); } + if !preview.is_empty() { o.insert("summary".into(), json!(preview)); } + pend_changed = true; + } + } + } + let mut cs = self.owner_claim(&m.id); + cs.push(set(item_key(&m.id), "dedup", self.now)); + cs.push(set(batch_key(bot), &jshow(json!(xs)), self.now)); + if pend_changed { cs.push(set(pending_key(bot), &jshow(json!(pend)), self.now)); } + self.replay(&cs); + return Some(Step { cs, outs: vec![] }); + } + if let Some(existing_p) = pend.iter_mut().find(|i| i["thread"] == thread.as_str()) { + let mut pend_changed = false; + if let Some(o) = existing_p.as_object_mut() { + if !title.is_empty() { o.insert("title".into(), json!(title)); pend_changed = true; } + if !preview.is_empty() { o.insert("summary".into(), json!(preview)); pend_changed = true; } + } + let mut cs = self.owner_claim(&m.id); + cs.push(set(item_key(&m.id), "dedup", self.now)); + if pend_changed { cs.push(set(pending_key(bot), &jshow(json!(pend)), self.now)); } + self.replay(&cs); + return Some(Step { cs, outs: vec![] }); + } + if source == "triage-end" { + let told_at: u64 = self.setting(&told_at_key(bot, &thread), "").parse().unwrap_or(0); + if told_at > 0 && self.now.saturating_sub(told_at) < COOLDOWN { + let mut cs = self.owner_claim(&m.id); + cs.push(set(item_key(&m.id), "dedup", self.now)); + self.replay(&cs); + return Some(Step { cs, outs: vec![] }); + } + } + xs.push(json!({"input":m.id,"conv":m.conv,"thread":thread,"title":title,"summary":sum,"source":source,"at":self.now})); + pend.push(json!({"input":m.id,"thread":thread,"title":title,"summary":preview,"source":source,"at":self.now,"due_at":self.now + FALLBACK_AFTER,"lane":""})); let mut cs = self.owner_claim(&m.id); - cs.push(set(item_key(&m.id), "batched", self.now)); cs.push(set(batch_key(bot), &jshow(json!(xs)), self.now)); + cs.push(set(item_key(&m.id), "batched", self.now)); + cs.push(set(batch_key(bot), &jshow(json!(xs)), self.now)); + cs.push(set(pending_key(bot), &jshow(json!(pend)), self.now)); if self.setting(&due_key(bot), "").is_empty() { cs.push(set(due_key(bot), &(self.now + WINDOW).to_string(), self.now)) } self.replay(&cs); Some(Step { cs, outs: vec![] }) } + /// Whether `bot` currently has a live done lane still running inside its grace window. + pub(super) fn has_live_done_lane(&self, bot: &str) -> bool { + !bot.is_empty() && self.w.mail.runs.values().any(|r| { + r.live && r.bot == bot && self.w.private_is(&r.thread) + && !self.setting(&lane_key(&r.thread), "").is_empty() + && self.th(&r.thread).turn == "running" + && self.now.saturating_sub(r.at) < FALLBACK_AFTER + }) + } /// Done.flush: a batch whose window is over becomes one private lane (Private.spawn) that owes one tell_person - pub fn done_flush(&mut self, bot: &str) -> Step { - let due: u64 = self.setting(&due_key(bot), "").parse().unwrap_or(0); - if due == 0 || self.now < due { return Step::none() } - let xs = items(&self.setting(&batch_key(bot), "[]")); + pub fn done_flush(&mut self, bot: &str) -> Step { self.done_flush_inner(bot, false) } + /// Flush any queued finishes immediately (used when a running mailcoord lane ends while completions arrived). + pub fn done_flush_now(&mut self, bot: &str) -> Step { self.done_flush_inner(bot, true) } + fn done_flush_inner(&mut self, bot: &str, force: bool) -> Step { + if bot.is_empty() { return Step::none() } + if !force { + let due: u64 = self.setting(&due_key(bot), "").parse().unwrap_or(0); + if due == 0 || self.now < due { return Step::none() } + } + let mut xs = items(&self.setting(&batch_key(bot), "[]")); + if force && xs.is_empty() { return Step::none() } let mut cs = vec![set(batch_key(bot), "[]", self.now), set(due_key(bot), "", self.now)]; if xs.is_empty() || self.w.triage_thread().is_empty() { self.replay(&cs); return Step { cs, outs: vec![] } } + for i in &mut xs { + if let Some(th) = i["thread"].as_str().filter(|t| !t.is_empty()).map(str::to_string) { + let th_title = self.th(&th).title; + if !th_title.trim().is_empty() { + if let Some(o) = i.as_object_mut() { o.insert("title".into(), json!(th_title)); } + } + if let Some(last_r) = self.f.last.get(&th).map(|l| l.0.as_str()).filter(|s| !s.trim().is_empty()) { + let s = first_lines(last_r, 1, 200); + if !s.is_empty() { + if let Some(o) = i.as_object_mut() { o.insert("summary".into(), json!(s)); } + } + } + } + } let id = self.id("done"); let key = format!("done:{id}"); let build = running_build(); let list: String = xs.iter().map(|i| format!("- {} · input {}\n", line(i), i["input"].as_str().unwrap_or(""))).collect(); @@ -88,44 +281,227 @@ impl<'a> Ctx<'a> { self.replay(&cs); let spawn = self.private_spawn(bot, &format!("done-batch:{id}"), ¬e); let lane = spawn.cs.iter().find(|e| e["$"] == "ThreadCreated").and_then(|e| e["id"].as_str()).unwrap_or("").to_string(); - let mut own = vec![set(lane_key(&lane), &jshow(json!({"key":key,"text":digest(&xs)})), self.now)]; self.replay(&own); + let mut own = vec![set(lane_key(&lane), &jshow(json!({"key":key,"text":digest(&xs)})), self.now)]; + let mut pend = items(&self.setting(&pending_key(bot), "[]")); + if !pend.is_empty() && !lane.is_empty() { + let mut changed = false; + for p in &mut pend { + let inp = p["input"].as_str().unwrap_or(""); + let th = p["thread"].as_str().unwrap_or(""); + if xs.iter().any(|i| i["input"].as_str() == Some(inp) || (!th.is_empty() && i["thread"].as_str() == Some(th))) { + if let Some(o) = p.as_object_mut() { + o.insert("lane".into(), json!(lane)); + let old_due = o.get("due_at").and_then(Value::as_u64).unwrap_or(0); + o.insert("due_at".into(), json!(old_due.max(self.now + FALLBACK_AFTER))); + changed = true; + } + } + } + if changed { own.push(set(pending_key(bot), &jshow(json!(pend)), self.now)); } + } + self.replay(&own); cs.append(&mut own); Step { cs, outs: vec![] }.cat(spawn) } - /// Done.lane.end: a done lane that ended (any end) without telling has the hub post its digest, once; Private.lost's hand-over is not owed then + /// Clear pending fallback entries when `tell_person` handles them. + pub fn done_pending_clear(&mut self, bot: &str, lane: &str, r: Option<&super::gate::Ref>, text: &str) -> Vec { + let mut pend = items(&self.setting(&pending_key(bot), "[]")); + if pend.is_empty() { return vec![] } + let mut cleared_threads: Vec = vec![]; + let mut keep = vec![]; + let any_named = r.is_none() && pend.iter().any(|i| contains_id(text, i["thread"].as_str().unwrap_or(""))); + for i in pend.drain(..) { + let th = i["thread"].as_str().unwrap_or("").to_string(); + let remove = match r { + Some(super::gate::Ref::Thread { id }) => th == id.as_str(), + _ if any_named => !th.is_empty() && contains_id(text, &th), + _ => !lane.is_empty() && i["lane"].as_str() == Some(lane), + }; + if remove { + if !th.is_empty() && !cleared_threads.contains(&th) { cleared_threads.push(th); } + } else { + keep.push(i); + } + } + if cleared_threads.is_empty() && keep.len() == items(&self.setting(&pending_key(bot), "[]")).len() { + return vec![]; + } + let mut cs = vec![set(pending_key(bot), &jshow(json!(keep)), self.now)]; + for th in cleared_threads { + cs.push(set(told_at_key(bot, &th), &self.now.to_string(), self.now)); + } + cs + } + /// Done.lane.end: a done lane that ended (any end) without telling has the hub settle pending state: + /// a cleanly completed `launch` lane that chose silence removes its `launch` entries (no Nov 20 digest noise); + /// `triage-end` entries (or any failed/interrupted lane's entries) restore their `at + FALLBACK_AFTER` deadline. pub fn done_lane_end(&mut self, lane: &str, state: &str) -> Option { let owed = self.setting(&lane_key(lane), ""); if owed.is_empty() { return None } if !["completed", "failed", "interrupted"].contains(&state) { return Some(Step::none()) } if !self.setting(&said_key(lane), "").is_empty() || !self.setting(&handed_key(lane), "").is_empty() { return Some(Step::none()) } let v: Value = serde_json::from_str(&owed).unwrap_or(Value::Null); let (key, text) = (v["key"].as_str().unwrap_or("").to_string(), v["text"].as_str().unwrap_or("").to_string()); - let cs = vec![set(handed_key(lane), &self.now.to_string(), self.now)]; self.replay(&cs); + let mut cs = vec![set(handed_key(lane), &self.now.to_string(), self.now)]; let bot = self.w.private_owner(lane); + let mut pend = items(&self.setting(&pending_key(&bot), "[]")); + if !pend.is_empty() { + let mut changed = false; + let mut next_pend = vec![]; + for mut p in pend.drain(..) { + if p["lane"].as_str() == Some(lane) { + if state == "completed" && p["source"].as_str() == Some("launch") { + changed = true; + continue; + } + let base = p["at"].as_u64().unwrap_or(self.now); + let target_due = base + FALLBACK_AFTER; + if p["due_at"].as_u64() != Some(target_due) { + if let Some(o) = p.as_object_mut() { o.insert("due_at".into(), json!(target_due)); changed = true; } + } + } + next_pend.push(p); + } + if changed { cs.push(set(pending_key(&bot), &jshow(json!(next_pend)), self.now)); } + } + self.replay(&cs); if key.is_empty() || text.is_empty() || !self.setting(&private_told_key(&bot, &key), "").is_empty() { return Some(Step { cs, outs: vec![] }) } // Gate.tell: the hub's own digest names no verified landing, release or ask, so it is never told (Nov 20: 56 "Done: …" digests reached the person): a lane // that has something material tells it with tell_person and its ref; silence is the right end let _ = text; Some(Step { cs, outs: vec![] }) } - /// the owners with a done batch whose window is over + /// the owners with a done batch whose window is over (waiting if another done lane is still running inside its grace window) pub fn done_due(&self) -> Vec { let ub = self.w.uber_bot(); let due: u64 = self.setting(&due_key(&ub), "").parse().unwrap_or(0); - if ub.is_empty() || due == 0 || self.now < due { vec![] } else { vec![ub] } + if ub.is_empty() || due == 0 || self.now < due || self.has_live_done_lane(&ub) { vec![] } else { vec![ub] } } + /// the owners with an untold completion whose fallback deadline has expired + pub fn done_fallback_due(&self) -> Vec { + let ub = self.w.uber_bot(); + if ub.is_empty() { return vec![] } + let due = items(&self.setting(&pending_key(&ub), "[]")).iter().any(|i| { + let d = i["due_at"].as_u64().unwrap_or(0); + d > 0 && self.now >= d + }); + if due { vec![ub] } else { vec![] } + } + /// Post a plain fallback tell for any completion still untold past `FALLBACK_AFTER`. + pub fn done_fallback_flush(&mut self, bot: &str) -> Step { + if bot.is_empty() { return Step::none() } + let pend = items(&self.setting(&pending_key(bot), "[]")); + if pend.is_empty() { return Step::none() } + let (mut expired, mut keep) = (vec![], vec![]); + for i in pend { + let d = i["due_at"].as_u64().unwrap_or(0); + if d > 0 && self.now >= d { expired.push(i); } else { keep.push(i); } + } + if expired.is_empty() { return Step::none() } + let mut cs = vec![set(pending_key(bot), &jshow(json!(keep)), self.now)]; + let mut batch = items(&self.setting(&batch_key(bot), "[]")); + let blen = batch.len(); + batch.retain(|b| !expired.iter().any(|e| !e["thread"].as_str().unwrap_or("").is_empty() && e["thread"] == b["thread"])); + if batch.len() != blen { + cs.push(set(batch_key(bot), &jshow(json!(batch)), self.now)); + if batch.is_empty() { cs.push(set(due_key(bot), "", self.now)); } + } + self.replay(&cs); + let mut st = Step { cs, outs: vec![] }; + for i in expired { + let thread = i["thread"].as_str().unwrap_or(""); + let lane = i["lane"].as_str().unwrap_or(""); + let source = i["source"].as_str().unwrap_or(""); + let input = i["input"].as_str().unwrap_or(""); + if thread.is_empty() { continue } + if source == "triage-end" { + let told_at: u64 = self.setting(&told_at_key(bot, thread), "").parse().unwrap_or(0); + if told_at > 0 && self.now.saturating_sub(told_at) < COOLDOWN { continue } + } + let th_title = self.th(thread).title; + let title = if !th_title.trim().is_empty() { th_title } else { i["title"].as_str().unwrap_or("").to_string() }; + let reply = self.f.last.get(thread).map(|l| l.0.as_str()).filter(|s| !s.trim().is_empty()) + .unwrap_or_else(|| i["summary"].as_str().unwrap_or("")); + let preview = first_lines(reply, 3, 300); + if super::gate::quiet_report(&preview) { continue } + let text = fallback_text(&title, reply, thread); + let fb_key = if input.is_empty() { format!("done-fallback:{thread}:{}", self.now) } else { format!("done-fallback:{input}") }; + let told = self.private_tell_as(bot, lane, &text, &fb_key); + if !told.cs.is_empty() { + let mark = vec![ + set(told_at_key(bot, thread), &self.now.to_string(), self.now), + set(fallback_at_key(bot, thread), &self.now.to_string(), self.now), + ]; + self.replay(&mark); + st = st.cat(Step { cs: mark, outs: vec![] }).cat(told); + } + } + st + } +} + +/// Earliest pending timer deadline across done batch, fallback guarantees, and tell batch (0 = none). +pub fn next_deadline(w: &crate::bots::world::World, bot: &str) -> u64 { + if bot.is_empty() { return 0 } + let mut best = 0u64; + let mut consider = |v: u64| { if v > 0 && (best == 0 || v < best) { best = v; } }; + consider(w.setting(&due_key(bot), "").parse().unwrap_or(0)); + consider(w.setting(&super::gate::due_key(bot), "").parse().unwrap_or(0)); + for i in items(&w.setting(&pending_key(bot), "[]")) { + consider(i["due_at"].as_u64().unwrap_or(0)); + } + best } impl Bots { /// Done.tick: the minute tick, and the timer a batch's first finish sets, flush what is due - pub async fn done_tick(self: &Arc) { + pub async fn done_tick(self: &Arc) { self.done_tick_at(now_s()).await } + pub async fn done_tick_at(self: &Arc, now: u64) { if crate::copy::on() { return } - let outs = self.decide(&[], |c| { let mut st = Step::none(); for b in c.done_due() { let s = c.done_flush(&b); st = st.cat(s) } for b in c.tell_due() { let s = c.tell_flush(&b); st = st.cat(s) } st }).await; - self.perform(outs).await + let report: Vec = { + let w = self.world().await; + let ub = w.uber_bot(); + if ub.is_empty() { vec![] } else { + let mut threads: Vec = vec![]; + for key in [pending_key(&ub), batch_key(&ub)] { + for i in items(&w.setting(&key, "[]")) { + if let Some(th) = i["thread"].as_str().filter(|t| !t.is_empty()) { + let s = th.to_string(); + if !threads.contains(&s) { threads.push(s); } + } + } + } + threads + } + }; + let outs = self.decide_at(&report, now, |c| { + let mut st = Step::none(); + for b in c.done_due() { let s = c.done_flush(&b); st = st.cat(s); } + for b in c.done_fallback_due() { let s = c.done_fallback_flush(&b); st = st.cat(s); } + for b in c.tell_due() { let s = c.tell_flush(&b); st = st.cat(s); } + st + }).await; + self.perform(outs).await; + self.arm_done_timer().await; + } + /// Arm `done_timer` for the earliest pending batch, fallback, or tell deadline. + pub(super) async fn arm_done_timer(self: &Arc) { + if crate::copy::on() { return } + let due = { let w = self.world().await; next_deadline(&w, &w.uber_bot()) }; + self.done_timer(due); } /// Done.timer: once a batch opens, a flush when its window is over (the minute tick covers a restart in between) pub(super) fn done_timer(self: &Arc, due: u64) { if crate::copy::on() || due == 0 { return } + loop { + let cur = self.done_timer_at.load(std::sync::atomic::Ordering::Acquire); + if cur != 0 && cur <= due { return } + if self.done_timer_at.compare_exchange(cur, due, std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire).is_ok() { break } + } let me = Arc::downgrade(self); tokio::spawn(async move { - tokio::time::sleep(std::time::Duration::from_secs(due.saturating_sub(now_s()) + 1)).await; - if let Some(b) = me.upgrade() { b.done_tick().await } + let now = now_s(); + let wait_s = if due > now { due - now + 1 } else { 30 }; + tokio::time::sleep(std::time::Duration::from_secs(wait_s)).await; + let Some(b) = me.upgrade() else { return }; + let _ = b.done_timer_at.compare_exchange(due, 0, std::sync::atomic::Ordering::AcqRel, std::sync::atomic::Ordering::Acquire); + b.done_tick().await }); } } diff --git a/native/host/src/bots/mail/escalate.rs b/native/host/src/bots/mail/escalate.rs index af7894967a..ce12f22800 100644 --- a/native/host/src/bots/mail/escalate.rs +++ b/native/host/src/bots/mail/escalate.rs @@ -15,6 +15,8 @@ pub fn private_told_key(bot: &str, key: &str) -> String { pair_key("mail.private fn note_key(th: &str) -> String { format!("mail.private.note.{th}") } fn said_key(th: &str) -> String { format!("mail.private.said.{th}") } fn handed_key(th: &str) -> String { format!("mail.private.handed.{th}") } +/// Cooldown between repeated `triage-end` completion mails for the same unmanaged thread (seconds). +pub const TRIAGE_END_COOLDOWN: u64 = 1800; /// Continuity.inbound fn continuity_inbound(m: &Hdr, bot: &str) -> bool { m.from != format!("bot:{bot}") && m.want == "act" && (m.to == format!("bot:{bot}") || m.to.starts_with("room:")) } @@ -232,35 +234,91 @@ impl<'a> Ctx<'a> { if state == "completed" && text.trim().is_empty() { return Step::none() } self.operational(Origin::new(&self.w.mail_addr(th), "bot", ""), &self.w.triage_thread(), &format!("Bot report from {}:\n{text}", ref_uri("thread", th)), &format!("triage-bot:{th}:{}", self.now), "fyi", vec![]) } - /// Triage.thread.end: a thread nobody manages finished: the uberbot hears it as mail it reads when it next looks (fyi: it starts no turn), and decides; its own thread is not news to it + /// Triage.thread.end: an unmanaged thread finished: the uberbot files it for its done/fallback pipeline, deduplicated per thread. pub fn triage_thread_end(&mut self, th: &str, state: &str) -> Step { let tt = self.w.triage_thread(); if tt.is_empty() || th == tt || self.w.managed(th) || self.run_is(th) { return Step::none() } - // its words are not folded here (a big log's messages are not read): the mail names the thread, and the uberbot reads it when it matters - self.operational(Origin::new(&self.w.mail_addr(th), "thread", ""), &tt, &format!("Thread {state}: {}", ref_uri("thread", th)), &format!("triage-end:{th}:{}", self.now), "fyi", vec![]) + if state == "completed" { + let ub = self.w.uber_bot(); + let in_list = |key: &str| { + serde_json::from_str::(&self.setting(key, "[]")).ok() + .and_then(|v| v.as_array().cloned()) + .map_or(false, |xs| xs.iter().any(|i| i["thread"].as_str() == Some(th))) + }; + let last_at: u64 = self.setting(&format!("triage.end.last.{th}"), "").parse().unwrap_or(0); + if in_list(&super::done::batch_key(&ub)) + || in_list(&super::done::pending_key(&ub)) + || (last_at > 0 && self.now.saturating_sub(last_at) < TRIAGE_END_COOLDOWN) + { + return Step::none(); + } + } + let title = self.th(th).title; + let uri = ref_uri("thread", th); + let head_line = if title.trim().is_empty() { + format!("Thread {state}: {uri}") + } else { + format!("Thread {state}: {} ({uri})", title.trim()) + }; + let reply = self.f.last.get(th).map(|l| l.0.trim()).unwrap_or(""); + let text = if reply.is_empty() { + head_line + } else { + format!("{head_line}\n{}", take_chars(reply, 2000)) + }; + let op = self.operational(Origin::new(&self.w.mail_addr(th), "thread", ""), &tt, &text, &format!("triage-end:{th}:{}", self.now), "fyi", vec![]); + if state == "completed" { + let cs = vec![set(format!("triage.end.last.{th}"), &self.now.to_string(), self.now)]; + self.replay(&cs); + Step { cs, outs: vec![] }.cat(op) + } else { + op + } } pub fn run_is(&self, th: &str) -> bool { self.w.private_is(th) || self.run_of(th).filter(|r| self.runs_on(&r.bot)).is_some() } fn run_of_any(&self, th: &str) -> Option { self.run_of(th).filter(|r| !self.w.private_is(&r.thread)) } - /// Private.lost: a lane cut off before it told anyone hands its note to the owner's own agent, once + /// Private.lost: a lane cut off before it told anyone hands its note to the owner's own agent, once; + /// any ended private lane flushes completions that arrived while it ran into a follow-up lane. pub fn private_lost(&mut self, lane: &str, state: &str) -> Step { - if let Some(st) = self.done_lane_end(lane, state) { return st } // Done.lane.end: a done lane's digest is posted, not handed over - if !self.w.private_is(lane) || !(state == "interrupted" || state == "failed") { return Step::none() } - let note = self.setting(¬e_key(lane), ""); let target = self.w.triage_thread(); - if note.is_empty() || !self.setting(&said_key(lane), "").is_empty() || !self.setting(&handed_key(lane), "").is_empty() || target.is_empty() { return Step::none() } - let cs = vec![set(handed_key(lane), &self.now.to_string(), self.now)]; self.replay(&cs); - let text = format!("[Backplane] Your private mailroom lane {lane} was cut off (provider limit, failure or restart) before it finished, so this escalation reached no one. Assess it yourself now: told_check first, tell the person only what is material and new, and keep source approvals pending.\n\n{note}"); - Step { cs, outs: vec![RouteOut::Ride { thread: target, id: format!("lost:{lane}"), text }] } + if !self.w.private_is(lane) || !["completed", "failed", "interrupted"].contains(&state) { return Step::none() } + let bot = self.w.private_owner(lane); + let mut st = if let Some(s) = self.done_lane_end(lane, state) { + s // Done.lane.end: a done lane's digest is handled here, not handed over + } else if state == "interrupted" || state == "failed" { + let note = self.setting(¬e_key(lane), ""); let target = self.w.triage_thread(); + if note.is_empty() || !self.setting(&said_key(lane), "").is_empty() || !self.setting(&handed_key(lane), "").is_empty() || target.is_empty() { + Step::none() + } else { + let cs = vec![set(handed_key(lane), &self.now.to_string(), self.now)]; self.replay(&cs); + let text = format!("[Backplane] Your private mailroom lane {lane} was cut off (provider limit, failure or restart) before it finished, so this escalation reached no one. Assess it yourself now: told_check first, tell the person only what is material and new, and keep source approvals pending.\n\n{note}"); + Step { cs, outs: vec![RouteOut::Ride { thread: target, id: format!("lost:{lane}"), text }] } + } + } else { + Step::none() + }; + if !self.has_live_done_lane(&bot) { + let follow = self.done_flush_now(&bot); + st = st.cat(follow); + } + st } /// Private.tell: the one publication from the back office into the person's conversation, once per owner and key; the owner's own agent is told it was said pub fn private_tell(&mut self, thread: &str, text: &str, key: &str) -> Step { - let bot = self.w.private_owner(thread); let target = self.w.triage_thread(); - if !self.setting(&private_told_key(&bot, key), "").is_empty() { return Step::none() } + let bot = self.w.private_owner(thread); + self.private_tell_as(&bot, thread, text, key) + } + /// Publication into the uberbot's conversation on behalf of `bot` (with optional back-office `lane`). + pub(super) fn private_tell_as(&mut self, bot: &str, lane: &str, text: &str, key: &str) -> Step { + let target = self.w.triage_thread(); + if bot.is_empty() || target.is_empty() || !self.setting(&private_told_key(bot, key), "").is_empty() { return Step::none() } let msg = self.id("tell:"); let now = self.now; // Bot.told: `tell:` always shows in the chat - let mut cs = vec![json!({"$":"MessagePosted","thread":target,"msg":msg,"role":"assistant","text":text,"at":now}), json!({"$":"MessageFrom","thread":target,"msg":msg,"from":format!("thread:{thread}"),"kind":"tell-person","ref":key,"at":now}), - set(private_told_key(&bot, key), &msg, now), set(said_key(thread), &msg, now)]; + let from = if lane.is_empty() { format!("bot:{bot}") } else { format!("thread:{lane}") }; + let mut cs = vec![json!({"$":"MessagePosted","thread":target,"msg":msg,"role":"assistant","text":text,"at":now}), json!({"$":"MessageFrom","thread":target,"msg":msg,"from":from,"kind":"tell-person","ref":key,"at":now}), + set(private_told_key(bot, key), &msg, now)]; + if !lane.is_empty() { cs.push(set(said_key(lane), &msg, now)); } if self.policy_on("needs") || self.policy_on("settled") { cs.push(self.alert_set(&target, "note", &format!("tell-{msg}"), &Self::alert_text(text, 500))) } - cs.extend(self.told_mark(&msg, key, text, "chat", &bot)); + cs.extend(self.told_mark(&msg, key, text, "chat", bot)); self.replay(&cs); let note = format!("[Backplane] Your private mailroom just told the person this in your conversation (key {key}). It is on screen in your conversation, and no phone alert went out: only your notify_person reaches their phone, so call it if they must know now. Do not repeat it otherwise, take it into account. If you have nothing to add, end with an empty reply.\n\n{text}"); Step { cs, outs: vec![RouteOut::Note { thread: target, id: format!("told:{msg}"), text: note }] } diff --git a/native/host/src/bots/mail/gate.rs b/native/host/src/bots/mail/gate.rs index a926aec39d..78ed7510fe 100644 --- a/native/host/src/bots/mail/gate.rs +++ b/native/host/src/bots/mail/gate.rs @@ -157,15 +157,25 @@ impl<'a> Ctx<'a> { let bot = self.w.private_owner(lane); if let Some(why) = refusal(kind, text, proof) { let p = self.report_prefs(&bot); return Err(if p.is_empty() { why } else { format!("{why}\nThe person's rules:{p}") }) } let rkey = proof.as_ref().map(|(r, _)| r.key()).unwrap_or_default(); - if !self.setting(&private_told_key(&bot, &rkey), "").is_empty() || !self.setting(&private_told_key(&bot, key), "").is_empty() { return Ok((Step::none(), 0)) } - if items(&self.setting(&batch_key(&bot), "[]")).iter().any(|i| i["ref"] == rkey.as_str()) { return Ok((Step::none(), 0)) } + let ref_parsed = proof.as_ref().map(|(r, _)| r); + let fallback_recent = if let Some(super::gate::Ref::Thread { id }) = ref_parsed { + let fb_at: u64 = self.setting(&super::done::fallback_at_key(&bot, id), "").parse().unwrap_or(0); + fb_at > 0 && self.now.saturating_sub(fb_at) < super::done::COOLDOWN + } else { false }; + if fallback_recent || !self.setting(&private_told_key(&bot, &rkey), "").is_empty() || !self.setting(&private_told_key(&bot, key), "").is_empty() + || items(&self.setting(&batch_key(&bot), "[]")).iter().any(|i| i["ref"] == rkey.as_str()) { + let clr = self.done_pending_clear(&bot, lane, ref_parsed, text); + if !clr.is_empty() { self.replay(&clr); return Ok((Step { cs: clr, outs: vec![] }, 0)) } + return Ok((Step::none(), 0)) + } let urgent = Kind::parse(kind).is_some_and(Kind::urgent); let now = self.now; let (last, open) = (num(self.setting(&last_key(&bot), "")), num(self.setting(&due_key(&bot), ""))); let due = if urgent { let at = now.max(last + GAP); if open > 0 { open.min(at) } else { at } } else if open > 0 { open } else { (now + BATCH).max(last + BATCH) }; let mut xs = items(&self.setting(&batch_key(&bot), "[]")); xs.push(json!({"key":key,"ref":rkey,"text":text,"lane":lane,"kind":kind,"at":now})); - let cs = vec![set(batch_key(&bot), &jshow(json!(xs)), now), set(due_key(&bot), &due.to_string(), now), + let mut cs = vec![set(batch_key(&bot), &jshow(json!(xs)), now), set(due_key(&bot), &due.to_string(), now), set(private_told_key(&bot, key), &format!("queued:{due}"), now), set(private_told_key(&bot, &rkey), &format!("queued:{due}"), now), set(said_key(lane), &format!("queued:{key}"), now)]; + cs.extend(self.done_pending_clear(&bot, lane, ref_parsed, text)); self.replay(&cs); let st = Step { cs, outs: vec![] }; if due <= now { let f = self.tell_flush(&bot); return Ok((st.cat(f), due)) } diff --git a/native/host/src/bots/mail/owner.rs b/native/host/src/bots/mail/owner.rs index 27f28f25d5..26267841c7 100644 --- a/native/host/src/bots/mail/owner.rs +++ b/native/host/src/bots/mail/owner.rs @@ -107,11 +107,15 @@ impl Bots { async fn owner_current(&self, r: &Value) -> bool { self.setting_or_empty(&pending_key(&key(r))).await == show(r) } fn owner_stamp(&self, w: &World, now: u64) -> String { format!("{now}:{}:{}", self.hub.store.len(), w.lease().1) } - /// Owner.records: at most sixteen pending tickets, by key + /// Owner.records: at most sixteen pending tickets (up to 8 newest + up to 8 oldest so neither starves) pub async fn owner_records(&self) -> Vec { - let m = self.hub.model().await; let seqs: Vec = m.settings_with_prefix("owner.mail.pending.").map(|(_, s)| s).collect(); drop(m); + let m = self.hub.model().await; let mut seqs: Vec = m.settings_with_prefix("owner.mail.pending.").map(|(_, s)| s).collect(); drop(m); + seqs.sort_unstable(); + let mut picked: Vec = Vec::with_capacity(16); + for &s in seqs.iter().rev().take(8) { picked.push(s); } + for &s in seqs.iter().take(8) { if !picked.contains(&s) { picked.push(s); } } let mut out = vec![]; - for s in seqs { if out.len() >= 16 { break } + for s in picked { if out.len() >= 16 { break } let Some(v) = self.hub.store.get(s as usize - 1).ok().and_then(|l| serde_json::from_str::(&l).ok()) else { continue }; let Some(t) = v["value"].as_str().filter(|t| !t.is_empty()) else { continue }; if let Ok(r) = serde_json::from_str::(t) { out.push(r) } diff --git a/native/host/src/bots/mail/route.rs b/native/host/src/bots/mail/route.rs index 5d86848445..eba913ffdd 100644 --- a/native/host/src/bots/mail/route.rs +++ b/native/host/src/bots/mail/route.rs @@ -168,8 +168,6 @@ impl<'a> Ctx<'a> { let on = self.mail_on(); let m = &body.mail; // a header a run is already bound to is routed: the owner's outbox walk routes pending tickets again and again if self.w.mail.runs.values().any(|r| r.mail == m.id) { return Step::none() } - // Triage.thread.end: an unmanaged thread's end is filed for the uberbot to read when it next looks; it starts no run (one per worker turn would be noise and cost) - if m.want == "fyi" && m.id.starts_with("triage-end:") { return Step::none() } match of_addr(&m.to) { Some((k, bot)) if k == "bot" => if on { self.route_bot(body, &bot) } else { let act = self.triage_owner(&bot) && Self::inbound(m, &bot); self.route_bot_want(act, body, &bot) }, Some((k, _)) if k == "room" => self.route_parts(body), diff --git a/native/host/src/bots/mail/run.rs b/native/host/src/bots/mail/run.rs index ab9ed7f786..0b34a950ed 100644 --- a/native/host/src/bots/mail/run.rs +++ b/native/host/src/bots/mail/run.rs @@ -56,12 +56,16 @@ impl Bots { } /// Decide on the world as it is, commit the step, let the world go pub(crate) async fn decide(self: &Arc, report: &[String], f: impl FnOnce(&mut Ctx) -> Step) -> Vec { self.decide_with(report, |c| ((), f(c))).await.1 } + pub(crate) async fn decide_at(self: &Arc, report: &[String], now: u64, f: impl FnOnce(&mut Ctx) -> Step) -> Vec { self.decide_acc_at(report, true, now, |c| ((), f(c))).await.1 } /// the same, for a decision that also answers its caller (a tool) pub(crate) async fn decide_with(self: &Arc, report: &[String], f: impl FnOnce(&mut Ctx) -> (T, Step)) -> (T, Vec) { self.decide_acc(report, true, f).await } /// `accounts`: Accounts.created binds what the step creates; a step's own after-work (Run.after) comes past it in , and a back office it makes has only its explicit binding async fn decide_acc(self: &Arc, report: &[String], accounts: bool, f: impl FnOnce(&mut Ctx) -> (T, Step)) -> (T, Vec) { + self.decide_acc_at(report, accounts, now_s(), f).await + } + async fn decide_acc_at(self: &Arc, report: &[String], accounts: bool, now: u64, f: impl FnOnce(&mut Ctx) -> (T, Step)) -> (T, Vec) { let w = self.world().await; let facts = self.facts(&w, report).await; - let (now, seq) = (now_s(), self.hub.store.len() as u64); + let seq = self.hub.store.len() as u64; let mut ctx = Ctx::new(&w, &facts, now, seq); let (t, st) = f(&mut ctx); let cs = if accounts { self.accounts_created(st.cs).await } else { st.cs }; // Accounts.created: a run's thread starts on the default account if !cs.is_empty() && self.hub.commit_many(&cs).await.is_err() { eprintln!("mail: routing could not be committed"); return (t, vec![]) } @@ -75,9 +79,9 @@ impl Bots { } /// Mail.route for a header just filed pub async fn route_body(self: &Arc, body: Body) { - let outs = self.decide(&[], |c| c.route(&body)).await; self.perform(outs).await; - // Done.timer: a finish that opened the owner's batch flushes it when its window is over - if body.mail.kind == "launch" { let due = { let w = self.world().await; w.setting(&super::done::due_key(&w.uber_bot()), "").parse().unwrap_or(0) }; self.done_timer(due) } + let report: Vec = super::done::triage_end_thread(&body.mail.id).into_iter().collect(); + let outs = self.decide(&report, |c| c.route(&body)).await; self.perform(outs).await; + self.arm_done_timer().await; } /// Run.queue.start for RunNext pub async fn run_next(self: &Arc, bot: String, conv: String) { let outs = self.decide(&[], |c| c.queue_start(&bot, &conv)).await; self.perform(outs).await } @@ -98,7 +102,21 @@ impl Bots { pub async fn after_steps(self: &Arc) { let (steps, on) = { let mut w = self.world().await; (std::mem::take(&mut w.steps), w.setting("mail.on", "off") == "on" || !w.uber_bot().is_empty()) }; if crate::copy::on() || steps.is_empty() { return } - let report: Vec = steps.iter().filter_map(|s| match s { StepEnd::Turn { thread, .. } | StepEnd::Fallback { thread, .. } => Some(thread.clone()), _ => None }).collect(); + let mut report: Vec = steps.iter().filter_map(|s| match s { StepEnd::Turn { thread, .. } | StepEnd::Fallback { thread, .. } => Some(thread.clone()), _ => None }).collect(); + if on && steps.iter().any(|s| matches!(s, StepEnd::Turn { thread, .. } if thread.starts_with("mailcoord-"))) { + let w = self.world().await; + let ub = w.uber_bot(); + if !ub.is_empty() { + if let Ok(serde_json::Value::Array(arr)) = serde_json::from_str::(&w.setting(&super::done::batch_key(&ub), "[]")) { + for i in arr { + if let Some(th) = i["thread"].as_str().filter(|t| !t.is_empty()) { + let s = th.to_string(); + if !report.contains(&s) { report.push(s); } + } + } + } + } + } let ended: Vec = steps.iter().filter_map(|s| match s { StepEnd::Turn { thread, state, .. } if (state == "completed" || state == "failed") && ephemeral(thread) => Some(thread.clone()), _ => None }).collect(); let answers: Vec<(String, String, usize)> = steps.iter().filter_map(|s| match s { StepEnd::RoomReply { thread, room, line } => Some((thread.clone(), room.clone(), *line)), _ => None }).collect(); let (_, outs) = self.decide_acc(&report, false, |c| { @@ -119,6 +137,7 @@ impl Bots { ((), st) }).await; self.perform(outs).await; + self.arm_done_timer().await; // Room.answer: the person asked in a room and the bot answered only in its own chat, where they do not look: its reply is posted in the room as the bot's own room_post let answers = if answers.is_empty() || self.hub.setting("room.answer").await.map_or(false, |v| v == "off") { vec![] } else { answers }; // the setting `room.answer` = off leaves replies where the bot wrote them for (thread, room, line) in answers { diff --git a/native/host/src/bots/rpc.rs b/native/host/src/bots/rpc.rs index 865d9bf636..653183eb7c 100644 --- a/native/host/src/bots/rpc.rs +++ b/native/host/src/bots/rpc.rs @@ -79,7 +79,7 @@ impl Inbox for Arc { }) } } -pub struct Bots { pub hub: Arc, world: Mutex, pub(super) inbox: Arc, pub(crate) router: std::sync::OnceLock>, last_id: std::sync::Mutex<(u64, u64)>, pub(crate) owner_link: std::sync::OnceLock>, pub(crate) owner_busy: std::sync::atomic::AtomicBool, star: std::sync::OnceLock>, threads: std::sync::RwLock>, pub(crate) mail_lists: std::sync::RwLock>>, pub(super) far: super::far::FarState, pub(super) swarm: super::swarm::Give, +pub struct Bots { pub hub: Arc, world: Mutex, pub(super) inbox: Arc, pub(crate) router: std::sync::OnceLock>, last_id: std::sync::Mutex<(u64, u64)>, pub(crate) owner_link: std::sync::OnceLock>, pub(crate) owner_busy: std::sync::atomic::AtomicBool, pub(crate) done_timer_at: std::sync::atomic::AtomicU64, star: std::sync::OnceLock>, threads: std::sync::RwLock>, pub(crate) mail_lists: std::sync::RwLock>>, pub(super) far: super::far::FarState, pub(super) swarm: super::swarm::Give, /// the threads that run with infinite context (recall::on_threads), as last folded, and the memory tree's engine (Bots::start installs it) pub(crate) recall_on: std::sync::RwLock>, pub(crate) recall: std::sync::OnceLock>, #[cfg(test)] pub(crate) quiet: super::mail::run::Quiet } @@ -145,7 +145,7 @@ impl Bots { let store = hub.store.clone(); let w = tokio::task::spawn_blocking(move || { let mut w = crate::ckpt::take("bots", &store, || World::load(&store)).unwrap_or_default(); if let Err(e) = w.sync(&store) { eprintln!("bots: reading the log: {e:#}") } w }).await.unwrap_or_default(); let mut w = w; w.steps.clear(); // what the start folded was answered when it happened - let b = Arc::new(Bots { hub: hub.clone(), world: Mutex::new(w), inbox, router: Default::default(), last_id: Default::default(), owner_link: Default::default(), owner_busy: Default::default(), star: Default::default(), threads: Default::default(), mail_lists: Default::default(), far: Default::default(), swarm: Default::default(), recall_on: Default::default(), recall: Default::default(), #[cfg(test)] quiet: Default::default() }); + let b = Arc::new(Bots { hub: hub.clone(), world: Mutex::new(w), inbox, router: Default::default(), last_id: Default::default(), owner_link: Default::default(), owner_busy: Default::default(), done_timer_at: Default::default(), star: Default::default(), threads: Default::default(), mail_lists: Default::default(), far: Default::default(), swarm: Default::default(), recall_on: Default::default(), recall: Default::default(), #[cfg(test)] quiet: Default::default() }); { let g = b.world.lock().await; b.refresh_threads(&g); } { let me = b.clone(); crate::ckpt::register(move |store| me.world.blocking_lock().save(store)); } { let me = b.clone(); tokio::spawn(async move { loop { tokio::time::sleep(std::time::Duration::from_secs(20)).await; me.owner_outbox().await } }); } // OwnerJob: the outbox is walked again diff --git a/native/host/src/bots/tests/triage.rs b/native/host/src/bots/tests/triage.rs index 3da783b4c4..2a2d44757f 100644 --- a/native/host/src/bots/tests/triage.rs +++ b/native/host/src/bots/tests/triage.rs @@ -777,3 +777,200 @@ const QUIET: [&str; 10] = ["Nothing landed, and your build is unchanged. PR #136 assert_eq!(shown.len(), 1, "flushed into one message: {shown:?}"); assert!(shown[0].starts_with(&format!("- {ask_msg}")) && shown[0].contains(fw_msg) && shown[0].contains(cad_msg), "{}", shown[0]); } + +#[tokio::test] async fn a_completion_arriving_while_a_mailcoord_turn_is_running_spawns_a_followup_turn_and_tells() { + let (hub, bots, rec, bub, chat) = uber("followup").await; + hub.commit_many(&[ + json!({"$":"ThreadCreated","id":"t-first","project":"","title":"First task","env":"local","branch":"","worktree":"","provider":"claude","model":"","at":1}), + json!({"$":"ThreadCreated","id":"t-second","project":"","title":"Case 3D design","env":"local","branch":"","worktree":"","provider":"claude","model":"","at":2}), + json!({"$":"ThreadCreated","id":"t-ask","project":"","title":"Ask worker","env":"local","branch":"","worktree":"","provider":"claude","model":"","at":3}), + ]).await.unwrap(); + turn_said(&hub, "t-first", "completed", "First deliverable finished.").await; + until(&hub, |l| l.iter().any(|e| e["$"] == "MailPosted" && e["id"].as_str().unwrap_or("").starts_with("triage-end:t-first:"))).await; + settle(&bots).await; + due_now(&hub, &bots, &bub).await; + let ls = lanes(&hub, &bub); + assert_eq!(ls.len(), 1, "first completion opens lane1: {ls:?}"); + let lane1 = ls[0].clone(); + running(&hub, &lane1).await; + settle(&bots).await; + + // While lane1 is running, t-second completes and t-ask opens an actionable ask. + turn_said(&hub, "t-second", "completed", "Exported case_top.step and case_base.step.").await; + hub.commit(&json!({"$":"AskOpened","id":"q-mid","thread":"t-ask","kind":"approval","tool":"Bash","detail":"confirm step","options":"","at":now_s()})).await.unwrap(); + until(&hub, |l| l.iter().any(|e| e["$"] == "MailPosted" && e["id"].as_str().unwrap_or("").starts_with("triage-end:t-second:"))).await; + settle(&bots).await; + assert!(runs(&hub).iter().any(|r| r["mail"] == "triage-ask:q-mid"), "act ask starts a triage run even while mailcoord is running"); + + // Even if done_tick runs past WINDOW while lane1 is still active, done_due waits for lane1 to end. + bots.done_tick_at(now_s() + crate::bots::mail::done::WINDOW + 1).await; + settle(&bots).await; + assert_eq!(lanes(&hub, &bub).len(), 1, "t-second waits in done.batch until lane1 finishes"); + + // lane1 tells t-first cleanly, then ends -> follow-up lane2 starts immediately for t-second. + let key1 = lane_tell_key(&rec, &lane1); + let msg1 = "First task deliverable finished cleanly."; + assert!(bots.mail_tool(&lane1, "tell_person", &json!({"text":msg1,"key":key1,"kind":"completed","ref":"thread:t-first"})).await.0); + end(&hub, &lane1, "completed").await; + until(&hub, |l| l.iter().filter(|e| e["$"] == "RunSet" && e["thread"].as_str().unwrap_or("").starts_with(&format!("mailcoord-{bub}-"))).count() >= 2).await; + settle(&bots).await; + let ls2 = lanes(&hub, &bub); + assert_eq!(ls2.len(), 2, "follow-up lane started when lane1 ended: {ls2:?}"); + let lane2 = ls2[1].clone(); + let ride2 = rec.rides.lock().unwrap().iter().find(|r| r.0 == lane2).cloned().unwrap(); + assert!(ride2.2.contains("Case 3D design") && ride2.2.contains("Exported case_top.step"), "{}", ride2.2); + + running(&hub, &lane2).await; + settle(&bots).await; + let key2 = lane_tell_key(&rec, &lane2); + let msg2 = "Case 3D design finished (case_top.step and case_base.step exported)."; + let res = bots.mail_tool(&lane2, "tell_person", &json!({"text":msg2,"key":key2,"kind":"completed","ref":"thread:t-second"})).await; + assert!(res.0, "{res:?}"); + end(&hub, &lane2, "completed").await; + settle(&bots).await; + tell_now(&hub, &bots, &bub).await; + let shown = shown_lines(&hub, &chat); + assert_eq!(shown.len(), 1, "{shown:?}"); + assert!(shown[0].contains(msg1) && shown[0].contains(msg2), "{shown:?}"); + + // Advancing past FALLBACK_AFTER must not emit any duplicate fallback tell. + bots.done_tick_at(now_s() + crate::bots::mail::done::FALLBACK_AFTER + 60).await; + settle(&bots).await; + assert_eq!(shown_lines(&hub, &chat).len(), 1, "no duplicate fallback after tell_person"); +} + +#[tokio::test] async fn an_unmanaged_completion_with_no_other_traffic_wakes_within_window_and_falls_back_if_untold() { + let (hub, bots, rec, bub, chat) = uber("unmanaged-fallback").await; + hub.commit(&json!({"$":"ThreadCreated","id":"t-case","project":"","title":"3D printable case","env":"local","branch":"","worktree":"","provider":"claude","model":"","at":1})).await.unwrap(); + let t0 = now_s(); + turn_said(&hub, "t-case", "completed", "Case shells exported to case.step.\nZero interference on fit check.").await; + until(&hub, |l| l.iter().any(|e| e["$"] == "MailPosted" && e["id"].as_str().unwrap_or("").starts_with("triage-end:t-case:"))).await; + settle(&bots).await; + + assert!(bots.owner_records().await.is_empty(), "triage-end ticket must be claimed on admission"); + assert!(setting_of(&hub, &crate::bots::mail::done::batch_key(&bub)).contains("t-case")); + assert!(setting_of(&hub, &crate::bots::mail::done::pending_key(&bub)).contains("t-case")); + + // Within WINDOW (no other traffic), done_tick_at spawns a mailcoord lane and gives it a full FALLBACK_AFTER window. + let t_win = t0 + crate::bots::mail::done::WINDOW + 1; + bots.done_tick_at(t_win).await; + settle(&bots).await; + let ls = lanes(&hub, &bub); + assert_eq!(ls.len(), 1, "mailcoord lane spawned after WINDOW: {ls:?}"); + let lane = ls[0].clone(); + let ride = rec.rides.lock().unwrap().iter().find(|r| r.0 == lane).cloned().unwrap(); + assert!(ride.2.contains("3D printable case") && ride.2.contains("Case shells exported to case.step."), "{}", ride.2); + + // While lane is still running inside its bumped FALLBACK_AFTER grace, done_tick_at does NOT race with a fallback tell. + running(&hub, &lane).await; + settle(&bots).await; + bots.done_tick_at(t0 + crate::bots::mail::done::FALLBACK_AFTER + 1).await; + settle(&bots).await; + assert!(shown_lines(&hub, &chat).is_empty(), "running lane keeps its full grace before fallback"); + + // If that mailcoord lane fails without calling tell_person, its deadline restores to t0 + FALLBACK_AFTER and fires on the next tick. + end(&hub, &lane, "failed").await; + settle(&bots).await; + let t_fb = t0 + crate::bots::mail::done::FALLBACK_AFTER + 2; + bots.done_tick_at(t_fb).await; + settle(&bots).await; + let shown = shown_lines(&hub, &chat); + assert_eq!(shown.len(), 1, "fallback tell must reach chat: {shown:?}"); + assert!(shown[0].contains("3D printable case"), "{}", shown[0]); + assert!(shown[0].contains("Case shells exported to case.step."), "{}", shown[0]); + assert!(shown[0].contains("Zero interference on fit check."), "{}", shown[0]); + assert!(shown[0].contains("backplane://thread/t-case"), "{}", shown[0]); + + // Subsequent ticks must not repeat the fallback tell. + bots.done_tick_at(t_fb + 120).await; + settle(&bots).await; + assert_eq!(shown_lines(&hub, &chat).len(), 1); + + // A launched recurring-lead lane that completes cleanly without telling deliberately chose silence (no Nov 20 digest spam). + report(&bots, &chat, "t-lead", "launch", &crate::agents::launch::note("t-lead", "Lead: Repo", "completed", "Round 3 status from lanes.")).await; + settle(&bots).await; + bots.done_tick_at(t_fb + 200).await; + settle(&bots).await; + let ls2 = lanes(&hub, &bub); + assert_eq!(ls2.len(), 2); + running(&hub, &ls2[1]).await; + end(&hub, &ls2[1], "completed").await; + settle(&bots).await; + bots.done_tick_at(t_fb + 500).await; + settle(&bots).await; + assert_eq!(shown_lines(&hub, &chat).len(), 1, "silent completed launch lane must not trigger fallback"); +} + +#[tokio::test] async fn duplicate_completions_for_the_same_thread_are_deduplicated_and_told_once() { + let (hub, bots, rec, bub, chat) = uber("dedup-storm").await; + hub.commit(&json!({"$":"ThreadCreated","id":"t-storm","project":"","title":"Quick chat","env":"local","branch":"","worktree":"","provider":"claude","model":"","at":1})).await.unwrap(); + hub.commit(&json!({"$":"ThreadCreated","id":"t-lead-dup","project":"","title":"Lead","env":"local","branch":"","worktree":"","provider":"claude","model":"","at":1})).await.unwrap(); + + // 6 rapid completions of the same thread produce only 1 triage-end MailPosted. + for i in 0..6 { + turn_said(&hub, "t-storm", "completed", &format!("Answer {i}")).await; + settle(&bots).await; + } + let te_count = log(&hub).iter().filter(|e| e["$"] == "MailPosted" && e["id"].as_str().unwrap_or("").starts_with("triage-end:t-storm:")).count(); + assert_eq!(te_count, 1, "rapid turns on same thread must emit at most 1 triage-end"); + + // Duplicate triage-end mails filed directly update the open batch entry with the newer reply (not duplicated). + { + let w = bots.world().await; + let o = crate::bots::mail::Origin::new("thread:t-storm", "thread", ""); + let base = now_s(); + for i in 1..=3u64 { + let msg = format!("triage-end:t-storm:{}", base + i); + bots.file_operational(&w, base + i, &o, &format!("bot:{bub}"), &format!("Thread completed: Quick chat (backplane://thread/t-storm)\nLatest reply {i}"), &msg, "fyi", vec![]).await.unwrap(); + } + // An imported owner:[uid,origin,"triage-end:..."] mail is also recognized by done_admit (no triage run). + let imp = format!("owner:[\"u1\",\"m2\",\"triage-end:t-remote:{}\"]", base + 4); + let o_imp = crate::bots::mail::Origin::new("thread:L~t-remote", "thread", ""); + bots.file_operational(&w, base + 4, &o_imp, &format!("bot:{bub}"), "Thread completed: Remote deliverable (backplane://thread/L~t-remote)\nRemote output ready.", &imp, "fyi", vec![]).await.unwrap(); + // Stale historical triage-end (> 2 hours old) is claimed and dropped without entering batch/pending. + let o_old = crate::bots::mail::Origin::new("thread:t-old", "thread", ""); + bots.file_operational(&w, 1_700_000_100, &o_old, &format!("bot:{bub}"), "Thread completed: Old thread (backplane://thread/t-old)", "triage-end:t-old:1700000100", "fyi", vec![]).await.unwrap(); + } + settle(&bots).await; + assert!(bots.owner_records().await.is_empty(), "all duplicate, imported, and stale tickets must be claimed"); + assert!(runs(&hub).is_empty(), "imported triage-end must join done.batch, never start a triage run"); + let batch: Vec = serde_json::from_str(&setting_of(&hub, &crate::bots::mail::done::batch_key(&bub))).unwrap_or_default(); + assert_eq!(batch.len(), 2, "one entry for t-storm and one for L~t-remote, none for stale t-old: {batch:?}"); + let storm_item = batch.iter().find(|i| i["thread"] == "t-storm").unwrap(); + assert_eq!(storm_item["summary"], "Latest reply 3", "open batch keeps the newest reply"); + + let t_win = now_s() + crate::bots::mail::done::WINDOW + 1; + bots.done_tick_at(t_win).await; + settle(&bots).await; + assert_eq!(lanes(&hub, &bub).len(), 1, "exactly one mailcoord lane"); + let lane = lanes(&hub, &bub)[0].clone(); + running(&hub, &lane).await; + end(&hub, &lane, "failed").await; + settle(&bots).await; + + bots.done_tick_at(now_s() + crate::bots::mail::done::FALLBACK_AFTER + 2).await; + settle(&bots).await; + let shown = shown_lines(&hub, &chat); + assert_eq!(shown.len(), 2, "one tell for t-storm and one for L~t-remote: {shown:?}"); + assert!(shown.iter().any(|s| s.contains("t-storm")) && shown.iter().any(|s| s.contains("L~t-remote")), "{shown:?}"); + + // Verify a recurring launch thread is NOT permanently muted after an earlier completion. + report(&bots, &chat, "t-lead-dup", "launch", &crate::agents::launch::note("t-lead-dup", "Lead", "completed", "Landed aaa1111 on main.")).await; + settle(&bots).await; + bots.done_tick_at(now_s() + crate::bots::mail::done::FALLBACK_AFTER + 10).await; + settle(&bots).await; + let ls2 = lanes(&hub, &bub); + assert_eq!(ls2.len(), 2); + let k2 = lane_tell_key(&rec, &ls2[1]); + running(&hub, &ls2[1]).await; + verified("commit:BackplaneWorks/Backplane@aaa1111"); + assert!(bots.mail_tool(&ls2[1], "tell_person", &json!({"text":"Landed aaa1111 on main.","key":k2,"kind":"landed","ref":"commit:BackplaneWorks/Backplane@aaa1111"})).await.0); + end(&hub, &ls2[1], "completed").await; + settle(&bots).await; + // A second turn on the same launch thread later still opens a new lane (not permanently deduped). + report(&bots, &chat, "t-lead-dup", "launch", &crate::agents::launch::note("t-lead-dup", "Lead", "completed", "Landed bbb2222 on main.")).await; + settle(&bots).await; + bots.done_tick_at(now_s() + crate::bots::mail::done::FALLBACK_AFTER + 200).await; + settle(&bots).await; + assert_eq!(lanes(&hub, &bub).len(), 3, "recurring launch thread is not muted for future PR landings"); +}