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: a stalled lead chain gets a keep-going turn (0.9.2, on #520) (#526)

Oleksandr Ivanchenko46ce9477a560
diff --git a/src/db/waiting.rs b/src/db/waiting.rs
index a963023b..dfe7c3a0 100644
--- a/src/db/waiting.rs
+++ b/src/db/waiting.rs
@@ -167,6 +167,25 @@ impl Database {
Ok(res.rows_affected())
}
+ /// A bot's plain "waiting on a reply" entries in one chat (no question card) end: the ask
+ /// became a card, which has its own entry.
+ pub async fn close_plain_waiting(
+ &self,
+ kwant_id: &str,
+ channel_id: Option<&str>,
+ direct_kwant_id: Option<&str>,
+ thread_id: Option<&str>,
+ ) -> Result<u64, DbError> {
+ let res = sqlx::query(&format!("UPDATE waiting_on_person SET status = 'closed' WHERE question_id IS NULL AND status != 'closed' AND {SAME_CHAT}"))
+ .bind(kwant_id)
+ .bind(channel_id.unwrap_or(""))
+ .bind(direct_kwant_id.unwrap_or(""))
+ .bind(thread_id.unwrap_or(""))
+ .execute(&self.pool)
+ .await?;
+ Ok(res.rows_affected())
+ }
+
/// The entries whose reminder is due by `now`, each claimed (`open` → `reminded`) so it goes
/// out once, whoever else is looking.
pub async fn take_due_waiting(&self, now: DateTime<Utc>) -> Result<Vec<WaitingItem>, DbError> {
diff --git a/src/server/asks.rs b/src/server/asks.rs
index a04d152f..907f85df 100644
--- a/src/server/asks.rs
+++ b/src/server/asks.rs
@@ -177,7 +177,7 @@ pub(super) async fn consolidate(scope: &TurnScope) {
}
/// Adds `key` to a message's meta, keeping the rest, and tells the clients.
-async fn set_meta_key(state: &AppState, m: &Message, key: &str, value: Value) {
+pub(super) async fn set_meta_key(state: &AppState, m: &Message, key: &str, value: Value) {
let mut meta = match meta_of(m) {
Value::Object(o) => Value::Object(o),
_ => json!({}),
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index e0cb5808..4157865f 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -14,7 +14,7 @@ use axum::{
response::{IntoResponse, Response},
Json,
};
-use chrono::Utc;
+use chrono::{DateTime, Utc};
use serde::Deserialize;
use serde_json::{json, Value};
@@ -980,10 +980,9 @@ async fn finished_batch(state: &AppState, d: &Delegation) -> Option<Vec<Delegati
// the rest now, and that task comes back with its own batch once it ran
.filter(|s| s.continue_lead && s.origin_context() == d.origin_context() && !is_parked(s))
.collect();
- if siblings.iter().any(Delegation::is_open) {
- return None;
- }
- let end = |s: &Delegation| s.ended_at.unwrap_or(s.created_at);
+ // One still running hasn't ended yet: its run reaches to now, so it overlaps everything
+ // after its start
+ let end = |s: &Delegation| if s.is_open() { DateTime::<Utc>::MAX_UTC } else { s.ended_at.unwrap_or(s.created_at) };
// Grow from `d` to every delegation whose run overlaps the batch's span, to the results
// that relayed work to a batch member or were relayed from one (they ran one after the other),
// and to the hand-offs the same lead turn started (one may have ended before the next began)
@@ -1011,6 +1010,14 @@ async fn finished_batch(state: &AppState, d: &Delegation) -> Option<Vec<Delegati
batch.push(s);
}
}
+ // Wait for a member still running: the last one to end reports them all. A task the lead
+ // started after this batch ended isn't part of it and doesn't hold its report back: it
+ // used to, and when it began between this one's end and this check (the next hand-off
+ // starting while this result was still being posted), this result was never reported
+ // because that task's own batch doesn't reach back to it
+ if batch.iter().any(Delegation::is_open) {
+ return None;
+ }
// 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 batch.iter().all(|b| b.status == "cancelled") {
@@ -1051,7 +1058,9 @@ async fn result_of(state: &AppState, d: &Delegation) -> String {
}
/// Gives the lead one turn in the origin chat with every result of the batch, so it checks them
-/// and gives the user one answer. Tasks that didn't complete say what the lead should do about it.
+/// and keeps the person's request moving: it hands the next step on, asks the person, or ends with
+/// `Done: …` (see [`super::keep_going`], which steps in when it does none of these). Tasks that
+/// didn't complete say what the lead should do about it.
async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation], opening: Option<String>) {
let Ok(Some(lead)) = state.db.get_kwant(&d.lead_kwant_id).await else {
return;
@@ -1116,8 +1125,10 @@ 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, 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\
+ correction by @mention (below). If a task failed, was stopped or was cut short, say so plainly. Don't repeat the \
+ results in full. Then take the user's request to its next step: a draft or step on the way needs no approval \
+ unless the person asked to approve it, so show it, say what comes next and go on (they can say stop if they want \
+ changes).\n\n\
{rules}",
rules = handoff_rules(),
);
@@ -1129,6 +1140,8 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation], o
let beside_running = lead_turn_runs(state, batch.iter().chain([d]));
let mut opts = TurnOpts::default();
opts.beside_running = beside_running;
+ let context = d.origin_context().unwrap_or(&lead.id).to_string();
+ let before = super::keep_going::snapshot(state, &context, &lead).await;
let outcome = try_kwant_turn(&scope, &lead, prompt, opts).await;
// The cards of the batch are reviewed in a turn of their own that sees only each brief and
// result (fresh eyes), then the ones still waiting get one reminder (a failed turn counts too)
@@ -1147,9 +1160,12 @@ async fn continue_lead(state: &AppState, d: &Delegation, batch: &[Delegation], o
.find(|m| m.sender_role == "user")
.map(|m| m.text)
.unwrap_or_else(|| d.task.clone());
- super::routes::run_handoffs_boxed(&scope, &spoken, &[(lead.clone(), reply)], &user_prompt).await;
+ super::routes::run_handoffs_boxed(&scope, &spoken, &[(lead.clone(), reply.clone())], &user_prompt).await;
// The chain may be over now: several open questions for the person become one list
super::asks::consolidate(&scope).await;
+ // Nothing handed on, asked or marked done: the lead goes on (after the review above, so
+ // a review line isn't where the chat stops)
+ super::keep_going::after_lead_turn(&scope, &lead, before, reply).await;
}
}
@@ -1276,7 +1292,12 @@ pub fn handoff_rules() -> String {
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.",
+ what's waiting instead of claiming a handoff.\n\n\
+ End every reply in one of three ways: (1) hand the next step on by @mention, or do it yourself in this reply; \
+ (2) if only the person can give what's needed (a choice they asked to make, a sign-in, money, sending something), \
+ ask them with the question tool; (3) if the whole request is finished and you checked it, end with a last line \
+ `Done: <what you checked>`. A summary that hands nothing on, asks nothing and isn't done leaves the work \
+ stopped, so kwnt asks you to go on.",
streak = super::routes::FAILURE_STREAK_LEN,
ceiling = super::routes::MAX_DELEGATIONS_PER_REQUEST,
)
diff --git a/src/server/keep_going.rs b/src/server/keep_going.rs
new file mode 100644
index 00000000..f07f308e
--- /dev/null
+++ b/src/server/keep_going.rs
@@ -0,0 +1,387 @@
+//! Keep going (0.9.2): a lead's chain never just stops. After a lead's results turn (see
+//! [`super::delegation`]), its hand-offs and the list of open asks, kwnt checks whether the chain
+//! is still moving: something handed on or still open, a question waiting on the person, a
+//! pause, the person writing or pressing Stop, or the lead ending with `Done: …`. When none of
+//! that holds the chain has stalled (Oleks's Studio/Director video, 2026-11-11: "Next decision
+//! for you: review animatic v10 … Nothing else is waiting on you", then nothing), and:
+//!
+//! - a reply whose last line asks the person something becomes a question card at once;
+//! - else the lead gets a keep-going turn in the same chat, at most [`DEFAULT_TURNS`] per person
+//! message (counted like the hand-off ceiling, see [`super::routes`]'s request start);
+//! - past that, one "Keep going?" card. "Keep going" is a person message, so it brings a fresh
+//! allowance and starts a keep-going turn; "That's enough for now" ends it.
+//!
+//! The `Done:` line is stored on the reply's meta as [`DONE_KEY`].
+
+use super::routes::{try_kwant_turn, TurnOpts, TurnScope};
+use super::AppState;
+use crate::db::models::{Kwant, Message};
+use crate::db::questions::{Question, QuestionPlace, QuestionReason};
+use crate::db::waiting::NewWaitingItem;
+use chrono::{Duration, Utc};
+use serde_json::{json, Value};
+use std::collections::HashSet;
+
+/// Keep-going turns per person message; `0` turns them off. A plain setting (no API), for a
+/// kill switch and for tests that predate keep-going turns.
+pub const SETTING: &str = "keep_going_turns";
+pub const DEFAULT_TURNS: usize = 2;
+const MAX_TURNS: usize = 5;
+/// On a keep-going turn's reply (or its failure note): which turn of the allowance it was.
+pub const TURN_KEY: &str = "keep_going";
+/// On the "Keep going?" card's message.
+pub const CARD_KEY: &str = "keep_going_card";
+/// On a card kwant made from a lead's reply that asked the person in prose: its answer resumes
+/// the lead's chain (hand-offs, then this check again).
+pub const ASK_KEY: &str = "keep_going_ask";
+/// On a reply that ends with `Done: …`: `{text}`, what the lead said it checked.
+pub const DONE_KEY: &str = "chain_done";
+pub const KEEP_GOING: &str = "Keep going";
+pub const ENOUGH: &str = "That's enough for now";
+/// What a keep-going turn is told.
+pub const PROMPT: &str = "The person's request isn't marked done, nothing is handed on and nothing is asked. Do the next \
+ step now: hand it on or do it yourself. If it really is finished, check it and end with `Done: …`. If only the \
+ person can unblock it, ask with the question tool.";
+/// The person messages a keep-going turn quotes.
+const QUOTED: usize = 3;
+const QUOTE_CHARS: usize = 600;
+const CARD_LINE_CHARS: usize = 160;
+
+/// How many keep-going turns one person message allows.
+pub async fn turns_allowed(state: &AppState) -> usize {
+ state
+ .db
+ .get_setting(SETTING)
+ .await
+ .ok()
+ .flatten()
+ .and_then(|v| v.trim().parse::<usize>().ok())
+ .map(|n| n.min(MAX_TURNS))
+ .unwrap_or(DEFAULT_TURNS)
+}
+
+/// The `Done: …` line a reply ends with, if it does: its last non-empty line, markdown
+/// decoration aside, starts with "Done:" and says what was done.
+pub fn done_line(reply: &str) -> Option<String> {
+ let last = reply.lines().map(str::trim).rfind(|l| !l.is_empty())?;
+ let bare = last.trim_start_matches(['*', '_', '-', '>', '`', ' ']);
+ let head = bare.get(..5)?;
+ if !head.eq_ignore_ascii_case("done:") {
+ return None;
+ }
+ let what = bare[5..].trim().trim_matches(['*', '_', '`', ' ']).trim();
+ (!what.is_empty()).then(|| what.to_string())
+}
+
+/// What the chat looked like before a lead turn: whatever isn't here afterwards is new.
+pub(super) struct Snapshot {
+ context: String,
+ messages: HashSet<String>,
+ delegations: HashSet<String>,
+ last_user: Option<String>,
+}
+
+/// The chat `context` and `lead`'s hand-offs from it, before a turn of `lead` there.
+pub(super) async fn snapshot(state: &AppState, context: &str, lead: &Kwant) -> Snapshot {
+ let msgs = state.db.list_messages(context, 100).await.unwrap_or_default();
+ Snapshot {
+ context: context.to_string(),
+ messages: msgs.iter().map(|m| m.id.clone()).collect(),
+ delegations: lead_delegations(state, context, lead).await.into_iter().map(|d| d.id).collect(),
+ last_user: msgs.iter().rev().find(|m| m.sender_role == "user").map(|m| m.id.clone()),
+ }
+}
+
+async fn lead_delegations(state: &AppState, context: &str, lead: &Kwant) -> Vec<crate::db::threads::Delegation> {
+ state
+ .db
+ .list_delegations(Some(&lead.id), None, 100)
+ .await
+ .unwrap_or_default()
+ .into_iter()
+ .filter(|d| d.origin_context().unwrap_or(&lead.id) == context)
+ .collect()
+}
+
+fn meta_of(m: &Message) -> Value {
+ m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null)
+}
+
+/// Where this person message's request starts: after the person's last message, or after a
+/// hand-off ceiling notice they pressed Continue on (like the hand-off ceiling's count).
+fn request_tail(msgs: &[Message]) -> &[Message] {
+ let start = msgs.iter().rposition(|m| {
+ let meta = meta_of(m);
+ m.sender_role == "user" || (meta["kind"] == super::budget::CAPPED_KIND && meta["resumed"] == true)
+ });
+ match start {
+ Some(i) => &msgs[i + 1..],
+ None => msgs,
+ }
+}
+
+#[derive(Debug, PartialEq)]
+enum Verdict {
+ /// Something still moves the chain, or the person or a pause holds it.
+ Moving,
+ /// The lead ended with `Done: …`.
+ Done(String),
+ /// The lead's last line asks the person this, in prose.
+ Asks(String),
+ Stalled,
+}
+
+async fn verdict(scope: &TurnScope, lead: &Kwant, snap: &Snapshot, reply: &str) -> Verdict {
+ let state = &scope.state;
+ // The person pressed Stop
+ if scope.cancel_token.is_cancelled() {
+ return Verdict::Moving;
+ }
+ let msgs = state.db.list_messages(&snap.context, 100).await.unwrap_or_default();
+ // The person wrote: their message has its own turn
+ if msgs.iter().rev().find(|m| m.sender_role == "user").map(|m| &m.id) != snap.last_user.as_ref() {
+ return Verdict::Moving;
+ }
+ for m in msgs.iter().filter(|m| !snap.messages.contains(&m.id)) {
+ let meta = meta_of(m);
+ let kind = meta["kind"].as_str().unwrap_or("");
+ // A pause the person lifts (the chain's budget, the hand-off ceiling, a bot's budget),
+ // one list of what the team needs from them, or another bot speaking in the chat
+ if [super::budget::KIND, super::budget::CAPPED_KIND, super::bot_budget::STOPPED_KIND].contains(&kind)
+ || meta.get(super::asks::META_KEY).is_some()
+ || (m.sender_role == "kwant" && m.sender_id != lead.name && m.sender_id != lead.id)
+ {
+ return Verdict::Moving;
+ }
+ }
+ let delegations = lead_delegations(state, &snap.context, lead).await;
+ // Handed on, or a hand-off of this lead here is still open or parked
+ if delegations.iter().any(|d| !snap.delegations.contains(&d.id) || d.is_open()) {
+ return Verdict::Moving;
+ }
+ // A question card waits on the person here, or in a thread of this request's hand-offs
+ if !state.db.list_questions(Some("open"), Some(&snap.context), None).await.unwrap_or_default().is_empty() {
+ return Verdict::Moving;
+ }
+ let since = request_tail(&msgs).first().and_then(|m| m.created_at);
+ for d in delegations.iter().filter(|d| since.is_none_or(|s| d.created_at >= s)) {
+ if !state.db.list_questions(Some("open"), Some(&d.thread_id), None).await.unwrap_or_default().is_empty() {
+ return Verdict::Moving;
+ }
+ }
+ // Monthly bot budget or the space's spend stop: nothing runs until the person lifts it
+ if super::bot_budget::held(state, &lead.id).await.is_some() || super::spend_stop::held(state, &lead.space_id).await.is_some() {
+ return Verdict::Moving;
+ }
+ if let Some(done) = done_line(reply) {
+ return Verdict::Done(done);
+ }
+ let names: Vec<&str> = scope.teammates.iter().map(|k| k.name.as_str()).collect();
+ if let Some(q) = crate::router::sticky::person_question(reply).filter(|_| !super::asks::hands_on(reply, &names)) {
+ return Verdict::Asks(q);
+ }
+ Verdict::Stalled
+}
+
+/// After a lead's turn in a person's chat (its results turn, a keep-going turn, its turn on a
+/// late answer) once its hand-offs ran: keeps the chain going if it stalled. `snap` is the chat
+/// before that turn, `reply` the turn's reply.
+pub(super) async fn after_lead_turn(scope: &TurnScope, lead: &Kwant, mut snap: Snapshot, mut reply: String) {
+ // Only where the lead answers the person: a lead inside a hand-off reports to its own lead
+ if scope.delegation_depth != 0 {
+ return;
+ }
+ let state = &scope.state;
+ loop {
+ match verdict(scope, lead, &snap, &reply).await {
+ Verdict::Moving => return,
+ Verdict::Done(text) => return mark_done(state, &snap, lead, &text).await,
+ Verdict::Asks(q) => {
+ ask_card(scope, lead, &q, &[], ASK_KEY).await;
+ return;
+ }
+ Verdict::Stalled => {}
+ }
+ let allowed = turns_allowed(state).await;
+ if allowed == 0 {
+ return;
+ }
+ let msgs = state.db.list_messages(&snap.context, 100).await.unwrap_or_default();
+ let tail = request_tail(&msgs);
+ let used = tail.iter().filter(|m| meta_of(m).get(TURN_KEY).is_some()).count();
+ if used >= allowed {
+ // One card per person message, never a second
+ if !tail.iter().any(|m| meta_of(m).get(CARD_KEY).is_some()) {
+ tracing::info!(lead = %lead.id, context = %snap.context, "a lead stopped before its request was done; asking the person");
+ let question = format!("{} stopped before the job was done: {}. Keep going?", lead.name, first_line(&reply));
+ ask_card(scope, lead, &question, &[KEEP_GOING.into(), ENOUGH.into()], CARD_KEY).await;
+ }
+ return;
+ }
+ tracing::info!(lead = %lead.id, context = %snap.context, turn = used + 1, "a lead's chain stalled; a keep-going turn");
+ snap = snapshot(state, &snap.context, lead).await;
+ match keep_going_turn(scope, lead, used + 1).await {
+ Some(r) => reply = r,
+ None => return,
+ }
+ }
+}
+
+/// One keep-going turn of `lead` in the chat, then its hand-offs. `None` when it failed.
+async fn keep_going_turn(scope: &TurnScope, lead: &Kwant, n: usize) -> Option<String> {
+ let state = &scope.state;
+ let context = scope.context_id(lead);
+ let msgs = state.db.list_messages(&context, 100).await.unwrap_or_default();
+ let mut asked: Vec<&Message> = msgs.iter().rev().filter(|m| m.sender_role == "user").take(QUOTED).collect();
+ asked.reverse();
+ let quoted: Vec<String> = asked.iter().map(|m| format!("> {}", clip(&m.text, QUOTE_CHARS).replace('\n', "\n> "))).collect();
+ let prompt = format!(
+ "[kwnt: {PROMPT}]\n\nThe person's last messages here, oldest first:\n{}\n\n{}",
+ if quoted.is_empty() { "(none)".to_string() } else { quoted.join("\n\n") },
+ super::delegation::handoff_rules(),
+ );
+ let mut opts = TurnOpts::default();
+ opts.label = Some("Keeping the work going".into());
+ opts.extra_meta = Some(json!({ TURN_KEY: n }));
+ opts.failure_meta = Some(json!({ TURN_KEY: n }));
+ opts.purpose = Some("keep_going".into());
+ let reply = try_kwant_turn(scope, lead, prompt, opts).await.ok()?;
+ let user_prompt = asked.last().map(|m| m.text.clone()).unwrap_or_default();
+ super::routes::run_handoffs_boxed(scope, std::slice::from_ref(&lead.id), &[(lead.clone(), reply.clone())], &user_prompt).await;
+ super::asks::consolidate(scope).await;
+ Some(reply)
+}
+
+/// The first line of a reply, for the card: plain, short, without a closing full stop.
+fn first_line(reply: &str) -> String {
+ let line = reply.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("it gave no reply");
+ let line = line.trim_start_matches(['#', '*', '_', '>', '-', ' ']).trim_end_matches(['*', '_', ' ']);
+ clip(line, CARD_LINE_CHARS).trim_end_matches(['.', ':', ' ']).to_string()
+}
+
+fn clip(text: &str, max: usize) -> String {
+ match text.char_indices().nth(max) {
+ Some((at, _)) => format!("{}…", &text[..at]),
+ None => text.to_string(),
+ }
+}
+
+/// Stores the lead's `Done: …` on its newest reply here since `snap`.
+async fn mark_done(state: &AppState, snap: &Snapshot, lead: &Kwant, text: &str) {
+ let msgs = state.db.list_messages(&snap.context, 100).await.unwrap_or_default();
+ let Some(m) = msgs.iter().rev().find(|m| !snap.messages.contains(&m.id) && super::routes::is_reply_by(m, &lead.name)) else {
+ return;
+ };
+ super::asks::set_meta_key(state, m, DONE_KEY, json!({ "text": text, "at": Utc::now() })).await;
+}
+
+/// A question card from `lead` in the scope's chat with no turn waiting on it; its answer comes
+/// back as a new turn (see [`super::questions`]). It replaces the plain "waiting on a reply"
+/// entry the reply left, so the person gets one reminder, for the card.
+async fn ask_card(scope: &TurnScope, lead: &Kwant, question: &str, choices: &[String], key: &str) -> Option<Question> {
+ let state = &scope.state;
+ let direct = match (&scope.channel_id, &scope.thread_id) {
+ (None, None) => Some(scope.kwant_id.clone().unwrap_or_else(|| lead.id.clone())),
+ _ => None,
+ };
+ let place = QuestionPlace {
+ kwant_id: lead.id.clone(),
+ channel_id: scope.channel_id.clone(),
+ direct_kwant_id: direct.clone(),
+ thread_id: scope.thread_id.clone(),
+ turn_id: None,
+ };
+ let question: String = question.chars().take(crate::db::questions::MAX_QUESTION_CHARS).collect();
+ let q = super::questions::ask_without_waiter(state, &place, &lead.name, &question, choices, QuestionReason::default()).await?;
+ if let Some(m) = card_message(state, &q).await {
+ super::asks::set_meta_key(state, &m, key, json!(true)).await;
+ }
+ let _ = state.db.close_plain_waiting(&lead.id, scope.channel_id.as_deref(), direct.as_deref(), scope.thread_id.as_deref()).await;
+ let hours = super::waiting::follow_up_hours(state).await;
+ let item = NewWaitingItem {
+ kwant_id: lead.id.clone(),
+ channel_id: q.channel_id.clone(),
+ direct_kwant_id: q.direct_kwant_id.clone(),
+ thread_id: q.thread_id.clone(),
+ question_id: Some(q.id.clone()),
+ message_id: q.message_id.clone(),
+ question: q.question.clone(),
+ due_at: (hours > 0).then(|| Utc::now() + Duration::hours(hours)),
+ };
+ if matches!(state.db.add_waiting(&item).await, Ok(Some(_))) {
+ state.scheduler_wake.notify_one();
+ }
+ Some(q)
+}
+
+/// The person answered a question kwant asked with no turn waiting. For the "Keep going?" card:
+/// "That's enough for now" ends the chain, anything else starts a keep-going turn (the answer is
+/// already saved as their message, so it has a fresh allowance). `false` for any other card.
+pub(super) async fn on_card_answer(state: &AppState, q: &Question, answer: &str) -> bool {
+ if !card_has(state, q, CARD_KEY).await {
+ return false;
+ }
+ if answer.trim().eq_ignore_ascii_case(ENOUGH) {
+ return true;
+ }
+ let Ok(Some(lead)) = state.db.get_kwant(&q.kwant_id).await else {
+ return true;
+ };
+ let job = state.turns.start_job([q.context_id(), q.id.clone()]);
+ let Ok(scope) = super::routes::scope_for(state, &lead, q.channel_id.clone(), q.thread_id.clone(), &job, 0).await else {
+ return true;
+ };
+ tokio::spawn(async move {
+ let _job = job;
+ let context = scope.context_id(&lead);
+ let snap = snapshot(&scope.state, &context, &lead).await;
+ // The answer is the person's message: a fresh allowance, of which this is the first turn
+ if let Some(reply) = keep_going_turn(&scope, &lead, 1).await {
+ after_lead_turn(&scope, &lead, snap, reply).await;
+ }
+ });
+ true
+}
+
+async fn card_message(state: &AppState, q: &Question) -> Option<Message> {
+ state.db.get_message(q.message_id.as_deref()?).await.ok().flatten()
+}
+
+/// Whether `q`'s card message carries `key` (see [`CARD_KEY`], [`ASK_KEY`]).
+pub(super) async fn card_has(state: &AppState, q: &Question, key: &str) -> bool {
+ card_message(state, q).await.is_some_and(|m| meta_of(&m).get(key).is_some())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_done_line_ends_the_reply() {
+ assert_eq!(done_line("Summary.\n\nDone: checked the cover and the PDF.").as_deref(), Some("checked the cover and the PDF."));
+ assert_eq!(done_line("**Done:** all 3 drafts reviewed\n").as_deref(), Some("all 3 drafts reviewed"));
+ assert_eq!(done_line("- done: tests pass").as_deref(), Some("tests pass"));
+ assert_eq!(done_line("`Done: built`").as_deref(), Some("built"));
+ // Not the last line, empty, or only a word that starts with "done"
+ assert_eq!(done_line("Done: checked it.\nNext I'll draft chapter 2."), None);
+ assert_eq!(done_line("Done:"), None);
+ assert_eq!(done_line("Doneness: fine"), None);
+ assert_eq!(done_line("All done."), None);
+ assert_eq!(done_line(""), None);
+ assert_eq!(done_line("Dön"), None);
+ }
+
+ #[test]
+ fn the_card_quotes_a_plain_first_line() {
+ assert_eq!(first_line("\n## Passed Builder's floor-dot task.\nMore."), "Passed Builder's floor-dot task");
+ assert_eq!(first_line(""), "it gave no reply");
+ assert!(first_line(&"x".repeat(400)).chars().count() <= CARD_LINE_CHARS + 1);
+ }
+
+ #[test]
+ fn the_prompt_names_the_three_ends() {
+ assert!(PROMPT.contains("hand it on or do it yourself"));
+ assert!(PROMPT.contains("`Done: …`"));
+ assert!(PROMPT.contains("question tool"));
+ }
+}
diff --git a/src/server/mod.rs b/src/server/mod.rs
index e6309f24..9e987d54 100644
--- a/src/server/mod.rs
+++ b/src/server/mod.rs
@@ -23,6 +23,7 @@ pub mod bot_budget;
pub mod scheduler;
pub mod turns;
pub mod delegation;
+pub mod keep_going;
pub mod parked;
pub mod attachments;
pub mod picture_claims;
diff --git a/src/server/questions.rs b/src/server/questions.rs
index 1291c9e3..257528e3 100644
--- a/src/server/questions.rs
+++ b/src/server/questions.rs
@@ -128,7 +128,15 @@ async fn save_message(state: &AppState, q: &Question, role: &str, sender: &str,
/// Sends `question_updated` and refreshes the question's card in the chat.
async fn changed(state: &AppState, q: &Question) {
if let Some(mid) = &q.message_id {
- let _ = state.db.set_message_meta(mid, &card_meta(q)).await;
+ let mut meta = card_meta(q);
+ // Keys kwnt added to the card (a keep-going card's marker) outlive its answer
+ let old = state.db.get_message(mid).await.ok().flatten().and_then(|m| serde_json::from_str::<Value>(m.meta.as_deref()?).ok());
+ if let (Some(Value::Object(old)), Some(new)) = (old, meta.as_object_mut()) {
+ for (k, v) in old {
+ new.entry(k).or_insert(v);
+ }
+ }
+ let _ = state.db.set_message_meta(mid, &meta).await;
}
let _ = state.event_sender.send(RuntimeEvent::QuestionUpdated { question: serde_json::to_value(q).unwrap_or(Value::Null) });
}
@@ -439,8 +447,12 @@ pub async fn answer_via(state: &AppState, id: &str, text: &str, via: Option<&str
Some(tx) => tx.send(Reply::Answer(text.clone())).is_ok(),
None => false,
};
- // A Dev mode brief's question has no turn behind it: the brief takes the answer instead
- if !live && !super::dev::tickets::hooks::on_question(state, &q, Some(&text), "card").await {
+ // A Dev mode brief's question has no turn behind it: the brief takes the answer instead; the
+ // "Keep going?" card starts a keep-going turn (or ends the chain)
+ if !live
+ && !super::keep_going::on_card_answer(state, &q, &text).await
+ && !super::dev::tickets::hooks::on_question(state, &q, Some(&text), "card").await
+ {
resume(state, &q, &text).await;
}
Some((q, live))
@@ -483,13 +495,29 @@ async fn resume(state: &AppState, q: &Question, answer: &str) {
}
}
let depth = delegation.map(|d| d.depth).unwrap_or(0);
+ // A card kwant made from a lead's prose question: the lead's chain goes on from the answer
+ let in_chat = q.thread_id.is_none();
+ let chain = in_chat && super::keep_going::card_has(state, q, super::keep_going::ASK_KEY).await;
let job = state.turns.start_job([q.context_id(), q.id.clone()]);
let Ok(scope) = scope_for(state, &kwant, q.channel_id.clone(), q.thread_id.clone(), &job, depth).await else {
return;
};
+ let answer = answer.to_string();
tokio::spawn(async move {
let _job = job;
- let _ = try_kwant_turn(&scope, &kwant, prompt, TurnOpts::default()).await;
+ let snap = super::keep_going::snapshot(&scope.state, &scope.context_id(&kwant), &kwant).await;
+ let Ok(reply) = try_kwant_turn(&scope, &kwant, prompt, TurnOpts::default()).await else {
+ return;
+ };
+ // Like any reply in a person's chat: an @mention hands on (a late answer used to end
+ // there, so a lead's "@Writer, go ahead" after it did nothing)
+ if in_chat {
+ super::routes::run_handoffs_boxed(&scope, std::slice::from_ref(&kwant.id), &[(kwant.clone(), reply.clone())], &answer).await;
+ super::asks::consolidate(&scope).await;
+ }
+ if chain {
+ super::keep_going::after_lead_turn(&scope, &kwant, snap, reply).await;
+ }
});
}
diff --git a/tests/auditor_test.rs b/tests/auditor_test.rs
index 3a7b7078..83b2b634 100644
--- a/tests/auditor_test.rs
+++ b/tests/auditor_test.rs
@@ -44,6 +44,8 @@ async fn setup() -> Env {
let tmp = tempdir().unwrap();
let data = tmp.path().join("data");
let db = Database::init(&data).await.unwrap();
+ // These chains predate keep-going turns; a stalled lead isn't nudged here.
+ db.set_setting("keep_going_turns", "0").await.unwrap();
let config = Config {
data_dir: data.clone(),
laya_url: "http://127.0.0.1:9".into(),
diff --git a/tests/away_test.rs b/tests/away_test.rs
index d8edbe34..c4445422 100644
--- a/tests/away_test.rs
+++ b/tests/away_test.rs
@@ -31,6 +31,8 @@ const SECRET: &str = "sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123456789";
async fn setup() -> (Router, AppState, TempDir) {
let tmp = tempdir().unwrap();
let db = Database::init(tmp.path()).await.unwrap();
+ // These chains predate keep-going turns; a stalled lead isn't nudged here.
+ db.set_setting("keep_going_turns", "0").await.unwrap();
// Start from an asking install (a fresh one asks only when risky)
db.set_space_approvals(&kwnt::db::spaces::SpaceId::default_space(), "ask").await.unwrap();
let config = Config {
diff --git a/tests/chain_budget_test.rs b/tests/chain_budget_test.rs
index 903c7d6f..9648237d 100644
--- a/tests/chain_budget_test.rs
+++ b/tests/chain_budget_test.rs
@@ -82,6 +82,8 @@ async fn setup() -> Env {
fake_cli();
let tmp = tempfile::tempdir().unwrap();
let db = Database::init(tmp.path()).await.unwrap();
+ // These chains predate keep-going turns; a stalled lead isn't nudged here.
+ db.set_setting("keep_going_turns", "0").await.unwrap();
let config = Config {
data_dir: tmp.path().to_path_buf(),
laya_url: "http://127.0.0.1:9".into(),
diff --git a/tests/chain_order_test.rs b/tests/chain_order_test.rs
index 8a826f40..6ad3fc9a 100644
--- a/tests/chain_order_test.rs
+++ b/tests/chain_order_test.rs
@@ -143,6 +143,8 @@ async fn setup() -> Env {
let db = Database::init(&data).await.unwrap();
// These turns predate the mission board, which is now on by default; keep it off here.
db.set_setting("mission_board", "false").await.unwrap();
+ // These chains predate keep-going turns; a stalled lead isn't nudged here.
+ db.set_setting("keep_going_turns", "0").await.unwrap();
// Laya is unreachable: turns use the kwant's preferred model, the fake claude
let config = Config {
data_dir: data.clone(),
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index f559dfc7..786c3fca 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -219,6 +219,8 @@ pub async fn setup_with(change: impl FnOnce(&mut AppState)) -> Env {
let tmp = tempfile::tempdir().unwrap();
let data = tmp.path().join("data");
let db = Database::init(&data).await.unwrap();
+ // These chains predate keep-going turns; a stalled lead isn't nudged here.
+ db.set_setting("keep_going_turns", "0").await.unwrap();
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port = listener.local_addr().unwrap().port();
let config = Config {
diff --git a/tests/delegation_test.rs b/tests/delegation_test.rs
index 5edd65ff..707486b8 100644
--- a/tests/delegation_test.rs
+++ b/tests/delegation_test.rs
@@ -137,6 +137,8 @@ async fn setup() -> Env {
let db = Database::init(&data).await.unwrap();
// These turns predate the mission board, which is now on by default; keep it off here.
db.set_setting("mission_board", "false").await.unwrap();
+ // These chains predate keep-going turns; a stalled lead isn't nudged here.
+ db.set_setting("keep_going_turns", "0").await.unwrap();
// Laya is unreachable: turns use the kwant's preferred model, the fake claude
let config = Config {
data_dir: data.clone(),
@@ -182,6 +184,37 @@ where
panic!("timed out waiting for {what}");
}
+/// [`wait_for`] that, when it times out, shows what happened in `channel` (its messages and the
+/// lead's hand-offs from it), so a failure on CI says where the chain stopped.
+async fn wait_or_dump<F, Fut>(env: &Env, channel: &str, what: &str, mut check: F)
+where
+ F: FnMut() -> Fut,
+ Fut: std::future::Future<Output = bool>,
+{
+ for _ in 0..300 {
+ if check().await {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ let msgs: Vec<String> = channel_messages(env, channel)
+ .await
+ .iter()
+ .map(|m| format!("{:?} {}/{} [{}] {}", m.created_at, m.sender_role, m.sender_id, meta_kind(m).unwrap_or_default(), m.text.chars().take(160).collect::<String>()))
+ .collect();
+ let handoffs: Vec<String> = env
+ .state
+ .db
+ .list_delegations(Some(&env.lead), None, 12)
+ .await
+ .unwrap_or_default()
+ .iter()
+ .filter(|d| d.origin_channel_id.as_deref() == Some(channel))
+ .map(|d| format!("{} {:?}..{:?} {} → {} “{}”", d.status, d.created_at, d.ended_at, d.id, d.specialist_kwant_id, d.title))
+ .collect();
+ panic!("timed out waiting for {what}\nmessages:\n{}\nhand-offs (newest first):\n{}", msgs.join("\n"), handoffs.join("\n"));
+}
+
async fn delegation_status(env: &Env, id: &str) -> String {
let (_, d) = call(&env.app, "GET", &format!("/api/delegations/{id}"), None).await;
d["status"].as_str().unwrap_or("").to_string()
@@ -1704,10 +1737,20 @@ async fn the_65th_hand_off_pauses_and_continue_sends_it_once() {
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 lead hears part 2 before the next round starts, so that round is the only one running
+ let lead = name(&env, &env.lead).await;
+ let part2 = ds[1].id.clone();
+ let reported = || async {
+ let msgs = channel_messages(&env, &channel).await;
+ let result = msgs.iter().position(|m| meta_kind(m).as_deref() == Some("delegation_result") && meta_of(m)["delegation_id"] == part2.as_str());
+ result.is_some_and(|at| msgs[at..].iter().any(|m| m.sender_role == "kwant" && m.sender_id == lead))
+ };
+ wait_or_dump(&env, &channel, "the lead's turn with part 2", || async { reported().await }).await;
+
// 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;
+ wait_or_dump(&env, &channel, "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 = 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");
@@ -1716,6 +1759,64 @@ async fn the_65th_hand_off_pauses_and_continue_sends_it_once() {
assert_eq!(meta_of(&notices[0])["resumed"], json!(true));
}
+/// A result whose report runs after the lead already started the next hand-off still reaches
+/// the lead. The next one, still running, began after this one ended, so it isn't part of its
+/// batch: it used to hold the report back, and its own batch doesn't reach back to this one, so
+/// the lead never heard this result (CI, 2026-11-12: the next round started while a result was
+/// still being posted).
+#[tokio::test]
+async fn a_result_reported_after_the_next_hand_off_started_still_reaches_the_lead() {
+ let env = setup().await;
+ let channel = team_channel_with(&env, "race", &[&env.lead, &env.specialist]).await;
+ // The first one ended; its report waits for the lead's turn that started it
+ let (_, first) = 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: "Racemark first REPLYTAG:racefirst".into(),
+ title: "Racemark first".into(),
+ continue_lead: true,
+ depth: 1,
+ follow_up_at: None,
+ })
+ .await
+ .unwrap();
+ env.state.db.set_delegation_lead_turn(&first.id, "racemark-turn").await.unwrap();
+ assert!(env.state.db.finish_delegation(&first.id, "completed", None, None).await.unwrap());
+ // Before it is reported, the lead hands on the next one, which keeps running
+ let release = env.release_file("racemark-next");
+ let next = delegate_from(&env, &channel, &env.specialist, &format!("Racemark next LONGTASK:{} REPLYTAG:racenext", release.display()), "Racemark next").await;
+ assert!(["queued", "running"].contains(&delegation_status(&env, &next).await.as_str()));
+ // Now the first one's report runs (its lead turn ended; a restart cut it short here)
+ let turn = kwnt::db::continuity::RunningTurn {
+ turn_id: "racemark-turn".into(),
+ kwant_id: env.lead.clone(),
+ kwant_name: name(&env, &env.lead).await,
+ channel_id: Some(channel.clone()),
+ direct_kwant_id: None,
+ thread_id: None,
+ started_at: chrono::Utc::now(),
+ };
+ delegation::release_cut_short(&env.state, &[turn]).await;
+ wait_or_dump(&env, &channel, "the lead's turn with the first result", || async {
+ !prompts_with("finished the task you delegated (“Racemark first”)").is_empty()
+ })
+ .await;
+ // The next one reports on its own when it ends
+ std::fs::write(&release, "").unwrap();
+ wait_for("the next one", || async { delegation_status(&env, &next).await == "completed" }).await;
+ wait_or_dump(&env, &channel, "the lead's turn with the next result", || async {
+ !prompts_with("finished the task you delegated (“Racemark next”)").is_empty()
+ })
+ .await;
+}
+
/// A call to kwnt's own tools as the agent turn that holds `token`, as its CLI makes it.
async fn self_tool(env: &Env, token: &str, name: &str, args: Value) -> (String, bool) {
let resp = env
diff --git a/tests/handoff_continue_test.rs b/tests/handoff_continue_test.rs
index c5dec11b..00a5cee8 100644
--- a/tests/handoff_continue_test.rs
+++ b/tests/handoff_continue_test.rs
@@ -101,6 +101,8 @@ async fn setup() -> Env {
let tmp = tempfile::tempdir().unwrap();
let data = tmp.path().join("data");
let db = Database::init(&data).await.unwrap();
+ // These chains predate keep-going turns; a stalled lead isn't nudged here.
+ db.set_setting("keep_going_turns", "0").await.unwrap();
// Laya is unreachable: turns use the kwant's preferred model, the fake claude
let config = Config {
data_dir: data.clone(),
diff --git a/tests/handoff_folder_test.rs b/tests/handoff_folder_test.rs
index 51fb0ac0..c7a439e2 100644
--- a/tests/handoff_folder_test.rs
+++ b/tests/handoff_folder_test.rs
@@ -78,6 +78,8 @@ async fn setup() -> Env {
let tmp = tempfile::tempdir().unwrap();
let data = tmp.path().join("data");
let db = Database::init(&data).await.unwrap();
+ // These chains predate keep-going turns; a stalled lead isn't nudged here.
+ db.set_setting("keep_going_turns", "0").await.unwrap();
let config = Config {
data_dir: data.clone(),
laya_url: "http://127.0.0.1:9".into(),
diff --git a/tests/handoff_review_test.rs b/tests/handoff_review_test.rs
index cfbc18c2..2ac5c635 100644
--- a/tests/handoff_review_test.rs
+++ b/tests/handoff_review_test.rs
@@ -96,6 +96,8 @@ async fn setup() -> Env {
let tmp = tempfile::tempdir().unwrap();
let data = tmp.path().join("data");
let db = Database::init(&data).await.unwrap();
+ // These chains predate keep-going turns; a stalled lead isn't nudged here.
+ db.set_setting("keep_going_turns", "0").await.unwrap();
// Laya is unreachable: turns use the kwant's preferred model, the fake claude
let config = Config {
data_dir: data.clone(),
diff --git a/tests/inbox_test.rs b/tests/inbox_test.rs
index 6f699bec..e3cb2d5c 100644
--- a/tests/inbox_test.rs
+++ b/tests/inbox_test.rs
@@ -28,6 +28,8 @@ use tower::ServiceExt;
async fn setup() -> (Router, AppState, TempDir) {
let tmp = tempdir().unwrap();
let db = Database::init(tmp.path()).await.unwrap();
+ // These chains predate keep-going turns; a stalled lead isn't nudged here.
+ db.set_setting("keep_going_turns", "0").await.unwrap();
let config = Config {
data_dir: tmp.path().to_path_buf(),
..Config::default()
diff --git a/tests/keep_going_test.rs b/tests/keep_going_test.rs
new file mode 100644
index 00000000..bc6085c3
--- /dev/null
+++ b/tests/keep_going_test.rs
@@ -0,0 +1,555 @@
+//! Keep going (0.9.2): a lead's chain never just stops after its results turn. A scripted fake
+//! claude CLI replies from per-test queue files, so each test says what the lead answers on each
+//! results turn and each keep-going turn. Its own test binary: it changes PATH.
+
+#[path = "common/exe.rs"]
+mod exe;
+
+use axum::{
+ body::{to_bytes, Body},
+ http::{Request, StatusCode},
+ Router,
+};
+use kwnt::{
+ broker::PermissionBroker,
+ config::Config,
+ db::{models::Message, Database},
+ router::LayaRouter,
+ server::{create_router, delegation, keep_going, AppState},
+ tools::ToolRunner,
+};
+use serde_json::{json, Value};
+use std::path::PathBuf;
+use std::sync::OnceLock;
+use std::time::Duration;
+use tower::ServiceExt;
+
+/// The person's message carries "SCRIPT:<dir>" (and delegation titles repeat it, so the results
+/// prompt has it too). A prompt is a keep-going turn ("isn't marked done", queue `<dir>/kg`), a
+/// lead's results turn ("finished the task you delegated" / "tasks you delegated have ended",
+/// queue `<dir>/res`), or anything else (the lead's first turn, a teammate's task, a turn on an
+/// answer), which replies "ok"; a teammate's task with "SPECHOLD:<file>" waits for that file
+/// first. Each queue line is one reply (`\n` for a line break); an empty queue replies "Here is
+/// where things stand.". A line "HOLD:<file> <reply>" waits for the file, then replies. Every
+/// prompt is saved as `<dir>/prompts/<kind>-…`.
+const FAKE_CLAUDE: &str = r#"#!/bin/sh
+case "$1" in
+ auth) echo '{"loggedIn":true}'; exit 0 ;;
+esac
+for a; do last="$a"; done
+dir=$(printf '%s\n' "$last" | sed -n 's/.*SCRIPT:\([^ ]*\).*/\1/p' | head -n 1)
+kind=other
+case "$last" in
+ *"isn't marked done"*) kind=kg ;;
+ *"finished the task you delegated"*|*"tasks you delegated have ended"*) kind=res ;;
+esac
+if [ -n "$dir" ]; then
+ mkdir -p "$dir/prompts"
+ printf '%s' "$last" > "$dir/prompts/$kind-$(date +%s%N)-$$"
+fi
+out="ok"
+if [ "$kind" = other ]; then
+ hold=$(printf '%s\n' "$last" | sed -n 's/.*SPECHOLD:\([^ ]*\).*/\1/p' | head -n 1)
+ if [ -n "$hold" ]; then
+ i=0
+ while [ ! -f "$hold" ] && [ $i -lt 600 ]; do sleep 0.1; i=$((i+1)); done
+ fi
+elif [ -n "$dir" ] && [ -s "$dir/$kind" ]; then
+ out=$(head -n 1 "$dir/$kind")
+ tail -n +2 "$dir/$kind" > "$dir/$kind.rest"
+ mv "$dir/$kind.rest" "$dir/$kind"
+else
+ out="Here is where things stand."
+fi
+case "$out" in
+ HOLD:*)
+ f=${out#HOLD:}; f=${f%% *}; out=${out#HOLD:* }
+ i=0
+ while [ ! -f "$f" ] && [ $i -lt 600 ]; do sleep 0.1; i=$((i+1)); done
+ ;;
+esac
+printf '{"type":"result","is_error":false,"num_turns":1,"result":"%s"}\n' "$out"
+"#;
+
+fn fake_on_path() {
+ static DONE: OnceLock<()> = OnceLock::new();
+ DONE.get_or_init(|| {
+ let root = tempfile::tempdir().unwrap().keep();
+ let bin = root.join("bin");
+ std::fs::create_dir_all(&bin).unwrap();
+ exe::write_executable(bin.join("claude"), FAKE_CLAUDE);
+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));
+ });
+}
+
+async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {
+ let resp = app
+ .clone()
+ .oneshot(
+ Request::builder()
+ .method(method)
+ .uri(uri)
+ .header("content-type", "application/json")
+ .body(body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty))
+ .unwrap(),
+ )
+ .await
+ .unwrap();
+ let s = resp.status();
+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
+ (s, serde_json::from_slice(&bytes).unwrap_or(Value::Null))
+}
+
+struct Env {
+ app: Router,
+ state: AppState,
+ lead: String,
+ lead_name: String,
+ checker: String,
+ channel: String,
+ tmp: tempfile::TempDir,
+}
+
+impl Env {
+ fn script(&self) -> PathBuf {
+ self.tmp.path().join("script")
+ }
+
+ fn file(&self, name: &str) -> PathBuf {
+ self.tmp.path().join(name)
+ }
+
+ /// What the lead answers on its results turns (`res`) and keep-going turns (`kg`), in order.
+ fn queue(&self, kind: &str, lines: &[&str]) {
+ let mut text = lines.join("\n");
+ text.push('\n');
+ std::fs::write(self.script().join(kind), text).unwrap();
+ }
+
+ /// The prompts the fake got of `kind`, oldest first.
+ fn prompts(&self, kind: &str) -> Vec<String> {
+ let Ok(dir) = std::fs::read_dir(self.script().join("prompts")) else { return Vec::new() };
+ let mut files: Vec<PathBuf> = dir
+ .filter_map(|e| e.ok().map(|e| e.path()))
+ .filter(|p| p.file_name().and_then(|n| n.to_str()).is_some_and(|n| n.starts_with(&format!("{kind}-"))))
+ .collect();
+ files.sort();
+ files.iter().filter_map(|p| std::fs::read_to_string(p).ok()).collect()
+ }
+
+ fn marker(&self) -> String {
+ format!("SCRIPT:{} ", self.script().display())
+ }
+}
+
+/// A team led by the first built-in bot, with a new teammate "Checker", in its own channel.
+async fn setup() -> Env {
+ fake_on_path();
+ let tmp = tempfile::tempdir().unwrap();
+ let data = tmp.path().join("data");
+ let db = Database::init(&data).await.unwrap();
+ db.set_setting("mission_board", "false").await.unwrap();
+ let config = Config {
+ data_dir: data.clone(),
+ laya_url: "http://127.0.0.1:9".into(),
+ browser_cdp_url: Some("http://127.0.0.1:9".into()),
+ ..Config::default()
+ };
+ let state = AppState::new(config.clone(), db, ToolRunner::new(data.join("workspace")), PermissionBroker::new(), LayaRouter::new(config.laya_url.clone()));
+ let app = create_router(state.clone());
+ let (_, kwants) = call(&app, "GET", "/api/kwants", None).await;
+ let k = kwants.as_array().unwrap()[0].clone();
+ let lead = k["id"].as_str().unwrap().to_string();
+ let lead_name = k["name"].as_str().unwrap().to_string();
+ let mut body = k.clone();
+ body.as_object_mut().unwrap().retain(|key, _| ["name", "title", "persona_prompt", "soul", "avatar_sprite"].contains(&key.as_str()));
+ body["preferred_model"] = json!("claude");
+ let (s, v) = call(&app, "PUT", &format!("/api/kwants/{lead}"), Some(body)).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let (s, v) = call(&app, "POST", "/api/kwants", Some(json!({"name": "Checker", "title": "Reviewer", "persona_prompt": "", "soul": "", "avatar_sprite": "default", "driver_type": "cli", "preferred_model": "claude"}))).await;
+ assert!(s.is_success(), "{s} {v}");
+ let checker = v["id"].as_str().or(v["kwant"]["id"].as_str()).unwrap().to_string();
+ let (s, v) = call(&app, "POST", "/api/teams", Some(json!({"name": "keep", "lead_kwant_id": lead, "member_kwants": [lead, checker]}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ let (_, channels) = call(&app, "GET", "/api/channels", None).await;
+ let channel = channels.as_array().unwrap().iter().find(|c| c["name"] == "team-keep").unwrap()["id"].as_str().unwrap().to_string();
+ let env = Env { app, state, lead, lead_name, checker, channel, tmp };
+ std::fs::create_dir_all(env.script()).unwrap();
+ env
+}
+
+async fn wait_for<F, Fut>(what: &str, mut check: F)
+where
+ F: FnMut() -> Fut,
+ Fut: std::future::Future<Output = bool>,
+{
+ for _ in 0..300 {
+ if check().await {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(100)).await;
+ }
+ panic!("timed out waiting for {what}");
+}
+
+/// No turn has run for a second: the chain has settled.
+async fn settled(env: &Env) {
+ let mut quiet = 0;
+ for _ in 0..300 {
+ let (_, t) = call(&env.app, "GET", "/api/turns", None).await;
+ let busy = t["turns"].as_array().is_some_and(|a| !a.is_empty());
+ quiet = if busy { 0 } else { quiet + 1 };
+ if quiet >= 5 {
+ return;
+ }
+ tokio::time::sleep(Duration::from_millis(200)).await;
+ }
+ panic!("turns kept running");
+}
+
+async fn messages(env: &Env) -> Vec<Message> {
+ env.state.db.list_messages(&env.channel, 200).await.unwrap()
+}
+
+fn meta_of(m: &Message) -> Value {
+ serde_json::from_str(m.meta.as_deref().unwrap_or("null")).unwrap_or(Value::Null)
+}
+
+fn lead_replies<'a>(env: &Env, msgs: &'a [Message]) -> Vec<&'a Message> {
+ msgs.iter().filter(|m| m.sender_role == "kwant" && (m.sender_id == env.lead_name || m.sender_id == env.lead)).collect()
+}
+
+/// The person asks the lead in the team channel, and the lead's first turn answers.
+async fn person_asks(env: &Env, text: &str) {
+ let prompt = format!("@{} {text} {}please", env.lead_name, env.marker());
+ let (s, v) = call(&env.app, "POST", "/api/chat/send", Some(json!({"channel_id": env.channel, "prompt": prompt, "sender_id": "user"}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ wait_for("the lead's first answer", || async { messages(env).await.iter().any(|m| m.sender_role == "kwant" && m.text == "ok") }).await;
+}
+
+/// A hand-off from the lead to Checker from the team channel (resuming the lead when it ends,
+/// unless `resumes` is false); returns its id.
+async fn hand_off(env: &Env, task: &str, resumes: bool) -> String {
+ let (s, d) = call(
+ &env.app,
+ "POST",
+ "/api/delegations",
+ Some(json!({
+ "lead_kwant_id": env.lead,
+ "specialist_kwant_id": env.checker,
+ "task": task,
+ "title": format!("Check {}", env.marker()),
+ "channel_id": env.channel,
+ "continue_lead": resumes,
+ })),
+ )
+ .await;
+ assert_eq!(s, StatusCode::ACCEPTED, "{d}");
+ d["id"].as_str().unwrap().to_string()
+}
+
+async fn delegations(env: &Env) -> Vec<kwnt::db::threads::Delegation> {
+ env.state.db.list_delegations(Some(&env.lead), None, 200).await.unwrap()
+}
+
+async fn open_questions(env: &Env) -> Vec<kwnt::db::questions::Question> {
+ env.state.db.list_questions(Some("open"), Some(&env.channel), None).await.unwrap()
+}
+
+async fn card_meta(env: &Env, q: &kwnt::db::questions::Question) -> Value {
+ let m = env.state.db.get_message(q.message_id.as_deref().unwrap()).await.unwrap().unwrap();
+ meta_of(&m)
+}
+
+async fn answer(env: &Env, q: &str, text: &str) {
+ let (s, v) = call(&env.app, "POST", &format!("/api/questions/{q}/answer"), Some(json!({"text": text}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+}
+
+/// The case from Oleks's video: the lead's results turn says "Passed …" and stops. kwnt gives it
+/// a keep-going turn that quotes the person's message; its @mention goes out as a hand-off, and
+/// the next results turn ends with `Done:`, which is stored and ends the chain.
+#[tokio::test]
+async fn a_stalled_lead_gets_a_keep_going_turn_and_its_mention_goes_out() {
+ let env = setup().await;
+ env.queue("res", &["Passed Checker's floor-dot task.", "Both parts look right.\\nDone: checked part 1 and part 2 against the brief."]);
+ env.queue("kg", &["@Checker, please check part 2 KGMARK."]);
+ person_asks(&env, "Build the level, both parts.").await;
+ hand_off(&env, "Check part 1", true).await;
+ wait_for("the second hand-off", || async { delegations(&env).await.len() == 2 }).await;
+ settled(&env).await;
+
+ let kg = env.prompts("kg");
+ assert_eq!(kg.len(), 1, "one keep-going turn");
+ assert!(kg[0].contains(keep_going::PROMPT), "{}", kg[0]);
+ assert!(kg[0].contains("> @"), "it quotes the person: {}", kg[0]);
+ assert!(kg[0].contains("Build the level, both parts."), "{}", kg[0]);
+ assert!(kg[0].contains("End every reply in one of three ways"), "{}", kg[0]);
+ let second = delegations(&env).await.into_iter().find(|d| d.task.contains("KGMARK")).expect("the keep-going turn's mention is a hand-off");
+ assert_eq!(second.specialist_kwant_id, env.checker);
+ assert_eq!(second.origin_channel_id.as_deref(), Some(env.channel.as_str()));
+ assert_eq!(second.status, "completed");
+
+ let msgs = messages(&env).await;
+ let replies = lead_replies(&env, &msgs);
+ let texts: Vec<&str> = replies.iter().map(|m| m.text.as_str()).collect();
+ let passed = texts.iter().position(|t| t.starts_with("Passed")).expect("the review line");
+ let nudged = replies.iter().position(|m| meta_of(m)[keep_going::TURN_KEY] == 1).expect("the keep-going reply");
+ assert!(passed < nudged, "the review line isn't where the chat stops: {texts:?}");
+ let last = replies.last().unwrap();
+ assert_eq!(meta_of(last)[keep_going::DONE_KEY]["text"], "checked part 1 and part 2 against the brief.");
+ assert!(open_questions(&env).await.is_empty(), "no card");
+ // The results prompt no longer asks for one final answer
+ let res = env.prompts("res");
+ assert_eq!(res.len(), 2);
+ assert!(res.iter().all(|p| !p.contains("one answer") && !p.contains("one final answer")), "{}", res[0]);
+ assert!(res.iter().all(|p| p.contains("needs no approval unless the person asked")), "{}", res[0]);
+}
+
+/// A results turn that ends with `Done: …` ends the chain: the marker is stored, no keep-going turn.
+#[tokio::test]
+async fn a_done_line_is_stored_and_needs_no_keep_going_turn() {
+ let env = setup().await;
+ env.queue("res", &["All three checks pass.\\n**Done:** checked the build, the tests and the copy"]);
+ person_asks(&env, "Check the release.").await;
+ let id = hand_off(&env, "Run the checks", true).await;
+ wait_for("the results turn", || async { !env.prompts("res").is_empty() }).await;
+ settled(&env).await;
+ assert!(env.prompts("kg").is_empty());
+ let msgs = messages(&env).await;
+ let done = lead_replies(&env, &msgs).into_iter().find(|m| m.text.starts_with("All three")).expect("the reply");
+ assert_eq!(meta_of(done)[keep_going::DONE_KEY]["text"], "checked the build, the tests and the copy");
+ assert!(open_questions(&env).await.is_empty());
+ assert_eq!(delegations(&env).await.iter().map(|d| d.id.as_str()).collect::<Vec<_>>(), vec![id.as_str()]);
+}
+
+/// The lead asked with the question tool (an open card in the chat): it waits on the person, so
+/// no keep-going turn and no second card.
+#[tokio::test]
+async fn asking_with_the_question_tool_needs_no_keep_going_turn() {
+ let env = setup().await;
+ let release = env.file("asked");
+ std::fs::write(env.script().join("res"), format!("HOLD:{} I asked you which cover to use.\n", release.display())).unwrap();
+ person_asks(&env, "Make the cover.").await;
+ hand_off(&env, "Draft two covers", true).await;
+ wait_for("the results turn", || async { !env.prompts("res").is_empty() }).await;
+ // The lead's question card, as its ask tool leaves it, while the turn runs
+ let place = kwnt::db::questions::QuestionPlace { kwant_id: env.lead.clone(), channel_id: Some(env.channel.clone()), direct_kwant_id: None, thread_id: None, turn_id: None };
+ env.state.db.create_question(&place, "Cover A or cover B?", &["A".into(), "B".into()]).await.unwrap();
+ std::fs::write(&release, "go").unwrap();
+ settled(&env).await;
+ assert!(env.prompts("kg").is_empty());
+ let open = open_questions(&env).await;
+ assert_eq!(open.len(), 1, "only the lead's own card: {open:?}");
+ assert_eq!(open[0].question, "Cover A or cover B?");
+}
+
+/// A reply whose last line asks the person in prose (something only they can approve, so the
+/// decide-first round doesn't take it) becomes a question card at once, with no keep-going turn. Its answer resumes the chain: the lead's turn on it stalls, so it gets a
+/// keep-going turn, which ends with `Done:`.
+#[tokio::test]
+async fn a_prose_question_becomes_a_card_and_its_answer_keeps_the_chain_going() {
+ let env = setup().await;
+ env.queue("res", &["Cover A is ready.\\nShould I publish cover A on the store now?"]);
+ env.queue("kg", &["Published cover A.\\nDone: published cover A and checked the store page."]);
+ person_asks(&env, "Make the cover.").await;
+ hand_off(&env, "Draft two covers", true).await;
+ wait_for("the card", || async { !open_questions(&env).await.is_empty() }).await;
+ settled(&env).await;
+ assert!(env.prompts("kg").is_empty(), "a question waits on the person");
+ let open = open_questions(&env).await;
+ assert_eq!(open.len(), 1);
+ assert_eq!(open[0].question, "Should I publish cover A on the store now?");
+ assert_eq!(card_meta(&env, &open[0]).await[keep_going::ASK_KEY], true);
+ // One reminder, for the card (the reply's plain "waiting on a reply" entry is closed)
+ let waiting = env.state.db.list_waiting(None).await.unwrap();
+ let live: Vec<_> = waiting.iter().filter(|w| w.kwant_id == env.lead && w.status != "closed").collect();
+ assert_eq!(live.len(), 1, "{waiting:?}");
+ assert_eq!(live[0].question_id.as_deref(), Some(open[0].id.as_str()));
+
+ answer(&env, &open[0].id, "Yes, publish it").await;
+ wait_for("the keep-going turn after the answer", || async { !env.prompts("kg").is_empty() }).await;
+ settled(&env).await;
+ assert_eq!(env.prompts("kg").len(), 1);
+ let msgs = messages(&env).await;
+ let last = *lead_replies(&env, &msgs).last().unwrap();
+ assert_eq!(meta_of(last)[keep_going::DONE_KEY]["text"], "published cover A and checked the store page.");
+ assert!(open_questions(&env).await.is_empty());
+}
+
+/// Two keep-going turns that still hand nothing on: one "Keep going?" card, never a second.
+/// "Keep going" is a person message: a fresh allowance and a keep-going turn at once.
+#[tokio::test]
+async fn two_silent_keep_going_turns_end_in_one_card_and_keep_going_starts_another() {
+ let env = setup().await;
+ env.queue("res", &["Passed Checker's draft."]);
+ env.queue("kg", &["Still looking at the draft.", "Reading it once more.", "Finished the last pass.\\nDone: checked the whole draft."]);
+ person_asks(&env, "Write the chapter.").await;
+ hand_off(&env, "Draft chapter 1", true).await;
+ wait_for("the card", || async { !open_questions(&env).await.is_empty() }).await;
+ settled(&env).await;
+ assert_eq!(env.prompts("kg").len(), 2, "the allowance is 2 turns");
+ let open = open_questions(&env).await;
+ assert_eq!(open.len(), 1);
+ let lead = env.lead_name.clone();
+ assert_eq!(open[0].question, format!("{lead} stopped before the job was done: Reading it once more. Keep going?"));
+ assert_eq!(open[0].choice_list(), vec![keep_going::KEEP_GOING.to_string(), keep_going::ENOUGH.to_string()]);
+ assert_eq!(card_meta(&env, &open[0]).await[keep_going::CARD_KEY], true);
+ let msgs = messages(&env).await;
+ let turns: Vec<Value> = lead_replies(&env, &msgs).iter().map(|m| meta_of(m)[keep_going::TURN_KEY].clone()).filter(|v| !v.is_null()).collect();
+ assert_eq!(turns, vec![json!(1), json!(2)]);
+
+ answer(&env, &open[0].id, keep_going::KEEP_GOING).await;
+ wait_for("the third keep-going turn", || async { env.prompts("kg").len() == 3 }).await;
+ settled(&env).await;
+ assert_eq!(env.prompts("kg").len(), 3);
+ let msgs = messages(&env).await;
+ let last = *lead_replies(&env, &msgs).last().unwrap();
+ assert_eq!(meta_of(last)[keep_going::TURN_KEY], 1, "a fresh allowance");
+ assert_eq!(meta_of(last)[keep_going::DONE_KEY]["text"], "checked the whole draft.");
+ let cards = env.state.db.list_questions(None, Some(&env.channel), None).await.unwrap();
+ assert_eq!(cards.len(), 1, "never a second card: {cards:?}");
+}
+
+/// "That's enough for now" ends the chain: no keep-going turn.
+#[tokio::test]
+async fn thats_enough_for_now_ends_the_chain() {
+ let env = setup().await;
+ env.queue("res", &["Passed Checker's draft."]);
+ env.queue("kg", &["Still looking.", "Still looking.", "SHOULD NOT RUN"]);
+ person_asks(&env, "Write the chapter.").await;
+ hand_off(&env, "Draft chapter 1", true).await;
+ wait_for("the card", || async { !open_questions(&env).await.is_empty() }).await;
+ settled(&env).await;
+ let q = open_questions(&env).await.remove(0);
+ answer(&env, &q.id, keep_going::ENOUGH).await;
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ settled(&env).await;
+ assert_eq!(env.prompts("kg").len(), 2);
+ assert!(open_questions(&env).await.is_empty());
+}
+
+/// The person writes while the lead's results turn runs: their message has its own turn, so the
+/// chain isn't nudged.
+#[tokio::test]
+async fn the_person_writing_means_no_keep_going_turn() {
+ let env = setup().await;
+ let release = env.file("person-wrote");
+ std::fs::write(env.script().join("res"), format!("HOLD:{} Passed Checker's draft.\n", release.display())).unwrap();
+ person_asks(&env, "Write the chapter.").await;
+ hand_off(&env, "Draft chapter 1", true).await;
+ wait_for("the results turn", || async { !env.prompts("res").is_empty() }).await;
+ let (s, v) = call(&env.app, "POST", "/api/chat/send", Some(json!({"channel_id": env.channel, "prompt": "Actually, I'll read it myself.", "sender_id": "user"}))).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ std::fs::write(&release, "go").unwrap();
+ wait_for("the results reply", || async { messages(&env).await.iter().any(|m| m.text == "Passed Checker's draft.") }).await;
+ settled(&env).await;
+ assert!(env.prompts("kg").is_empty());
+ assert!(open_questions(&env).await.is_empty());
+}
+
+/// At the hand-off ceiling the lead's mention waits on Continue: that's a pause the person lifts,
+/// not a stall.
+#[tokio::test]
+async fn the_hand_off_ceiling_means_no_keep_going_turn() {
+ let env = setup().await;
+ env.queue("res", &["@Checker, please check part 3."]);
+ person_asks(&env, "Check every part.").await;
+ // This request already started the most hand-offs it may (all ended)
+ for i in 0..kwnt::server::routes::MAX_DELEGATIONS_PER_REQUEST {
+ let (_, d) = env
+ .state
+ .db
+ .create_delegation(&kwnt::db::threads::NewDelegation {
+ lead_kwant_id: env.lead.clone(),
+ specialist_kwant_id: env.checker.clone(),
+ origin_channel_id: Some(env.channel.clone()),
+ origin_kwant_id: None,
+ origin_thread_id: None,
+ team_id: None,
+ task: format!("earlier round {i}"),
+ 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());
+ }
+ hand_off(&env, "Check part 2", true).await;
+ wait_for("the Continue notice", || async {
+ messages(&env).await.iter().any(|m| meta_of(m)["kind"] == kwnt::server::budget::CAPPED_KIND)
+ })
+ .await;
+ settled(&env).await;
+ assert!(env.prompts("kg").is_empty());
+ assert!(open_questions(&env).await.is_empty());
+}
+
+/// A chain budget pause posted during the results turn holds the chain until the person lifts it.
+#[tokio::test]
+async fn a_budget_pause_means_no_keep_going_turn() {
+ let env = setup().await;
+ let release = env.file("paused");
+ std::fs::write(env.script().join("res"), format!("HOLD:{} Passed Checker's draft.\n", release.display())).unwrap();
+ person_asks(&env, "Write the chapter.").await;
+ hand_off(&env, "Draft chapter 1", true).await;
+ wait_for("the results turn", || async { !env.prompts("res").is_empty() }).await;
+ env.state
+ .db
+ .insert_message_with(
+ &kwnt::db::models::NewMessage {
+ channel_id: Some(env.channel.clone()),
+ direct_kwant_id: None,
+ sender_role: "system".into(),
+ sender_id: "kwnt".into(),
+ text: "Paused: this chain used its budget.".into(),
+ reasoning_content: None,
+ tool_calls: None,
+ tokens_used: 0,
+ },
+ &kwnt::db::models::MessageExtra { thread_id: None, meta: Some(json!({"kind": kwnt::server::budget::KIND})) },
+ )
+ .await
+ .unwrap();
+ std::fs::write(&release, "go").unwrap();
+ wait_for("the results reply", || async { messages(&env).await.iter().any(|m| m.text == "Passed Checker's draft.") }).await;
+ settled(&env).await;
+ assert!(env.prompts("kg").is_empty());
+ assert!(open_questions(&env).await.is_empty());
+}
+
+/// Another hand-off of the lead from this chat is still running: the chain is moving.
+#[tokio::test]
+async fn another_open_hand_off_means_no_keep_going_turn() {
+ let env = setup().await;
+ env.queue("res", &["Passed Checker's part 1."]);
+ person_asks(&env, "Check both parts.").await;
+ let release = env.file("part2");
+ let running = hand_off(&env, &format!("Check part 2 SPECHOLD:{}", release.display()), false).await;
+ wait_for("part 2 to run", || async {
+ env.state.db.get_delegation(&running).await.unwrap().is_some_and(|d| d.status == "running")
+ })
+ .await;
+ hand_off(&env, "Check part 1", true).await;
+ wait_for("the results turn", || async { !env.prompts("res").is_empty() }).await;
+ wait_for("the results reply", || async { messages(&env).await.iter().any(|m| m.text == "Passed Checker's part 1.") }).await;
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ assert!(env.prompts("kg").is_empty(), "part 2 still runs");
+ assert!(open_questions(&env).await.is_empty());
+ std::fs::write(&release, "go").unwrap();
+ settled(&env).await;
+}
+
+/// The lead's prompts: no "one answer" left, and the hand-off rules name the three ends.
+#[test]
+fn the_prompts_name_the_three_ends() {
+ let rules = delegation::handoff_rules();
+ assert!(!rules.contains("one answer"), "{rules}");
+ assert!(rules.contains("End every reply in one of three ways"), "{rules}");
+ assert!(rules.contains("@mention, or do it yourself in this reply"), "{rules}");
+ assert!(rules.contains("ask them with the question tool"), "{rules}");
+ assert!(rules.contains("`Done: <what you checked>`"), "{rules}");
+ assert!(keep_going::PROMPT.starts_with("The person's request isn't marked done"));
+}
diff --git a/tests/spaces_s2_fixes_test.rs b/tests/spaces_s2_fixes_test.rs
index b35ea18e..72e772f6 100644
--- a/tests/spaces_s2_fixes_test.rs
+++ b/tests/spaces_s2_fixes_test.rs
@@ -122,6 +122,8 @@ async fn setup() -> Env {
let tmp = tempfile::tempdir().unwrap();
let data = tmp.path().join("data");
let db = Database::init(&data).await.unwrap();
+ // These chains predate keep-going turns; a stalled lead isn't nudged here.
+ db.set_setting("keep_going_turns", "0").await.unwrap();
let config = Config {
data_dir: data.clone(),
laya_url: "http://127.0.0.1:9".into(),