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.

0.9.4: follow through after a failed step, and a Blocked: ending (#535)

Oleksandr Ivanchenkof430c8c9956f
diff --git a/src/drivers/mod.rs b/src/drivers/mod.rs
index 46146265..e5d35f38 100644
--- a/src/drivers/mod.rs
+++ b/src/drivers/mod.rs
@@ -453,8 +453,14 @@ pub const BROWSER_SPEED: &str = "\n[Browser speed]\n\
pub const LOOK_FIRST: &str = "\n\n[Look first, then finish]\n\
- Before you propose or build anything for a project, read what is there: its README, the live site, its design tokens, \
CSS and components. Reuse its styles and words; never guess what a product does from its name.\n\
- - When a step fails, try at least two other ways before you report it (grep without the glob; for dark mode, emulate \
- prefers-color-scheme or set the theme class). Never delete a good result because a retry failed.\n\
+ - On a failed or refused step (an error, a tool that isn't allowed, a timeout), don't stop: retry once if it may have \
+ been a fluke, then reach the result another way: another tool or command, reading instead of running (grep without \
+ the glob; for dark mode, emulate prefers-color-scheme or set the theme class), your bot browser, or a teammate who can. \
+ Never delete a good result because a retry failed. If the person declined an approval card, don't retry that step.\n\
+ - If nothing works, end with one line `Blocked: <what is blocked>. <what would unblock it>`, for example `Blocked: \
+ terminal commands are off for this bot on the shared Mac. Allow Terminal for this team on that computer, then say \
+ continue.`\n\
+ - Never end a turn on \"I'll check…\", \"Let me…\" or \"Next I'll…\": do it in this turn, or end with the Blocked: line.\n\
- Before you say it's done, check the result yourself: run it, render it or take a screenshot.\n\
- Keep the reply short: what you did, what you checked, what is left.";
@@ -1167,9 +1173,24 @@ pub(crate) mod tests {
assert!(!prompt.contains("[Speed]"), "{access:?}");
assert_eq!(prompt.contains("[Browser speed]"), access != BrowserAccess::Unavailable, "{access:?}");
assert_eq!(prompt.matches(LOOK_FIRST).count(), 1, "{access:?}");
- assert!(prompt.contains("try at least two other ways"), "{access:?}");
assert_eq!(prompt.matches(PERSON_SEES).count(), 1, "{access:?}");
}
+ // 0.9.4 follow-through: the three parts of the failed-step rule, once on every engine
+ let rule = [
+ "On a failed or refused step (an error, a tool that isn't allowed, a timeout), don't stop: retry once if it may have been a fluke",
+ "If the person declined an approval card, don't retry that step.",
+ "If nothing works, end with one line `Blocked: <what is blocked>. <what would unblock it>`",
+ "Never end a turn on \"I'll check…\", \"Let me…\" or \"Next I'll…\": do it in this turn, or end with the Blocked: line.",
+ ];
+ let i = with_approvals(crate::mcp::Approvals::Ask);
+ for access in ACCESSES {
+ for (engine, prompt) in engine_prompts(&i, access) {
+ for part in rule {
+ assert_eq!(prompt.matches(part).count(), 1, "{engine} {access:?}: {part}");
+ }
+ assert!(!prompt.contains("try at least two other ways"), "{engine} {access:?}: the old rule is gone");
+ }
+ }
let mut i = input();
i.no_tools = true;
let prompt = i.format_system_prompt();
diff --git a/src/server/delegation.rs b/src/server/delegation.rs
index 4157865f..94c13b80 100644
--- a/src/server/delegation.rs
+++ b/src/server/delegation.rs
@@ -1293,10 +1293,11 @@ pub fn handoff_rules() -> String {
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.\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; \
+ End every reply in one of four 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 \
+ `Done: <what you checked>`; (4) if a step failed and nothing you or a teammate can do gets past it, end with a last \
+ line `Blocked: <what is blocked>. <what would unblock it>`, and kwnt asks the person. 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/delivery_check.rs b/src/server/delivery_check.rs
index 0a91ce41..ad238279 100644
--- a/src/server/delivery_check.rs
+++ b/src/server/delivery_check.rs
@@ -10,6 +10,12 @@
//! Only a firm plan continues ([`DeliveryPlan::firm`]): a lean one ("@Ann look at this") is
//! recorded as a hit or a miss and gets the no-picture line only when the reply claims a picture.
//! - The result is recorded as a delivery hit or miss ([`record_delivery_note`]).
+//! - Follow-through (0.9.4): a turn whose last tool step failed or was refused and whose reply
+//! 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.
//!
//! 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`].
@@ -42,7 +48,7 @@ impl Expect {
}
/// What the turn really did.
-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Seen {
/// It put an image into the chat (`share_file`, `browser_screenshot` with `share: true`).
pub image_shared: bool,
@@ -50,16 +56,45 @@ pub struct Seen {
pub has_shot: bool,
/// It pushed a commit or opened a PR (see [`pushed_in`]).
pub pushed: bool,
+ /// It ran at least one tool step (see [`tool_steps_in`]).
+ pub ran_tools: bool,
+ /// Its last tool step, when that one failed or was refused (see [`tool_steps_in`]). A later
+ /// tool step that worked means the bot moved on: then this is `None`.
+ pub failed_step: Option<FailedStep>,
+ /// The person declined an approval card in it: that step is never pushed again.
+ pub declined: bool,
+}
+
+/// A tool step that failed or was refused: the tool's name and the step's short title.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct FailedStep {
+ pub tool: String,
+ pub title: String,
}
impl Seen {
/// This turn's `self` counted with what its delivery's earlier turns did (`so_far`, which it
/// then joins): an image shared or a push made by any turn of the delivery counts (0.8.1 F1).
/// `has_shot` stays this turn's own: only its own screenshot can be shared under its reply.
+ /// The last tool step is the delivery's last: a turn that ran no tool (a continuation that
+ /// only promised again) still ends after the earlier turn's failed step, and a turn that ran
+ /// tools has its own. A declined card in any of its turns counts.
pub fn with_earlier(self, so_far: &mut Seen) -> Seen {
so_far.image_shared |= self.image_shared;
so_far.pushed |= self.pushed;
- Seen { image_shared: so_far.image_shared, has_shot: self.has_shot, pushed: so_far.pushed }
+ so_far.declined |= self.declined;
+ if self.ran_tools {
+ so_far.ran_tools = true;
+ so_far.failed_step = self.failed_step;
+ }
+ Seen {
+ image_shared: so_far.image_shared,
+ has_shot: self.has_shot,
+ pushed: so_far.pushed,
+ ran_tools: so_far.ran_tools,
+ failed_step: so_far.failed_step.clone(),
+ declined: so_far.declined,
+ }
}
}
@@ -71,6 +106,9 @@ pub enum Missing {
Image,
/// No PR or branch link in the reply, and nothing pushed.
Link,
+ /// The last tool step failed or was refused, and the reply ends on a plan it didn't carry
+ /// out. Never a delivery note (see [`shows`]).
+ FollowThrough,
}
/// A delivery note's verdict.
@@ -95,6 +133,9 @@ pub struct Verdict {
pub continue_with: Option<String>,
/// The delivery note to record: none without a plan, nor while a continuation decides it.
pub outcome: Option<Outcome>,
+ /// Add [`follow_line`] for this tool: the continuation still ended on a promise after a
+ /// failed step.
+ pub follow_line: Option<String>,
}
/// The P9 continuation for a missing image (Ada's wording).
@@ -105,12 +146,42 @@ take a screenshot with share: true, and reply.";
pub const LINK_PROMPT: &str = "You were asked for a change, and your reply has no link to it. Commit and push your work, \
then reply with the PR or branch link.";
+/// Longest promise or step title quoted in the follow-through prompt (characters).
+const MAX_QUOTE_CHARS: usize = 200;
+
+/// The follow-through continuation (0.9.4): what failed and what the reply promised, then the
+/// rule. Ada's wording.
+pub fn follow_prompt(step: &FailedStep, promise: &str) -> String {
+ let title = clip(step.title.trim(), MAX_QUOTE_CHARS);
+ let what = if title.is_empty() || title == step.tool { step.tool.clone() } else { format!("{}: {title}", step.tool) };
+ format!(
+ "Your last step ({what}) failed or was refused, and your reply ends with a plan that didn't run (\"{}\"). \
+Do it now: retry once if it may have been a fluke, then try another way (another tool or command, reading instead of \
+running, your bot browser, or a teammate who can). If nothing works, end with one line \
+`Blocked: <what is blocked>. <what would unblock it>`.",
+ clip(promise.trim(), MAX_QUOTE_CHARS)
+ )
+}
+
+/// 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._")
+}
+
+fn clip(text: &str, max: usize) -> String {
+ match text.char_indices().nth(max) {
+ Some((at, _)) => format!("{}…", &text[..at]),
+ None => text.to_string(),
+ }
+}
+
/// Most `done_when` checks quoted in a continuation, and the longest one (characters).
const MAX_CHECKS: usize = 5;
const MAX_CHECK_CHARS: usize = 200;
/// Checks one reply. `continued` says the turn is the one continuation already. A lean `expect`
-/// never continues and adds the no-picture line only for a claimed picture.
+/// never continues and adds the no-picture line only for a claimed picture. Follow-through
+/// continues with or without a plan (see the module docs).
pub fn check(reply: &str, expect: Option<&Expect>, continued: bool, seen: &Seen) -> Verdict {
let claims = claims_picture(reply);
let wants_image = expect.is_some_and(|e| e.image);
@@ -127,35 +198,51 @@ pub fn check(reply: &str, expect: Option<&Expect>, continued: bool, seen: &Seen)
if expect.is_some_and(|e| e.link) && !seen.pushed && !has_change_link(reply) {
v.missing.push(Missing::Link);
}
+ // Planned misses, before follow-through joins them: only these are a delivery note
+ let planned = v.missing.clone();
+ let follow = seen.failed_step.as_ref().filter(|_| !seen.declined).and_then(|step| Some((step, promise_line(reply)?)));
+ if follow.is_some() {
+ v.missing.push(Missing::FollowThrough);
+ }
let firm = expect.is_some_and(|e| e.firm);
- match expect {
- Some(e) if firm && !v.missing.is_empty() && !continued => {
- v.continue_with = Some(continuation_prompt(&v.missing, &e.done_when))
- }
- _ => {
- v.no_picture_line = !image && (claims || (wants_image && firm));
- v.outcome = expect.map(|_| if v.missing.is_empty() { Outcome::Hit } else { Outcome::Miss });
- }
+ // What one continuation would ask for: a firm plan's misses, and follow-through
+ let mut asks: Vec<Missing> = if firm { planned.clone() } else { vec![] };
+ if follow.is_some() {
+ asks.push(Missing::FollowThrough);
+ }
+ if !asks.is_empty() && !continued {
+ let done_when = expect.map(|e| e.done_when.as_slice()).unwrap_or_default();
+ v.continue_with = Some(continuation_prompt(&asks, done_when, follow));
+ } 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
}
/// The continuation's prompt: what is missing, how to deliver it, and the plan's checks.
-pub fn continuation_prompt(missing: &[Missing], done_when: &[String]) -> String {
+/// `follow` is the failed step and the reply's promise, for [`Missing::FollowThrough`].
+pub fn continuation_prompt(missing: &[Missing], done_when: &[String], follow: Option<(&FailedStep, String)>) -> String {
let what: Vec<&str> = missing
.iter()
.map(|m| match m {
Missing::Image => "an image in the chat",
Missing::Link => "a PR or branch link",
+ Missing::FollowThrough => "another try after the failed step",
})
.collect();
let mut out = format!("[kwnt: one automatic continuation. Missing from your last reply: {}.]", what.join(" and "));
for m in missing {
out.push(' ');
- out.push_str(match m {
- Missing::Image => IMAGE_PROMPT,
- Missing::Link => LINK_PROMPT,
- });
+ match m {
+ Missing::Image => out.push_str(IMAGE_PROMPT),
+ Missing::Link => out.push_str(LINK_PROMPT),
+ Missing::FollowThrough => match &follow {
+ Some((step, promise)) => out.push_str(&follow_prompt(step, promise)),
+ None => continue,
+ },
+ }
}
let checks: Vec<String> = done_when
.iter()
@@ -170,6 +257,113 @@ pub fn continuation_prompt(missing: &[Missing], done_when: &[String]) -> String
out
}
+/// Words that open a first-person plan: "I'll check…", "Let me retry…", "I'm going to…".
+const PROMISE_OPENERS: &[&str] = &["i'll ", "i will ", "let me ", "i'm going to ", "i am going to ", "going to ", "i'm gonna "];
+/// Words a plan may start with before its opener: "Next, I'll…", "Now let me…".
+const PROMISE_LEADS: &[&str] = &["next", "now", "then", "so", "ok", "okay", "first", "and", "after that"];
+/// A last paragraph with any of these waits on the person or offers, so it isn't a promise:
+/// "I'll continue once you allow Terminal", "Let me know if…", "I'll wait for your answer".
+const NOT_A_PROMISE: &[&str] = &[
+ "once you", "when you", "after you", "if you", "as soon as you", "until you", "let me know", "wait for you",
+ "waiting for you", "wait for your", "i'll be here", "i'll wait",
+];
+
+/// The plan the reply ends on and didn't carry out, if it does (0.9.4): its last paragraph
+/// (the last item of a list), markdown aside, has a sentence that opens in the first person with
+/// "I'll", "I will", "Let me", "Next I'll", "Now I'll", "I'm going to" or "Going to". Not a promise:
+/// a `Done:` or `Blocked:` line, a question to the person, or a line that waits on the person
+/// ("once you…", "when you…", "after you…", "if you…") or offers ("Let me know…"). Conservative
+/// on purpose: it only matters after a failed step. Returns that sentence.
+pub fn promise_line(reply: &str) -> Option<String> {
+ let para = reply.split("\n\n").map(str::trim).filter(|p| !p.is_empty()).last()?;
+ let lines: Vec<&str> = para.lines().map(str::trim).filter(|l| !l.is_empty()).collect();
+ let listed = |l: &str| l.starts_with(['-', '*', '+']) || l.split_once(['.', ')']).is_some_and(|(n, _)| !n.is_empty() && n.chars().all(|c| c.is_ascii_digit()));
+ let last = if lines.iter().any(|l| listed(l)) { lines.last()?.to_string() } else { lines.join(" ") };
+ let bare = strip_markdown(&last).replace(['’', '‘'], "'");
+ // ASCII lowercase keeps byte offsets, so the sentence spans index `bare` too
+ let lower = bare.to_ascii_lowercase();
+ if lower.starts_with("done:") || lower.starts_with("blocked:") || lower.trim_end_matches(['*', '_', '`', ')', ' ']).ends_with('?') {
+ return None;
+ }
+ if NOT_A_PROMISE.iter().any(|w| lower.contains(w)) {
+ return None;
+ }
+ let sentences = sentence_spans(&lower);
+ sentences.into_iter().find_map(|(at, end)| {
+ let s = lower[at..end].trim_start();
+ let s = strip_leads(s);
+ PROMISE_OPENERS.iter().any(|o| s.starts_with(o)).then(|| bare[at..end].trim().to_string())
+ })
+}
+
+/// A line without its leading list marker, heading or quote, and the emphasis around it.
+fn strip_markdown(line: &str) -> String {
+ let mut s = line.trim();
+ loop {
+ let before = s;
+ s = s.trim_start_matches(['#', '>', '*', '_', '`', '-', '+', ' ']);
+ if let Some((n, rest)) = s.split_once(['.', ')']) {
+ if !n.is_empty() && n.len() <= 3 && n.chars().all(|c| c.is_ascii_digit()) {
+ s = rest;
+ }
+ }
+ if s == before {
+ break;
+ }
+ }
+ s.replace("**", "").replace("__", "").trim().to_string()
+}
+
+/// Byte spans of the sentences in `text`: they end at ". ", "! ", "; " or ": ".
+fn sentence_spans(text: &str) -> Vec<(usize, usize)> {
+ let mut out = Vec::new();
+ let mut start = 0;
+ let bytes = text.as_bytes();
+ for (i, b) in bytes.iter().enumerate() {
+ if matches!(b, b'.' | b'!' | b';' | b':') && bytes.get(i + 1).is_some_and(|n| *n == b' ') {
+ out.push((start, i + 1));
+ start = i + 1;
+ }
+ }
+ if start < text.len() {
+ out.push((start, text.len()));
+ }
+ out
+}
+
+/// A sentence without the words a plan may start with ("Next, ", "Now ").
+fn strip_leads(mut s: &str) -> &str {
+ loop {
+ let before = s;
+ for lead in PROMISE_LEADS {
+ if let Some(rest) = s.strip_prefix(lead) {
+ if rest.starts_with([' ', ',']) {
+ s = rest.trim_start_matches([',', ' ']);
+ }
+ }
+ }
+ if s == before {
+ return s;
+ }
+ }
+}
+
+/// The turn's tool steps, from its saved activity (`{"steps": [...]}`): whether it ran any, its
+/// last one when that one failed (a refused tool call is a failed step too), and whether the
+/// person declined an approval card in it.
+pub fn tool_steps_in(activity: Option<&Value>) -> (bool, Option<FailedStep>, bool) {
+ let Some(steps) = activity.and_then(|a| a["steps"].as_array()) else {
+ return (false, None, false);
+ };
+ let declined = steps.iter().any(|s| s["kind"] == "approval" && s["status"] == "declined");
+ let last = steps.iter().rfind(|s| s["kind"] == "tool" && !matches!(s["status"].as_str(), Some("running" | "waiting")));
+ 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(),
+ });
+ (last.is_some(), failed, declined)
+}
+
/// The reply links a PR, merge request, branch, compare view or commit on a git host
/// (`…/owner/repo/pull/12`, `…/-/merge_requests/3`, `…/pull-requests/4`, `…/tree/branch`,
/// `…/compare/a...b`, `…/commit/sha`).
@@ -249,11 +443,13 @@ async fn record_in(db: &crate::db::Database, kwant_id: &str, context_id: &str, e
super::delivery_plan::record_check(db, kwant_id, context_id, &wanted, outcome == Outcome::Hit, &missing).await;
}
-/// What `expect` wanted and what was `missing`, as the delivery note's [`Show`]s.
+/// What `expect` wanted and what was `missing`, as the delivery note's [`Show`]s. Follow-through
+/// isn't something the plan wanted, so the planner never learns from it.
fn shows(expect: &Expect, missing: &[Missing]) -> (Vec<Show>, Vec<Show>) {
let show = |m: &Missing| match m {
- Missing::Image => Show::Image,
- Missing::Link => Show::Link,
+ Missing::Image => Some(Show::Image),
+ Missing::Link => Some(Show::Link),
+ Missing::FollowThrough => None,
};
let mut wanted = Vec::new();
if expect.image {
@@ -262,7 +458,7 @@ fn shows(expect: &Expect, missing: &[Missing]) -> (Vec<Show>, Vec<Show>) {
if expect.link {
wanted.push(Show::Link);
}
- (wanted, missing.iter().map(show).collect())
+ (wanted, missing.iter().filter_map(show).collect())
}
/// Runs `again` (the continuation turn, given its prompt) when the first turn's check asked for
@@ -282,18 +478,20 @@ where
}
}
-/// The reply as saved: with [`NO_PICTURE_LINE`](super::picture_claims::NO_PICTURE_LINE) when the verdict says so.
+/// 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 {
- if v.no_picture_line {
- super::picture_claims::with_no_picture_line(&reply)
- } else {
- reply
+ 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(),
+ None => reply,
}
}
/// The reply's `meta.delivery`, when the check ran (`checked`) and did something or had an
/// expectation: `{"missing": [...], "auto_shared": bool, "no_picture": bool, "continues": bool,
-/// "outcome": "hit"|"miss", "lean": bool}` (`lean`: the plan only leaned, so it didn't continue). A turn the check skips (see `TurnOpts::delivery_checked`) has none.
+/// "outcome": "hit"|"miss", "lean": bool, "follow_line": bool}` (`lean`: the plan only leaned, so it didn't continue;
+/// `follow_line`: [`follow_line`] was added). A turn the check skips (see `TurnOpts::delivery_checked`) has none.
pub fn meta(v: &Verdict, expect: Option<&Expect>, checked: bool) -> Option<Value> {
if !checked || (*v == Verdict::default() && expect.is_none()) {
return None;
@@ -305,6 +503,7 @@ pub fn meta(v: &Verdict, expect: Option<&Expect>, checked: bool) -> Option<Value
"continues": v.continue_with.is_some(),
"outcome": v.outcome,
"lean": expect.is_some_and(|e| !e.firm),
+ "follow_line": v.follow_line.is_some(),
}))
}
@@ -312,6 +511,7 @@ pub fn meta(v: &Verdict, expect: Option<&Expect>, checked: bool) -> Option<Value
mod tests {
use super::*;
use crate::router::delivery::Deliverable;
+ use serde_json::json;
use crate::server::picture_claims::NO_PICTURE_LINE;
use std::sync::atomic::{AtomicUsize, Ordering};
@@ -324,9 +524,9 @@ mod tests {
fn explain() -> Expect {
Expect::default()
}
- const NOTHING: Seen = Seen { image_shared: false, has_shot: false, pushed: false };
- const SHARED: Seen = Seen { image_shared: true, has_shot: true, pushed: false };
- const SHOT: Seen = Seen { image_shared: false, has_shot: true, pushed: false };
+ const NOTHING: Seen = Seen { image_shared: false, has_shot: false, pushed: false, ran_tools: false, failed_step: None, declined: false };
+ const SHARED: Seen = Seen { image_shared: true, has_shot: true, ..NOTHING };
+ const SHOT: Seen = Seen { has_shot: true, ..NOTHING };
/// Plays a turn and its continuation the way `routes::try_kwant_turn` does: returns the joined
/// reply, how many continuations ran, and the last verdict.
@@ -687,9 +887,163 @@ mod tests {
let mut delivery = Seen::default();
let pushed = Seen { pushed: true, ..SHOT }.with_earlier(&mut delivery);
- assert_eq!(pushed, Seen { image_shared: false, has_shot: true, pushed: true });
+ assert_eq!(pushed, Seen { has_shot: true, pushed: true, ..NOTHING });
let next = NOTHING.with_earlier(&mut delivery);
- assert_eq!(next, Seen { image_shared: false, has_shot: false, pushed: true }, "the shot stays the first turn's");
+ assert_eq!(next, Seen { pushed: true, ..NOTHING }, "the shot stays the first turn's");
assert!(!check("Done, no link here.", Some(&change()), true, &next).missing.contains(&Missing::Link));
}
+
+ // ---- 0.9.4 follow-through ----
+
+ 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 }
+ }
+
+ #[test]
+ fn a_reply_that_ends_on_a_plan_is_a_promise() {
+ assert_eq!(promise_line(REAL).as_deref(), Some("I'll check the file sizes and measure the frame timings next."));
+ for (reply, want) in [
+ ("Tried it.\n\nLet me retry with a smaller batch.", "Let me retry with a smaller batch."),
+ ("Failed.\n\nNext, I’ll open the page in the browser.", "Next, I'll open the page in the browser."),
+ ("Failed.\n\n**Now I'll** read the log instead.", "Now I'll read the log instead."),
+ ("The build broke. I'm going to run it again with logs.", "I'm going to run it again with logs."),
+ ("Summary:\n- tests pass\n- I will push the fix next", "I will push the fix next"),
+ ("Refused.\n\nGoing to try the API instead.", "Going to try the API instead."),
+ ] {
+ assert_eq!(promise_line(reply).as_deref(), Some(want), "{reply}");
+ }
+ }
+
+ #[test]
+ fn done_blocked_questions_and_waits_are_not_promises() {
+ for reply in [
+ "Done: the render is at out.mp4 and plays.",
+ "The render was refused.\n\nBlocked: terminal commands are off for this bot. Allow Terminal, then say continue.",
+ "I'll need your pick: should I use the dark theme?",
+ "I'll continue once you allow Terminal on the Mac.",
+ "I'll pick it up when you've signed in.",
+ "Let me know if you want the long version.",
+ "I'll wait for your answer.",
+ "I'll run it again after you add the key.",
+ "If you want, I'll redo it in 4K.",
+ "The render failed, so I used the old frames instead. The video is at out.mp4.",
+ "I'll check the logs.\n\nThe render is at out.mp4 and plays.",
+ "",
+ ] {
+ assert_eq!(promise_line(reply), None, "{reply}");
+ }
+ }
+
+ #[test]
+ fn the_last_tool_step_is_read_from_the_activity() {
+ let steps = |s: Value| Some(json!({ "steps": s }));
+ 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": "note", "status": "done" },
+ ]))
+ .as_ref());
+ assert!(ran && !d);
+ assert_eq!(f, Some(FailedStep { tool: "Bash".into(), title: "render".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" },
+ { "kind": "tool", "tool": "Bash", "title": "render small", "status": "ok" },
+ ]))
+ .as_ref());
+ assert_eq!(f, None);
+ // A declined card is seen; no activity is nothing
+ let (_, _, d) = tool_steps_in(steps(json!([{ "kind": "approval", "status": "declined" }, { "kind": "tool", "tool": "Bash", "status": "failed" }])).as_ref());
+ assert!(d);
+ assert_eq!(tool_steps_in(None), (false, None, false));
+ }
+
+ #[test]
+ fn a_failed_step_and_a_promise_continue_once_without_a_plan() {
+ let v = check(REAL, None, false, &failed("Bash"));
+ assert_eq!(v.missing, vec![Missing::FollowThrough]);
+ let prompt = v.continue_with.expect("follow-through continues without a plan");
+ assert!(prompt.contains("Your last step (Bash: render the video) failed or was refused"), "{prompt}");
+ assert!(prompt.contains("(\"I'll check the file sizes and measure the frame timings next.\")"), "{prompt}");
+ assert!(prompt.contains("`Blocked: <what is blocked>. <what would unblock it>`"), "{prompt}");
+ assert_eq!(v.outcome, None, "no plan, no delivery note");
+ // Lean plans and firm ones alike
+ let lean = Expect { firm: false, ..explain() };
+ assert!(check(REAL, Some(&lean), false, &failed("Bash")).continue_with.is_some());
+ assert!(check(REAL, Some(&explain()), false, &failed("Bash")).continue_with.is_some());
+ }
+
+ #[test]
+ fn a_later_ok_step_a_declined_card_or_no_promise_doesnt_continue() {
+ assert_eq!(check(REAL, None, false, &Seen { ran_tools: true, ..NOTHING }).continue_with, None, "the last step worked");
+ assert_eq!(check(REAL, None, false, &Seen { declined: true, ..failed("Bash") }).continue_with, None, "the person declined");
+ let blocked = "Refused.\n\nBlocked: terminal is off. Allow Terminal, then say continue.";
+ assert_eq!(check(blocked, None, false, &failed("Bash")).continue_with, None);
+ assert_eq!(check("The render is at out.mp4.", None, false, &failed("Bash")).continue_with, None);
+ }
+
+ #[test]
+ fn the_continuation_never_continues_and_gets_the_kwant_line() {
+ 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!(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);
+ }
+
+ #[test]
+ fn an_image_miss_and_follow_through_are_one_prompt() {
+ let v = check(REAL, Some(&ideas()), false, &failed("Bash"));
+ assert_eq!(v.missing, vec![Missing::Image, Missing::FollowThrough]);
+ let prompt = v.continue_with.unwrap();
+ assert_eq!(prompt.matches("[kwnt: one automatic continuation").count(), 1, "{prompt}");
+ assert!(prompt.contains("Missing from your last reply: an image in the chat and another try after the failed step."), "{prompt}");
+ assert!(prompt.contains(IMAGE_PROMPT) && prompt.contains("Your last step (Bash"), "{prompt}");
+ assert!(prompt.contains("Done when: one mockup image per idea is shared."), "{prompt}");
+ // A lean plan's image miss isn't asked for; follow-through still is
+ let lean = Expect { firm: false, ..ideas() };
+ let prompt = check(REAL, Some(&lean), false, &failed("Bash")).continue_with.unwrap();
+ assert!(!prompt.contains(IMAGE_PROMPT) && prompt.contains("Your last step"), "{prompt}");
+ }
+
+ #[test]
+ fn follow_through_is_never_a_delivery_note() {
+ let (_, missing) = shows(&change(), &[Missing::FollowThrough]);
+ assert!(missing.is_empty());
+ // The outcome after the continuation is the plan's own: a hit here
+ let v = check("Still broken.\n\nI'll look again.", Some(&change()), true, &Seen { pushed: true, ..failed("Bash") });
+ assert_eq!((v.outcome, v.missing), (Some(Outcome::Hit), vec![Missing::FollowThrough]));
+ }
+
+ #[test]
+ fn a_continuation_without_tools_keeps_the_failed_step() {
+ let mut delivery = Seen::default();
+ let first = failed("Bash").with_earlier(&mut delivery);
+ assert!(first.failed_step.is_some());
+ let then = NOTHING.with_earlier(&mut delivery);
+ assert_eq!(then.failed_step, first.failed_step, "it promised again without trying");
+ let fixed = Seen { ran_tools: true, ..NOTHING }.with_earlier(&mut delivery);
+ assert_eq!(fixed.failed_step, None, "it ran a tool that worked");
+ let declined = Seen { declined: true, ..NOTHING }.with_earlier(&mut delivery);
+ assert!(declined.declined && Seen::default().with_earlier(&mut delivery).declined);
+ }
+
+ #[tokio::test]
+ async fn a_failed_step_plays_out_as_one_continuation() {
+ let (text, runs, last) = play(None, (REAL, failed("Bash")), ("Rendered with ffmpeg instead: out.mp4.", Seen { ran_tools: true, ..NOTHING })).await;
+ assert_eq!(runs, 1);
+ assert_eq!(text, format!("{REAL}\n\nRendered with ffmpeg instead: out.mp4."));
+ assert_eq!(last.follow_line, None);
+ }
}
diff --git a/src/server/keep_going.rs b/src/server/keep_going.rs
index f07f308e..f7ea231c 100644
--- a/src/server/keep_going.rs
+++ b/src/server/keep_going.rs
@@ -11,7 +11,10 @@
//! - 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`].
+//! The `Done:` line is stored on the reply's meta as [`DONE_KEY`]. A lead whose last line is
+//! `Blocked: <what is blocked>. <what would unblock it>` (0.9.4) never gets a keep-going turn: the
+//! line becomes a question card at once, like a question, and its answer resumes the chain. The
+//! save step stores any reply's `Blocked:` line on its meta as [`BLOCKED_KEY`].
use super::routes::{try_kwant_turn, TurnOpts, TurnScope};
use super::AppState;
@@ -36,6 +39,8 @@ pub const CARD_KEY: &str = "keep_going_card";
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";
+/// On a reply that ends with `Blocked: …` (0.9.4): `{text}`, what is blocked and what unblocks it.
+pub const BLOCKED_KEY: &str = "blocked";
pub const KEEP_GOING: &str = "Keep going";
pub const ENOUGH: &str = "That's enough for now";
/// What a keep-going turn is told.
@@ -63,13 +68,24 @@ pub async fn turns_allowed(state: &AppState) -> usize {
/// 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> {
+ end_line(reply, "done:")
+}
+
+/// The `Blocked: <what is blocked>. <what would unblock it>` line a reply ends with, if it does
+/// (0.9.4): parsed like [`done_line`].
+pub fn blocked_line(reply: &str) -> Option<String> {
+ end_line(reply, "blocked:")
+}
+
+/// The reply's last non-empty line, markdown decoration aside, when it starts with `head`
+/// (lowercase, ASCII, ending in ':'): what follows it.
+fn end_line(reply: &str, head: &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:") {
+ if !bare.get(..head.len())?.eq_ignore_ascii_case(head) {
return None;
}
- let what = bare[5..].trim().trim_matches(['*', '_', '`', ' ']).trim();
+ let what = bare[head.len()..].trim().trim_matches(['*', '_', '`', ' ']).trim();
(!what.is_empty()).then(|| what.to_string())
}
@@ -176,6 +192,10 @@ async fn verdict(scope: &TurnScope, lead: &Kwant, snap: &Snapshot, reply: &str)
if let Some(done) = done_line(reply) {
return Verdict::Done(done);
}
+ // Blocked: only the person (or a setting) unblocks it, so it is asked, never pushed on
+ if let Some(blocked) = blocked_line(reply) {
+ return Verdict::Asks(format!("Blocked: {blocked}"));
+ }
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);
@@ -371,6 +391,24 @@ mod tests {
assert_eq!(done_line("Dön"), None);
}
+ #[test]
+ fn a_blocked_line_ends_the_reply() {
+ let real = "The render failed twice.\n\nBlocked: terminal commands are off for this bot on the shared Mac. Allow Terminal for this team on that computer, then say continue.";
+ assert_eq!(
+ blocked_line(real).as_deref(),
+ Some("terminal commands are off for this bot on the shared Mac. Allow Terminal for this team on that computer, then say continue.")
+ );
+ assert_eq!(blocked_line("**Blocked:** no key for the Stripe API. Add it in Settings.").as_deref(), Some("no key for the Stripe API. Add it in Settings."));
+ assert_eq!(blocked_line("- blocked: CI is down\n\n").as_deref(), Some("CI is down"));
+ // Not the last line, empty, a Done line, or "blocked" inside a sentence
+ assert_eq!(blocked_line("Blocked: CI.\nI'll retry later."), None);
+ assert_eq!(blocked_line("Blocked:"), None);
+ assert_eq!(blocked_line("Done: checked it."), None);
+ assert_eq!(blocked_line("The deploy is blocked: no key."), None);
+ assert_eq!(done_line("Blocked: CI is down."), None);
+ assert_eq!(blocked_line(""), 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");
diff --git a/src/server/routes.rs b/src/server/routes.rs
index 09e7a286..7044959b 100644
--- a/src/server/routes.rs
+++ b/src/server/routes.rs
@@ -2043,7 +2043,19 @@ pub(super) type ChatHandover = std::sync::Arc<std::sync::Mutex<Option<super::tur
pub(super) type DeliverySeen = std::sync::Arc<std::sync::Mutex<super::delivery_check::Seen>>;
/// See [`TurnOpts::delivery_next`].
-pub(super) type DeliveryNext = std::sync::Arc<std::sync::Mutex<Option<(String, crate::router::delivery::DeliveryPlan)>>>;
+pub(super) type DeliveryNext = std::sync::Arc<std::sync::Mutex<Option<NextTurn>>>;
+
+/// The delivery check's one continuation, as the save step asked for it.
+#[derive(Debug, Clone)]
+pub struct NextTurn {
+ pub prompt: String,
+ /// The plan it is checked against: none for a follow-through continuation without one.
+ pub plan: Option<crate::router::delivery::DeliveryPlan>,
+ /// It is only a follow-through continuation: the last step failed and the reply ended on a
+ /// plan it didn't carry out (see [`super::delivery_check::promise_line`]), and nothing the
+ /// plan wanted is missing. Its label says so.
+ pub follow_through: bool,
+}
impl TurnOpts {
/// Options that run the turn on `agent` at `effort` (both needed), skipping Laya.
@@ -2148,11 +2160,11 @@ pub(super) async fn try_kwant_turn(
opts.delivery_seen = Some(DeliverySeen::default());
let carried = Carried::of(&opts);
let first = try_kwant_turn_once(scope, target_kwant, prompt, opts).await;
- let Some((prompt, plan)) = next.and_then(|n| n.lock().ok().and_then(|mut n| n.take())) else {
+ let Some(NextTurn { prompt, plan, follow_through }) = next.and_then(|n| n.lock().ok().and_then(|mut n| n.take())) else {
return first;
};
- tracing::info!(kwant = %target_kwant.id, "reply missed what the person expected: one automatic continuation");
- let again = |prompt: String| try_kwant_turn_once(scope, target_kwant, prompt, carried.continuation(plan, handover));
+ tracing::info!(kwant = %target_kwant.id, follow_through, "reply missed what the person expected: one automatic continuation");
+ let again = |prompt: String| try_kwant_turn_once(scope, target_kwant, prompt, carried.continuation(plan, follow_through, handover));
super::delivery_check::after_turn(first, Some(prompt), scope.cancel_token.is_cancelled(), again).await
}
@@ -2254,11 +2266,17 @@ impl Carried {
/// (kwant's continuation prompt never makes a new one), and never continued again. It starts
/// on the first turn's chat slot when `handover` holds it (see [`TurnOpts::chat_handover`]),
/// and counts what the delivery's earlier turns did (see [`TurnOpts::delivery_seen`]).
- fn continuation(self, plan: crate::router::delivery::DeliveryPlan, handover: Option<ChatHandover>) -> TurnOpts {
+ /// `follow_through`: it only continues after a failed step the reply promised to get past.
+ fn continuation(self, plan: Option<crate::router::delivery::DeliveryPlan>, follow_through: bool, handover: Option<ChatHandover>) -> TurnOpts {
let delivery_seen = self.delivery_seen.clone();
+ let label = if follow_through {
+ "Automatic continuation (once): the last step failed and the reply ended on a plan that didn't run"
+ } else {
+ "Automatic continuation (once): the reply was missing what the person expected"
+ };
TurnOpts {
- label: Some("Automatic continuation (once): the reply was missing what the person expected".into()),
- delivery: Some(plan),
+ label: Some(label.into()),
+ delivery: plan,
delivery_continued: true,
chat_handover: handover,
delivery_seen,
@@ -3643,10 +3661,15 @@ async fn run_kwant_turn_inner(
let expect = plan.as_ref().and_then(super::delivery_check::Expect::from_plan);
let checked = opts.delivery_checked();
let verdict = if checked {
+ // Follow-through (0.9.4): the turn's last tool step, if it failed, and a declined card
+ let (ran_tools, failed_step, declined) = super::delivery_check::tool_steps_in(activity.as_ref());
let own = super::delivery_check::Seen {
image_shared: pictures.shared_image,
has_shot: pictures.last_shot.is_some(),
pushed: super::delivery_check::pushed_in(activity.as_ref()),
+ ran_tools,
+ failed_step,
+ declined,
};
// ...counting what the delivery's earlier turns did (F1)
let seen = match opts.delivery_seen.as_ref().map(|d| d.lock()) {
@@ -3701,6 +3724,10 @@ async fn run_kwant_turn_inner(
if let Some(delivery) = super::delivery_check::meta(&verdict, expect.as_ref(), checked) {
meta.get_or_insert_with(|| serde_json::json!({}))["delivery"] = delivery;
}
+ // 0.9.4: a reply that ends with `Blocked: <what>. <what unblocks it>` says so in its meta
+ if let Some(blocked) = super::keep_going::blocked_line(&asst_msg.text) {
+ meta.get_or_insert_with(|| serde_json::json!({}))[super::keep_going::BLOCKED_KEY] = serde_json::json!({ "text": blocked });
+ }
let meta = super::decide::with_decisions(meta, &decisions);
let meta = super::activity::with_activity(meta, activity);
// The claimed picture goes with the reply, posted as the bot. Saved before the reply,
@@ -3755,9 +3782,15 @@ async fn run_kwant_turn_inner(
// A held reply is decided first (the decided reply is checked against the held
// plan and continues through the same slot); only a reply the person sees is
// continued or recorded. The continuation carries this plan, never a new one.
- if let (Some(prompt), Some(next), Some(p)) = (&verdict.continue_with, &opts.delivery_next, &plan) {
- if let Ok(mut next) = next.lock() {
- *next = Some((prompt.clone(), p.clone()));
+ if let (Some(prompt), Some(next)) = (&verdict.continue_with, &opts.delivery_next) {
+ use super::delivery_check::Missing;
+ let follow = verdict.missing.contains(&Missing::FollowThrough);
+ let follow_through = follow && verdict.missing.iter().all(|m| *m == Missing::FollowThrough);
+ // A plan's misses continue only with that plan; follow-through needs none
+ if plan.is_some() || follow {
+ if let Ok(mut next) = next.lock() {
+ *next = Some(NextTurn { prompt: prompt.clone(), plan: plan.clone(), follow_through });
+ }
}
}
if let (Some(outcome), Some(e)) = (verdict.outcome, &expect) {
@@ -6736,7 +6769,7 @@ mod tests {
let first = person_turn();
assert!(first.continuation_slot().is_some());
let ideas = turn_plan(&first, Some(&saved("user", "user", "What cool feature can we add?", None)), &[], true, "").unwrap();
- let next = Carried::of(&first).continuation(ideas.clone(), None);
+ let next = Carried::of(&first).continuation(Some(ideas.clone()), false, None);
assert_eq!(next.delivery.as_ref(), Some(&ideas));
assert!(next.delivery_continued && next.continuation_slot().is_none(), "continued once at most");
// kwant's continuation prompt can't make a plan of its own
@@ -6747,6 +6780,18 @@ mod tests {
assert!(v.continue_with.is_none() && v.outcome.is_some(), "{v:?}");
}
+ /// 0.9.4 follow-through: a continuation with no plan stays without one (kwant's prompt can't
+ /// make one), says why it runs, and is never continued again.
+ #[test]
+ fn a_follow_through_continuation_has_no_plan_and_never_continues_again() {
+ let next = Carried::of(&person_turn()).continuation(None, true, None);
+ assert_eq!(next.delivery, None);
+ assert!(next.label.as_deref().is_some_and(|l| l.contains("the last step failed")), "{:?}", next.label);
+ assert!(next.delivery_continued && next.continuation_slot().is_none());
+ let prompt = saved("user", "user", "Your last step (Bash) failed or was refused, and your reply ends with a plan", None);
+ assert_eq!(turn_plan(&next, Some(&prompt), &[], true, ""), None);
+ }
+
/// #469 round 3, must-fix 2: no-tools, fresh-eyes and BRIEF turns get no plan, so no hint
/// and no delivery note, even with a plan carried in.
#[test]
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
index 786c3fca..019797f7 100644
--- a/tests/common/mod.rs
+++ b/tests/common/mod.rs
@@ -14,6 +14,8 @@
//! slow reply, or a stall when it waits past the stall limit).
//! - `FAILTURN`: die with no output. `APIERROR:<tag>` / `APIERRORPLAIN:<tag>`: end with "API Error:
//! 500 test stub" as claude's error result / as plain text, once per tag.
+//! - `FAILSTEP:<tag>` / `BLOCKSTEP:<tag>` in the current request (not the history): run a Bash
+//! tool step that fails, then end on a plan ("I'll retry the render…") / on a `Blocked:` line.
//!
//! Each test file that uses it is its own binary, because it changes PATH.
#![allow(dead_code)]
@@ -91,6 +93,22 @@ if cap:
text = "partial " + cap[-1] + note
print(json.dumps({"type": "result", "is_error": False, "num_turns": 1, "result": text}))
sys.exit(0)
+# FAILSTEP:<tag> / BLOCKSTEP:<tag> in the current request: a Bash step that fails, then a reply
+# that ends on a plan / on a Blocked: line
+req = prompt.rsplit("Current User Request:\n", 1)[-1]
+fs = re.findall(r"(FAIL|BLOCK)STEP:([A-Za-z0-9_]+)", req)
+if fs:
+ kind, tag = fs[-1]
+ tid = "toolu_" + tag
+ print(json.dumps({"type": "assistant", "message": {"id": "msg_" + tag, "content": [
+ {"type": "tool_use", "id": tid, "name": "Bash", "input": {"command": "render.sh", "description": "render the intro"}}]}}))
+ print(json.dumps({"type": "user", "message": {"content": [
+ {"type": "tool_result", "tool_use_id": tid, "is_error": True, "content": "Permission to use Bash has been denied."}]}}))
+ end = ("I'll retry the render with a smaller size next." if kind == "FAIL"
+ else "Blocked: terminal commands are off for this bot. Allow Terminal for this team, then say continue.")
+ print(json.dumps({"type": "result", "is_error": False, "num_turns": 2,
+ "result": "The render command was refused (" + tag + ").\n\n" + end}))
+ sys.exit(0)
# REPLYTEXT:<base64>: reply exactly that text
rt = re.findall(r"REPLYTEXT:([A-Za-z0-9+/=]+)", prompt)
if rt:
diff --git a/tests/follow_through_test.rs b/tests/follow_through_test.rs
new file mode 100644
index 00000000..0f9c9992
--- /dev/null
+++ b/tests/follow_through_test.rs
@@ -0,0 +1,103 @@
+//! 0.9.4 follow-through: a turn whose last tool step failed and whose reply ends on a plan it
+//! didn't carry out ("I'll retry the render…") gets exactly one automatic continuation, with no
+//! delivery plan needed. A reply that ends with `Blocked: …` instead gets none, and its meta keeps
+//! the line (`meta.blocked`).
+//!
+//! The bot's folder isn't a git repository and the asks aren't for a picture or a change, so
+//! nothing but follow-through can continue them.
+
+mod common;
+
+use common::*;
+use std::time::Duration;
+
+/// The start of kwant's follow-through prompt (`delivery_check::follow_prompt`).
+const FOLLOW: &str = "failed or was refused, and your reply ends with a plan that didn't run";
+
+/// The request a CLI run answers: its prompt's current request, without the chat history.
+fn request_of(args: &str) -> &str {
+ let prompt = args.rsplit_once("\n-p\n").map_or(args, |(_, p)| p);
+ prompt.rsplit_once("### Current User Request:\n").map_or(prompt, |(_, r)| r)
+}
+
+/// The requests of `env`'s CLI runs (their arguments name its data folder).
+fn requests(env: &Env) -> Vec<String> {
+ let data = env.tmp.path().display().to_string();
+ std::fs::read_dir(prompts_dir())
+ .unwrap()
+ .filter_map(|e| std::fs::read_to_string(e.ok()?.path()).ok())
+ .filter(|args| args.contains(&data))
+ .map(|args| request_of(&args).to_string())
+ .collect()
+}
+
+fn meta_of(m: &kwnt::db::models::Message) -> serde_json::Value {
+ m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or_default()
+}
+
+async fn replies_of(env: &Env, kwant: &str) -> Vec<kwnt::db::models::Message> {
+ messages(env, kwant).await.into_iter().filter(|m| m.sender_role == "kwant").collect()
+}
+
+fn bot_idle(env: &Env, kwant: &str) -> bool {
+ env.state.turns.active_turns().iter().all(|t| t.kwant_id != kwant)
+}
+
+#[tokio::test]
+async fn a_failed_step_and_a_promise_get_one_continuation() {
+ let env = setup().await;
+ let a = env.a.clone();
+ send_direct(&env, &a, "How long are the intro's frames? FAILSTEP:zqfail REPLYTAG:zqfail", serde_json::json!({})).await;
+ wait_for("two replies", || async { replies_of(&env, &a).await.len() >= 2 }).await;
+ wait_for("the bot to finish", || async { bot_idle(&env, &a) }).await;
+ tokio::time::sleep(Duration::from_millis(500)).await;
+
+ let replies = replies_of(&env, &a).await;
+ assert_eq!(replies.len(), 2, "the reply and its one continuation: {replies:#?}");
+ assert_eq!(replies[0].text, "The render command was refused (zqfail).\n\nI'll retry the render with a smaller size next.");
+ let first = meta_of(&replies[0]);
+ assert_eq!(first["delivery"]["missing"], serde_json::json!(["follow_through"]), "{first}");
+ assert_eq!(first["delivery"]["continues"], true, "{first}");
+ let steps = first["activity"]["steps"].as_array().cloned().unwrap_or_default();
+ assert!(steps.iter().any(|s| s["kind"] == "tool" && s["status"] == "failed"), "the failed step is in the activity: {first}");
+
+ // Exactly one continuation, told what failed and what it promised
+ let all = requests(&env);
+ let cont: Vec<&String> = all.iter().filter(|r| r.contains(FOLLOW)).collect();
+ assert_eq!(cont.len(), 1, "{all:#?}");
+ assert!(cont[0].contains("Your last step (Bash"), "{}", cont[0]);
+ assert!(cont[0].contains("(\"I'll retry the render with a smaller size next.\")"), "{}", cont[0]);
+ assert!(cont[0].contains("`Blocked: <what is blocked>. <what would unblock it>`"), "{}", cont[0]);
+ assert_eq!(all.len(), 2, "{all:#?}");
+
+ // The continuation ran no tool and answered without a promise: never continued, no kwant line
+ assert_eq!(replies[1].text, "answer zqfail");
+ let second = meta_of(&replies[1]);
+ assert_ne!(second["delivery"]["continues"], true, "{second}");
+ assert!(second.get("blocked").is_none(), "{second}");
+ let label = replies[1].reasoning_content.as_deref().unwrap_or_default();
+ assert!(label.contains("the last step failed and the reply ended on a plan"), "{label}");
+}
+
+#[tokio::test]
+async fn a_blocked_line_ends_it_without_a_continuation() {
+ let env = setup().await;
+ let a = env.a.clone();
+ send_direct(&env, &a, "How long are the outro's frames? BLOCKSTEP:zqblock REPLYTAG:zqblock", serde_json::json!({})).await;
+ wait_for("a reply", || async { !replies_of(&env, &a).await.is_empty() }).await;
+ wait_for("the bot to finish", || async { bot_idle(&env, &a) }).await;
+ tokio::time::sleep(Duration::from_millis(800)).await;
+
+ let replies = replies_of(&env, &a).await;
+ assert_eq!(replies.len(), 1, "no continuation: {replies:#?}");
+ let meta = meta_of(&replies[0]);
+ assert_eq!(
+ meta["blocked"],
+ serde_json::json!({"text": "terminal commands are off for this bot. Allow Terminal for this team, then say continue."}),
+ "{meta}"
+ );
+ assert_ne!(meta["delivery"]["continues"], true, "{meta}");
+ let all = requests(&env);
+ assert!(!all.iter().any(|r| r.contains(FOLLOW)), "{all:#?}");
+ assert_eq!(all.len(), 1, "{all:#?}");
+}
diff --git a/tests/keep_going_test.rs b/tests/keep_going_test.rs
index bc6085c3..d986af51 100644
--- a/tests/keep_going_test.rs
+++ b/tests/keep_going_test.rs
@@ -284,7 +284,7 @@ async fn a_stalled_lead_gets_a_keep_going_turn_and_its_mention_goes_out() {
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]);
+ assert!(kg[0].contains("End every reply in one of four 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()));
@@ -377,6 +377,36 @@ async fn a_prose_question_becomes_a_card_and_its_answer_keeps_the_chain_going()
assert!(open_questions(&env).await.is_empty());
}
+/// 0.9.4: a lead whose last line is `Blocked: …` gets no keep-going turn: the line is stored as
+/// `meta.blocked` and becomes a question card at once, whose answer resumes the chain.
+#[tokio::test]
+async fn a_blocked_line_becomes_a_card_not_a_keep_going_turn() {
+ let env = setup().await;
+ env.queue("res", &["The render was refused twice.\\nBlocked: terminal commands are off for this bot on the shared Mac. Allow Terminal for this team, then say continue."]);
+ env.queue("kg", &["Rendered it.\\nDone: rendered the intro and checked its length."]);
+ person_asks(&env, "Render the intro.").await;
+ hand_off(&env, "Cut the intro", true).await;
+ wait_for("the card", || async { !open_questions(&env).await.is_empty() }).await;
+ settled(&env).await;
+ assert!(env.prompts("kg").is_empty(), "blocked: asked, never pushed on");
+ let msgs = messages(&env).await;
+ let blocked = lead_replies(&env, &msgs).into_iter().find(|m| m.text.starts_with("The render was refused")).expect("the reply");
+ let text = "terminal commands are off for this bot on the shared Mac. Allow Terminal for this team, then say continue.";
+ assert_eq!(meta_of(blocked)[keep_going::BLOCKED_KEY]["text"], text);
+ 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);
+
+ // The person unblocks it: the chain resumes
+ answer(&env, &open[0].id, "Allowed. Continue").await;
+ wait_for("the keep-going turn after the answer", || async { !env.prompts("kg").is_empty() }).await;
+ settled(&env).await;
+ let msgs = messages(&env).await;
+ let last = *lead_replies(&env, &msgs).last().unwrap();
+ assert_eq!(meta_of(last)[keep_going::DONE_KEY]["text"], "rendered the intro and checked its length.");
+}
+
/// 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]
@@ -542,14 +572,15 @@ async fn another_open_hand_off_means_no_keep_going_turn() {
settled(&env).await;
}
-/// The lead's prompts: no "one answer" left, and the hand-off rules name the three ends.
+/// The lead's prompts: no "one answer" left, and the hand-off rules name the four 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("End every reply in one of four 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!(rules.contains("`Blocked: <what is blocked>. <what would unblock it>`"), "{rules}");
assert!(keep_going::PROMPT.starts_with("The person's request isn't marked done"));
}