Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Let a lead's follow-up hand corrections back to teammates who just reported
Lin (kwant bot)6adaa8861215
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rsindex e66236cd..2066691d 100644--- a/src/drivers/mod.rs+++ b/src/drivers/mod.rs@@ -385,7 +385,9 @@ impl TurnInput {and they answer here in the same chat. Only use @ when you actually want that teammate to reply now; \to merely refer to a teammate, write their name without the @. \Never contact anyone else: no other agents, sessions, chats or people through tools, CLIs or APIs. \- Never claim you asked or will relay something from a teammate unless you @mentioned them in this reply.",+ Never claim you asked, handed off to or will relay something from a teammate unless you @mentioned them in this reply, \+ and give a teammate you hand work to the concrete task in the same sentence. kwnt limits how often one message may hand \+ work on; a mention past a limit isn't sent and a \"Not sent to …\" notice in the chat says so: then don't say it was.",list = list,first = self.teammates[0].name,)diff --git a/src/router/mod.rs b/src/router/mod.rsindex afcccad2..b9f2ecb3 100644--- a/src/router/mod.rs+++ b/src/router/mod.rs@@ -6,7 +6,7 @@ pub mod team;pub use fallback::heuristic_fallback;pub use laya::LayaRouter;-pub use tags::{handoff_mentions, handoff_targets, HandoffMentions, parse_mentions, parse_mentions_with_lookup, TagMention};+pub use tags::{handoff_mentions, handoff_targets, only_credited, HandoffMentions, parse_mentions, parse_mentions_with_lookup, TagMention};pub use team::{heuristic_pick_kwant, heuristic_team_decision, matched_terms, parse_laya_kwant_choice,parse_laya_team_answers, ChannelRoute, TeamDecision,diff --git a/src/router/tags.rs b/src/router/tags.rsindex 19f2b3b5..2603b2e0 100644--- a/src/router/tags.rs+++ b/src/router/tags.rs@@ -193,6 +193,45 @@ pub fn handoff_mentions(text: &str, names: &[&str]) -> HandoffMentions {out}+/// Words right before an @mention that make it a credit ("as @Writer found", "thanks to @SEO").+const CREDIT_BEFORE: [&str; 8] = ["as", "per", "by", "from", "via", "thanks", "credit", "kudos"];+/// Past-tense words right after an @mention that report what the teammate did ("@SEO found …").+const CREDIT_AFTER: [&str; 14] = [+ "said", "noted", "found", "reported", "suggested", "wrote", "mentioned", "confirmed", "flagged", "pointed", "drafted",+ "shared", "delivered", "showed",+];++/// Whether every @mention of `name` in `text` only credits the teammate for what it did ("As @SEO+/// found, …", "thanks to @Writer", "@Social suggested …"), so the mention asks nothing new. A+/// mention without such words counts as an ask: this is deliberately narrow, and the per-teammate+/// limit stops repeats it misses. `false` when `name` isn't mentioned at all.+pub fn only_credited(text: &str, name: &str) -> bool {+ let lower = text.to_lowercase();+ let tag = format!("@{}", name.to_lowercase());+ let word = |s: &str| s.trim_matches(|c: char| !c.is_alphanumeric()).to_string();+ let mut seen = false;+ let mut from = 0;+ while let Some(at) = lower[from..].find(&tag).map(|i| i + from) {+ let end = at + tag.len();+ from = end;+ // `@Growthteam` isn't `@Growth`+ if lower[end..].chars().next().is_some_and(|c| c.is_alphanumeric() || c == '_') {+ continue;+ }+ seen = true;+ let before: Vec<String> = lower[..at].split_whitespace().rev().take(2).map(word).collect();+ let after = lower[end..].split_whitespace().next().map(word).unwrap_or_default();+ let credit = before.first().is_some_and(|w| CREDIT_BEFORE.contains(&w.as_str()))+ || (before.first().is_some_and(|w| w == "to")+ && before.get(1).is_some_and(|w| ["thanks", "according", "credit", "kudos"].contains(&w.as_str())))+ || CREDIT_AFTER.contains(&after.as_str());+ if !credit {+ return false;+ }+ }+ seen+}+#[cfg(test)]mod tests {use super::*;@@ -306,5 +345,22 @@ mod tests {assert!(mentions[0].is_team());assert!(mentions[1].is_kwant());}-}+ /// Oleks's screenshot (2026-10-24): "Handing off now: @Social revise …, @Writer draft Pillar 1 …"+ /// asks; "As @SEO found, …" only credits.+ #[test]+ fn credit_only_mentions_ask_nothing_new() {+ let handoff = "Handing off now: @Social revise the hooks, @Writer draft Pillar 1, @SEO write the brief.";+ for n in ["Social", "Writer", "SEO"] {+ assert!(!only_credited(handoff, n), "{n} is asked");+ }+ assert!(only_credited("As @SEO found, the keyword is taken. Thanks to @Writer the draft is done.", "SEO"));+ assert!(only_credited("As @SEO found, the keyword is taken. Thanks to @Writer the draft is done.", "Writer"));+ assert!(only_credited("@Social suggested three hooks; I picked the second.", "social"));+ // One real ask among credits is an ask+ assert!(!only_credited("As @SEO found, the keyword is taken. @SEO, pick another one.", "SEO"));+ assert!(!only_credited("@Writer, thanks! Now tighten Pillar 2.", "Writer"));+ assert!(!only_credited("no mention here", "Writer"));+ assert!(!only_credited("@Writers found it", "Writer"), "another name");+ }+}diff --git a/src/server/delegation.rs b/src/server/delegation.rsindex 591d9569..b5d7446b 100644--- a/src/server/delegation.rs+++ b/src/server/delegation.rs@@ -573,9 +573,17 @@ pub async fn resume_after_answer(state: &AppState, d: Delegation, question_id: &true}+/// Batches whose lead was already resumed, by their sorted ids (see [`finished_batch`]).+static RESUMED_BATCHES: std::sync::OnceLock<std::sync::Mutex<std::collections::HashSet<String>>> = std::sync::OnceLock::new();+/// The delegations a lead sent from one chat that ran at the same time as `d`, once all of them-/// have ended. `None` while one is still open, or when another one of them ended later: the last-/// to end resumes the lead, once, with every result.+/// have ended. `None` while one is still open, or when the batch was already claimed: the first+/// finisher to see every one of them ended resumes the lead, once, with every result.+///+/// Not "the one with the latest `ended_at`": that time is taken before the row is written, so+/// under write contention the latest one could check while a sibling was still open, the+/// sibling then saw it wasn't the latest, and nobody resumed the lead (1 run in 5 of a 4-bot+/// team on 2026-10-24: every teammate replied and the lead never answered).async fn finished_batch(state: &AppState, d: &Delegation) -> Option<Vec<Delegation>> {let siblings: Vec<Delegation> = state.db@@ -607,12 +615,21 @@ async fn finished_batch(state: &AppState, d: &Delegation) -> Option<Vec<Delegatibatch.push(s);}}- let last = batch.iter().max_by(|a, b| end(a).cmp(&end(b)).then_with(|| a.id.cmp(&b.id)))?;// A batch the person stopped entirely stays stopped; anything else (a result, a failure, a// restart cutting it short) is the lead's to report- if last.id != d.id || batch.iter().all(|b| b.status == "cancelled") {+ if batch.iter().all(|b| b.status == "cancelled") {+ return None;+ }+ let mut ids: Vec<&str> = batch.iter().map(|b| b.id.as_str()).collect();+ ids.sort_unstable();+ let mut claimed = RESUMED_BATCHES.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner());+ if claimed.len() > 10_000 {+ claimed.clear();+ }+ if !claimed.insert(ids.join(",")) {return None;}+ drop(claimed);batch.sort_by_key(|b| b.created_at);Some(batch)}@@ -680,12 +697,15 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation], o};let prompt = format!("{opening} The results are in the chat above, quoted here:\n\n{results}\- Check each result against what the user asked. If something is missing or wrong, delegate a concrete \- correction. Otherwise continue with the user's request and give them one answer that uses the results. \- If a task failed, was stopped or was cut short, say so plainly. Don't repeat the results in full."+ Check each result against what the user asked. If something is missing or wrong, hand that teammate a concrete \+ correction by @mention (below). Otherwise continue with the user's request and give them one answer \+ that uses the results. If a task failed, was stopped or was cut short, say so plainly. Don't repeat the results in full.\n\n\+ {rules}",+ rules = handoff_rules(),);- // The follow-up may hand on to the next teammate by @mention, like any lead reply. Not back to- // the ones that just reported (the result is what it's about), and within the usual limits.+ // The follow-up may hand on by @mention, like any lead reply: to the next teammate, or back to+ // one that just reported with a correction (not a mention that only credits it), within the+ // usual limits.if let Ok(reply) = try_kwant_turn(&scope, &lead, prompt, TurnOpts::default()).await {let mut spoken = vec![lead.id.clone()];spoken.extend(batch.iter().map(|b| b.specialist_kwant_id.clone()));@@ -703,6 +723,21 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation], o}}+/// How a lead hands work on from its results follow-up, so it never announces a handoff that+/// doesn't happen (Oleks's screenshot, 2026-10-24: "Handing off now: @Social …" and nothing ran).+pub fn handoff_rules() -> String {+ format!(+ "How handing on works: to give a teammate a correction or the next step, @mention them in this reply with the \+ concrete task (\"@Writer, draft Pillar 1: …\"); kwnt sends it to them and resumes you with their result. That works for \+ a teammate who just reported, too. Only say you're handing off, asking or waiting for someone when you @mention them \+ with a task in this reply; to merely refer to a teammate, write the name without @. Limits for this user message: each \+ teammate gets at most {per_bot} tasks by mention and all teammates at most {total} in total. Past that the mention is \+ not sent and a \"Not sent to …\" notice says so; then tell the person what's left instead of claiming a handoff.",+ per_bot = super::routes::MAX_MENTION_DELEGATIONS_PER_BOT,+ total = super::routes::MAX_DELEGATIONS_PER_REQUEST,+ )+}+/// What the lead should do about a task that ended without a result.fn status_guidance(status: &str) -> Option<&'static str> {match status {diff --git a/src/server/routes.rs b/src/server/routes.rsindex 91eded23..fa0860dc 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -993,11 +993,18 @@ async fn run_handoffs(scope: &TurnScope, already_spoken: &[String], replies: &[(}const IN_CODE_BLOCK: &str = "the mention was inside code. Write the name as plain text to ask them";--/// Says in the chat, and logs, each @mention that handed nothing on: "Growth wasn't asked: <why>".-/// An empty reason means no teammate has that name; it's worked out here.+/// A follow-up that only credited a teammate who just reported ("As @SEO found, …").+const CREDIT_ONLY: &str = "the mention only credited their result. To hand them more work, @mention them with the task";++/// Says in the chat, and logs, the @mentions of one reply that handed nothing on, as ONE line+/// under it: "Not sent to Social, Writer: <why>", or "Not sent to Social: <why>; Writer: <why>"+/// when the reasons differ. The note is in the chat's history, so the speaker reads it on its next+/// turn. Reasons don't repeat the name. An empty reason means no teammate has that name; it's+/// worked out here.async fn report_skipped(scope: &TurnScope, skipped: Vec<(String, String)>) {let mut said: Vec<String> = Vec::new();+ // (reason, names), in order of first mention+ let mut groups: Vec<(String, Vec<String>)> = Vec::new();for (name, why) in skipped {if said.iter().any(|n| n.eq_ignore_ascii_case(&name)) {continue;@@ -1005,14 +1012,25 @@ async fn report_skipped(scope: &TurnScope, skipped: Vec<(String, String)>) {said.push(name.clone());let why = if why.is_empty() { unknown_mention(scope, &name).await } else { why };tracing::info!(context = ?scope.channel_id.as_ref().or(scope.thread_id.as_ref()), mention = %name, "mention handed nothing on: {why}");- let note = scope.message("system", "kwnt", format!("{name} wasn't asked: {why}"));- if let Some(saved) = scope.save(¬e, Some(serde_json::json!({"kind": "handoff_refused", "mention": name}))).await {- let _ = scope- .state- .event_sender- .send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or_default() });+ match groups.iter_mut().find(|(w, _)| *w == why) {+ Some((_, names)) => names.push(name),+ None => groups.push((why, vec![name])),}}+ let Some(text) = refusal_line(&groups) else { return };+ let meta = serde_json::json!({"kind": "handoff_refused", "mention": said[0], "mentions": said});+ if let Some(saved) = scope.save(&scope.message("system", "kwnt", text), Some(meta)).await {+ let _ = scope+ .state+ .event_sender+ .send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or_default() });+ }+}++/// "Not sent to A, B: why" for refused mentions grouped by reason; `None` when there are none.+pub fn refusal_line(groups: &[(String, Vec<String>)]) -> Option<String> {+ let parts: Vec<String> = groups.iter().map(|(why, names)| format!("{}: {why}", names.join(", "))).collect();+ (!parts.is_empty()).then(|| format!("Not sent to {}", parts.join("; ")))}/// Why `@name` matched no one in this chat.@@ -1023,9 +1041,9 @@ async fn unknown_mention(scope: &TurnScope, name: &str) -> String {None => false,};if in_space {- format!("{name} isn't in this chat")+ "not in this chat".to_string()} else {- format!("there's no teammate called {name} here")+ "no teammate has that name here".to_string()}}@@ -1043,10 +1061,11 @@ async fn is_team_channel_lead(scope: &TurnScope, kwant: &Kwant) -> bool {/// A team lead's @mentions in its team channel hand work on as delegations, not handoff turns:/// each teammate gets the task in its own thread (Sent-to chip, queue, the same guards as the/// delegate tool), and when the last one ends the lead is resumed once with every result to give-/// the user one answer; that follow-up may hand on again. `just_reported` teammates (whose results-/// the follow-up is about) aren't sent it again by a mention, and one user message starts at most+/// the user one answer; that follow-up may hand on again, also to `just_reported` teammates (whose+/// results it is about): a mention there is a correction or the next step, unless it only credits+/// them ([`crate::router::only_credited`]). One user message starts at most/// [`MAX_DELEGATIONS_PER_REQUEST`], at most [`MAX_MENTION_DELEGATIONS_PER_BOT`] to any one-/// teammate. Every mention that hands nothing on is said in the channel.+/// teammate, which is what ends a loop. Every mention that hands nothing on is said in the channel./// Teammates the lead already delegated to from this channel (with the tool) aren't sent it twice.async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_prompt: &str, just_reported: &[String]) {let Some(cid) = scope.channel_id.clone() else { return };@@ -1080,14 +1099,14 @@ async fn delegate_mentions(scope: &TurnScope, lead: &Kwant, text: &str, user_proif k.id == lead.id || targets.iter().any(|t| t.id == k.id) {continue;}- if just_reported.contains(&k.id) {- skipped.push((k.name.clone(), format!("{} just reported back on this. For a correction, delegate a concrete task", k.name)));+ if just_reported.contains(&k.id) && crate::router::only_credited(text, &k.name) {+ skipped.push((k.name.clone(), CREDIT_ONLY.to_string()));} else if open.contains(&k.id.as_str()) {- skipped.push((k.name.clone(), format!("{} is still working on an earlier task from this chat", k.name)));+ skipped.push((k.name.clone(), "still working on an earlier task from this chat".to_string()));} else if asked(&k.id) >= MAX_MENTION_DELEGATIONS_PER_BOT {skipped.push((k.name.clone(),- format!("{} was already asked {MAX_MENTION_DELEGATIONS_PER_BOT} times for this request. Send a new message to go on", k.name),+ format!("already asked {MAX_MENTION_DELEGATIONS_PER_BOT} times for this request. Send a new message to go on"),));} else {targets.push(k);diff --git a/tests/delegation_test.rs b/tests/delegation_test.rsindex 84de84fb..b092ed19 100644--- a/tests/delegation_test.rs+++ b/tests/delegation_test.rs@@ -23,9 +23,10 @@ use std::time::Duration;use tower::ServiceExt;/// Replies "answer <tag>" for a prompt with "REPLYTAG:<tag>", followed by "@<name>" for one with-/// "MENTION:<name>", and by "`@<name>`" (inline code, as models write it) for a lead's results-/// follow-up with "FOLLOWUP:<name>"; a "LONGTASK:<file>" prompt waits (up to 60 s) for that file first, and a-/// "FAILTASK" prompt fails. Every prompt is saved under `$KWNT_TEST_PROMPTS`.+/// "MENTION:<name>", and by "`@<name>` please revise your part." (inline code, as models write it)+/// for a lead's results follow-up with "FOLLOWUP:<name>"; several names go as "<a>+<b>". A+/// follow-up with "CREDIT:<name>" adds "As @<name> found, it's done." (a mention that asks nothing);+/// a "LONGTASK:<file>" prompt waits (up to 60 s) for that file first, and a "FAILTASK" prompt fails. Every prompt is saved under `$KWNT_TEST_PROMPTS`.const FAKE_CLAUDE: &str = r#"#!/bin/shcase "$1" inauth) echo '{"loggedIn":true}'; exit 0 ;;@@ -39,10 +40,15 @@ if [ -n "$release" ]; thenwhile [ ! -f "$release" ] && [ $i -lt 600 ]; do sleep 0.1; i=$((i+1)); donefitag=$(printf '%s\n' "$last" | sed -n 's/.*REPLYTAG:\([A-Za-z0-9_]*\).*/\1/p' | tail -n 1)-mention=$(printf '%s\n' "$last" | sed -n 's/.*MENTION:\([A-Za-z0-9_]*\).*/\1/p' | head -n 1)-followup=$(printf '%s\n' "$last" | sed -n 's/.*FOLLOWUP:\([A-Za-z0-9_]*\).*/\1/p' | head -n 1)-case "$last" in *"finished the task you delegated"*) ;; *) followup="" ;; esac-echo "{\"type\":\"result\",\"is_error\":false,\"num_turns\":1,\"result\":\"answer ${tag:-none}${mention:+ @$mention}${followup:+ \`@$followup\`}\"}"+mention=$(printf '%s\n' "$last" | sed -n 's/.*MENTION:\([A-Za-z0-9_+]*\).*/\1/p' | head -n 1)+followup=$(printf '%s\n' "$last" | sed -n 's/.*FOLLOWUP:\([A-Za-z0-9_+]*\).*/\1/p' | head -n 1)+credit=$(printf '%s\n' "$last" | sed -n 's/.*CREDIT:\([A-Za-z0-9_]*\).*/\1/p' | head -n 1)+case "$last" in *"finished the task you delegated"*|*"tasks you delegated have ended"*) ;; *) followup=""; credit="" ;; esac+out="answer ${tag:-none}"+for n in $(printf '%s' "$mention" | tr '+' ' '); do out="$out @$n"; done+for n in $(printf '%s' "$followup" | tr '+' ' '); do out="$out \`@$n\` please revise your part."; done+[ -n "$credit" ] && out="$out As @$credit found, it's done."+echo "{\"type\":\"result\",\"is_error\":false,\"num_turns\":1,\"result\":\"$out\"}""#;fn prompts_dir() -> &'static PathBuf {@@ -1013,8 +1019,8 @@ fn refusals(msgs: &[kwnt::db::models::Message]) -> Vec<String> {/// Bug 3 (team-Startup, 2026-10-21): the lead's follow-up after results came back said "`@Growth`,/// please draft the launch plan" and Growth never ran. The follow-up now hands on like any lead-/// reply, a name in inline code counts, and mentioning the teammate who just reported back hands-/// nothing on but says so.+/// reply and a name in inline code counts. Mentioning the teammate who just reported back with a+/// task hands it a second round (2026-10-24); the third is refused in one line.#[tokio::test]async fn a_leads_follow_up_after_results_hands_on_to_the_next_teammate() {let env = setup().await;@@ -1033,14 +1039,14 @@ async fn a_leads_follow_up_after_results_hands_on_to_the_next_teammate() {assert!(d.task.contains("`@Growth`"), "Growth gets the lead's words: {}", d.task);wait_for("Growth's result", || async { delegation_status(&env, &d.id).await == "completed" }).await;- // Growth's own follow-up names Growth again (its title carries the marker): not sent back- wait_for("the just-reported notice", || async { !refusals(&channel_messages(&env, &channel).await).is_empty() }).await;+ // Growth's own follow-up names Growth again with a task: a second round, then the limit+ wait_for("the limit notice", || async { !refusals(&channel_messages(&env, &channel).await).is_empty() }).await;tokio::time::sleep(Duration::from_millis(1500)).await;let notes = refusals(&channel_messages(&env, &channel).await);- assert_eq!(notes.len(), 1, "{notes:?}");- assert!(notes[0].starts_with("Growth wasn't asked: Growth just reported back"), "{}", notes[0]);+ assert_eq!(notes, vec![format!("Not sent to Growth: already asked {} times for this request. Send a new message to go on", per_bot_limit())]);let all = env.state.db.list_delegations(Some(&env.lead), None, 20).await.unwrap();- assert_eq!(all.len(), 2, "the review and Growth's plan, no loop: {all:?}");+ assert_eq!(all.len(), 1 + per_bot_limit(), "the review and Growth's two rounds, no loop: {all:?}");+ assert!(all.iter().all(|d| d.status == "completed"), "{all:?}");}/// Mentions that hand nothing on are said in the channel: a name no teammate has, and a follow-up@@ -1054,7 +1060,7 @@ async fn mentions_that_hand_nothing_on_are_said_in_the_channel() {say_in(&env, &channel, &format!("@{lead} Who else? UNKNOWNMARK REPLYTAG:who MENTION:Marketer")).await;wait_for("the unknown-name notice", || async { !refusals(&channel_messages(&env, &channel).await).is_empty() }).await;let notes = refusals(&channel_messages(&env, &channel).await);- assert_eq!(notes, vec!["Marketer wasn't asked: there's no teammate called Marketer here".to_string()]);+ assert_eq!(notes, vec!["Not sent to Marketer: no teammate has that name here".to_string()]);assert!(env.state.db.list_delegations(Some(&env.lead), None, 20).await.unwrap().is_empty());// This request already started the most delegations it may (earlier rounds, all ended)@@ -1082,7 +1088,7 @@ async fn mentions_that_hand_nothing_on_are_said_in_the_channel() {let last = delegate_from(&env, &channel, &env.specialist, "One more REPLYTAG:more", "Last part FOLLOWUP:Growth").await;wait_for("the last part", || async { delegation_status(&env, &last).await == "completed" }).await;let limit_note = || async {- refusals(&channel_messages(&env, &channel).await).into_iter().find(|n| n.starts_with("Growth wasn't asked"))+ refusals(&channel_messages(&env, &channel).await).into_iter().find(|n| n.contains("Growth: "))};for _ in 0..100 {if limit_note().await.is_some() {@@ -1092,7 +1098,11 @@ async fn mentions_that_hand_nothing_on_are_said_in_the_channel() {}let msgs: Vec<String> = channel_messages(&env, &channel).await.iter().map(|m| format!("{}: {}", m.sender_id, m.text)).collect();let note = limit_note().await.unwrap_or_else(|| panic!("no limit notice: {msgs:#?}"));- assert!(note.starts_with("Growth wasn't asked: this request has already gone to"), "{note}");+ // One line for the reply's refused mentions: the unknown name again, and Growth past the limit+ assert_eq!(+ note,+ format!("Not sent to Marketer: no teammate has that name here; Growth: this request has already gone to {} teammates. Send a new message to go on", routes_limit())+ );let delegated_growth = env.state.db.list_delegations(Some(&env.lead), None, 50).await.unwrap().iter().any(|d| d.specialist_kwant_id == growth);assert!(!delegated_growth, "over the limit, Growth isn't asked");}@@ -1134,16 +1144,120 @@ async fn one_teammate_is_asked_by_mention_at_most_twice_per_request() {// The specialist reports back and the lead's follow-up names Growth a third timelet last = delegate_from(&env, &channel, &env.specialist, "Review REPLYTAG:rev", "Review FOLLOWUP:Growth").await;wait_for("the review", || async { delegation_status(&env, &last).await == "completed" }).await;- let note = || async { refusals(&channel_messages(&env, &channel).await).into_iter().find(|n| n.starts_with("Growth wasn't asked")) };+ let note = || async { refusals(&channel_messages(&env, &channel).await).into_iter().find(|n| n.starts_with("Not sent to Growth")) };wait_for("the per-teammate notice", || async { note().await.is_some() }).await;let note = note().await.unwrap();- assert_eq!(note, "Growth wasn't asked: Growth was already asked 2 times for this request. Send a new message to go on");+ assert_eq!(note, "Not sent to Growth: already asked 2 times for this request. Send a new message to go on");tokio::time::sleep(Duration::from_millis(1000)).await;let to_growth = env.state.db.list_delegations(Some(&env.lead), None, 50).await.unwrap().iter().filter(|d| d.specialist_kwant_id == growth).count();assert_eq!(to_growth, per_bot_limit(), "no third delegation to Growth");assert_eq!(refusals(&channel_messages(&env, &channel).await).len(), 1, "one notice, no flood");}+/// Oleks's screenshot (2026-10-24): the Marketing lead's follow-up said "Handing off now: @Social …,+/// @Writer …, @SEO …" and nobody was asked, because all three had just reported. Now a 4-bot team+/// runs: lead → three teammates → follow-up hands each a correction → they run a second round →+/// the lead's next follow-up asks again, which is past the per-teammate limit: ONE line names all+/// three and nothing loops. Every result is posted in the channel and the lead answers each round.+#[tokio::test]+async fn a_follow_up_hands_corrections_back_to_teammates_who_just_reported() {+ let env = setup().await;+ let lead = name(&env, &env.lead).await;+ let ids = [add_bot(&env, "Social").await, add_bot(&env, "Writer").await, add_bot(&env, "SEO").await];+ let channel = team_channel_with(&env, "marketing-rounds", &[&env.lead, &ids[0], &ids[1], &ids[2]]).await;+ say_in(&env, &channel, &format!("@{lead} Marketing plan ROUNDSMARK REPLYTAG:plan MENTION:Social+Writer+SEO FOLLOWUP:Social+Writer+SEO")).await;++ let notes = || async { refusals(&channel_messages(&env, &channel).await) };+ wait_for("the limit notice after two rounds", || async { !notes().await.is_empty() }).await;+ tokio::time::sleep(Duration::from_millis(1500)).await;+ assert_eq!(+ notes().await,+ vec![format!("Not sent to Social, Writer, SEO: already asked {} times for this request. Send a new message to go on", per_bot_limit())],+ "one line for all three"+ );+ let all = env.state.db.list_delegations(Some(&env.lead), None, 50).await.unwrap();+ for id in &ids {+ let rounds = all.iter().filter(|d| &d.specialist_kwant_id == id).count();+ assert_eq!(rounds, per_bot_limit(), "each teammate ran twice: {all:?}");+ }+ assert!(all.iter().all(|d| d.status == "completed" && d.origin_channel_id.as_deref() == Some(channel.as_str())), "{all:?}");+ let second = all.iter().filter(|d| d.task.contains("please revise your part")).count();+ assert_eq!(second, 3, "the second round carries the lead's correction");++ let msgs = channel_messages(&env, &channel).await;+ let kinds: Vec<Option<String>> = msgs.iter().map(meta_kind).collect();+ assert_eq!(kinds.iter().filter(|k| k.as_deref() == Some("delegation_started")).count(), 6, "a Sent-to chip per task");+ assert_eq!(kinds.iter().filter(|k| k.as_deref() == Some("delegation_result")).count(), 6, "every result in the channel");+ let lead_replies = msgs.iter().filter(|m| m.sender_role == "kwant" && m.sender_id == lead).count();+ assert_eq!(lead_replies, 3, "the handoff, the follow-up after round one and the one after round two");+ let resumes = prompts_with("ROUNDSMARK").into_iter().filter(|p| p.contains("tasks you delegated have ended")).count();+ assert_eq!(resumes, 2, "the lead is resumed once per round");+ assert!(+ prompts_with("ROUNDSMARK").iter().filter(|p| p.contains("tasks you delegated have ended")).all(|p| p.contains("How handing on works")),+ "the follow-up states the real rules"+ );+}++/// A follow-up that only credits a teammate who just reported ("As @Growth found, …") asks it+/// nothing: no second round, and one line says why.+#[tokio::test]+async fn a_follow_up_that_only_credits_a_teammate_hands_nothing_on() {+ let env = setup().await;+ let growth = add_bot(&env, "Growth").await;+ let channel = team_channel_with(&env, "credit-only", &[&env.lead, &env.specialist, &growth]).await;+ let first = delegate_from(&env, &channel, &growth, "Find users REPLYTAG:found", "Find users CREDIT:Growth").await;+ wait_for("the task", || async { delegation_status(&env, &first).await == "completed" }).await;+ wait_for("the credit notice", || async { !refusals(&channel_messages(&env, &channel).await).is_empty() }).await;+ tokio::time::sleep(Duration::from_millis(1000)).await;+ let notes = refusals(&channel_messages(&env, &channel).await);+ assert_eq!(notes.len(), 1, "{notes:?}");+ assert!(notes[0].starts_with("Not sent to Growth: the mention only credited their result"), "{}", notes[0]);+ assert_eq!(env.state.db.list_delegations(Some(&env.lead), None, 20).await.unwrap().len(), 1, "no second round");+}++/// The lost final answer (2026-10-24, 1 run in 5 of a 4-bot team): a delegation's `ended_at` is+/// taken before its row is written, so under write contention the one that ended "last" checked+/// its batch while a sibling was still open, and the sibling, ending "earlier", didn't resume the+/// lead either. Every teammate replied and the lead never answered. Here that order is forced: A+/// ends with the later time and has already checked; B ends next. The lead is resumed exactly once.+#[tokio::test]+async fn the_lead_is_resumed_even_when_the_batch_ends_out_of_order() {+ let env = setup().await;+ let growth = add_bot(&env, "Growth").await;+ let channel = team_channel_with(&env, "race-squad", &[&env.lead, &env.specialist, &growth]).await;+ let new = |to: &str| kwnt::db::threads::NewDelegation {+ lead_kwant_id: env.lead.clone(),+ specialist_kwant_id: to.to_string(),+ origin_channel_id: Some(channel.clone()),+ origin_kwant_id: None,+ origin_thread_id: None,+ team_id: None,+ task: "Part RACEMARK".into(),+ title: "Part RACEMARK".into(),+ continue_lead: true,+ depth: 1,+ follow_up_at: None,+ };+ let (_, a) = env.state.db.create_delegation(&new(&growth)).await.unwrap();+ let (_, b) = env.state.db.create_delegation(&new(&env.specialist)).await.unwrap();+ assert!(env.state.db.finish_delegation(&a.id, "completed", None, None).await.unwrap());+ // A's time is later than B's will be, as when A's write waited behind other writes+ let pool = sqlx::SqlitePool::connect(&format!("sqlite://{}", env.tmp.path().join("data/kwnt.db").display())).await.unwrap();+ sqlx::query("UPDATE delegations SET ended_at = ? WHERE id = ?")+ .bind(chrono::Utc::now() + chrono::Duration::seconds(5))+ .bind(&a.id)+ .execute(&pool)+ .await+ .unwrap();+ pool.close().await;++ assert!(delegation::cancel(&env.state, &b.id).await.is_some());+ let resumes = || prompts_with("RACEMARK").into_iter().filter(|p| p.contains("tasks you delegated have ended")).count();+ wait_for("the lead's resume", || async { resumes() == 1 }).await;+ tokio::time::sleep(Duration::from_millis(1000)).await;+ assert_eq!(resumes(), 1, "resumed once");+}+fn per_bot_limit() -> usize {kwnt::server::routes::MAX_MENTION_DELEGATIONS_PER_BOT}