Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

Hand-offs keep going without a person: machine guards, 64 ceiling (#520)

Oleksandr Ivanchenko52bae9046905
diff --git a/docs/mission-control.md b/docs/mission-control.md
index 5b217615..6119f726 100644
--- a/docs/mission-control.md
+++ b/docs/mission-control.md
@@ -811,25 +811,41 @@ hand-off of the batch ends. Lines inside a code fence don't count.
Dedupe, and why: a teammate named on **one** line, or on lines that also name other teammates,
still gets one hand-off with the whole message, as before, since kwant can't tell which part of a
shared line is whose. The same line repeated word for word counts once (it's a repeat, not more
-work). Lines past the per-teammate cap (4) wait for Continue; on Continue, lines already sent are
-skipped, so no line is sent twice. The lead's open limit (`delegation::MAX_OPEN_PER_LEAD`, 5 unfinished)
+work). Lines past the hard ceiling (64 hand-offs for one message) wait for Continue; on Continue,
+lines already sent are skipped, so no line is sent twice. The lead's open limit (`delegation::MAX_OPEN_PER_LEAD`, 5 unfinished)
still applies per hand-off: a line past it is refused with the usual `handoff_refused` note. A dependency wait
("after @X") on a teammate with several cards waits for the last of them started.
-### Capped hand-offs: the Continue notice
-
-One person message starts at most `routes::MAX_DELEGATIONS_PER_REQUEST` (16) hand-offs by mention,
-at most `routes::MAX_MENTION_DELEGATIONS_PER_BOT` (4) to one teammate. These caps are what stop
-loops by default; `chain_token_budget` adds a token limit only when the person sets one (§15). Mentions past a cap are not dropped: kwant saves one system message in the channel
-with meta
+### Hand-off guards, and the Continue notice
+
+A lead hands on by mention as often as the work needs; there is no per-teammate cap. Loops end on
+machine guards that skip the mention with a `handoff_refused` note ("Not sent to X: why") and
+never wait for the person:
+
+- **Exact repeat**: the same task, normalised (trimmed, lowercased, whitespace collapsed; the
+ lines that @mention the teammate, or its own line when it was sent one line of several), to the
+ same teammate for this message: "already asked X exactly this in this request". A reworded
+ retry goes out. Earlier hand-offs that ended `failed` don't count, so a failed task may be
+ retried word for word until the failure-streak guard stops it; completed and cancelled ones do
+ count (open ones are already skipped as "still working").
+- **Failure streak**: the teammate's last 3 hand-offs for this message all ended `failed`
+ (cancelled or completed break it): "X failed its last 3 tasks here: do it yourself or give it to
+ someone else". The person's next message resets it.
+- **Relay ping-pong**: a teammate's result can't hand work back up its own chain of relays.
+
+`chain_token_budget` adds a token limit only when the person sets one (§15). The one hand-off
+count that waits for the person is the hard ceiling `routes::MAX_DELEGATIONS_PER_REQUEST` (64
+hand-offs by mention for one person message, counted from the later of their last message and the
+last capped notice they carried on). Mentions past it are not dropped: kwant saves one system
+message in the channel with meta
```json
{"kind": "handoff_capped", "lead": "<lead id>", "waiting": ["<name>"], "waiting_ids": ["<id>"],
- "sent": 16, "text": "<the lead's reply>", "user_prompt": "<the person's message>", "resumed": false}
+ "sent": 64, "text": "<the lead's reply>", "user_prompt": "<the person's message>", "resumed": false}
```
-and text "Paused after N hand-offs so it doesn't loop: A, B not sent yet. Press Continue or say
-"continue" to hand it on." It works like the `budget_paused` notice: `POST
+and text "Paused after 64 hand-offs for one message: A, B not sent yet. Press Continue or say
+"continue" to carry on." It works like the `budget_paused` notice: `POST
/api/chains/:message_id/continue` (person only; 409 once continued, 410 if the lead is gone), or the
person typing "continue" while it's the newest bot message. Continuing sets `resumed` true and hands
only the waiting teammates the lead's reply, with a fresh allowance.
diff --git a/src/router/tags.rs b/src/router/tags.rs
index 2d9b0211..0c7f65ae 100644
--- a/src/router/tags.rs
+++ b/src/router/tags.rs
@@ -245,8 +245,8 @@ const CREDIT_AFTER: [&str; 14] = [
/// 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.
+/// mention without such words counts as an ask: this is deliberately narrow, and the exact-repeat
+/// guard on hand-offs 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());
diff --git a/src/server/budget.rs b/src/server/budget.rs
index b1b33735..3435e09a 100644
--- a/src/server/budget.rs
+++ b/src/server/budget.rs
@@ -18,7 +18,7 @@ use serde_json::json;
/// Setting key: fresh tokens one chain may use before hand-offs pause; 0 turns the guard off.
pub const SETTING: &str = "chain_token_budget";
/// Off unless the person sets a budget, like task and mission limits (docs/mission-control.md §15).
-/// The hand-off count caps still stop a chain that loops.
+/// The hand-off guards still stop a chain that loops.
pub const DEFAULT: u64 = 0;
/// The budget every install had before it became opt-in; a stored value equal to it is cleared
/// once ([`crate::db::Database::migrate_chain_budget_default`]).
@@ -26,8 +26,8 @@ pub const OLD_DEFAULT: u64 = 200_000;
pub const MAX: u64 = 100_000_000;
/// Message meta kind of the notice.
pub const KIND: &str = "budget_paused";
-/// Message meta kind of the notice a lead's @mentions leave past the hand-off caps
-/// ([`super::routes::MAX_MENTION_DELEGATIONS_PER_BOT`], [`super::routes::MAX_DELEGATIONS_PER_REQUEST`]).
+/// Message meta kind of the notice a lead's @mentions leave past the hard ceiling on hand-offs
+/// for one message ([`super::routes::MAX_DELEGATIONS_PER_REQUEST`]).
/// Carried on like a paused chain: Continue on it, or "continue" typed after it.
pub const CAPPED_KIND: &str = "handoff_capped";
@@ -97,13 +97,15 @@ pub(super) async fn pause_if_over(scope: &TurnScope, spoken: &[String], replies:
true
}
-/// A lead's @mentions went past a hand-off cap: saves one notice naming the teammates `capped`
-/// (`sent` hand-offs so far for this request), which the person carries on with one press.
+/// A lead's @mentions went past the hard ceiling on hand-offs for one message: saves one notice
+/// naming the teammates `capped` (`sent` hand-offs so far for this request), which the person
+/// carries on with one press.
pub(super) async fn pause_capped(scope: &TurnScope, lead: &Kwant, capped: &[&Kwant], sent: usize, text: &str, user_prompt: &str) {
let names: Vec<String> = capped.iter().map(|k| k.name.clone()).collect();
- tracing::info!(lead = %lead.id, sent, waiting = ?names, "hand-off caps reached: waiting for Continue");
+ tracing::info!(lead = %lead.id, sent, waiting = ?names, "hand-off ceiling reached: waiting for Continue");
let line = format!(
- "Paused after {sent} hand-offs so it doesn't loop: {} not sent yet. Press Continue or say \"continue\" to hand it on.",
+ "Paused after {} hand-offs for one message: {} not sent yet. Press Continue or say \"continue\" to carry on.",
+ super::routes::MAX_DELEGATIONS_PER_REQUEST,
names.join(", "),
);
let meta = json!({
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 18be5938..e0cb5808 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -1272,11 +1272,13 @@ pub fn handoff_rules() -> String {
"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 yet: a notice asks the person to press Continue, so tell them what's waiting instead of claiming a handoff.",
- per_bot = super::routes::MAX_MENTION_DELEGATIONS_PER_BOT,
- total = super::routes::MAX_DELEGATIONS_PER_REQUEST,
+ with a task in this reply; to merely refer to a teammate, write the name without @. Keep handing on as the work needs. \
+ kwnt skips a mention, and tells you why under your reply, when it repeats exactly a task that teammate already finished \
+ or was cancelled on for this user message (a failed task may be retried as it was), or when that teammate failed its last {streak} tasks in a row here: then do it yourself or give it \
+ to someone else. Only after {ceiling} hand-offs for one user message does the person press Continue; then tell them \
+ what's waiting instead of claiming a handoff.",
+ streak = super::routes::FAILURE_STREAK_LEN,
+ ceiling = super::routes::MAX_DELEGATIONS_PER_REQUEST,
)
}
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 78a0fa02..ed2403ef 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -940,14 +940,15 @@ fn team_context(t: &Team) -> crate::drivers::TeamContext {
/// Max follow-up turns kwants may trigger by @mentioning each other for one user message.
const MAX_HANDOFFS: usize = 4;
-/// Delegations a lead's @mentions may start for one user message, follow-up rounds included:
-/// a lead resumed with results can hand on again, but never in an endless loop.
-pub const MAX_DELEGATIONS_PER_REQUEST: usize = 16;
-/// How often one teammate may be handed work by @mention for one user message, so two bots
-/// naming each other stop after a few rounds instead of running to the total cap. A mention past
-/// either cap leaves a Continue notice ([`super::budget::CAPPED_KIND`]); the chain token budget
-/// still pauses a long chain on its own.
-pub const MAX_MENTION_DELEGATIONS_PER_BOT: usize = 4;
+/// The hard ceiling on delegations a lead's @mentions may start for one user message, follow-up
+/// rounds included. It's the only hand-off count that waits for the person: a mention past it
+/// leaves a Continue notice ([`super::budget::CAPPED_KIND`]). Below it, loops end on machine
+/// guards that skip with a reason ([`REPEATED_TASK`], [`FAILURE_STREAK`], [`RELAY_PING_PONG`]);
+/// the chain token budget still pauses a long chain on its own.
+pub const MAX_DELEGATIONS_PER_REQUEST: usize = 64;
+/// Failed delegations in a row, to one teammate in one request, after which a mention to it is
+/// skipped (the lead does it itself or gives it to someone else).
+pub const FAILURE_STREAK_LEN: usize = 3;
#[allow(clippy::too_many_arguments)]
fn execute_single_turn(
@@ -1363,6 +1364,10 @@ where
/// A teammate's result @mentioned one already in this chain of relays.
const RELAY_PING_PONG: &str = "it already worked on this chain of hand-offs, so a teammate's result can't hand it back. Ask the lead to send it";
const IN_CODE_BLOCK: &str = "the mention was inside code. Write the name as plain text to ask them";
+/// The same task, normalised, already went to this teammate for this user message.
+pub const REPEATED_TASK: &str = "already asked {name} exactly this in this request";
+/// The teammate's last [`FAILURE_STREAK_LEN`] delegations for this user message all failed.
+pub const FAILURE_STREAK: &str = "{name} failed its last 3 tasks here: do it yourself or give it to someone else";
/// 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";
@@ -1456,13 +1461,16 @@ pub(super) struct Relay<'a> {
/// 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, 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, which is what ends a loop; mentions past a cap wait on a Continue notice
-/// ([`super::budget::pause_capped`]). Every other 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. `resumed`: the person pressed Continue on such a notice: only these teammates are
-/// handed the work, with a fresh allowance.
+/// them ([`crate::router::only_credited`]). Loops end on machine guards that skip with a reason
+/// and never wait for the person: the same normalised task to the same teammate twice in one
+/// request ([`REPEATED_TASK`]; an earlier one that failed doesn't count, so a failed task may be
+/// retried as-is until the failure-streak guard stops it), a teammate whose last [`FAILURE_STREAK_LEN`] tasks here failed
+/// ([`FAILURE_STREAK`]) and a relay back up its chain ([`RELAY_PING_PONG`]). Only past the hard
+/// ceiling [`MAX_DELEGATIONS_PER_REQUEST`] do mentions wait on a Continue notice
+/// ([`super::budget::pause_capped`]). 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.
+/// `resumed`: the person pressed Continue on such a notice: only these teammates are handed the
+/// work, with a fresh allowance.
pub(super) async fn delegate_mentions(
scope: &TurnScope,
lead: &Kwant,
@@ -1491,7 +1499,7 @@ pub(super) async fn delegate_mentions(
let mine: Vec<_> = scope
.state
.db
- .list_delegations(Some(&lead.id), None, 50)
+ .list_delegations(Some(&lead.id), None, 4 * MAX_DELEGATIONS_PER_REQUEST as i64)
.await
.unwrap_or_default()
.into_iter()
@@ -1499,17 +1507,17 @@ pub(super) async fn delegate_mentions(
.collect();
let open: Vec<&str> = mine.iter().filter(|d| d.is_open()).map(|d| d.specialist_kwant_id.as_str()).collect();
// Delegations this user message already started, counting earlier follow-up rounds
- let messages = scope.state.db.list_messages(&cid, 100).await.unwrap_or_default();
- let since = messages.iter().rev().find(|m| m.sender_role == "user").or(messages.first()).and_then(|m| m.created_at);
- let this_request: Vec<_> = match resumed {
+ let messages = scope.state.db.list_messages(&cid, 400).await.unwrap_or_default();
+ let since = request_start(&messages);
+ let mut this_request: Vec<_> = match resumed {
Some(_) => Vec::new(),
None => mine.iter().filter(|d| d.continue_lead && since.is_some_and(|t| d.created_at >= t)).collect(),
};
+ this_request.sort_by_key(|d| d.created_at);
let mut room = MAX_DELEGATIONS_PER_REQUEST.saturating_sub(this_request.len());
- let asked = |id: &str| this_request.iter().filter(|d| d.specialist_kwant_id == id).count();
let mut targets: Vec<&Kwant> = Vec::new();
- // Past a cap: they wait on a Continue notice instead of a dead end
+ // Past the ceiling: they wait on a Continue notice instead of a dead end
let mut capped: Vec<&Kwant> = Vec::new();
for &i in &found.targets {
let k = &scope.teammates[i];
@@ -1528,8 +1536,8 @@ pub(super) async fn delegate_mentions(
skipped.push((k.name.clone(), CREDIT_ONLY.to_string()));
} else if open.contains(&k.id.as_str()) {
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 {
- capped.push(k);
+ } else if failure_streak(this_request.iter().copied(), &k.id) {
+ skipped.push((k.name.clone(), FAILURE_STREAK.replace("{name}", &k.name)));
} else {
targets.push(k);
}
@@ -1592,24 +1600,29 @@ pub(super) async fn delegate_mentions(
units.push((specialist, None));
continue;
}
- let mut left = MAX_MENTION_DELEGATIONS_PER_BOT.saturating_sub(asked(&specialist.id));
for line in lines {
- // Continue sends only the lines that weren't sent before the cap
+ // Continue sends only the lines that weren't sent before the ceiling
let sent = |d: &crate::db::threads::Delegation| d.specialist_kwant_id == specialist.id && d.task.starts_with(&line_task(&line));
if resumed.is_some() && mine.iter().any(sent) {
continue;
}
- if left == 0 {
- if !capped.iter().any(|c| c.id == specialist.id) {
- capped.push(specialist);
- }
- break;
- }
- left -= 1;
units.push((specialist, Some(line)));
}
}
+ // (teammate, normalised task) handed out this round, so a line said twice goes once
+ let mut asked_now: Vec<(String, String)> = Vec::new();
for (specialist, line) in units {
+ let unit_task = line.as_deref().map_or_else(|| task.clone(), line_task);
+ let key = repeat_key(&unit_task, &specialist.name);
+ let repeated = asked_now.iter().any(|(id, k)| id == &specialist.id && *k == key)
+ || this_request.iter().any(|d| {
+ // A failed one may be retried as-is; the failure-streak guard stops that loop
+ d.specialist_kwant_id == specialist.id && d.status != "failed" && repeat_key(&d.task, &specialist.name) == key
+ });
+ if repeated {
+ skipped.push((specialist.name.clone(), REPEATED_TASK.replace("{name}", &specialist.name)));
+ continue;
+ }
if room == 0 {
if !capped.iter().any(|c| c.id == specialist.id) {
capped.push(specialist);
@@ -1635,7 +1648,7 @@ pub(super) async fn delegate_mentions(
let req = super::delegation::StartRequest {
lead: lead.clone(),
specialist: specialist.clone(),
- task: line.as_deref().map_or_else(|| task.clone(), line_task),
+ task: unit_task,
title: Some(match &line {
Some(l) => handoff_title(l, &specialist.name).unwrap_or_else(|| first_line(l)),
None => handoff_title(text, &specialist.name).unwrap_or_else(|| title_for(specialist)),
@@ -1651,6 +1664,7 @@ pub(super) async fn delegate_mentions(
match super::delegation::create(&scope.state, req).await {
Ok(c) => {
started.insert(specialist.id.clone(), c.delegation.id.clone());
+ asked_now.push((specialist.id.clone(), key));
sent += 1;
room -= 1;
created.push(c);
@@ -1669,6 +1683,56 @@ pub(super) async fn delegate_mentions(
}
}
+/// When the current request's hand-offs are counted from: the later of the person's last message
+/// and the last capped-hand-off notice they carried on, so a Continue starts a fresh allowance even
+/// when no "continue" message follows it. Falls back to the oldest message in view.
+fn request_start(messages: &[crate::db::models::Message]) -> Option<chrono::DateTime<chrono::Utc>> {
+ let user = messages.iter().rev().find(|m| m.sender_role == "user").and_then(|m| m.created_at);
+ let resumed = messages
+ .iter()
+ .rev()
+ .find(|m| {
+ m.meta
+ .as_deref()
+ .and_then(|x| serde_json::from_str::<serde_json::Value>(x).ok())
+ .is_some_and(|meta| meta["kind"] == super::budget::CAPPED_KIND && meta["resumed"] == true)
+ })
+ .and_then(|m| m.created_at);
+ user.max(resumed).or_else(|| messages.first().and_then(|m| m.created_at))
+}
+
+/// What a hand-off asks of `name`, normalised (trimmed, lowercased, whitespace collapsed), for the
+/// exact-repeat guard: the line it was given when it was sent one line of several, else the lines
+/// that @mention it in what the lead (or a relaying teammate) said, after the last "mentioned you".
+/// Not the quoted request before it: a follow-up with no person message quotes the previous task
+/// there, so it grows each round. The same lead line asked twice matches; a reworded one doesn't.
+/// Earlier hand-offs that ended `failed` are not compared, so an identical retry goes out.
+pub fn repeat_key(task: &str, name: &str) -> String {
+ const LINE: &str = "\n\nYour task is this line of ";
+ let asked = match task.rfind(LINE).and_then(|at| task[at..].split_once("only:\n")) {
+ Some((_, rest)) => rest.lines().next().unwrap_or_default().to_string(),
+ None => {
+ let said = task.rfind(" mentioned you").map_or(task, |at| &task[at..]);
+ let lines: Vec<&str> = said.lines().filter(|l| mentions(l, name)).collect();
+ if lines.is_empty() { task.to_string() } else { lines.join("\n") }
+ }
+ };
+ asked.split_whitespace().collect::<Vec<_>>().join(" ").to_lowercase()
+}
+
+/// Whether `line` @mentions `name` (case-insensitive, whole name).
+fn mentions(line: &str, name: &str) -> bool {
+ let (line, at) = (line.to_lowercase(), format!("@{}", name.to_lowercase()));
+ line.match_indices(&at).any(|(i, _)| !line[i + at.len()..].starts_with(|c: char| c.is_alphanumeric() || c == '_'))
+}
+
+/// Whether the teammate's last [`FAILURE_STREAK_LEN`] delegations of this request (oldest first)
+/// all failed. Cancelled or completed ones break the streak.
+fn failure_streak<'a>(this_request: impl DoubleEndedIterator<Item = &'a crate::db::threads::Delegation>, id: &str) -> bool {
+ let last: Vec<_> = this_request.rev().filter(|d| d.specialist_kwant_id == id).take(FAILURE_STREAK_LEN).collect();
+ last.len() == FAILURE_STREAK_LEN && last.iter().all(|d| d.status == "failed")
+}
+
/// A hand-off's title from what the lead asked `name` for: the first sentence of the line that
/// @mentions them, without the mention. Two hand-offs from one message then read differently on
/// the board (Oleks, 2026-10-29: four cards all named after his message). `None` when the line
@@ -1685,12 +1749,17 @@ pub fn handoff_title(text: &str, name: &str) -> Option<String> {
return None;
}
let rest = &line[lower.find(&mention)? + mention.len()..];
- let rest = rest.trim_start_matches(|c: char| c.is_whitespace() || matches!(c, ',' | ':' | '-' | '–' | '—' | '*' | '_' | '.'));
+ // A '`' right after the name closes the inline code it was mentioned in ("`@QA` please …")
+ let rest = rest.trim_start_matches(|c: char| c.is_whitespace() || matches!(c, ',' | ':' | '-' | '–' | '—' | '*' | '_' | '.' | '`'));
let end = rest
.char_indices()
.find(|&(i, c)| matches!(c, '.' | '!' | '?') && rest[i + c.len_utf8()..].starts_with(char::is_whitespace))
.map(|(i, c)| i + c.len_utf8());
- let sentence = rest[..end.unwrap_or(rest.len())].trim().trim_end_matches(['*', '_']).trim();
+ let mut sentence = rest[..end.unwrap_or(rest.len())].trim().trim_end_matches(['*', '_']).trim();
+ if sentence.matches('`').count() % 2 == 1 {
+ // An unpaired '`' closes inline code the mention opened ("`@QA run it`")
+ sentence = sentence.trim_end_matches('`').trim();
+ }
if sentence.chars().filter(|c| c.is_alphanumeric()).count() < 3 {
return None;
}
@@ -6410,6 +6479,14 @@ pub async fn execute_tool(
#[cfg(test)]
mod tests {
+ #[test]
+ fn a_mention_in_inline_code_leaves_no_stray_backtick_in_the_title() {
+ use super::handoff_title;
+ assert_eq!(handoff_title("`@QA` please revise your part.", "QA").as_deref(), Some("Please revise your part."));
+ assert_eq!(handoff_title("`@QA run the smoke tests`", "QA").as_deref(), Some("Run the smoke tests"));
+ assert_eq!(handoff_title("@QA run `cargo test` on staging.", "QA").as_deref(), Some("Run `cargo test` on staging."));
+ }
+
use super::{
is_persons, is_reply_by, person_words, scrub_urls, turn_failed_text, turn_plan, with_failure_meta, Carried, TurnOpts,
};
diff --git a/tests/delegation_test.rs b/tests/delegation_test.rs
index 256f8506..5edd65ff 100644
--- a/tests/delegation_test.rs
+++ b/tests/delegation_test.rs
@@ -1045,12 +1045,12 @@ fn capped(msgs: &[kwnt::db::models::Message]) -> Vec<kwnt::db::models::Message>
msgs.iter().filter(|m| meta_kind(m).as_deref() == Some(kwnt::server::budget::CAPPED_KIND)).cloned().collect()
}
-/// `n` ended rounds from the lead to `to` in `channel` that count for the current request (dated
-/// ahead, so they are after any message of it). The fake CLI's markers fall out of the lead's
-/// recent history after a few rounds, so rounds up to a cap are seeded rather than run.
-async fn seed_rounds(env: &Env, channel: &str, to: &str, n: usize) {
- let pool = sqlx::SqlitePool::connect(&format!("sqlite://{}", env.tmp.path().join("data/kwnt.db").display())).await.unwrap();
- for _ in 0..n {
+/// `n` ended hand-offs from the lead to `to` in `channel`, ended with `status`, created now: after
+/// the person's message, so they count for its request. Tasks are `task` or "earlier round <i>".
+/// The fake CLI's markers fall out of the lead's recent history after a few rounds, so rounds up to
+/// a guard are seeded rather than run.
+async fn seed(env: &Env, channel: &str, to: &str, n: usize, status: &str, task: Option<&str>) {
+ for i in 0..n {
let (_, d) = env
.state
.db
@@ -1061,7 +1061,7 @@ async fn seed_rounds(env: &Env, channel: &str, to: &str, n: usize) {
origin_kwant_id: None,
origin_thread_id: None,
team_id: None,
- task: "earlier round".into(),
+ task: task.map_or_else(|| format!("earlier round {i}"), str::to_string),
title: "Earlier round".into(),
continue_lead: true,
depth: 1,
@@ -1069,15 +1069,22 @@ async fn seed_rounds(env: &Env, channel: &str, to: &str, n: usize) {
})
.await
.unwrap();
- assert!(env.state.db.finish_delegation(&d.id, "completed", None, None).await.unwrap());
- sqlx::query("UPDATE delegations SET created_at = ? WHERE id = ?")
- .bind(chrono::Utc::now() + chrono::Duration::hours(1))
- .bind(&d.id)
- .execute(&pool)
- .await
- .unwrap();
+ assert!(env.state.db.finish_delegation(&d.id, status, None, None).await.unwrap());
}
- pool.close().await;
+}
+
+/// The person asks the lead in `channel` with `prompt`; the lead's turn holds until `seeding` has
+/// added this request's earlier rounds, then replies.
+async fn say_after_seeding<F: std::future::Future<Output = ()>>(env: &Env, channel: &str, prompt: &str, seeding: F) {
+ let release = env.release_file(&format!("seeded-{}", uuid_like()));
+ let lead = name(env, &env.lead).await;
+ say_in(env, channel, &format!("@{lead} {prompt} HOLDTURN:{}", release.display())).await;
+ seeding.await;
+ std::fs::write(&release, "go").unwrap();
+}
+
+fn uuid_like() -> String {
+ format!("{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos())
}
fn meta_of(m: &kwnt::db::models::Message) -> Value {
@@ -1087,22 +1094,18 @@ fn meta_of(m: &kwnt::db::models::Message) -> Value {
/// 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 and a name in inline code counts. Mentioning the teammate who just reported back with a
-/// task hands it another round (2026-10-24), up to the per-teammate cap. Past it (2026-10-28,
-/// "send a new message to go on"??? so it stuck without my message??) a Continue notice waits:
-/// pressing it hands Growth the work again, and the chain still stops at the cap.
+/// task hands it another round (2026-10-24). When the follow-up asks Growth exactly the same thing
+/// again, that's a loop: it's skipped with the reason, and nothing waits for the person
+/// (2026-11-11: no per-teammate Continue).
#[tokio::test]
async fn a_leads_follow_up_after_results_hands_on_to_the_next_teammate() {
let env = setup().await;
let growth = add_bot(&env, "Growth").await;
let channel = team_channel_with(&env, "startup-follow", &[&env.lead, &env.specialist, &growth]).await;
- // Growth already ran all but two of its rounds for this request
- seed_rounds(&env, &channel, &growth, per_bot_limit() - 2).await;
let first = delegate_from(&env, &channel, &env.specialist, "Review the app REPLYTAG:reviewed", "Security review FOLLOWUP:Growth").await;
wait_for("the review to complete", || async { delegation_status(&env, &first).await == "completed" }).await;
- let to_growth = || async {
- env.state.db.list_delegations(Some(&env.lead), None, 20).await.unwrap().into_iter().find(|d| d.specialist_kwant_id == growth && d.title != "Earlier round")
- };
+ let to_growth = || async { env.state.db.list_delegations(Some(&env.lead), None, 20).await.unwrap().into_iter().find(|d| d.specialist_kwant_id == growth) };
wait_for("the follow-up's delegation to Growth", || async { to_growth().await.is_some() }).await;
let d = to_growth().await.unwrap();
assert_eq!(d.origin_channel_id.as_deref(), Some(channel.as_str()));
@@ -1110,37 +1113,19 @@ 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 with a task: more rounds, then the cap
- wait_for("the Continue notice", || async { !capped(&channel_messages(&env, &channel).await).is_empty() }).await;
+ // The next follow-up asks Growth the very same thing: skipped, said why, no Continue
+ wait_for("the repeat note", || async { !refusals(&channel_messages(&env, &channel).await).is_empty() }).await;
tokio::time::sleep(Duration::from_millis(1500)).await;
let msgs = channel_messages(&env, &channel).await;
- assert!(refusals(&msgs).is_empty(), "past the cap is not a dead end: {:?}", refusals(&msgs));
- let notices = capped(&msgs);
- assert_eq!(notices.len(), 1, "one notice, no flood");
- let notice = &notices[0];
- assert!(notice.text.starts_with("Paused after ") && notice.text.contains("Growth not sent yet. Press Continue"), "{}", notice.text);
- let meta = meta_of(notice);
- assert_eq!((meta["lead"].as_str(), meta["waiting_ids"].clone(), meta["resumed"].clone()), (Some(env.lead.as_str()), json!([growth]), json!(false)));
- let to_growth_count = || async {
- env.state.db.list_delegations(Some(&env.lead), None, 50).await.unwrap().iter().filter(|d| d.specialist_kwant_id == growth).count()
- };
+ assert_eq!(refusals(&msgs), vec!["Not sent to Growth: already asked Growth exactly this in this request".to_string()]);
+ assert!(capped(&msgs).is_empty(), "nothing waits for the person");
let all = env.state.db.list_delegations(Some(&env.lead), None, 20).await.unwrap();
- assert_eq!(all.len(), 1 + per_bot_limit(), "the review and Growth's rounds up to the cap, no loop: {all:?}");
+ assert_eq!(all.len(), 2, "the review and Growth's one round, no loop: {all:?}");
assert!(all.iter().all(|d| d.status == "completed"), "{all:?}");
-
- // One press carries it on: Growth is handed the work again
- let (s, body) = call(&env.app, "POST", &format!("/api/chains/{}/continue", notice.id), None).await;
- assert_eq!(s, StatusCode::OK, "{body}");
- wait_for("Growth's next round", || async { to_growth_count().await > per_bot_limit() }).await;
- let (s, _) = call(&env.app, "POST", &format!("/api/chains/{}/continue", notice.id), None).await;
- assert_eq!(s, StatusCode::CONFLICT, "a notice carries on once");
- // A fresh allowance, still bounded by the cap
- tokio::time::sleep(Duration::from_millis(3000)).await;
- assert!(to_growth_count().await <= 2 * per_bot_limit() + 1, "still bounded");
}
/// Mentions that hand nothing on are said in the channel: a name no teammate has. A follow-up after
-/// the request already went to the most teammates one message may reach leaves a Continue notice.
+/// the request already reached the hard ceiling of hand-offs leaves a Continue notice.
#[tokio::test]
async fn mentions_that_hand_nothing_on_are_said_in_the_channel() {
let env = setup().await;
@@ -1154,27 +1139,7 @@ async fn mentions_that_hand_nothing_on_are_said_in_the_channel() {
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)
- for _ in 0..routes_limit() {
- let (_, d) = env
- .state
- .db
- .create_delegation(&kwnt::db::threads::NewDelegation {
- lead_kwant_id: env.lead.clone(),
- specialist_kwant_id: env.specialist.clone(),
- origin_channel_id: Some(channel.clone()),
- origin_kwant_id: None,
- origin_thread_id: None,
- team_id: None,
- task: "earlier round".into(),
- title: "Earlier round".into(),
- continue_lead: true,
- depth: 1,
- follow_up_at: None,
- })
- .await
- .unwrap();
- assert!(env.state.db.finish_delegation(&d.id, "completed", None, None).await.unwrap());
- }
+ seed(&env, &channel, &env.specialist, routes_limit(), "completed", None).await;
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;
wait_for("the Continue notice", || async { !capped(&channel_messages(&env, &channel).await).is_empty() }).await;
@@ -1184,7 +1149,7 @@ async fn mentions_that_hand_nothing_on_are_said_in_the_channel() {
assert_eq!(notes.last().map(String::as_str), Some("Not sent to Marketer: no teammate has that name here"), "{notes:?}");
assert!(notes.iter().all(|n| !n.contains("Growth")), "{notes:?}");
let notice = &capped(&msgs)[0];
- assert_eq!(notice.text, format!("Paused after {} hand-offs so it doesn't loop: Growth not sent yet. Press Continue or say \"continue\" to hand it on.", routes_limit() + 1));
+ assert_eq!(notice.text, "Paused after 64 hand-offs for one message: Growth not sent yet. Press Continue or say \"continue\" to carry on.");
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");
}
@@ -1208,86 +1173,197 @@ async fn an_account_the_person_linked_is_not_said_as_an_unknown_teammate() {
assert_eq!(notes, vec!["Not sent to Marketer: no teammate has that name here".to_string(); 2]);
}
-/// Rigel's ping-pong (2026-10-21): two bots naming each other ran all 8 rounds of a request. One
-/// teammate is handed work by mention at most [`per_bot_limit`] times per user message; the next
-/// mention starts nothing and leaves one Continue notice.
+/// Ada's release-0.9.1 brief (2026-11-11): a lead stopped at "Continue?" after 4 hand-offs to one
+/// teammate. There is no per-teammate cap: a 5th and 6th mention to the same teammate in one
+/// request go out like the first, with no notice.
#[tokio::test]
-async fn one_teammate_is_asked_by_mention_at_most_the_cap_per_request() {
+async fn a_fifth_and_sixth_mention_to_one_teammate_go_out_with_no_notice() {
let env = setup().await;
- let lead = name(&env, &env.lead).await;
let growth = add_bot(&env, "Growth").await;
- let channel = team_channel_with(&env, "startup-pingpong", &[&env.lead, &env.specialist, &growth]).await;
- say_in(&env, &channel, &format!("@{lead} Plan the launch REPLYTAG:plan")).await;
- wait_for("the lead's reply", || async { channel_messages(&env, &channel).await.iter().any(|m| m.text.contains("answer plan")) }).await;
+ let channel = team_channel_with(&env, "startup-fifth", &[&env.lead, &env.specialist, &growth]).await;
+ // Growth already ran 4 rounds for this message; the lead's reply hands it two more lines
+ say_after_seeding(&env, &channel, "Plan the launch FIFTHMARK REPLYTAG:fifth LINES:Growth:2", seed(&env, &channel, &growth, 4, "completed", None)).await;
+
+ let to_growth = || async { handoffs_from(&env, &channel).await.into_iter().filter(|d| d.specialist_kwant_id == growth).collect::<Vec<_>>() };
+ wait_for("the 5th and 6th hand-offs", || async { to_growth().await.len() >= 6 }).await;
+ let ds = to_growth().await;
+ for d in &ds[4..] {
+ wait_for("a part to finish", || async { delegation_status(&env, &d.id).await == "completed" }).await;
+ }
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ let msgs = channel_messages(&env, &channel).await;
+ assert!(capped(&msgs).is_empty(), "no Continue notice: {:?}", capped(&msgs).iter().map(|m| &m.text).collect::<Vec<_>>());
+ assert!(refusals(&msgs).is_empty(), "{:?}", refusals(&msgs));
+ let ds = to_growth().await;
+ assert_eq!(ds.len(), 6, "{:?}", ds.iter().map(|d| &d.title).collect::<Vec<_>>());
+ assert!(ds[4].title.to_lowercase().contains("build part 1.") && ds[5].title.to_lowercase().contains("build part 2."));
+}
- // Growth already ran up to the cap for this message (earlier rounds, all ended)
- for _ in 0..per_bot_limit() {
- let (_, d) = env
- .state
- .db
- .create_delegation(&kwnt::db::threads::NewDelegation {
- lead_kwant_id: env.lead.clone(),
- specialist_kwant_id: growth.clone(),
- origin_channel_id: Some(channel.clone()),
- origin_kwant_id: None,
- origin_thread_id: None,
- team_id: None,
- task: "earlier round".into(),
- title: "Earlier round".into(),
- continue_lead: true,
- depth: 1,
- follow_up_at: None,
- })
- .await
- .unwrap();
- assert!(env.state.db.finish_delegation(&d.id, "completed", None, None).await.unwrap());
+/// The same task, normalised (case, spaces), to the same teammate twice in one request is a loop:
+/// it's skipped with the reason under the lead's reply. A reworded ask (another line) goes out.
+#[tokio::test]
+async fn an_exact_repeat_is_skipped_with_the_reason_and_a_reworded_ask_goes_out() {
+ let env = setup().await;
+ let growth = add_bot(&env, "Growth").await;
+ let channel = team_channel_with(&env, "startup-repeat", &[&env.lead, &env.specialist, &growth]).await;
+ // Earlier this request Growth was handed line 1, worded with other case and spacing
+ let earlier = "The user asked in the team channel:\nPlan\n\nYour task is this line of Lead's message only:\n @GROWTH, please build PART 1. \nother lines";
+ say_after_seeding(&env, &channel, "Plan the launch REPEATMARK REPLYTAG:rep LINES:Growth:2", seed(&env, &channel, &growth, 1, "completed", Some(earlier))).await;
+
+ wait_for("the repeat note", || async { !refusals(&channel_messages(&env, &channel).await).is_empty() }).await;
+ let to_growth = || async { handoffs_from(&env, &channel).await.into_iter().filter(|d| d.specialist_kwant_id == growth).collect::<Vec<_>>() };
+ wait_for("the reworded line", || async { to_growth().await.len() >= 2 }).await;
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ let msgs = channel_messages(&env, &channel).await;
+ assert_eq!(refusals(&msgs), vec!["Not sent to Growth: already asked Growth exactly this in this request".to_string()]);
+ assert!(capped(&msgs).is_empty(), "nothing waits for the person");
+ let ds = to_growth().await;
+ assert_eq!(ds.len(), 2, "the earlier round and line 2 only: {:?}", ds.iter().map(|d| &d.title).collect::<Vec<_>>());
+ assert!(ds[1].title.to_lowercase().contains("build part 2."), "{}", ds[1].title);
+}
+
+/// Ada's review of #520: a lead retrying a teammate that failed often uses the same words. An
+/// earlier identical hand-off that ended `failed` isn't a repeat: the same line goes out again.
+#[tokio::test]
+async fn a_failed_task_asked_again_word_for_word_goes_out() {
+ let env = setup().await;
+ let growth = add_bot(&env, "Growth").await;
+ let channel = team_channel_with(&env, "startup-retry", &[&env.lead, &env.specialist, &growth]).await;
+ say_after_seeding(&env, &channel, "Plan the launch RETRYMARK REPLYTAG:retry LINES:Growth:2", seed(&env, &channel, &growth, 1, "failed", Some("@Growth, please build part 1."))).await;
+
+ let to_growth = || async { handoffs_from(&env, &channel).await.into_iter().filter(|d| d.specialist_kwant_id == growth).collect::<Vec<_>>() };
+ wait_for("both lines", || async { to_growth().await.len() >= 3 }).await;
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ let msgs = channel_messages(&env, &channel).await;
+ assert!(refusals(&msgs).is_empty(), "no skip line: {:?}", refusals(&msgs));
+ assert!(capped(&msgs).is_empty(), "nothing waits for the person");
+ let ds = to_growth().await;
+ assert_eq!(ds.len(), 3, "the failed round, then lines 1 and 2: {:?}", ds.iter().map(|d| &d.title).collect::<Vec<_>>());
+ assert!(ds[1..].iter().any(|d| d.title.to_lowercase().contains("build part 1.")), "line 1 is retried as-is");
+}
+
+/// The same line failing 3 times in a row isn't retried a 4th time: the failure-streak guard skips
+/// it (not the repeat guard, which lets failed tasks through), and nothing pauses.
+#[tokio::test]
+async fn the_same_line_failing_three_times_is_stopped_by_the_streak_not_the_repeat_guard() {
+ let env = setup().await;
+ let growth = add_bot(&env, "Growth").await;
+ let channel = team_channel_with(&env, "startup-retry3", &[&env.lead, &env.specialist, &growth]).await;
+ say_after_seeding(&env, &channel, "Plan the launch RETRY3MARK REPLYTAG:retry3 LINES:Growth:2", seed(&env, &channel, &growth, 3, "failed", Some("@Growth, please build part 1."))).await;
+
+ wait_for("the skip note", || async { !refusals(&channel_messages(&env, &channel).await).is_empty() }).await;
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ let msgs = channel_messages(&env, &channel).await;
+ let reason = kwnt::server::routes::FAILURE_STREAK.replace("{name}", "Growth");
+ assert_eq!(refusals(&msgs), vec![format!("Not sent to Growth: {reason}")]);
+ assert!(capped(&msgs).is_empty(), "nothing waits for the person");
+ let n = handoffs_from(&env, &channel).await.into_iter().filter(|d| d.specialist_kwant_id == growth).count();
+ assert_eq!(n, 3, "no 4th try is started");
+}
+
+/// Only failed tasks may be retried as-is: the same line after a completed or a cancelled
+/// hand-off is still skipped as a repeat, and the other line goes out.
+#[tokio::test]
+async fn an_exact_repeat_after_a_completed_or_cancelled_hand_off_is_still_skipped() {
+ let env = setup().await;
+ let growth = add_bot(&env, "Growth").await;
+ for status in ["completed", "cancelled"] {
+ let channel = team_channel_with(&env, &format!("startup-done-{status}"), &[&env.lead, &env.specialist, &growth]).await;
+ let prompt = format!("Plan the launch DONEMARK{status} REPLYTAG:done{status} LINES:Growth:2");
+ say_after_seeding(&env, &channel, &prompt, seed(&env, &channel, &growth, 1, status, Some("@Growth, please build part 1."))).await;
+
+ let to_growth = || async { handoffs_from(&env, &channel).await.into_iter().filter(|d| d.specialist_kwant_id == growth).collect::<Vec<_>>() };
+ wait_for("the repeat note", || async { !refusals(&channel_messages(&env, &channel).await).is_empty() }).await;
+ wait_for("line 2", || async { to_growth().await.len() >= 2 }).await;
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ let msgs = channel_messages(&env, &channel).await;
+ let reason = kwnt::server::routes::REPEATED_TASK.replace("{name}", "Growth");
+ assert_eq!(refusals(&msgs), vec![format!("Not sent to Growth: {reason}")], "after a {status} one");
+ let ds = to_growth().await;
+ assert_eq!(ds.len(), 2, "after a {status} one: {:?}", ds.iter().map(|d| &d.title).collect::<Vec<_>>());
+ assert!(ds[1].title.to_lowercase().contains("build part 2."), "{}", ds[1].title);
}
- // The specialist reports back and the lead's follow-up names Growth once more
- let 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;
- wait_for("the per-teammate notice", || async { !capped(&channel_messages(&env, &channel).await).is_empty() }).await;
+}
+
+#[test]
+fn the_repeat_key_is_what_the_teammate_was_asked_normalised() {
+ use kwnt::server::routes::repeat_key;
+ let whole = |reply: &str| format!("The user asked in the team channel:\nShip it\n\nLead mentioned you:\nGood work all.\n{reply}\nThanks.\n\nAnswer the ask.");
+ let a = repeat_key(&whole("@Writer Draft the INTRO."), "Writer");
+ assert_eq!(a, "@writer draft the intro.");
+ assert_eq!(a, repeat_key(&whole(" @writer draft the intro. "), "Writer"), "case and spaces don't count");
+ assert_ne!(a, repeat_key(&whole("@Writer Draft the intro in smaller steps."), "Writer"), "a reworded retry is new");
+ assert_ne!(a, repeat_key(&whole("@Writers Draft the intro."), "Writer"), "only a whole-name mention");
+ let line = "Base task @Writer\n\nYour task is this line of Lead's message only:\n@Writer, please build part 2.\nLead sent each line…";
+ assert_eq!(repeat_key(line, "Writer"), "@writer, please build part 2.");
+ assert_eq!(repeat_key("earlier round", "Writer"), "earlier round", "no mention: the whole task");
+ // With no person message, a follow-up quotes the previous task as the request: only what the
+ // lead said this time counts
+ let nested = format!("The user asked in the team channel:\n{}\n\nLead mentioned you:\n@Writer Draft the INTRO.\n\nAnswer the ask.", whole("@Writer Draft the intro."));
+ assert_eq!(repeat_key(&nested, "Writer"), a);
+ let relayed = "The user asked in the team channel:\n@Writer old\n\nSocial mentioned you in its result for Lead's task “Plan”. Do it.\n[Message from bot Social]\n@writer draft the intro.\n[End of message from Social]";
+ assert_eq!(repeat_key(relayed, "Writer"), a);
+}
+
+/// A teammate whose last 3 tasks for this request all failed isn't handed a 4th: the mention is
+/// skipped with the reason (do it yourself or give it to someone else), nothing waits for the
+/// person, and the person's next message starts afresh.
+#[tokio::test]
+async fn three_failures_in_a_row_skip_the_fourth_mention_without_pausing() {
+ let env = setup().await;
+ let growth = add_bot(&env, "Growth").await;
+ let channel = team_channel_with(&env, "startup-streak", &[&env.lead, &env.specialist, &growth]).await;
+ let seeding = async {
+ seed(&env, &channel, &growth, 1, "completed", None).await;
+ seed(&env, &channel, &growth, 3, "failed", None).await;
+ };
+ say_after_seeding(&env, &channel, "Plan the launch STREAKMARK REPLYTAG:streak MENTION:Growth", seeding).await;
+
+ wait_for("the streak note", || async { !refusals(&channel_messages(&env, &channel).await).is_empty() }).await;
tokio::time::sleep(Duration::from_millis(1000)).await;
let msgs = channel_messages(&env, &channel).await;
- let notices = capped(&msgs);
- assert_eq!(notices.len(), 1, "one notice, no flood");
- assert!(notices[0].text.contains("Growth not sent yet"), "{}", notices[0].text);
- assert!(refusals(&msgs).is_empty(), "{:?}", refusals(&msgs));
- 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(), "nothing past the cap until Continue");
+ assert_eq!(
+ refusals(&msgs),
+ vec!["Not sent to Growth: Growth failed its last 3 tasks here: do it yourself or give it to someone else".to_string()]
+ );
+ assert!(capped(&msgs).is_empty(), "nothing waits for the person");
+ let to_growth = || async { handoffs_from(&env, &channel).await.into_iter().filter(|d| d.specialist_kwant_id == growth).count() };
+ assert_eq!(to_growth().await, 4, "no 4th failure in a row is started");
+
+ // The person's next message resets the streak
+ let lead = name(&env, &env.lead).await;
+ say_in(&env, &channel, &format!("@{lead} Try again STREAKMARK2 REPLYTAG:again MENTION:Growth")).await;
+ wait_for("Growth's new task", || async { to_growth().await == 5 }).await;
}
/// 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 → each follow-up hands each a correction → they run rounds up to
-/// the per-teammate limit → the lead's next follow-up asks again: ONE Continue notice names all
-/// three and nothing loops. Every result is posted in the channel and the lead answers each round.
+/// runs: lead → three teammates → each follow-up hands each a correction → the lead's next
+/// follow-up asks the very same correction again: ONE note says why for all three, nothing loops
+/// and nothing waits for the person. 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;
- // Each already ran all but two of its rounds for this request
- for id in &ids {
- seed_rounds(&env, &channel, id, per_bot_limit() - 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 { capped(&channel_messages(&env, &channel).await) };
- wait_for("the Continue notice after the last round", || async { !notes().await.is_empty() }).await;
+ let notes = || async { refusals(&channel_messages(&env, &channel).await) };
+ wait_for("the repeat note after the last round", || async { !notes().await.is_empty() }).await;
tokio::time::sleep(Duration::from_millis(1500)).await;
let notes = notes().await;
- assert_eq!(notes.len(), 1, "one notice for all three");
- let (rounds_total, run) = (3 * per_bot_limit(), 6);
- assert_eq!(
- notes[0].text,
- format!("Paused after {rounds_total} hand-offs so it doesn't loop: Social, Writer, SEO not sent yet. Press Continue or say \"continue\" to hand it on.")
- );
- assert!(refusals(&channel_messages(&env, &channel).await).is_empty());
+ assert_eq!(notes.len(), 1, "one note for all three: {notes:?}");
+ for who in ["Social", "Writer", "SEO"] {
+ assert!(notes[0].contains(&format!("already asked {who} exactly this in this request")), "{}", notes[0]);
+ }
+ assert!(capped(&channel_messages(&env, &channel).await).is_empty(), "nothing waits for the person");
+ let run = 6;
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 up to the cap: {all:?}");
+ assert_eq!(rounds, 2, "each teammate ran the task and one correction: {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();
@@ -1367,13 +1443,21 @@ async fn the_lead_is_resumed_even_when_the_batch_ends_out_of_order() {
assert_eq!(resumes(), 1, "resumed once");
}
-fn per_bot_limit() -> usize {
- kwnt::server::routes::MAX_MENTION_DELEGATIONS_PER_BOT
+#[test]
+fn only_the_hard_ceiling_waits_for_the_person() {
+ assert_eq!((routes_limit(), kwnt::server::routes::FAILURE_STREAK_LEN), (64, 3));
}
+/// The lead's hand-on rules say how it really works now: no per-teammate or 4/16 limits.
#[test]
-fn hand_off_caps_leave_room_for_a_team() {
- assert_eq!((per_bot_limit(), routes_limit()), (4, 16));
+fn handoff_rules_have_no_per_teammate_limits() {
+ let rules = kwnt::server::delegation::handoff_rules();
+ for gone in ["at most 4", "at most 16", "each teammate gets", "per teammate", "per-teammate", " 4 tasks", " 16 "] {
+ assert!(!rules.contains(gone), "{gone:?} in: {rules}");
+ }
+ for said in ["Keep handing on", "repeats exactly a task", "failed its last 3 tasks", "do it yourself or give it to someone else", "after 64 hand-offs", "Continue"] {
+ assert!(rules.contains(said), "{said:?} missing in: {rules}");
+ }
}
fn routes_limit() -> usize {
@@ -1508,10 +1592,10 @@ async fn a_relayed_result_cannot_hand_work_back_up_its_chain() {
assert_eq!(ds.iter().filter(|d| d.specialist_kwant_id == growth).count(), 1);
}
-/// A result's mention of a teammate already asked up to the per-teammate cap leaves the Continue
-/// notice, like the lead's own mentions.
+/// A result's mention of a teammate past the hard ceiling of hand-offs leaves the Continue notice,
+/// like the lead's own mentions.
#[tokio::test]
-async fn a_relayed_mention_past_the_cap_waits_for_continue() {
+async fn a_relayed_mention_past_the_ceiling_waits_for_continue() {
let env = setup().await;
let lead = name(&env, &env.lead).await;
let social = add_bot(&env, "Social").await;
@@ -1519,14 +1603,14 @@ async fn a_relayed_mention_past_the_cap_waits_for_continue() {
let channel = team_channel_with(&env, "relay-cap", &[&env.lead, &social, &growth]).await;
say_in(&env, &channel, &format!("@{lead} Plan the launch REPLYTAG:capplan")).await;
wait_for("the lead's reply", || async { channel_messages(&env, &channel).await.iter().any(|m| m.text.contains("answer capplan")) }).await;
- seed_rounds(&env, &channel, &growth, per_bot_limit()).await;
+ seed(&env, &channel, &growth, routes_limit() - 1, "completed", None).await;
let d = delegate_from(&env, &channel, &social, "Review REPLYTAG:capped MENTION:Growth", "Review").await;
wait_for("the review", || async { delegation_status(&env, &d).await == "completed" }).await;
- wait_for("the per-teammate notice", || async { !capped(&channel_messages(&env, &channel).await).is_empty() }).await;
+ wait_for("the ceiling notice", || async { !capped(&channel_messages(&env, &channel).await).is_empty() }).await;
let notices = capped(&channel_messages(&env, &channel).await);
assert!(notices[0].text.contains("Growth not sent yet"), "{}", notices[0].text);
- 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(), "nothing past the cap until Continue");
+ let to_growth = env.state.db.list_delegations(Some(&env.lead), None, 200).await.unwrap().iter().filter(|d| d.specialist_kwant_id == growth).count();
+ assert_eq!(to_growth, routes_limit() - 1, "nothing past the ceiling until Continue");
}
/// The lead's delegations from `channel`, oldest first.
@@ -1578,31 +1662,58 @@ async fn each_line_for_the_same_teammate_is_its_own_hand_off() {
assert!(capped(&channel_messages(&env, &channel).await).is_empty());
}
-/// Five lines for one teammate: the per-teammate cap sends four, a Continue notice holds the
-/// fifth, and Continue sends just that one, not the four again.
+/// Five lines for one teammate all go out: there's no per-teammate cap.
#[tokio::test]
-async fn lines_past_the_per_teammate_cap_wait_for_continue_and_are_sent_once() {
+async fn five_lines_for_one_teammate_all_go_out() {
let env = setup().await;
let (lead, specialist) = (name(&env, &env.lead).await, name(&env, &env.specialist).await);
let channel = team_channel(&env, "five-lines").await;
say_in(&env, &channel, &format!("@{lead} Build the site LINESMARK2 REPLYTAG:plan LINES:{specialist}:5")).await;
- wait_for("the Continue notice", || async { !capped(&channel_messages(&env, &channel).await).is_empty() }).await;
+ wait_for("five hand-offs", || async { handoffs_from(&env, &channel).await.len() >= 5 }).await;
+ tokio::time::sleep(Duration::from_millis(1500)).await;
let ds = handoffs_from(&env, &channel).await;
- assert_eq!(ds.len(), per_bot_limit(), "up to the per-teammate cap");
+ assert_eq!(ds.len(), 5, "{:?}", ds.iter().map(|d| &d.title).collect::<Vec<_>>());
+ assert!(capped(&channel_messages(&env, &channel).await).is_empty());
+}
+
+/// The one pause left: the 65th hand-off for one message waits on the ceiling notice. Continue
+/// sends just that one (not the lines already sent), and the next round hands on again without
+/// pausing, since a carried-on notice starts a fresh allowance.
+#[tokio::test]
+async fn the_65th_hand_off_pauses_and_continue_sends_it_once() {
+ let env = setup().await;
+ let builder = add_bot(&env, "Builder").await;
+ let channel = team_channel_with(&env, "ceiling", &[&env.lead, &env.specialist, &builder]).await;
+ // 63 hand-offs ran for this message; the lead's reply hands Builder two lines: the 64th and 65th
+ say_after_seeding(&env, &channel, "Build the site CEILINGMARK REPLYTAG:ceil LINES:Builder:2", seed(&env, &channel, &env.specialist, routes_limit() - 1, "completed", None)).await;
+
+ wait_for("the ceiling notice", || async { !capped(&channel_messages(&env, &channel).await).is_empty() }).await;
+ let to_builder = || async { handoffs_from(&env, &channel).await.into_iter().filter(|d| d.specialist_kwant_id == builder).collect::<Vec<_>>() };
+ let ds = to_builder().await;
+ assert_eq!(ds.len(), 1, "the 64th went out");
+ assert!(ds[0].title.to_lowercase().contains("build part 1."), "{}", ds[0].title);
let notice = capped(&channel_messages(&env, &channel).await).remove(0);
- assert!(notice.text.contains(&format!("{specialist} not sent yet")), "{}", notice.text);
- for d in &ds {
- wait_for("a part to finish", || async { delegation_status(&env, &d.id).await == "completed" }).await;
- }
+ assert_eq!(notice.text, "Paused after 64 hand-offs for one message: Builder not sent yet. Press Continue or say \"continue\" to carry on.");
+ wait_for("part 1 to finish", || async { delegation_status(&env, &ds[0].id).await == "completed" }).await;
let (s, v) = call(&env.app, "POST", &format!("/api/chains/{}/continue", notice.id), None).await;
assert_eq!(s, StatusCode::OK, "{v}");
- wait_for("the fifth part", || async { handoffs_from(&env, &channel).await.len() > per_bot_limit() }).await;
+ wait_for("the 65th", || async { to_builder().await.len() >= 2 }).await;
+ let ds = to_builder().await;
+ wait_for("part 2 to finish", || async { delegation_status(&env, &ds[1].id).await == "completed" }).await;
+ assert!(ds[1].title.to_lowercase().contains("build part 2."), "{}", ds[1].title);
+
+ // The next round: the lead's follow-up hands Builder a correction, with no second notice
+ let d = delegate_from(&env, &channel, &env.specialist, "Check REPLYTAG:after", "Check FOLLOWUP:Builder").await;
+ wait_for("the check", || async { delegation_status(&env, &d).await == "completed" }).await;
+ wait_for("Builder's correction", || async { to_builder().await.iter().any(|d| d.task.contains("please revise your part")) }).await;
tokio::time::sleep(Duration::from_millis(1500)).await;
- let ds = handoffs_from(&env, &channel).await;
- assert_eq!(ds.len(), 5, "Continue sends only the line that waited: {:?}", ds.iter().map(|d| &d.title).collect::<Vec<_>>());
- assert!(ds[4].title.to_lowercase().contains("build part 5."), "{}", ds[4].title);
+ let ds = to_builder().await;
+ assert_eq!(ds.iter().filter(|d| d.task.contains("Your task is this line")).count(), 2, "Continue sent only the line that waited");
+ let notices = capped(&channel_messages(&env, &channel).await);
+ assert_eq!(notices.len(), 1, "no re-pause: {:?}", notices.iter().map(|m| &m.text).collect::<Vec<_>>());
+ assert_eq!(meta_of(&notices[0])["resumed"], json!(true));
}
/// A call to kwnt's own tools as the agent turn that holds `token`, as its CLI makes it.