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.

22j: a failed step never loops (#705)

Oleksandr Ivanchenkoeae592df6097
diff --git a/src/drivers/activity.rs b/src/drivers/activity.rs
index f5a3e9b3..7d5901fa 100644
--- a/src/drivers/activity.rs
+++ b/src/drivers/activity.rs
@@ -728,13 +728,25 @@ fn command_line(args: &Value) -> Option<String> {
}
/// Whether `name` is a tool that runs a shell command (`Bash`, codex's `exec_command`,
-/// `mcp__x__run_shell_command`), ignoring an `mcp__server__` prefix and case. The one list of
+/// `mcp__x__run_shell_command`, an agent's `run_terminal_command`), ignoring an `mcp__server__`
+/// prefix and case. The one list of
/// shell tools: [`summarize`] titles them "Running `…`", and the desktop island names only their
/// program (server/activity.rs).
pub fn is_shell_tool(name: &str) -> bool {
matches!(
tool_part(name).to_ascii_lowercase().as_str(),
- "bash" | "shell" | "exec" | "exec_command" | "command_execution" | "run_terminal_cmd" | "run_shell_command" | "local_shell"
+ "bash"
+ | "shell"
+ | "exec"
+ | "exec_command"
+ | "command_execution"
+ | "run_terminal_cmd"
+ | "run_shell_command"
+ | "local_shell"
+ // 22j: Quant's failed step (2026-11-15), and the other common names for it
+ | "run_terminal_command"
+ | "execute_command"
+ | "run_command"
)
}
@@ -1145,6 +1157,18 @@ mod tests {
}
}
+ #[test]
+ fn terminal_tools_are_shell_tools() {
+ for name in ["run_terminal_command", "mcp__desktop__run_terminal_command", "execute_command", "Run_Command", "Bash", "run_terminal_cmd"] {
+ assert!(is_shell_tool(name), "{name}");
+ }
+ for name in ["Read", "run_tests", "mcp__x__run_query", "command"] {
+ assert!(!is_shell_tool(name), "{name}");
+ }
+ let cmd = json!({"command": "journalctl -u maker --since 17:18"});
+ assert_eq!(summarize("run_terminal_command", &cmd).0, "Running `journalctl -u maker --since 17:18`");
+ }
+
#[test]
fn home_folders_are_hidden() {
assert_eq!(
diff --git a/src/server/delivery_check.rs b/src/server/delivery_check.rs
index 21dac5a8..84d7e8c8 100644
--- a/src/server/delivery_check.rs
+++ b/src/server/delivery_check.rs
@@ -14,8 +14,11 @@
//! ends on a plan it didn't carry out ("I'll check the file sizes next.", see [`promise_line`])
//! gets the same one continuation, told to retry, try another way, or end with a
//! `Blocked: <what>. <what unblocks it>` line. It needs no plan. If the continuation still ends
-//! on a promise after a failed step, its reply gets [`follow_line`]. A step the person declined
-//! on an approval card is never pushed again. Follow-through is never a delivery note.
+//! on a promise after a failed step, its reply gets [`follow_line`], and (22j) the save step
+//! stores kwant's own [`blocked_text`] on it, so the lead's chain is Blocked at once (one card
+//! naming the step and its error) instead of looping through keep-going turns. A step the
+//! person declined on an approval card is never pushed again. Follow-through is never a
+//! delivery note.
//!
//! What the person expected comes from the turn's one `DeliveryPlan` (`src/router/delivery.rs`),
//! the same plan the prompt's "[What to deliver]" hint renders, read through [`Expect::from_plan`].
@@ -65,11 +68,46 @@ pub struct Seen {
pub declined: bool,
}
-/// A tool step that failed or was refused: the tool's name and the step's short title.
+/// A tool step that failed or was refused: the tool's name, the step's short title and (22j) its
+/// `detail`, which for a failed step is why it failed (see [`crate::drivers::activity`]).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FailedStep {
pub tool: String,
pub title: String,
+ pub detail: String,
+}
+
+/// Longest error quoted from a failed step's detail (characters).
+const MAX_ERROR_CHARS: usize = 160;
+
+impl FailedStep {
+ /// What the step did, for a sentence: its title without the "Running "/"Using " kwant puts in
+ /// front ("`journalctl -u bot`"), or the tool's name when it has no title.
+ pub fn name(&self) -> String {
+ let title = self.title.trim();
+ let bare = ["Running ", "Using "].iter().find_map(|p| title.strip_prefix(p)).unwrap_or(title).trim();
+ if bare.is_empty() { self.tool.clone() } else { clip(bare, MAX_QUOTE_CHARS) }
+ }
+
+ /// The first non-empty line of the step's detail (why it failed), at most
+ /// [`MAX_ERROR_CHARS`], without a closing full stop. `None` when it has none.
+ pub fn error(&self) -> Option<String> {
+ let line = self.detail.lines().map(str::trim).find(|l| !l.is_empty())?;
+ let line = cut_at_word(line, MAX_ERROR_CHARS);
+ let line = line.trim_end_matches(['.', ' ']);
+ (!line.is_empty()).then(|| line.to_string())
+ }
+}
+
+/// 22j: kwant's own `meta.blocked` text for `bot`'s reply that still ended on a promise after
+/// `step` failed: "<Bot> couldn't run <step>: <error>." It becomes the Blocked card's question
+/// ("Blocked: …", see [`super::keep_going`]).
+pub fn blocked_text(bot: &str, step: &FailedStep) -> String {
+ match step.error() {
+ Some(error) if error.ends_with('…') => format!("{bot} couldn't run {}: {error}", step.name()),
+ Some(error) => format!("{bot} couldn't run {}: {error}.", step.name()),
+ None => format!("{bot} couldn't run {}.", step.name()),
+ }
}
impl Seen {
@@ -136,6 +174,9 @@ pub struct Verdict {
/// Add [`follow_line`] for this tool: the continuation still ended on a promise after a
/// failed step.
pub follow_line: Option<String>,
+ /// The failed step behind [`Verdict::follow_line`] (22j): the save step stores
+ /// [`blocked_text`] for it, so the chain is Blocked, not stalled.
+ pub stuck_on: Option<FailedStep>,
}
/// The P9 continuation for a missing image (Ada's wording).
@@ -163,9 +204,10 @@ running, your bot browser, or a teammate who can). If nothing works, end with on
)
}
-/// Added to a continuation's reply that still ends on a promise after a failed step.
-pub fn follow_line(tool: &str) -> String {
- format!("_kwant: this stopped after a failed step ({tool}) without another try or a reason._")
+/// Added to a continuation's reply that still ends on a promise after a failed step: the
+/// continuation was the other try, so the line says the step failed again (22j).
+pub fn follow_line(tool: &str, bot: &str) -> String {
+ format!("_kwant: {tool} failed again, and {bot} didn't try another way or say why._")
}
fn clip(text: &str, max: usize) -> String {
@@ -216,7 +258,8 @@ pub fn check(reply: &str, expect: Option<&Expect>, continued: bool, seen: &Seen)
} else {
v.no_picture_line = !image && (claims || (wants_image && firm));
v.outcome = expect.map(|_| if planned.is_empty() { Outcome::Hit } else { Outcome::Miss });
- v.follow_line = follow.map(|(step, _)| step.tool.clone());
+ v.follow_line = follow.as_ref().map(|(step, _)| step.tool.clone());
+ v.stuck_on = follow.map(|(step, _)| step.clone());
}
v
}
@@ -674,6 +717,7 @@ pub fn tool_steps_in(activity: Option<&Value>) -> (bool, Option<FailedStep>, boo
let failed = last.filter(|s| s["status"] == "failed").map(|s| FailedStep {
tool: s["tool"].as_str().unwrap_or("a tool").to_string(),
title: s["title"].as_str().unwrap_or("").to_string(),
+ detail: s["detail"].as_str().unwrap_or("").to_string(),
});
(last.is_some(), failed, declined)
}
@@ -793,11 +837,11 @@ where
}
/// The reply as saved: with [`NO_PICTURE_LINE`](super::picture_claims::NO_PICTURE_LINE) and
-/// [`follow_line`] when the verdict says so.
-pub fn apply(reply: String, v: &Verdict) -> String {
+/// [`follow_line`] (naming `bot`) when the verdict says so.
+pub fn apply(reply: String, v: &Verdict, bot: &str) -> String {
let reply = if v.no_picture_line { super::picture_claims::with_no_picture_line(&reply) } else { reply };
match &v.follow_line {
- Some(tool) => format!("{}\n\n{}", reply.trim_end(), follow_line(tool)).trim_start().to_string(),
+ Some(tool) => format!("{}\n\n{}", reply.trim_end(), follow_line(tool, bot)).trim_start().to_string(),
None => reply,
}
}
@@ -848,14 +892,14 @@ mod tests {
let v1 = check(first.0, expect.as_ref(), false, &first.1);
let runs = AtomicUsize::new(0);
let last = std::sync::Mutex::new(v1.clone());
- let joined = after_turn(Ok(apply(first.0.into(), &v1)), v1.continue_with.clone(), false, |prompt| {
+ let joined = after_turn(Ok(apply(first.0.into(), &v1, "Ann")), v1.continue_with.clone(), false, |prompt| {
let (runs, last, expect) = (&runs, &last, expect.clone());
async move {
runs.fetch_add(1, Ordering::SeqCst);
assert!(prompt.contains("Missing from your last reply"), "{prompt}");
let v2 = check(then.0, expect.as_ref(), true, &then.1);
assert_eq!(v2.continue_with, None, "a continuation never continues again");
- let text = apply(then.0.into(), &v2);
+ let text = apply(then.0.into(), &v2, "Ann");
*last.lock().unwrap() = v2;
Ok(text)
}
@@ -953,7 +997,7 @@ mod tests {
assert_eq!(v(SHARED), Verdict::default());
assert_eq!(check("The button is orange now.", None, false, &SHOT), Verdict::default());
assert_eq!(check("I can take a screenshot if you want.", None, false, &NOTHING), Verdict::default());
- assert_eq!(apply(claim.into(), &v(NOTHING)), format!("{claim}\n\n{NO_PICTURE_LINE}"));
+ assert_eq!(apply(claim.into(), &v(NOTHING), "Ann"), format!("{claim}\n\n{NO_PICTURE_LINE}"));
assert_eq!(meta(&Verdict::default(), None, true), None);
assert_eq!(meta(&v(NOTHING), None, true).unwrap()["no_picture"], true);
// A turn the check skipped records nothing, even with an expectation
@@ -1176,7 +1220,7 @@ mod tests {
let v2 = check(reply, Some(&visible), true, &then);
assert!(v2.missing.is_empty() && !v2.no_picture_line && !v2.share_last_shot, "{v2:?}");
assert_eq!(v2.outcome, Some(Outcome::Hit));
- assert!(!apply(reply.into(), &v2).contains(NO_PICTURE_LINE));
+ assert!(!apply(reply.into(), &v2, "Ann").contains(NO_PICTURE_LINE));
// What the bug did: the continuation's own pictures only
let per_turn = check(reply, Some(&visible), true, &NOTHING);
@@ -1212,7 +1256,7 @@ mod tests {
const REAL: &str = "The render command was refused.\n\nI'll check the file sizes and measure the frame timings next.";
fn failed(tool: &str) -> Seen {
- Seen { ran_tools: true, failed_step: Some(FailedStep { tool: tool.into(), title: "render the video".into() }), ..NOTHING }
+ Seen { ran_tools: true, failed_step: Some(FailedStep { tool: tool.into(), title: "render the video".into(), detail: String::new() }), ..NOTHING }
}
#[test]
@@ -1256,12 +1300,12 @@ mod tests {
let (ran, f, d) = tool_steps_in(steps(json!([
{ "kind": "thinking", "status": "done" },
{ "kind": "tool", "tool": "Read", "title": "read a.txt", "status": "ok" },
- { "kind": "tool", "tool": "Bash", "title": "render", "status": "failed" },
+ { "kind": "tool", "tool": "Bash", "title": "render", "status": "failed", "detail": "exit 1: no such file" },
{ "kind": "note", "status": "done" },
]))
.as_ref());
assert!(ran && !d);
- assert_eq!(f, Some(FailedStep { tool: "Bash".into(), title: "render".into() }));
+ assert_eq!(f, Some(FailedStep { tool: "Bash".into(), title: "render".into(), detail: "exit 1: no such file".into() }));
// A later tool step that worked: nothing to follow through
let (_, f, _) = tool_steps_in(steps(json!([
{ "kind": "tool", "tool": "Bash", "title": "render", "status": "failed" },
@@ -1304,16 +1348,36 @@ mod tests {
let v = check("Still failing.\n\nI'll try again later.", None, true, &failed("Bash"));
assert_eq!(v.continue_with, None);
assert_eq!(v.follow_line.as_deref(), Some("Bash"));
- let text = apply("Still failing.\n\nI'll try again later.".into(), &v);
- assert!(text.ends_with(&follow_line("Bash")), "{text}");
- assert_eq!(follow_line("Bash"), "_kwant: this stopped after a failed step (Bash) without another try or a reason._");
+ assert_eq!(v.stuck_on, failed("Bash").failed_step, "22j: the step the chain is Blocked on");
+ let text = apply("Still failing.\n\nI'll try again later.".into(), &v, "Quant");
+ assert!(text.ends_with(&follow_line("Bash", "Quant")), "{text}");
+ // 22j: the continuation was the other try, so the line says it failed again
+ assert_eq!(follow_line("Bash", "Quant"), "_kwant: Bash failed again, and Quant didn't try another way or say why._");
assert_eq!(meta(&v, None, true).unwrap()["missing"], json!(["follow_through"]));
assert_eq!(meta(&v, None, true).unwrap()["follow_line"], json!(true));
// A continuation that got past it, or ended Blocked:, gets no line
let ok = check("Rendered with ffmpeg instead: out.mp4.", None, true, &Seen { ran_tools: true, ..NOTHING });
assert_eq!((ok.follow_line, ok.missing), (None, vec![]));
let b = check("Blocked: terminal is off. Allow it, then say continue.", None, true, &failed("Bash"));
- assert_eq!(b.follow_line, None);
+ assert_eq!((b.follow_line, b.stuck_on), (None, None));
+ }
+
+ /// 22j: kwant's own Blocked text names the step (a shell step by its command) and the first
+ /// line of its error, clipped.
+ #[test]
+ fn the_blocked_text_names_the_step_and_its_error() {
+ let step = |tool: &str, title: &str, detail: &str| FailedStep { tool: tool.into(), title: title.into(), detail: detail.into() };
+ let shell = step("run_terminal_command", "Running `journalctl -u maker --since 17:18`", "\nError: no terminal session is open.\nat line 2");
+ assert_eq!(shell.name(), "`journalctl -u maker --since 17:18`");
+ assert_eq!(shell.error().as_deref(), Some("Error: no terminal session is open"));
+ assert_eq!(blocked_text("Quant", &shell), "Quant couldn't run `journalctl -u maker --since 17:18`: Error: no terminal session is open.");
+ // No title: the tool's name; no detail: no error
+ assert_eq!(blocked_text("Quant", &step("run_terminal_command", "", "")), "Quant couldn't run run_terminal_command.");
+ assert_eq!(step("mcp__github__create_issue", "Using create_issue (github)", "401").name(), "create_issue (github)");
+ // A long error is cut at a word, at most 160 characters and the ellipsis
+ let long = step("Bash", "Running `x`", &"word ".repeat(80)).error().unwrap();
+ assert!(long.chars().count() <= 161 && long.ends_with('…'), "{long}");
+ assert!(blocked_text("Ann", &step("Bash", "Running `x`", &"word ".repeat(80))).ends_with("word…"));
}
#[test]
diff --git a/src/server/keep_going.rs b/src/server/keep_going.rs
index 816cf2d6..a8283304 100644
--- a/src/server/keep_going.rs
+++ b/src/server/keep_going.rs
@@ -17,7 +17,20 @@
//! save step stores any reply's `Blocked:` line on its meta as [`BLOCKED_KEY`], and (13a) the
//! ending of a reply that waits on the person in prose after a failed or declined tool step; that
//! stored text counts the same.
-
+//!
+//! A failed step never loops (22j, Oleks's Quant chat, 2026-11-15: three near-identical "I'll read
+//! the local repo and the open terminal…" replies, then a "Keep going?" card quoting the plan):
+//!
+//! - a reply whose follow-through continuation still ended on a promise after the step failed
+//! again carries kwant's own `meta.blocked` (see [`super::delivery_check::blocked_text`]), so it
+//! is Blocked at once, never stalled;
+//! - a keep-going turn after a failed step is told which step failed and why, and not to run the
+//! same command again ([`failure_note`]);
+//! - a reply after a failed step that repeats an earlier reply of the request ([`same_opening`])
+//! ends the chain with the same Blocked card;
+//! - the "Keep going?" card says what failed instead of quoting the plan.
+
+use super::delivery_check::FailedStep;
use super::routes::{try_kwant_turn, TurnOpts, TurnScope};
use super::AppState;
use crate::db::models::{Kwant, Message};
@@ -123,16 +136,100 @@ async fn lead_delegations(state: &AppState, context: &str, lead: &Kwant) -> Vec<
/// The `meta.blocked` text saved on `lead`'s `reply` (its newest message with that text that is new
/// since `snap`), if any.
+///
+/// A turn its delivery check continued returns both replies joined (see
+/// [`super::delivery_check::after_turn`]), so the continuation's saved reply is its end (22j).
fn saved_blocked(msgs: &[Message], snap: &Snapshot, lead: &Kwant, reply: &str) -> Option<String> {
- let reply = msgs
- .iter()
- .rev()
- .filter(|m| !snap.messages.contains(&m.id))
- .find(|m| m.sender_role == "kwant" && (m.sender_id == lead.id || m.sender_id == lead.name) && m.text.trim() == reply.trim())?;
+ let reply = msgs.iter().rev().filter(|m| !snap.messages.contains(&m.id)).find(|m| {
+ let text = m.text.trim();
+ is_lead(m, lead) && !text.is_empty() && (text == reply.trim() || reply.trim_end().ends_with(text))
+ })?;
let text = meta_of(reply)[BLOCKED_KEY]["text"].as_str()?.trim().to_string();
(!text.is_empty()).then_some(text)
}
+fn is_lead(m: &Message, lead: &Kwant) -> bool {
+ m.sender_role == "kwant" && (m.sender_id == lead.id || m.sender_id == lead.name)
+}
+
+/// 22j: the lead's last tool step in `msgs` when it failed: read from its newest reply that ran a
+/// tool, looking back past the person's answers to kwant's cards ("Keep going", an answer to a
+/// Blocked card) but not past a message of their own. `None` when that step worked, when the
+/// person declined a card in that reply (a declined step is never pushed), or when no reply of
+/// this request ran a tool.
+fn last_failed_step(msgs: &[Message], lead: &Kwant) -> Option<FailedStep> {
+ for m in msgs.iter().rev() {
+ if crate::drivers::from_person(m) {
+ if meta_of(m)["kind"] == "question_answer" {
+ continue;
+ }
+ return None;
+ }
+ if !is_lead(m, lead) {
+ continue;
+ }
+ let meta = meta_of(m);
+ let (ran_tools, failed, declined) = super::delivery_check::tool_steps_in(meta.get("activity"));
+ if ran_tools || declined {
+ return failed.filter(|_| !declined);
+ }
+ }
+ None
+}
+
+/// What a keep-going turn after a failed step is told (22j), after [`PROMPT`].
+fn failure_note(step: &FailedStep) -> String {
+ let title = step.title.trim();
+ let what = if title.is_empty() || title == step.tool { step.tool.clone() } else { format!("{}: {title}", step.tool) };
+ let failed = match step.error() {
+ Some(error) => format!("failed: {error}."),
+ None => "failed.".to_string(),
+ };
+ format!(
+ "Your last step ({what}) {failed} Don't run the same command again. Try another way (another tool, reading a \
+file instead of running, your bot browser, a teammate), or end with `Blocked: <what>. <what would unblock it>`."
+ )
+}
+
+/// The words of a reply's first sentence, for [`same_opening`]: lowercase, letters, digits and
+/// apostrophes only.
+fn opening_words(reply: &str) -> Vec<String> {
+ let line = reply.lines().map(str::trim).find(|l| !l.is_empty()).unwrap_or("");
+ let line = line.trim_start_matches(['#', '*', '_', '>', '-', ' ']);
+ let end = line.char_indices().find(|&(i, c)| matches!(c, '.' | '!' | '?') && line[i + c.len_utf8()..].starts_with(char::is_whitespace)).map_or(line.len(), |(i, _)| i);
+ line[..end]
+ .replace('’', "'")
+ .to_lowercase()
+ .split(|c: char| !(c.is_alphanumeric() || c == '\''))
+ .filter(|w| !w.is_empty())
+ .map(str::to_string)
+ .collect()
+}
+
+/// 22j: two replies open with the same sentence, give or take two words ("The last checks…" /
+/// "The earlier checks…"): whitespace, case and punctuation aside, the first sentences are equal,
+/// or differ by at most 2 words added, dropped or changed when both have at least 5 words.
+fn same_opening(a: &str, b: &str) -> bool {
+ let (a, b) = (opening_words(a), opening_words(b));
+ if a.is_empty() || b.is_empty() {
+ return false;
+ }
+ a == b || (a.len().min(b.len()) >= 5 && word_distance(&a, &b) <= 2)
+}
+
+/// Words added, dropped or changed to turn `a` into `b` (Levenshtein over words).
+fn word_distance(a: &[String], b: &[String]) -> usize {
+ let mut prev: Vec<usize> = (0..=b.len()).collect();
+ for (i, wa) in a.iter().enumerate() {
+ let mut row = vec![i + 1];
+ for (j, wb) in b.iter().enumerate() {
+ row.push((prev[j] + usize::from(wa != wb)).min(prev[j + 1] + 1).min(row[j] + 1));
+ }
+ prev = row;
+ }
+ prev[b.len()]
+}
+
fn meta_of(m: &Message) -> Value {
m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null)
}
@@ -250,12 +347,25 @@ pub(super) async fn after_lead_turn(scope: &TurnScope, lead: &Kwant, mut snap: S
}
let msgs = state.db.list_messages(&snap.context, 100).await.unwrap_or_default();
let tail = request_tail(&msgs);
+ // 22j: this turn's step failed again and its reply repeats an earlier one (also one from
+ // before a card the person answered): another turn would only say it again, so it is
+ // Blocked on that step
+ if let Some(step) = repeats_after_failure(&msgs, &snap, lead, &reply) {
+ return blocked_on(scope, lead, &snap, &msgs, &step).await;
+ }
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));
+ // 22j: after a failed step the card says what failed, not the plan
+ let question = match last_failed_step(&msgs, lead) {
+ Some(step) => match step.error() {
+ Some(error) => format!("{} is stuck: {} failed ({error}). Keep going?", lead.name, step.name()),
+ None => format!("{} is stuck: {} failed. Keep going?", lead.name, step.name()),
+ },
+ None => 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;
@@ -269,6 +379,49 @@ pub(super) async fn after_lead_turn(scope: &TurnScope, lead: &Kwant, mut snap: S
}
}
+/// 22j: the failed step when this turn's last tool step (its newest reply since `snap` that ran a
+/// tool) failed, and its reply opens like an earlier reply of the lead's ([`replies_before`]). A
+/// turn whose step worked is never blocked, however it opens.
+fn repeats_after_failure(msgs: &[Message], snap: &Snapshot, lead: &Kwant, reply: &str) -> Option<FailedStep> {
+ let new: Vec<Message> = msgs.iter().filter(|m| !snap.messages.contains(&m.id) && is_lead(m, lead)).cloned().collect();
+ let step = last_failed_step(&new, lead)?;
+ replies_before(msgs, snap, lead).iter().any(|m| same_opening(&m.text, reply)).then_some(step)
+}
+
+/// 22j: the lead's replies before this turn (in `snap`), newest first, with the same look-back as
+/// [`last_failed_step`]: past the person's answers to kwant's cards ("Keep going", an answer to a
+/// Blocked card), so the first turn after that answer is compared with the reply before the card
+/// (round 2), but not past a message of their own. kwant's cards (`meta.kind`) aren't replies.
+/// Not [`request_tail`], which starts after any person message: the allowance and the one card
+/// per request count from there.
+fn replies_before<'a>(msgs: &'a [Message], snap: &Snapshot, lead: &Kwant) -> Vec<&'a Message> {
+ let mut out = Vec::new();
+ for m in msgs.iter().rev().filter(|m| snap.messages.contains(&m.id)) {
+ if crate::drivers::from_person(m) {
+ if meta_of(m)["kind"] == "question_answer" {
+ continue;
+ }
+ break;
+ }
+ if is_lead(m, lead) && meta_of(m).get("kind").is_none() {
+ out.push(m);
+ }
+ }
+ out
+}
+
+/// 22j: the chain is Blocked on `step`: kwant's own text goes on the lead's newest reply (as
+/// `meta.blocked`, like the save step's) and becomes the one Blocked card, whose answer resumes
+/// the chain.
+async fn blocked_on(scope: &TurnScope, lead: &Kwant, snap: &Snapshot, msgs: &[Message], step: &FailedStep) {
+ let text = super::delivery_check::blocked_text(&lead.name, step);
+ tracing::info!(lead = %lead.id, context = %snap.context, step = %step.tool, "a lead repeated itself after a failed step; blocked");
+ if let Some(m) = msgs.iter().rev().find(|m| !snap.messages.contains(&m.id) && is_lead(m, lead)) {
+ super::asks::set_meta_key(&scope.state, m, BLOCKED_KEY, json!({ "text": text, "from": "repeat" })).await;
+ }
+ ask_card(scope, lead, &format!("Blocked: {text}"), &[], ASK_KEY).await;
+}
+
/// The person's last [`QUOTED`] messages in `msgs`, oldest first: what a keep-going turn quotes as
/// theirs. A customer's or a connected agent's "user" message (16d), or one a bot sent through the
/// chat API (22b), is never quoted as the person's ([`super::routes::is_persons`]).
@@ -278,11 +431,19 @@ fn persons_last(msgs: &[Message]) -> Vec<&Message> {
asked
}
-/// The keep-going turn's prompt for the chat's messages `msgs` (oldest first).
+/// The keep-going turn's prompt for the chat's messages `msgs` (oldest first), with no failure
+/// note. Only main's 22b tests call it; the server goes through [`keep_going_prompt_after`].
+#[cfg(test)]
fn keep_going_prompt(msgs: &[Message]) -> String {
+ keep_going_prompt_after(msgs, "")
+}
+
+/// The keep-going prompt with `failure` (22j: " " + [`failure_note`], or empty) at the end of
+/// kwant's own line, so a turn after a failed step is told what failed and doesn't run it again.
+fn keep_going_prompt_after(msgs: &[Message], failure: &str) -> String {
let quoted: Vec<String> = persons_last(msgs).iter().map(|m| format!("> {}", clip(&m.text, QUOTE_CHARS).replace('\n', "\n> "))).collect();
format!(
- "[kwnt: {PROMPT}]\n\nThe person's last messages here, oldest first:\n{}\n\n{}",
+ "[kwnt: {PROMPT}{failure}]\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(),
)
@@ -293,7 +454,9 @@ async fn keep_going_turn(scope: &TurnScope, lead: &Kwant, n: usize) -> Option<St
let state = &scope.state;
let context = scope.context_id(lead);
let msgs = state.db.list_messages(&context, 100).await.unwrap_or_default();
- let prompt = keep_going_prompt(&msgs);
+ // 22j: after a failed step the turn is told what failed, so it doesn't run it again
+ let failure = last_failed_step(&msgs, lead).map(|step| format!(" {}", failure_note(&step))).unwrap_or_default();
+ let prompt = keep_going_prompt_after(&msgs, &failure);
let mut opts = TurnOpts::default();
opts.label = Some("Keeping the work going".into());
opts.extra_meta = Some(json!({ TURN_KEY: n }));
@@ -529,6 +692,38 @@ mod tests {
assert_eq!(blocked_line(""), None);
}
+ /// 22j: Quant's replies ("The last checks…" / "The earlier checks…") open the same way; a new
+ /// finding doesn't.
+ #[test]
+ fn a_repeat_opens_like_an_earlier_reply() {
+ let quant = "The last checks never landed a merge SHA or the live maker-first flag. I'll read the local repo and the open terminal.";
+ let again = "**The earlier checks never landed a merge SHA or the live maker-first flag.**\n\nI'll read the local repo…";
+ assert!(same_opening(quant, again));
+ assert!(same_opening("The LOGS are empty.", "the logs are empty!"), "case, spaces and punctuation aside");
+ assert!(same_opening(quant, "The checks never landed a merge SHA or the maker-first flag."), "two words dropped");
+ assert!(!same_opening(quant, "The checks never landed a merge SHA or the maker-first flag yet."), "two dropped, one added: 3");
+ assert!(!same_opening(quant, "The checks never landed a merge SHA or the maker-first flag yet, sadly."), "4 words apart");
+ assert!(!same_opening("The logs are empty.", "The deploy logs are full."), "short sentences must match exactly");
+ assert!(!same_opening(quant, "Found the merge: 3b876b8d is on main and live."));
+ assert!(!same_opening("", ""));
+ let w = |s: &str| s.split(' ').map(str::to_string).collect::<Vec<_>>();
+ assert_eq!(word_distance(&w("a b c d"), &w("a x c d e")), 2);
+ }
+
+ /// 22j: a keep-going turn after a failed step hears the step, its error and the rule.
+ #[test]
+ fn the_failure_note_names_the_step_and_its_error() {
+ let step = FailedStep { tool: "run_terminal_command".into(), title: "Running `ls`".into(), detail: "Error: no terminal session is open.\nmore".into() };
+ assert_eq!(
+ failure_note(&step),
+ "Your last step (run_terminal_command: Running `ls`) failed: Error: no terminal session is open. Don't run the same \
+command again. Try another way (another tool, reading a file instead of running, your bot browser, a teammate), or end \
+with `Blocked: <what>. <what would unblock it>`."
+ );
+ let bare = FailedStep { tool: "Bash".into(), title: String::new(), detail: String::new() };
+ assert!(failure_note(&bare).starts_with("Your last step (Bash) failed. Don't run"), "{}", failure_note(&bare));
+ }
+
#[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");
diff --git a/src/server/routes.rs b/src/server/routes.rs
index d1cfb106..5b82aa34 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -3970,7 +3970,7 @@ async fn run_kwant_turn_inner(
} else {
super::delivery_check::Verdict::default()
};
- let text = super::delivery_check::apply(text, &verdict);
+ let text = super::delivery_check::apply(text, &verdict, &target_kwant.name);
if opts.discussion.is_none() {
reply_text = text.clone();
}
@@ -4026,13 +4026,21 @@ async fn run_kwant_turn_inner(
// link didn't open and it ran no tool) and whose reply ends waiting on the person in
// prose is blocked too, in the bot's own words. Not while kwnt sends the turn one more
// try (a continuation): that reply isn't the last word. A decided reply counts what
- // its held turn left too
+ // its held turn left too. 22j: a continuation that got the kwant line is blocked on
+ // its failed step
let before = super::delivery_check::FailedBefore { failed: page_failed || opts.failed_before.failed, ..opts.failed_before };
let blocked = super::keep_going::blocked_line(&asst_msg.text)
.map(|text| serde_json::json!({ "text": text }))
.or_else(|| {
let text = super::delivery_check::failed_step_blocked(&asst_msg.text, activity.as_ref(), before).filter(|_| verdict.continue_with.is_none() || opts.delivery_next.is_none())?;
Some(serde_json::json!({ "text": text, "from": "failed_step" }))
+ })
+ // 22j: the one continuation still ended on a promise after the step failed again
+ // (it gets the kwant line): blocked in kwant's own words, the step and its error,
+ // so the lead's chain asks the person once instead of looping keep-going turns
+ .or_else(|| {
+ let step = verdict.stuck_on.as_ref()?;
+ Some(serde_json::json!({ "text": super::delivery_check::blocked_text(&target_kwant.name, step), "from": "follow_through" }))
});
// ...and if this reply is held, its decided reply (a new turn) counts what this one left
let failed_before = super::delivery_check::FailedBefore::of_turn(activity.as_ref(), before);
diff --git a/tests/keep_going_test.rs b/tests/keep_going_test.rs
index fb8cb13d..3831d904 100644
--- a/tests/keep_going_test.rs
+++ b/tests/keep_going_test.rs
@@ -31,8 +31,10 @@ use tower::ServiceExt;
/// 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; a line
-/// "FAILED:<reply>" runs a Bash step that fails first, then replies. Every
-/// prompt is saved as `<dir>/prompts/<kind>-…`.
+/// "FAILED:<reply>" runs a Bash step that fails first, then replies; "TFAILED:<reply>" runs a
+/// `run_terminal_command` step that fails ("Error: no terminal session is open"), then replies
+/// (22j, Quant's step); "TOK:<reply>" runs that step and it works, then replies. A follow-through continuation ("…failed or was refused, and your reply
+/// ends with a plan…") reads queue `<dir>/ft`. Every prompt is saved as `<dir>/prompts/<kind>-…`.
const FAKE_CLAUDE: &str = r#"#!/bin/sh
case "$1" in
auth) echo '{"loggedIn":true}'; exit 0 ;;
@@ -41,6 +43,7 @@ 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
+ *"failed or was refused, and your reply ends with a plan"*) kind=ft ;;
*"isn't marked done"*) kind=kg ;;
*"finished the task you delegated"*|*"tasks you delegated have ended"*) kind=res ;;
esac
@@ -68,6 +71,16 @@ case "$out" in
printf '{"type":"assistant","message":{"id":"msg_f","content":[{"type":"tool_use","id":"toolu_f","name":"Bash","input":{"command":"run_tests.sh"}}]}}\n'
printf '{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_f","is_error":true,"content":"Permission to use Bash has been denied."}]}}\n'
;;
+ TFAILED:*)
+ out=${out#TFAILED:}
+ printf '{"type":"assistant","message":{"id":"msg_t","content":[{"type":"tool_use","id":"toolu_t","name":"run_terminal_command","input":{"command":"journalctl -u maker --since 17:18"}}]}}\n'
+ printf '{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_t","is_error":true,"content":"Error: no terminal session is open."}]}}\n'
+ ;;
+ TOK:*)
+ out=${out#TOK:}
+ printf '{"type":"assistant","message":{"id":"msg_o","content":[{"type":"tool_use","id":"toolu_o","name":"run_terminal_command","input":{"command":"journalctl -u maker --since 17:18"}}]}}\n'
+ printf '{"type":"user","message":{"content":[{"type":"tool_result","tool_use_id":"toolu_o","is_error":false,"content":"maker started, maker_first=true"}]}}\n'
+ ;;
HOLD:*)
f=${out#HOLD:}; f=${f%% *}; out=${out#HOLD:* }
i=0
@@ -473,6 +486,187 @@ async fn a_failed_step_and_a_prose_ask_become_a_card_not_a_keep_going_turn() {
assert_eq!(card_meta(&env, &open[0]).await[keep_going::ASK_KEY], true);
}
+/// 22j, Oleks's Quant chat (2026-11-15): the lead's terminal step fails on every try and each
+/// reply ends "I'll read the local repo…". The results turn gets its one follow-through
+/// continuation, which fails the same way: that is one lead reply (the turn and its
+/// continuation), then one Blocked card naming the step and its error. No keep-going turn, no
+/// "Keep going?" card.
+#[tokio::test]
+async fn a_step_that_fails_on_every_try_is_one_reply_and_one_blocked_card() {
+ let env = setup().await;
+ env.queue("res", &["TFAILED:The last checks never landed a merge SHA or the live maker-first flag. I'll read the local repo and the open terminal, then answer from what those show."]);
+ env.queue("ft", &["TFAILED:The earlier checks never landed a merge SHA or the live maker-first flag. I'll read the local repo and the open terminal, then answer from what those show."]);
+ env.queue("kg", &["TFAILED:SHOULD NOT RUN. I'll read the local repo and the open terminal."]);
+ person_asks(&env, "Is the maker-first fix merged and live?").await;
+ let before = lead_replies(&env, &messages(&env).await).len();
+ hand_off(&env, "Check the maker logs", true).await;
+ wait_for("the card", || async { !open_questions(&env).await.is_empty() }).await;
+ settled(&env).await;
+
+ assert_eq!(env.prompts("res").len(), 1);
+ let ft = env.prompts("ft");
+ assert_eq!(ft.len(), 1, "one follow-through continuation");
+ assert!(ft[0].contains("Your last step (run_terminal_command: Running `journalctl -u maker --since 17:18`)"), "{}", ft[0]);
+ assert!(env.prompts("kg").is_empty(), "no keep-going turn");
+ let msgs = messages(&env).await;
+ let replies = lead_replies(&env, &msgs);
+ // kwant's Blocked card is a message of the lead's too (`meta.kind`), not a reply
+ let new: Vec<&&Message> = replies[before..].iter().filter(|m| meta_of(m).get("kind").is_none()).collect();
+ assert_eq!(new.len(), 2, "the turn and its continuation: {:?}", new.iter().map(|m| &m.text).collect::<Vec<_>>());
+ assert!(new[0].text.starts_with("The last checks"), "{}", new[0].text);
+ assert!(new[1].text.starts_with("The earlier checks"), "{}", new[1].text);
+ let lead = env.lead_name.clone();
+ assert!(new[1].text.contains(&format!("_kwant: run_terminal_command failed again, and {lead} didn't try another way or say why._")), "{}", new[1].text);
+ let text = format!("{lead} couldn't run `journalctl -u maker --since 17:18`: Error: no terminal session is open.");
+ assert_eq!(meta_of(new[1])[keep_going::BLOCKED_KEY], json!({"text": text, "from": "follow_through"}));
+ let cards = env.state.db.list_questions(None, Some(&env.channel), None).await.unwrap();
+ assert_eq!(cards.len(), 1, "one card: {cards:?}");
+ assert_eq!(cards[0].question, format!("Blocked: {text}"));
+ let meta = card_meta(&env, &cards[0]).await;
+ assert_eq!(meta[keep_going::ASK_KEY], true);
+ assert!(meta.get(keep_going::CARD_KEY).is_none(), "not a Keep going? card: {meta}");
+}
+
+/// 22j: a stalled reply after a failed step gets a keep-going turn that is told what failed; when
+/// that turn fails the same step and says the same thing again, the chain ends with one Blocked
+/// card, not a second keep-going turn.
+#[tokio::test]
+async fn a_keep_going_turn_hears_what_failed_and_a_repeat_ends_in_a_blocked_card() {
+ let env = setup().await;
+ env.queue("res", &["TFAILED:The merge checks found nothing yet in the maker logs."]);
+ env.queue("kg", &["TFAILED:The merge checks found nothing in the maker logs.", "SHOULD NOT RUN"]);
+ person_asks(&env, "Is the maker-first fix merged and live?").await;
+ hand_off(&env, "Check the maker logs", true).await;
+ wait_for("the card", || async { !open_questions(&env).await.is_empty() }).await;
+ settled(&env).await;
+
+ let kg = env.prompts("kg");
+ assert_eq!(kg.len(), 1, "one keep-going turn, then blocked");
+ assert!(kg[0].contains(keep_going::PROMPT), "{}", kg[0]);
+ assert!(
+ kg[0].contains("Your last step (run_terminal_command: Running `journalctl -u maker --since 17:18`) failed: Error: no terminal session is open. Don't run the same command again."),
+ "{}",
+ kg[0]
+ );
+ assert!(kg[0].contains("or end with `Blocked: <what>. <what would unblock it>`"), "{}", kg[0]);
+ let lead = env.lead_name.clone();
+ let text = format!("{lead} couldn't run `journalctl -u maker --since 17:18`: Error: no terminal session is open.");
+ let msgs = messages(&env).await;
+ // the newest reply, not kwant's Blocked card after it (`meta.kind`)
+ let last = *lead_replies(&env, &msgs).iter().rev().find(|m| meta_of(m).get("kind").is_none()).unwrap();
+ assert_eq!(meta_of(last)[keep_going::TURN_KEY], 1);
+ assert_eq!(meta_of(last)[keep_going::BLOCKED_KEY], json!({"text": text, "from": "repeat"}));
+ let cards = env.state.db.list_questions(None, Some(&env.channel), None).await.unwrap();
+ assert_eq!(cards.len(), 1, "{cards:?}");
+ assert_eq!(cards[0].question, format!("Blocked: {text}"));
+ assert_eq!(card_meta(&env, &cards[0]).await[keep_going::ASK_KEY], true);
+}
+
+/// 22j: when the turns after a failed step say something new each time but never finish, the
+/// "Keep going?" card says what failed instead of quoting the plan.
+#[tokio::test]
+async fn the_keep_going_card_after_a_failed_step_says_what_failed() {
+ let env = setup().await;
+ env.queue("res", &["TFAILED:The merge checks found nothing yet."]);
+ env.queue("kg", &["TFAILED:Tried the deploy log next, also empty.", "TFAILED:Looked at the release notes, no mention."]);
+ person_asks(&env, "Is the maker-first fix merged and live?").await;
+ hand_off(&env, "Check the maker logs", true).await;
+ wait_for("the card", || async { !open_questions(&env).await.is_empty() }).await;
+ settled(&env).await;
+ assert_eq!(env.prompts("kg").len(), 2);
+ let open = open_questions(&env).await;
+ assert_eq!(open.len(), 1);
+ let lead = env.lead_name.clone();
+ assert_eq!(open[0].question, format!("{lead} is stuck: `journalctl -u maker --since 17:18` failed (Error: no terminal session is open). Keep going?"));
+ assert_eq!(card_meta(&env, &open[0]).await[keep_going::CARD_KEY], true);
+}
+
+/// 22j round 2: Oleks pressed Keep going and the same loop started again. The first turn after
+/// "Keep going" fails the same step and opens like the reply before the card: it ends Blocked at
+/// once, with no further keep-going turn.
+#[tokio::test]
+async fn keep_going_then_the_same_reply_after_the_same_failed_step_ends_blocked() {
+ let env = setup().await;
+ env.queue("res", &["TFAILED:The merge checks found nothing yet."]);
+ env.queue(
+ "kg",
+ &[
+ "TFAILED:Tried the deploy log next, also empty.",
+ "TFAILED:Looked at the release notes, no mention.",
+ "TFAILED:Looked at the release notes again, no mention.",
+ "SHOULD NOT RUN",
+ ],
+ );
+ person_asks(&env, "Is the maker-first fix merged and live?").await;
+ hand_off(&env, "Check the maker logs", true).await;
+ wait_for("the card", || async { !open_questions(&env).await.is_empty() }).await;
+ settled(&env).await;
+ let card = open_questions(&env).await.remove(0);
+ assert_eq!(card_meta(&env, &card).await[keep_going::CARD_KEY], true, "the Keep going? card first");
+ assert_eq!(env.prompts("kg").len(), 2);
+
+ answer(&env, &card.id, keep_going::KEEP_GOING).await;
+ wait_for("the Blocked card", || async { open_questions(&env).await.iter().any(|q| q.question.starts_with("Blocked: ")) }).await;
+ settled(&env).await;
+
+ let kg = env.prompts("kg");
+ assert_eq!(kg.len(), 3, "one turn after Keep going, then blocked");
+ assert!(kg.iter().any(|p| p.contains("Your last step (run_terminal_command: Running `journalctl -u maker --since 17:18`) failed")), "{kg:?}");
+ let lead = env.lead_name.clone();
+ let text = format!("{lead} couldn't run `journalctl -u maker --since 17:18`: Error: no terminal session is open.");
+ let msgs = messages(&env).await;
+ let last = *lead_replies(&env, &msgs).iter().rev().find(|m| meta_of(m).get("kind").is_none()).unwrap();
+ assert!(last.text.starts_with("Looked at the release notes again"), "{}", last.text);
+ assert_eq!(meta_of(last)[keep_going::TURN_KEY], 1, "the first turn of the fresh allowance");
+ assert_eq!(meta_of(last)[keep_going::BLOCKED_KEY], json!({"text": text, "from": "repeat"}));
+ let open = open_questions(&env).await;
+ assert_eq!(open.len(), 1, "{open:?}");
+ assert_eq!(open[0].question, format!("Blocked: {text}"));
+ assert_eq!(card_meta(&env, &open[0]).await[keep_going::ASK_KEY], true);
+ let cards = env.state.db.list_questions(None, Some(&env.channel), None).await.unwrap();
+ assert_eq!(cards.len(), 2, "the answered Keep going? card and the Blocked card: {cards:?}");
+}
+
+/// 22j round 2: after "Keep going" the step works. The reply may open like the one before the
+/// card, but it isn't blocked: the chain goes on.
+#[tokio::test]
+async fn keep_going_then_the_step_works_is_never_blocked() {
+ let env = setup().await;
+ env.queue("res", &["TFAILED:The merge checks found nothing yet."]);
+ env.queue(
+ "kg",
+ &[
+ "TFAILED:Tried the deploy log next, also empty.",
+ "TFAILED:Looked at the release notes, no mention.",
+ "TOK:Looked at the release notes again, no mention.",
+ "Found the startup line.\\nDone: maker_first is on since the 17:18 restart.",
+ ],
+ );
+ person_asks(&env, "Is the maker-first fix merged and live?").await;
+ hand_off(&env, "Check the maker logs", true).await;
+ wait_for("the card", || async { !open_questions(&env).await.is_empty() }).await;
+ settled(&env).await;
+ let card = open_questions(&env).await.remove(0);
+ assert_eq!(card_meta(&env, &card).await[keep_going::CARD_KEY], true);
+
+ answer(&env, &card.id, keep_going::KEEP_GOING).await;
+ wait_for("both turns after Keep going", || async { env.prompts("kg").len() == 4 }).await;
+ settled(&env).await;
+
+ let kg = env.prompts("kg");
+ assert_eq!(kg.len(), 4, "the turn whose step worked goes on to another");
+ assert_eq!(kg.iter().filter(|p| p.contains("Your last step (")).count(), 3, "the turn after the step worked hears no failure: {kg:?}");
+ assert!(!kg[3].contains("Your last step ("), "{}", kg[3]);
+ let cards = env.state.db.list_questions(None, Some(&env.channel), None).await.unwrap();
+ assert!(cards.iter().all(|q| !q.question.starts_with("Blocked: ")), "{cards:?}");
+ assert!(open_questions(&env).await.is_empty());
+ let msgs = messages(&env).await;
+ let replies = lead_replies(&env, &msgs);
+ assert!(replies.iter().all(|m| meta_of(m).get(keep_going::BLOCKED_KEY).is_none()), "nothing blocked");
+ let last = *replies.iter().rev().find(|m| meta_of(m).get("kind").is_none()).unwrap();
+ assert_eq!(meta_of(last)[keep_going::DONE_KEY]["text"], "maker_first is on since the 17:18 restart.");
+}
+
/// 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]