Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Bots decide reversible choices first instead of asking the person to pick
Lin (kwant bot)42a4c7670de7
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7fe578a0..93581ba9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,6 +8,18 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).## Unreleased+### Added+- **Bots decide instead of asking you to pick.** When a reply ends by asking you to choose between+ options that can be undone (a design direction, wording, an approach), the bot first finishes the+ job: it runs the checks it said were still open, hears up to two teammates, picks, applies it, and+ tells you what it chose, why, and how to change it. Each choice shows as a chip with **Change**.+ Bots still ask before anything that can't be undone, reaches someone outside, costs money or needs a+ password or sign-in, and when you say you want to pick yourself. App settings has a switch for it.+- **Bots learn how you decide.** Your answers to question cards and your changes to the bots' choices+ are kept per space, and bots use them to predict your next pick instead of asking.+- **Questions say why only you can answer.** A bot's question card now says why it needs you and what+ it checked first; a question without a reason goes back to the bot to decide itself.+## [Mac 0.1.2] - 2026-10-26### Addeddiff --git a/src/db/decisions.rs b/src/db/decisions.rsnew file mode 100644index 00000000..65a3be1c--- /dev/null+++ b/src/db/decisions.rs@@ -0,0 +1,127 @@+//! Decision notes: how the person decides, so bots can predict it. A note is saved when the person+//! answers a question card with choices (`answered`), presses Change on a choice a bot made+//! (`changed`), and for every choice a bot made itself (`bot`), which gives the rate at which the+//! person keeps the bots' own choices.++use super::spaces::SpaceId;+use super::{Database, DbError};+use chrono::{DateTime, Utc};+use serde::Serialize;+use sqlx::FromRow;+use uuid::Uuid;++/// Where a note comes from.+pub const SOURCES: [&str; 3] = ["answered", "changed", "bot"];++#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct DecisionNote {+ pub id: String,+ pub space_id: String,+ pub kwant_id: Option<String>,+ /// The message the choice was made on (the card, or the bot's reply).+ pub message_id: Option<String>,+ pub question: String,+ /// JSON array of the options offered.+ pub options: String,+ /// What was finally picked.+ pub picked: String,+ /// For `changed`: what the bot had picked.+ pub bot_pick: Option<String>,+ pub source: String,+ pub created_at: DateTime<Utc>,+}++impl DecisionNote {+ pub fn option_list(&self) -> Vec<String> {+ serde_json::from_str(&self.options).unwrap_or_default()+ }+}++pub struct NewDecisionNote<'a> {+ pub space: &'a SpaceId,+ pub kwant_id: Option<&'a str>,+ pub message_id: Option<&'a str>,+ pub question: &'a str,+ pub options: &'a [String],+ pub picked: &'a str,+ pub bot_pick: Option<&'a str>,+ pub source: &'a str,+}++/// Longest question or option kept in a note, in characters.+pub const MAX_NOTE_TEXT: usize = 300;++fn clip(text: &str) -> String {+ let t = text.split_whitespace().collect::<Vec<_>>().join(" ");+ t.chars().take(MAX_NOTE_TEXT).collect()+}++impl Database {+ pub(super) async fn migrate_decisions(&self) -> Result<(), DbError> {+ for stmt in [+ "CREATE TABLE IF NOT EXISTS decision_notes (+ id TEXT PRIMARY KEY,+ space_id TEXT NOT NULL,+ kwant_id TEXT,+ message_id TEXT,+ question TEXT NOT NULL,+ options TEXT NOT NULL,+ picked TEXT NOT NULL,+ bot_pick TEXT,+ source TEXT NOT NULL CHECK (source IN ('answered', 'changed', 'bot')),+ created_at TIMESTAMP NOT NULL+ )",+ "CREATE INDEX IF NOT EXISTS decision_notes_space ON decision_notes (space_id, created_at)",+ ] {+ sqlx::query(stmt).execute(&self.pool).await?;+ }+ Ok(())+ }++ pub async fn add_decision_note(&self, n: &NewDecisionNote<'_>) -> Result<DecisionNote, DbError> {+ let options: Vec<String> = n.options.iter().map(|o| clip(o)).collect();+ Ok(sqlx::query_as::<_, DecisionNote>(+ "INSERT INTO decision_notes (id, space_id, kwant_id, message_id, question, options, picked, bot_pick, source, created_at) \+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) RETURNING *",+ )+ .bind(Uuid::new_v4().to_string())+ .bind(n.space.as_str())+ .bind(n.kwant_id)+ .bind(n.message_id)+ .bind(clip(n.question))+ .bind(serde_json::to_string(&options).unwrap_or_else(|_| "[]".into()))+ .bind(clip(n.picked))+ .bind(n.bot_pick.map(clip))+ .bind(n.source)+ .bind(Utc::now())+ .fetch_one(&self.pool)+ .await?)+ }++ /// The space's newest notes, newest first; `sources` limits them (all when empty).+ pub async fn list_decision_notes(&self, space: &SpaceId, sources: &[&str], limit: i64) -> Result<Vec<DecisionNote>, DbError> {+ let rows = sqlx::query_as::<_, DecisionNote>(+ "SELECT * FROM decision_notes WHERE space_id = ? ORDER BY created_at DESC, rowid DESC LIMIT ?",+ )+ .bind(space.as_str())+ .bind(limit.saturating_mul(4).max(limit))+ .fetch_all(&self.pool)+ .await?;+ Ok(rows.into_iter().filter(|n| sources.is_empty() || sources.contains(&n.source.as_str())).take(limit.max(0) as usize).collect())+ }++ /// Of the bots' own choices in the space (the newest `window`), how many the person kept:+ /// `(kept, made)`. A choice counts as changed when a `changed` note names its message and question.+ pub async fn decision_keep_rate(&self, space: &SpaceId, window: i64) -> Result<(i64, i64), DbError> {+ let (made, changed): (i64, i64) = sqlx::query_as(+ "SELECT COUNT(*), COALESCE(SUM(EXISTS (SELECT 1 FROM decision_notes c WHERE c.source = 'changed' \+ AND c.space_id = b.space_id AND c.message_id = b.message_id AND c.question = b.question)), 0) \+ FROM (SELECT * FROM decision_notes WHERE space_id = ? AND source = 'bot' ORDER BY created_at DESC LIMIT ?) b",+ )+ .bind(space.as_str())+ .bind(window)+ .fetch_one(&self.pool)+ .await?;+ Ok((made - changed, made))+ }+}diff --git a/src/db/mod.rs b/src/db/mod.rsindex bc38145f..bc1bcf0c 100644--- a/src/db/mod.rs+++ b/src/db/mod.rs@@ -20,6 +20,7 @@ pub mod imports;pub mod approval_modes;pub mod parked;pub mod waiting;+pub mod decisions;pub mod api_context;pub mod usage;@@ -150,6 +151,7 @@ impl Database {db.migrate_documents().await?;db.migrate_parked().await?;db.migrate_waiting().await?;+ db.migrate_decisions().await?;db.migrate_api_context().await?;db.migrate_usage().await?;if spaces {diff --git a/src/db/questions.rs b/src/db/questions.rsindex 7517783f..25de13e3 100644--- a/src/db/questions.rs+++ b/src/db/questions.rs@@ -38,6 +38,13 @@ pub struct Question {pub message_id: Option<String>,pub created_at: DateTime<Utc>,pub answered_at: Option<DateTime<Utc>>,+ /// Why the bot couldn't decide this itself (see `crate::server::questions::WHY_YOU`); `None` on+ /// older questions.+ #[sqlx(default)]+ pub why_you: Option<String>,+ /// What the bot checked before asking.+ #[sqlx(default)]+ pub checked: Option<String>,}fn as_json<S: serde::Serializer>(raw: &str, s: S) -> Result<S::Ok, S::Error> {@@ -143,6 +150,21 @@ impl Database {] {sqlx::query(stmt).execute(&self.pool).await?;}+ // Added later; fails harmlessly once the columns exist+ for col in ["why_you", "checked"] {+ let _ = sqlx::query(&format!("ALTER TABLE questions ADD COLUMN {col} TEXT")).execute(&self.pool).await;+ }+ Ok(())+ }++ /// Saves why the bot asked and what it checked first.+ pub async fn set_question_reason(&self, id: &str, why_you: Option<&str>, checked: Option<&str>) -> Result<(), DbError> {+ sqlx::query("UPDATE questions SET why_you = ?, checked = ? WHERE id = ?")+ .bind(why_you)+ .bind(checked)+ .bind(id)+ .execute(&self.pool)+ .await?;Ok(())}diff --git a/src/drivers/events.rs b/src/drivers/events.rsindex b3a53104..11eddd6f 100644--- a/src/drivers/events.rs+++ b/src/drivers/events.rs@@ -190,6 +190,19 @@ pub enum RuntimeEvent {context_id: Option<String>,candidates: Vec<RoutingCandidate>,},+ /// A reply with open choices is held while its bot decides them (see `crate::server::decide`):+ /// `state` is "deciding", then "done" with `outcome` "decided", "posted_original" or "cancelled".+ #[serde(rename = "decide_updated", alias = "DecideUpdated")]+ DecideUpdated {+ kwant_id: String,+ context_id: Option<String>,+ thread_id: Option<String>,+ state: String,+ held_turn_id: String,+ consulted: Vec<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ outcome: Option<String>,+ },#[serde(rename = "routing_decided", alias = "RoutingDecided")]RoutingDecided {context_id: Option<String>,diff --git a/src/router/sticky.rs b/src/router/sticky.rsindex 7afdee34..446bcd12 100644--- a/src/router/sticky.rs+++ b/src/router/sticky.rs@@ -116,7 +116,7 @@ const CLOSERS: &[&str] = &["else can i do",];-fn is_closer(question: &str) -> bool {+pub fn is_closer(question: &str) -> bool {let q: String = question.chars().map(|c| if c.is_alphanumeric() || c == '\'' || c == '’' { c.to_ascii_lowercase() } else { ' ' })@@ -218,6 +218,8 @@ mod tests {message_id: None,created_at: t(at),answered_at: None,+ why_you: None,+ checked: None,}}diff --git a/src/server/asks.rs b/src/server/asks.rsindex b4c898e2..84cfdbfc 100644--- a/src/server/asks.rs+++ b/src/server/asks.rs@@ -45,7 +45,7 @@ fn since_last_user(recent: &[Message]) -> Option<(&[Message], chrono::DateTime<c/// Whether a reply's last line hands on to a teammate ("@Writer, can you…?"): that question is/// for the teammate, not the person.-fn hands_on(text: &str, names: &[&str]) -> bool {+pub(super) fn hands_on(text: &str, names: &[&str]) -> bool {let last = text.trim_end().lines().last().unwrap_or("").to_lowercase();names.iter().any(|n| last.contains(&format!("@{}", n.to_lowercase())))}diff --git a/src/server/auth.rs b/src/server/auth.rsindex 73786ee7..ebccd985 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -338,6 +338,8 @@ pub fn person_only(method: &Method, path: &str) -> bool {["", "api", "settings", ..] => *method != Method::GET && *method != Method::HEAD,// Carrying on a chain that went over its token budget is the person's call["", "api", "chains", _, "continue"] => *method == Method::POST,+ // Changing a choice a bot made is the person's call+ ["", "api", "messages", _, "decisions", ..] => *method != Method::GET && *method != Method::HEAD,// The Mac app's update: check and install (which swaps and relaunches the app) are the// person's; the status stays readable["", "api", "app", "update", ..] => *method != Method::GET && *method != Method::HEAD,@@ -831,6 +833,7 @@ mod tests {assert!(person_only(&post, "/api/sandbox/t1/passwords/c1/reveal"));assert!(person_only(&del, "/api/sandbox/t1/passwords/c1"));assert!(person_only(&get, "/api/passwords/store"));+ assert!(person_only(&post, "/api/messages/m1/decisions/0/change"));assert!(person_only(&post, "/api/passwords/bitwarden/unlock"));assert!(person_only(&del, "/api/passwords/bitwarden"));assert!(person_only(&post, "/api/passwords/migrate"));diff --git a/src/server/continuity.rs b/src/server/continuity.rsindex 16f1c268..3b8b9f0f 100644--- a/src/server/continuity.rs+++ b/src/server/continuity.rs@@ -34,7 +34,7 @@ const AGENT_SEARCH_LIMIT: i64 = 20;/// Longest notification body.pub const NOTIFY_BODY_CHARS: usize = 200;const WEBHOOK_TIMEOUT: Duration = Duration::from_secs(5);-pub const NOTIFY_KINDS: [&str; 10] = [+pub const NOTIFY_KINDS: [&str; 11] = ["turn_finished","approval_needed","routine_failed",@@ -45,6 +45,7 @@ pub const NOTIFY_KINDS: [&str; 10] = ["loose_ends","human_step","app_update",+ "work_ahead",];const MASK: &str = "••••••••";@@ -137,10 +138,14 @@ pub async fn prompt_block(list or tips in your reply (\"I also added a shopping list and tips.\"). Only app changes get a card with Undo; saved notes don't. \Stay within 10 changes per turn. Never add one that costs money, contacts anyone or uses an outside service; offer \it instead. Never redo what the person undid or declined (\"Undone:\" means the person reversed it; your \- claim wasn't wrong): do the work yourself and offer to redo it."+ claim wasn't wrong): do the work yourself and offer to redo it.\n\n\+ [Choices you made]\n\+ When you chose between options for the person, end your reply with one line per choice in a block the person \+ sees as chips with Change: [DECISIONS] then `question: … | options: A; B; C | picked: B | why: …` then [/DECISIONS]."));out.push_str(&super::hires::prompt_block(state, &crate::db::spaces::SpaceId::new(&kwant.space_id)).await);}+ out.push_str(&super::decide::prompt_block(state, &crate::db::spaces::SpaceId::new(&kwant.space_id)).await);out}@@ -1145,7 +1150,7 @@ pub async fn notify_settings_view(state: &AppState) -> (String, Vec<String>) {pub const NOTIFY_KNOWN_SETTING: &str = "notify_known";/// Kinds added after `notify_on` lists were first saved but before `notify_known` existed: a list/// saved without `notify_known` was chosen from every kind but these.-const KINDS_SINCE_FIRST_LIST: [&str; 1] = ["app_update"];+const KINDS_SINCE_FIRST_LIST: [&str; 2] = ["app_update", "work_ahead"];/// Kinds the user wants to hear about; all of them unless set. A kind added after the list was/// saved is on, so a new event isn't silently off for everyone who ever saved the settings.diff --git a/src/server/decide.rs b/src/server/decide.rsnew file mode 100644index 00000000..ac00aeb9--- /dev/null+++ b/src/server/decide.rs@@ -0,0 +1,793 @@+//! Decide first: a bot's final reply that ends by asking the person to pick between reversible+//! options is held back. The bot gets one hidden round to finish the job instead: it runs the+//! checks its reply lists as not done, hears up to two teammates, decides, applies what it decided+//! and posts one reply that says what it chose, why, and how to change it. Each choice is kept in+//! the reply's `meta.decisions` with a Change button (see [`change`]), and every pick the person+//! makes or changes is kept as a decision note (see [`crate::db::decisions`]), which the bots read+//! back as "How the person usually decides" to predict the next one.+//!+//! The gate never holds a reply that asks about something that can't be undone or reaches outside+//! (sending, paying, deleting, contacting someone, passwords and sign-ins), a reply after the+//! person said they want to pick themselves, a reply that hands on to a teammate, a delegation or+//! system turn, or a second reply in the same chain (one round per person message). When the chain's budget can't fit the extra round, or+//! the round fails or is stopped, the original reply is posted as it was.++use super::routes::{turn_once, TurnOpts, TurnScope};+use super::AppState;+use crate::db::decisions::{DecisionNote, NewDecisionNote};+use crate::db::models::{Kwant, Message, NewMessage};+use crate::db::spaces::SpaceId;+use crate::drivers::RuntimeEvent;+use axum::{+ extract::{Path, State},+ http::StatusCode,+ response::{IntoResponse, Response},+ Json,+};+use serde::Deserialize;+use serde_json::{json, Value};+use std::sync::{Arc, Mutex};++/// Setting key: `"false"` turns the gate (and the `ask_user` reason check) off. On by default.+pub const SETTING: &str = "decide_first";+/// Fresh tokens the hidden round needs to be left in the chain's budget.+pub const RESERVE_TOKENS: u64 = 30_000;+/// Teammates asked for their view at most.+pub const MAX_CONSULTS: usize = 2;+/// The `purpose` of the hidden round's turns in `GET /api/turns` (`turns[]`).+pub const PURPOSE: &str = "decide";+/// Non-empty lines at a reply's end looked at for open choices.+const TAIL_LINES: usize = 12;++/// Setting key: `"false"` turns work-ahead runs in quiet chats off. On by default.+pub const WORK_AHEAD_SETTING: &str = "work_ahead";+/// Setting key: work-ahead runs per space per day.+pub const WORK_AHEAD_CAP_SETTING: &str = "work_ahead_daily_cap";+pub const DEFAULT_WORK_AHEAD_CAP: u64 = 3;+pub const MAX_WORK_AHEAD_CAP: u64 = 10;++fn is_off(v: Option<String>) -> bool {+ matches!(v.as_deref().map(str::trim), Some("false" | "0" | "off"))+}++/// Whether work-ahead runs are on (the default).+pub async fn work_ahead_enabled(state: &AppState) -> bool {+ !is_off(state.db.get_setting(WORK_AHEAD_SETTING).await.ok().flatten())+}++/// Work-ahead runs per space per day; a missing or bad value means the default.+pub async fn work_ahead_cap(state: &AppState) -> u64 {+ state+ .db+ .get_setting(WORK_AHEAD_CAP_SETTING)+ .await+ .ok()+ .flatten()+ .and_then(|v| v.trim().parse::<u64>().ok())+ .filter(|n| (1..=MAX_WORK_AHEAD_CAP).contains(n))+ .unwrap_or(DEFAULT_WORK_AHEAD_CAP)+}++/// Whether decide-first is on (the default).+pub async fn enabled(state: &AppState) -> bool {+ !is_off(state.db.get_setting(SETTING).await.ok().flatten())+}++/// A reply the gate held back, with what was about to be saved.+pub struct Held {+ pub turn_id: String,+ pub text: String,+ pub msg: NewMessage,+ pub meta: Option<Value>,+}++/// Shared with a turn's save step (see [`TurnOpts`]): whether to hold a reply with open choices,+/// what was held, and the message that was saved.+#[derive(Default)]+pub struct Hook {+ pub hold_choices: bool,+ /// Names whose @mention on the reply's last line hands it on (then it isn't held).+ pub teammates: Vec<String>,+ pub held: Option<Held>,+ pub saved: Option<Message>,+}++pub type HookSlot = Arc<Mutex<Hook>>;++// The heuristic++/// What the gate found in a reply.+#[derive(Debug, Default, PartialEq)]+pub struct Gate {+ /// Lines that ask the person to choose.+ pub choices: Vec<String>,+ /// Lines that say something wasn't checked.+ pub unchecked: Vec<String>,+}++const CHOICE_PHRASES: &[&str] = &[+ "decisions for you",+ "decision for you",+ "your call",+ "up to you",+ "which do you want",+ "which would you like",+ "which one do you",+ "which one should",+ "do you prefer",+ "would you prefer",+ "should i go with",+ "should we go with",+ "let me know which",+ "tell me which",+ "pick one",+ "when you pick",+ "once you pick",+ "once you choose",+ "until you answer",+ "until you decide",+ "choose between",+ "which option",+ "which direction",+ "which version",+ "which approach",+];++/// Words that make a question a choice.+const CHOICE_WORDS: &[&str] =+ &["prefer", "go with", "pick", "choose", "option", "direction", "version", "approach", "should i ", "should we ", "do you want", "would you like"];++const UNCHECKED: &[&str] = &[+ "not checked",+ "unchecked",+ "nobody has",+ "nobody looked",+ "no one has",+ "no one looked",+ "only looked at",+ "haven't checked",+ "have not checked",+ "haven't looked",+ "still need checking",+ "still needs checking",+ "not verified",+ "unverified",+ "untested",+ "not tested",+ "nobody ran",+ "no one ran",+];++/// Whole words that mark a step the person has to own: it can't be undone or reaches outside.+const HARD_WORDS: &[&str] = &[+ "send", "sending", "sent", "email", "emails", "emailing", "e-mail", "post", "posting", "publish", "publishing", "tweet",+ "pay", "paying", "payment", "buy", "buying", "purchase", "subscribe", "subscription", "charge", "refund", "delete",+ "deleting", "wipe", "password", "passwords", "credential", "credentials", "token", "contact", "contacting", "invite",+ "transfer", "irreversible", "permanent", "permanently", "bitwarden", "login",+];++/// Phrases with the same meaning as [`HARD_WORDS`].+const HARD_PHRASES: &[&str] =+ &["sign in", "sign-in", "log in", "api key", "can't be undone", "cannot be undone", "can't undo", "go live", "reach out", "message them"];++/// The person said they want to pick themselves.+const WANTS_TO_PICK: &[&str] = &[+ "let me pick",+ "let me choose",+ "let me decide",+ "i'll pick",+ "i'll choose",+ "i'll decide",+ "i will pick",+ "i will choose",+ "i will decide",+ "ask me",+ "give me options",+ "give me the options",+ "show me options",+ "show me the options",+ "i want to choose",+ "i want to pick",+ "i want to decide",+ "don't decide",+ "do not decide",+ "i decide",+ "my call",+];++fn words(line: &str) -> Vec<String> {+ line.split(|c: char| !(c.is_alphanumeric() || c == '-' || c == '\''))+ .filter(|w| !w.is_empty())+ .map(|w| w.trim_matches(|c| c == '\'' || c == '-').to_string())+ .collect()+}++/// Whether `line` (lower case) asks about a step the person has to own.+fn hard_line(line: &str) -> bool {+ let ws = words(line);+ HARD_WORDS.iter().any(|h| ws.iter().any(|w| w == h)) || HARD_PHRASES.iter().any(|p| line.contains(p))+}++/// Whether `line` (lower case) names options like "A, B or C" or "A or B?".+fn names_options(line: &str) -> bool {+ let ws = words(line);+ ws.windows(3).any(|w| w[1] == "or" && w[0].len() == 1 && w[2].len() == 1 && w[0] != "i" && w[2] != "i")+ || ws.windows(2).any(|w| (w[0] == "option" || w[0] == "options") && w[1].len() == 1)+}++/// A line that is a question in the reply's tail: ends in "?", or has one before trailing markup.+fn is_question(line: &str) -> bool {+ line.trim_end_matches(|c: char| c == '*' || c == '_' || c == ')' || c.is_whitespace()).ends_with('?')+}++/// The reply's open choices for the person, if it ends with any: a choice phrase ("decisions for+/// you", "which do you want"), options like "A, B or C?", or a question with a choice word or+/// " or ". `None` when there is nothing to choose, or when a choice line is about a step the+/// person has to own (see [`HARD_WORDS`]).+pub fn gate(text: &str) -> Option<Gate> {+ let lines: Vec<&str> = text.lines().map(str::trim).filter(|l| !l.is_empty()).collect();+ let tail = &lines[lines.len().saturating_sub(TAIL_LINES)..];+ let mut out = Gate::default();+ for line in tail {+ let l = line.to_lowercase();+ let question = is_question(&l);+ let phrase = CHOICE_PHRASES.iter().any(|p| l.contains(p));+ let choice = phrase+ || (question+ && (names_options(&l) || l.contains(" or ") || CHOICE_WORDS.iter().any(|w| l.contains(w)))+ && !crate::router::sticky::is_closer(&l));+ if choice {+ if hard_line(&l) {+ return None;+ }+ out.choices.push(line.to_string());+ }+ }+ if out.choices.is_empty() {+ return None;+ }+ // Undone checks anywhere in the reply feed the hidden round; they don't hold a reply alone+ out.unchecked =+ lines.iter().filter(|l| UNCHECKED.iter().any(|u| l.to_lowercase().contains(u))).map(|l| l.to_string()).take(8).collect();+ Some(out)+}++/// Whether the person's message asks to make the choice themselves.+pub fn wants_to_pick(person_text: &str) -> bool {+ let t = person_text.to_lowercase().replace('’', "'");+ WANTS_TO_PICK.iter().any(|p| t.contains(p))+}++// The [DECISIONS] block++/// One choice a bot made, as kept in `meta.decisions`.+#[derive(Debug, Clone, PartialEq, serde::Serialize, Deserialize)]+pub struct Decision {+ pub index: usize,+ pub question: String,+ pub options: Vec<String>,+ pub picked: String,+ pub why: String,+ pub status: String,+ pub changed_to: Option<String>,+}++pub const MAX_DECISIONS: usize = 6;+const OPEN: &str = "[DECISIONS]";+const CLOSE: &str = "[/DECISIONS]";++fn field<'a>(part: &'a str, name: &str) -> Option<&'a str> {+ let p = part.trim();+ let (k, v) = p.split_once(':')?;+ (k.trim().eq_ignore_ascii_case(name)).then(|| v.trim())+}++fn parse_line(line: &str) -> Option<(String, Vec<String>, String, String)> {+ let line = line.trim().trim_start_matches(['-', '*', '•']).trim();+ let parts: Vec<&str> = line.split('|').collect();+ let get = |name: &str| parts.iter().find_map(|p| field(p, name));+ let question = get("question")?.to_string();+ let options: Vec<String> = get("options")?.split(';').map(|o| o.trim().to_string()).filter(|o| !o.is_empty()).collect();+ let picked_raw = get("picked")?;+ let why = get("why").unwrap_or("").to_string();+ if question.is_empty() || !(2..=6).contains(&options.len()) {+ return None;+ }+ // The pick must be one of the options; kept as the option's exact text+ let norm = |s: &str| s.trim().trim_matches(['"', '“', '”', '.']).to_lowercase();+ let picked = options.iter().find(|o| norm(o) == norm(picked_raw))?.clone();+ Some((question, options, picked, why))+}++/// Takes a `[DECISIONS] … [/DECISIONS]` block off the end of a reply: the reply without it, and+/// its valid lines (`question: … | options: A; B | picked: B | why: …`). A reply without the+/// block comes back as it was.+pub fn take_decisions(text: &str) -> (String, Vec<Decision>) {+ let Some(start) = text.rfind(OPEN) else {+ return (text.to_string(), Vec::new());+ };+ let body_start = start + OPEN.len();+ let (body, rest) = match text[body_start..].find(CLOSE) {+ Some(end) => (&text[body_start..body_start + end], &text[body_start + end + CLOSE.len()..]),+ None => (&text[body_start..], ""),+ };+ let decisions = body+ .lines()+ .filter_map(parse_line)+ .take(MAX_DECISIONS)+ .enumerate()+ .map(|(index, (question, options, picked, why))| Decision {+ index,+ question,+ options,+ picked,+ why,+ status: "decided".into(),+ changed_to: None,+ })+ .collect();+ let stripped = format!("{}{}", text[..start].trim_end(), if rest.trim().is_empty() { "" } else { "\n\n" });+ (format!("{stripped}{}", rest.trim()).trim_end().to_string(), decisions)+}++/// `meta` with `decisions` set (when there are any).+pub fn with_decisions(meta: Option<Value>, decisions: &[Decision]) -> Option<Value> {+ if decisions.is_empty() {+ return meta;+ }+ let mut meta = meta.unwrap_or_else(|| json!({}));+ meta["decisions"] = json!(decisions);+ Some(meta)+}++// The hidden round++/// A turn the person didn't start (a discussion round or one kwnt runs on its own), or one+/// already inside the gate.+pub(super) fn system_turn(opts: &TurnOpts) -> bool {+ opts.discussion.is_some() || opts.label.is_some() || opts.always_ask || opts.hook.is_some()+}++/// Whether a turn may have its reply held: the setting is on, it's a turn the person started+/// (not a system turn or a delegation), the chain hasn't been through the gate yet, and the+/// person didn't just say they want to pick. `system` is [`system_turn`] of the turn's options (read before any await: they aren't Sync).+pub(super) async fn eligible(scope: &TurnScope, kwant: &Kwant, system: bool) -> bool {+ if system || scope.delegation_depth > 0 {+ return false;+ }+ if scope.state.turns.job_decided(&scope.job_id) || !enabled(&scope.state).await {+ return false;+ }+ let recent = scope.state.db.list_messages(&scope.context_id(kwant), 20).await.unwrap_or_default();+ !recent.iter().rev().find(|m| m.sender_role == "user").is_some_and(|m| wants_to_pick(&m.text))+}++fn event(scope: &TurnScope, kwant: &Kwant, state: &str, held_turn_id: &str, consulted: &[String], outcome: Option<&str>) {+ let _ = scope.state.event_sender.send(RuntimeEvent::DecideUpdated {+ kwant_id: kwant.id.clone(),+ context_id: Some(scope.context_id(kwant)),+ thread_id: scope.thread_id.clone(),+ state: state.into(),+ held_turn_id: held_turn_id.into(),+ consulted: consulted.to_vec(),+ outcome: outcome.map(str::to_string),+ });+}++/// Whether the chain's budget leaves room for the hidden round.+async fn fits_budget(scope: &TurnScope) -> bool {+ let budget = super::budget::limit(&scope.state).await;+ budget == 0 || scope.state.turns.job_tokens(&scope.job_id).saturating_add(RESERVE_TOKENS) <= budget+}++/// Teammates the held reply names (in a channel), besides the speaker, at most [`MAX_CONSULTS`].+fn consultees<'a>(scope: &'a TurnScope, speaker: &Kwant, text: &str) -> Vec<&'a Kwant> {+ if scope.channel_id.is_none() {+ return Vec::new();+ }+ let ws: Vec<String> = words(&text.to_lowercase());+ scope+ .teammates+ .iter()+ .filter(|k| k.id != speaker.id)+ .filter(|k| {+ let name = k.name.to_lowercase();+ let parts = words(&name);+ !parts.is_empty() && ws.windows(parts.len()).any(|w| w == parts.as_slice())+ })+ .take(MAX_CONSULTS)+ .collect()+}++fn bullet_list(items: &[String]) -> String {+ items.iter().map(|l| format!("- {l}")).collect::<Vec<_>>().join("\n")+}++fn consult_prompt(speaker: &str, held: &str) -> String {+ format!(+ "[Decide first] {speaker} wrote this reply but hasn't sent it to the person, because it asks them to choose. \+ The team decides reversible choices itself.\n---\n{held}\n---\n\+ In at most 6 lines: for each open choice, which option you would pick and why, from what you know or can check \+ quickly. Don't @mention anyone and don't ask the person anything."+ )+}++/// The prompt of the hidden round.+pub fn decide_prompt(held: &str, gate: &Gate, views: &[(String, String)]) -> String {+ let mut p = format!(+ "[Decide first] Your last reply hasn't reached the person. It ends by asking them to choose, and the person \+ wants the team to decide reversible choices itself instead of asking.\nYour held reply:\n---\n{held}\n---\n"+ );+ if !gate.choices.is_empty() {+ p.push_str(&format!("Open choices:\n{}\n", bullet_list(&gate.choices)));+ }+ if !gate.unchecked.is_empty() {+ p.push_str(&format!("Your reply says these weren't checked:\n{}\n", bullet_list(&gate.unchecked)));+ }+ for (name, view) in views {+ p.push_str(&format!("{name}'s view:\n{}\n", view.trim()));+ }+ p.push_str(+ "Now:\n\+ 1. Do the checks your reply lists as not done, where you can (read the files, open the pages, run the tools).\n\+ 2. Decide every reversible choice yourself, from what the person asked, what you found, your teammates' views and \+ [How the person usually decides] if you have it.\n\+ 3. Apply what you decided when it can be undone. Never send, publish, pay, contact anyone, delete or sign in for this.\n\+ 4. Write the reply the person sees instead of the held one: what you decided and why, what you checked, and that \+ they can change it. Keep a question only when it really needs the person (it can't be undone, costs money, reaches \+ someone outside, needs a password or sign-in, or nothing you can find answers it), and say why.\n\+ End with one line per choice you made:\n\+ [DECISIONS]\n\+ question: <the choice> | options: <option 1>; <option 2>; <option 3> | picked: <the exact option> | why: <one line>\n\+ [/DECISIONS]",+ );+ p+}++/// Saves the held reply as it was and says so: the gate couldn't finish.+async fn post_original(scope: &TurnScope, kwant: &Kwant, held: Held, consulted: &[String], outcome: &str) -> String {+ let mut meta = held.meta.unwrap_or_else(|| json!({}));+ meta["decide_first"] = json!({"consulted": consulted, "held_turn_id": held.turn_id, "kwant_id": kwant.id, "outcome": outcome});+ if let Some(saved) = scope.save(&held.msg, Some(meta)).await {+ let _ = scope.state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or(Value::Null) });+ }+ super::waiting::turn_ended(scope, kwant, &held.turn_id, &held.text).await;+ event(scope, kwant, "done", &held.turn_id, consulted, Some(outcome));+ held.text+}++/// Runs the hidden round for a held reply and returns the text that reached the person (the+/// decided reply, or the held one when the round couldn't run or finish).+pub(super) async fn decide(scope: &TurnScope, kwant: &Kwant, held: Held) -> String {+ scope.state.turns.mark_decided(&scope.job_id);+ let gate = gate(&held.text).unwrap_or_default();+ let consult: Vec<Kwant> = consultees(scope, kwant, &held.text).into_iter().cloned().collect();+ let names: Vec<String> = consult.iter().map(|k| k.name.clone()).collect();+ event(scope, kwant, "deciding", &held.turn_id, &names, None);+ if !fits_budget(scope).await {+ return post_original(scope, kwant, held, &[], "posted_original").await;+ }+ let mut views = Vec::new();+ for k in &consult {+ let mut opts = TurnOpts::default();+ (opts.unsaved, opts.quiet_failure, opts.purpose) = (true, true, Some(PURPOSE.into()));+ if let Ok(view) = turn_once(scope, k, consult_prompt(&kwant.name, &held.text), opts).await {+ views.push((k.name.clone(), view));+ }+ if scope.cancel_token.is_cancelled() {+ return post_original(scope, kwant, held, &names, "cancelled").await;+ }+ }+ let consulted: Vec<String> = views.iter().map(|(n, _)| n.clone()).collect();+ if !fits_budget(scope).await {+ return post_original(scope, kwant, held, &consulted, "posted_original").await;+ }+ let hook = HookSlot::default();+ let mut opts = TurnOpts::default();+ (opts.quiet_failure, opts.purpose, opts.hook) = (true, Some(PURPOSE.into()), Some(hook.clone()));+ opts.extra_meta = Some(json!({"decide_first": {"consulted": consulted, "held_turn_id": held.turn_id, "kwant_id": kwant.id}}));+ let reply = turn_once(scope, kwant, decide_prompt(&held.text, &gate, &views), opts).await;+ let saved = hook.lock().ok().and_then(|mut h| h.saved.take());+ match (reply, saved) {+ (Ok(text), Some(saved)) => {+ let _ = scope.state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&saved).unwrap_or(Value::Null) });+ event(scope, kwant, "done", &held.turn_id, &consulted, Some("decided"));+ text+ }+ _ if scope.cancel_token.is_cancelled() => post_original(scope, kwant, held, &consulted, "cancelled").await,+ _ => post_original(scope, kwant, held, &consulted, "posted_original").await,+ }+}++fn meta_of(m: &Message) -> Value {+ m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null)+}++fn decisions_of(meta: &Value) -> Vec<Decision> {+ serde_json::from_value(meta["decisions"].clone()).unwrap_or_default()+}++/// Keeps a note of each choice a bot made in `saved` (for the keep rate).+pub(super) async fn note_bot_decisions(state: &AppState, kwant: &Kwant, saved: &Message) {+ let space = SpaceId::new(&kwant.space_id);+ for d in decisions_of(&meta_of(saved)) {+ let _ = state+ .db+ .add_decision_note(&NewDecisionNote {+ space: &space,+ kwant_id: Some(&kwant.id),+ message_id: Some(&saved.id),+ question: &d.question,+ options: &d.options,+ picked: &d.picked,+ bot_pick: None,+ source: "bot",+ })+ .await;+ }+}++/// Keeps a note of the person's answer to a question card with choices.+pub(super) async fn note_answer(state: &AppState, q: &crate::db::questions::Question) {+ let options = q.choice_list();+ let Some(answer) = q.answer.as_deref() else { return };+ if options.len() < 2 {+ return;+ }+ let Ok(Some(space)) = state.db.space_of_kwant(&q.kwant_id).await else { return };+ let _ = state+ .db+ .add_decision_note(&NewDecisionNote {+ space: &space,+ kwant_id: Some(&q.kwant_id),+ message_id: q.message_id.as_deref(),+ question: &q.question,+ options: &options,+ picked: answer,+ bot_pick: None,+ source: "answered",+ })+ .await;+}++// Change++#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+pub struct ChangePayload {+ pub picked: String,+}++fn error(status: StatusCode, msg: impl Into<String>) -> Response {+ (status, Json(json!({"error": msg.into()}))).into_response()+}++/// The person's message that asks the bot to redo a decision.+pub fn change_prompt(bot: Option<&str>, d: &Decision, picked: &str) -> String {+ let mention = bot.map(|b| format!("@{b} ")).unwrap_or_default();+ format!("{mention}Change of decision: for “{}” use “{picked}” instead of “{}”. Redo what depended on it.", d.question, d.picked)+}++/// `POST /api/messages/:message_id/decisions/:index/change` (person-only): marks a bot's choice as+/// changed, keeps a note of it, and returns `{message, prompt}`; the client then sends `prompt` to+/// the same chat.+pub async fn change(+ State(state): State<AppState>,+ Path((message_id, index)): Path<(String, usize)>,+ payload: Result<Json<ChangePayload>, axum::extract::rejection::JsonRejection>,+) -> Response {+ let Json(p) = match payload {+ Ok(p) => p,+ Err(e) => return error(StatusCode::BAD_REQUEST, e.body_text()),+ };+ let msg = match state.db.get_message(&message_id).await {+ Ok(Some(m)) if m.sender_role == "kwant" => m,+ Ok(_) => return error(StatusCode::NOT_FOUND, "no such message"),+ Err(_) => return error(StatusCode::INTERNAL_SERVER_ERROR, "could not load the message"),+ };+ let mut meta = meta_of(&msg);+ let mut decisions = decisions_of(&meta);+ let Some(d) = decisions.iter_mut().find(|d| d.index == index) else {+ return error(StatusCode::NOT_FOUND, "no such decision");+ };+ if d.status == "changed" {+ return error(StatusCode::CONFLICT, "that decision was already changed");+ }+ let picked = p.picked.trim();+ let Some(picked) = d.options.iter().find(|o| o.as_str() == picked).cloned() else {+ return error(StatusCode::BAD_REQUEST, "picked must be one of the options");+ };+ if picked == d.picked {+ return error(StatusCode::BAD_REQUEST, "that is already the pick");+ }+ let before = d.clone();+ d.status = "changed".into();+ d.changed_to = Some(picked.clone());+ meta["decisions"] = json!(decisions);+ if state.db.set_message_meta(&message_id, &meta).await.is_err() {+ return error(StatusCode::INTERNAL_SERVER_ERROR, "could not save the change");+ }+ let Ok(Some(updated)) = state.db.get_message(&message_id).await else {+ return error(StatusCode::INTERNAL_SERVER_ERROR, "could not load the message");+ };+ let context = msg.thread_id.as_deref().or(msg.channel_id.as_deref()).or(msg.direct_kwant_id.as_deref()).unwrap_or("");+ if let Ok(Some(space)) = state.db.space_of_context(context).await {+ let kwant_id = meta["decide_first"]["kwant_id"].as_str().map(str::to_string);+ let _ = state+ .db+ .add_decision_note(&NewDecisionNote {+ space: &space,+ kwant_id: kwant_id.as_deref(),+ message_id: Some(&message_id),+ question: &before.question,+ options: &before.options,+ picked: &picked,+ bot_pick: Some(&before.picked),+ source: "changed",+ })+ .await;+ }+ let _ = state.event_sender.send(RuntimeEvent::MessageAdded { message: serde_json::to_value(&updated).unwrap_or(Value::Null) });+ // In a channel the prompt goes to the bot that decided+ let bot = msg.channel_id.as_ref().map(|_| msg.sender_id.as_str());+ Json(json!({"message": updated, "prompt": change_prompt(bot, &before, &picked)})).into_response()+}++// "How the person usually decides"++/// Notes shown in the prompt block at most.+pub const NOTES_SHOWN: i64 = 15;+/// The block's size cap, in bytes.+pub const MAX_BLOCK_BYTES: usize = 2000;++fn note_line(n: &DecisionNote) -> String {+ let opts = n.option_list().join(" / ");+ match (n.source.as_str(), &n.bot_pick) {+ ("changed", Some(bot)) => format!("- “{}” ({opts}): changed the bot's “{bot}” to “{}”", n.question, n.picked),+ _ => format!("- “{}” ({opts}): picked “{}”", n.question, n.picked),+ }+}++/// The block from the space's notes, at most [`MAX_BLOCK_BYTES`]; `None` without notes.+pub fn block_from(person: &str, notes: &[DecisionNote], kept: (i64, i64)) -> Option<String> {+ if notes.is_empty() && kept.1 == 0 {+ return None;+ }+ let mut out = format!(+ "\n\n[How {person} usually decides]\nPredict their choice from these and act on it; say \"predicted from your earlier choices\" \+ and that they can change it, instead of asking.\n"+ );+ if kept.1 > 0 {+ out.push_str(&format!("They kept {} of the bots' last {} own choices.\n", kept.0, kept.1));+ }+ for n in notes {+ let line = note_line(n);+ if out.len() + line.len() + 1 > MAX_BLOCK_BYTES {+ break;+ }+ out.push_str(&line);+ out.push('\n');+ }+ Some(out.trim_end().to_string())+}++/// The prompt block for `space` (empty without notes or with decide-first off).+pub async fn prompt_block(state: &AppState, space: &SpaceId) -> String {+ if !enabled(state).await {+ return String::new();+ }+ let notes = state.db.list_decision_notes(space, &["answered", "changed"], NOTES_SHOWN).await.unwrap_or_default();+ let kept = state.db.decision_keep_rate(space, 20).await.unwrap_or((0, 0));+ block_from("the person", ¬es, kept).unwrap_or_default()+}++#[cfg(test)]+mod tests {+ use super::*;++ /// Oleks's screenshot: the lead's reply that asked him to pick.+ const SCREENSHOT: &str = "Here's where the three directions stand.\n\n\+ **A: Classic** keeps the current layout with a serif title.\n\+ **B: Wax seal** puts the seal on the hero; Designer mocked it up and it reads well.\n\+ **C: Green desk** uses the dark green palette.\n\n\+ Status: Designer only looked at B; nobody looked at A and C; nobody ran a contrast checker; C's focus rings unchecked. \+ This used about 40k tokens so far.\n\n\+ Two decisions for you:\n\+ 1. A, B or C?\n\+ 2. FM monogram or plain?\n\n\+ I'll hold the build until you answer.";++ #[test]+ fn the_screenshot_reply_is_held_with_its_undone_checks() {+ let g = gate(SCREENSHOT).expect("held");+ assert!(g.choices.iter().any(|c| c.contains("A, B or C")));+ assert!(g.choices.iter().any(|c| c.contains("monogram")));+ assert!(g.unchecked.iter().any(|c| c.contains("nobody looked at A and C")));+ }++ #[test]+ fn an_ask_about_a_step_that_cant_be_undone_is_not_held() {+ assert_eq!(gate("The draft is ready.\n\nShould I send the email to Mia now, or wait until Monday?"), None);+ assert_eq!(gate("Which plan should I buy: Pro or Team?"), None);+ assert_eq!(gate("Want me to delete the old branch or keep it?"), None);+ assert_eq!(gate("Should I sign in with your Google account or the work one?"), None);+ }++ #[test]+ fn replies_without_an_open_choice_are_not_held() {+ assert_eq!(gate("Done: the page is live on staging and the tests pass."), None);+ assert_eq!(gate("I fixed it.\n\nAnything else?"), None);+ assert_eq!(gate("I fixed it. Let me know if you need anything else."), None);+ assert_eq!(gate("Not checked yet: the dark mode contrast. I'll run it next."), None);+ }++ #[test]+ fn other_choice_shapes_are_held() {+ assert!(gate("Two headlines are ready.\nDo you prefer the short one or the long one?").is_some());+ assert!(gate("Pricing could be $9 or $12.\nYour call.").is_some());+ assert!(gate("Which direction do you want for the logo?").is_some());+ }++ #[test]+ fn the_person_asking_to_pick_is_seen() {+ assert!(wants_to_pick("Give me options for the hero, let me pick"));+ assert!(wants_to_pick("Show me the options; I’ll decide"));+ assert!(!wants_to_pick("Make the hero nicer"));+ }++ #[test]+ fn the_decisions_block_is_taken_off_and_parsed() {+ let text = "I went with B.\n\n[DECISIONS]\n\+ question: Which design direction? | options: A: Classic; B: Wax seal; C: Green desk | picked: b: wax seal | why: matches the seal\n\+ question: Monogram? | options: FM monogram; plain | picked: plain | why: cleaner\n\+ question: bad | options: only one | picked: only one | why: x\n\+ question: Off list | options: X; Y | picked: Z | why: x\n\+ [/DECISIONS]";+ let (stripped, ds) = take_decisions(text);+ assert_eq!(stripped, "I went with B.");+ assert_eq!(ds.len(), 2);+ assert_eq!(ds[0].picked, "B: Wax seal");+ assert_eq!(ds[0].options.len(), 3);+ assert_eq!((ds[1].index, ds[1].picked.as_str(), ds[1].status.as_str()), (1, "plain", "decided"));+ assert_eq!(take_decisions("no block").0, "no block");+ }++ #[test]+ fn the_change_prompt_names_the_bot_in_channels() {+ let d = Decision {+ index: 0,+ question: "Which design direction?".into(),+ options: vec!["A: Classic".into(), "B: Wax seal".into()],+ picked: "B: Wax seal".into(),+ why: String::new(),+ status: "decided".into(),+ changed_to: None,+ };+ assert_eq!(+ change_prompt(Some("Designer"), &d, "A: Classic"),+ "@Designer Change of decision: for “Which design direction?” use “A: Classic” instead of “B: Wax seal”. Redo what depended on it."+ );+ assert!(change_prompt(None, &d, "A: Classic").starts_with("Change of decision"));+ }++ #[test]+ fn the_block_is_capped() {+ let note = |i: usize| DecisionNote {+ id: i.to_string(),+ space_id: "s".into(),+ kwant_id: None,+ message_id: None,+ question: "q".repeat(250),+ options: serde_json::to_string(&["a".repeat(100), "b".repeat(100)]).unwrap(),+ picked: "a".repeat(100),+ bot_pick: None,+ source: "answered".into(),+ created_at: chrono::Utc::now(),+ };+ let notes: Vec<_> = (0..15).map(note).collect();+ let block = block_from("the person", ¬es, (3, 4)).unwrap();+ assert!(block.len() <= MAX_BLOCK_BYTES, "{}", block.len());+ assert!(block.contains("kept 3 of the bots' last 4"));+ assert_eq!(block_from("the person", &[], (0, 0)), None);+ }+}diff --git a/src/server/mod.rs b/src/server/mod.rsindex ebfe4559..be6fe26f 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -41,6 +41,7 @@ pub mod connections;pub mod setup_routes;pub mod push;pub mod waiting;+pub mod decide;pub mod app_update_routes;use crate::broker::PermissionBroker;@@ -351,6 +352,7 @@ pub fn create_router(state: AppState) -> Router {.route("/api/questions", get(questions::list)).route("/api/questions/:id", get(questions::get)).route("/api/questions/:id/answer", post(questions::answer))+ .route("/api/messages/:message_id/decisions/:index/change", post(decide::change)).route("/api/questions/:id/cancel", post(questions::cancel)).route("/api/human-steps", get(human_steps::list)).route("/api/human-steps/:id", get(human_steps::get))diff --git a/src/server/questions.rs b/src/server/questions.rsindex d5c9ca05..58745a7c 100644--- a/src/server/questions.rs+++ b/src/server/questions.rs@@ -94,6 +94,8 @@ fn card_meta(q: &Question) -> Value {"choices": q.choice_list(),"status": q.status,"answer": q.answer,+ "why_you": q.why_you,+ "checked": q.checked,})}@@ -140,6 +142,9 @@ async fn close(state: &AppState, id: &str, status: &str, answer: Option<&str>) -let _ = state.db.close_waiting_for_question(id).await;let q = state.db.get_question(id).await.ok().flatten()?;changed(state, &q).await;+ if status == "answered" {+ super::decide::note_answer(state, &q).await;+ }Some(q)}@@ -152,7 +157,28 @@ pub const ASK_USER_DESCRIPTION: &str = "Ask the user one short question, only whwith no sensible default. For a reversible choice (wording, order, which of two fine options, a setting that can be \changed later) don't ask: pick the sensible option, state the assumption in your reply and continue. \Give 2 to 5 short choices; the user can also type their own answer. Your turn waits for the answer \- (a few minutes at most) and the tool returns it. Don't ask what you can find out or decide yourself.";+ (a few minutes at most) and the tool returns it. Don't ask what you can find out or decide yourself. \+ Say why only the user can answer (why_you) and what you already checked (checked).";++/// Why only the person can answer: the values `ask_user`'s `why_you` takes.+pub const WHY_YOU: [&str; 6] = ["irreversible", "outside", "money", "secret_or_signin", "taste_no_signal", "missing_after_research"];++/// Longest `checked` kept, in characters.+pub const MAX_CHECKED_CHARS: usize = 500;++/// Person decision notes after which "no signal on their taste" stops being a reason to ask.+pub const TASTE_NOTES: usize = 3;++/// The tool's answer to an `ask_user` call without a reason.+pub const DECIDE_YOURSELF: &str = "Not asked: decide it yourself. Pick the option you think is best, apply it, and say in \+ your reply what you chose, why, and that the user can change it. If only the user can answer (it can't be undone, \+ reaches outside, costs money, needs a secret or sign-in, or research found nothing), call ask_user again with why_you \+ and checked (what you already looked at).";++/// The tool's answer to "no signal on their taste" once there are notes on how the person decides.+pub const PREDICT_TASTE: &str = "Not asked: there are notes on how the user usually decides (see [How the person usually \+ decides]). Predict their pick from those, apply it, and say it was predicted from their earlier choices and how to \+ change it.";pub fn tools() -> Vec<Value> {vec![json!({@@ -169,8 +195,15 @@ pub fn tools() -> Vec<Value> {"maxItems": 5,"description": "2 to 5 short answers to pick from (max 80 characters each)",},+ "why_you": {+ "type": "string",+ "enum": WHY_YOU,+ "description": "Why only the user can answer: irreversible, outside (contacts someone), money, \+ secret_or_signin, taste_no_signal (a taste choice with nothing to go on), or missing_after_research",+ },+ "checked": {"type": "string", "description": "What you already checked or tried before asking (max 500 characters)"},},- "required": ["question", "choices"],+ "required": ["question", "choices", "why_you", "checked"],},})]}@@ -187,6 +220,25 @@ pub async fn tool_ask(state: &AppState, scope: &SelfScope, args: &Value) -> (StrOk(v) => v,Err(e) => return (e.to_string(), true),};+ let why_you = args["why_you"].as_str().map(str::trim).filter(|w| WHY_YOU.contains(w)).map(str::to_string);+ let checked: Option<String> =+ args["checked"].as_str().map(str::trim).filter(|c| !c.is_empty()).map(|c| c.chars().take(MAX_CHECKED_CHARS).collect());+ // With decide-first on, a question needs a reason only the person can answer it+ if super::decide::enabled(state).await {+ if why_you.is_none() || checked.is_none() {+ return (DECIDE_YOURSELF.into(), true);+ }+ if why_you.as_deref() == Some("taste_no_signal") {+ let space = state.db.space_of_kwant(&scope.kwant_id).await.ok().flatten();+ let notes = match &space {+ Some(s) => state.db.list_decision_notes(s, &["answered", "changed"], TASTE_NOTES as i64).await.unwrap_or_default().len(),+ None => 0,+ };+ if notes >= TASTE_NOTES {+ return (PREDICT_TASTE.into(), true);+ }+ }+ }let place = QuestionPlace {kwant_id: scope.kwant_id.clone(),channel_id: origin.channel_id.clone(),@@ -205,10 +257,11 @@ pub async fn tool_ask(state: &AppState, scope: &SelfScope, args: &Value) -> (Strwaiter = Some((q.id.clone(), hub.register(&q.id)));let text = format!("{}\n\nChoices: {}", q.question, choices.join(" · "));let (msg, extra) = place_message(q, "kwant", &scope.kwant_id, text);- Some((msg, MessageExtra { meta: Some(card_meta(q)), ..extra }))+ let shown = Question { why_you: why_you.clone(), checked: checked.clone(), ..q.clone() };+ Some((msg, MessageExtra { meta: Some(card_meta(&shown)), ..extra }))}).await;- let (q, card) = match created {+ let (mut q, card) = match created {Ok(v) => v,Err(e) => {if let Some((id, _)) = waiter {@@ -224,6 +277,11 @@ pub async fn tool_ask(state: &AppState, scope: &SelfScope, args: &Value) -> (Strreturn ("Could not save the question.".into(), true);};let _guard = WaiterGuard { hub, id: q.id.clone() };+ if why_you.is_some() || checked.is_some() {+ let _ = state.db.set_question_reason(&q.id, why_you.as_deref(), checked.as_deref()).await;+ q.why_you = why_you;+ q.checked = checked;+ }if let Some(card) = card {if let Some(t) = &q.thread_id {let _ = state.db.touch_thread(t).await;diff --git a/src/server/routes.rs b/src/server/routes.rsindex 81f8e5de..27b2b9e4 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -1470,6 +1470,17 @@ pub(super) struct TurnOpts {/// Every call that could change something asks the person, even with approvals off (an/// owner turn kwnt starts on its own; see [`super::loose_ends_owner`]).pub(super) always_ask: bool,+ /// Shared with the save step: holds a reply with open choices, and gets the saved message+ /// (see [`super::decide`]).+ pub(super) hook: Option<super::decide::HookSlot>,+ /// Merged into the saved reply's meta.+ pub(super) extra_meta: Option<serde_json::Value>,+ /// The reply isn't saved (a teammate's view for the decide-first round).+ pub(super) unsaved: bool,+ /// A failed turn saves no `turn_failed` note (the caller posts something else).+ pub(super) quiet_failure: bool,+ /// Shown as the turn's `purpose` in `GET /api/turns` (`turns[]`).+ pub(super) purpose: Option<String>,}impl TurnOpts {@@ -1502,7 +1513,34 @@ const MAX_FAILURE_CHARS: usize = 500;/// [`run_kwant_turn`], but a failed turn says why: the driver's error or the provider's refusal./// The turn first waits for a slot under the per-agent and server-wide caps (see [`super::turns`]).+/// A reply that ends by asking the person to choose may be held and decided first (see+/// [`super::decide`]); then the decided reply's text comes back.pub(super) async fn try_kwant_turn(+ scope: &TurnScope,+ target_kwant: &Kwant,+ prompt: String,+ mut opts: TurnOpts,+) -> Result<String, String> {+ let system = super::decide::system_turn(&opts);+ if !super::decide::eligible(scope, target_kwant, system).await {+ return turn_once(scope, target_kwant, prompt, opts).await;+ }+ let hook = std::sync::Arc::new(std::sync::Mutex::new(super::decide::Hook {+ hold_choices: true,+ teammates: scope.teammates.iter().map(|k| k.name.clone()).collect(),+ ..Default::default()+ }));+ opts.hook = Some(hook.clone());+ let reply = turn_once(scope, target_kwant, prompt, opts).await;+ let held = hook.lock().ok().and_then(|mut h| h.held.take());+ match (reply, held) {+ (Ok(_), Some(held)) => Ok(super::decide::decide(scope, target_kwant, held).await),+ (reply, _) => reply,+ }+}++/// One turn, without the decide-first gate.+pub(super) async fn turn_once(scope: &TurnScope,target_kwant: &Kwant,prompt: String,@@ -1534,6 +1572,7 @@ pub(super) async fn try_kwant_turn(thread_id: tag.thread_id.clone(),state: "running".into(),since: chrono::Utc::now(),+ purpose: opts.purpose.clone(),});// Kept until the turn ends, so a restart mid-reply is said in the chat (see interrupt_running_turns)let running = crate::db::continuity::RunningTurn {@@ -1562,9 +1601,11 @@ pub(super) async fn try_kwant_turn(if let Some(started) = opts.on_started.take() {started.await;}- // A discussion round's reply isn't saved as is, so it isn't followed up- let follow_up = opts.discussion.is_none();+ // A discussion round's reply isn't saved as is, so it isn't followed up; nor is a held one+ let follow_up = opts.discussion.is_none() && !opts.unsaved;+ let hook = opts.hook.clone();let reply = run_kwant_turn_inner(scope, target_kwant, prompt, opts, &tag).await;+ let follow_up = follow_up && !hook.is_some_and(|h| h.lock().is_ok_and(|h| h.held.is_some()));if scope.cancel_token.is_cancelled() {super::questions::cancel_for_turn(&scope.state, &tag.turn_id).await;super::human_steps::cancel_for_turn(&scope.state, &tag.turn_id).await;@@ -2339,11 +2380,13 @@ async fn run_kwant_turn_inner(event_broadcast.send(RuntimeEvent::ThinkingDelta("⏹️ Cancelled by user".into()));return Err("stopped by the user".into());} else if let Some(text) = gave_up {- let msg = NewMessage {- reasoning_content: with_notices(opts.label.clone()),- ..scope.message("kwant", &target_kwant.name, text.clone())- };- scope.save(&msg, super::activity::with_activity(gave_up_meta, activity)).await;+ if !opts.quiet_failure {+ let msg = NewMessage {+ reasoning_content: with_notices(opts.label.clone()),+ ..scope.message("kwant", &target_kwant.name, text.clone())+ };+ scope.save(&msg, super::activity::with_activity(gave_up_meta, activity)).await;+ }return Err(text);} else if let Some(Ok(Ok(output))) = driver_result {// This chat got through: a turn parked behind a usage limit would only repeat it@@ -2379,7 +2422,9 @@ async fn run_kwant_turn_inner(let fresh = output.usage.map_or(output.tokens_used as u64, |u| u.fresh());state.turns.add_job_tokens(&scope.job_id, fresh);+ let mut reply_text = output.text.clone();let saved = match &opts.discussion {+ _ if opts.unsaved => None,None => Some((output.text.clone(),with_notices(opts.label.clone().or(output.reasoning)),@@ -2394,6 +2439,14 @@ async fn run_kwant_turn_inner(},};if let Some((text, reasoning_content)) = saved {+ // A reply's own choices come off its text into meta.decisions+ let (text, decisions) = match opts.discussion {+ None => super::decide::take_decisions(&text),+ Some(_) => (text, Vec::new()),+ };+ if opts.discussion.is_none() {+ reply_text = text.clone();+ }let asst_msg = NewMessage {reasoning_content,tool_calls: mcp_records.map(serde_json::Value::Array),@@ -2414,10 +2467,40 @@ async fn run_kwant_turn_inner(if let Some(routing) = &opts.routing {meta.get_or_insert_with(|| serde_json::json!({}))["routing"] = routing.clone();}+ if let Some(serde_json::Value::Object(extra)) = &opts.extra_meta {+ let m = meta.get_or_insert_with(|| serde_json::json!({}));+ for (k, v) in extra {+ m[k] = v.clone();+ }+ }+ let meta = super::decide::with_decisions(meta, &decisions);let meta = super::activity::with_activity(meta, activity);- scope.save(&asst_msg, meta).await;+ let hold = opts.hook.as_ref().is_some_and(|h| {+ h.lock().is_ok_and(|h| {+ let names: Vec<&str> = h.teammates.iter().map(String::as_str).collect();+ h.hold_choices && !super::asks::hands_on(&asst_msg.text, &names)+ })+ }) && super::decide::gate(&asst_msg.text).is_some();+ if hold {+ if let Some(h) = &opts.hook {+ if let Ok(mut h) = h.lock() {+ let text = asst_msg.text.clone();+ h.held = Some(super::decide::Held { turn_id: tag.turn_id.clone(), text, msg: asst_msg, meta });+ }+ }+ } else {+ let saved = scope.save(&asst_msg, meta).await;+ if let (Some(m), false) = (&saved, decisions.is_empty()) {+ super::decide::note_bot_decisions(state, target_kwant, m).await;+ }+ if let Some(h) = &opts.hook {+ if let Ok(mut h) = h.lock() {+ h.saved = saved;+ }+ }+ }}- return Ok(output.text);+ return Ok(reply_text);}let why = match driver_result {Some(Ok(Err(e))) => format!("the {target_model} driver failed: {e}"),@@ -2425,11 +2508,13 @@ async fn run_kwant_turn_inner(_ => format!("the {target_model} turn ended without a reply"),};// Saved like a reply, so the failure is still there after a reload (the live error event isn't)- let msg = NewMessage {- reasoning_content: with_notices(opts.label.clone()),- ..scope.message("kwant", &target_kwant.name, turn_failed_text(&target_kwant.name, &why, &event_broadcast.activity))- };- scope.save(&msg, super::activity::with_activity(Some(json!({"kind": "turn_failed"})), activity)).await;+ if !opts.quiet_failure {+ let msg = NewMessage {+ reasoning_content: with_notices(opts.label.clone()),+ ..scope.message("kwant", &target_kwant.name, turn_failed_text(&target_kwant.name, &why, &event_broadcast.activity))+ };+ scope.save(&msg, super::activity::with_activity(Some(json!({"kind": "turn_failed"})), activity)).await;+ }if let Some(e) = driver_error {event_broadcast.send(e);}@@ -3159,6 +3244,12 @@ pub struct SettingsResponse {pub waiting_follow_up_hours: i64,/// Fresh tokens one chain may use before hand-offs pause (see `super::budget`); 0 = off.pub chain_token_budget: u64,+ /// Bots decide reversible choices themselves (see `super::decide`).+ pub decide_first: bool,+ /// Bots work ahead in quiet chats.+ pub work_ahead: bool,+ /// Work-ahead runs per space per day (1–10).+ pub work_ahead_daily_cap: u64,}/// Unknown keys are refused, so a typo or a key from another version fails loudly instead of@@ -3188,6 +3279,9 @@ pub struct SaveSettingsPayload {pub captcha_timeout_minutes: Option<u64>,pub waiting_follow_up_hours: Option<i64>,pub chain_token_budget: Option<u64>,+ pub decide_first: Option<bool>,+ pub work_ahead: Option<bool>,+ pub work_ahead_daily_cap: Option<u64>,}pub async fn get_settings(State(state): State<AppState>) -> Result<Json<SettingsResponse>, StatusCode> {@@ -3226,6 +3320,9 @@ pub async fn get_settings(State(state): State<AppState>) -> Result<Json<Settings.unwrap_or(super::human_steps::DEFAULT_CAPTCHA_TIMEOUT_MINUTES),waiting_follow_up_hours: super::waiting::follow_up_hours(&state).await,chain_token_budget: super::budget::limit(&state).await,+ decide_first: super::decide::enabled(&state).await,+ work_ahead: super::decide::work_ahead_enabled(&state).await,+ work_ahead_daily_cap: super::decide::work_ahead_cap(&state).await,}))}@@ -3269,6 +3366,9 @@ pub async fn save_settings(if payload.waiting_follow_up_hours.is_some_and(|h| !(0..=max_hours).contains(&h)) {return bad(format!("waiting_follow_up_hours must be 0–{max_hours}"));}+ if payload.work_ahead_daily_cap.is_some_and(|n| !(1..=super::decide::MAX_WORK_AHEAD_CAP).contains(&n)) {+ return bad(format!("work_ahead_daily_cap must be 1–{}", super::decide::MAX_WORK_AHEAD_CAP));+ }if payload.chain_token_budget.is_some_and(|n| n > super::budget::MAX) {return bad(format!("chain_token_budget must be 0–{}", super::budget::MAX));}@@ -3349,6 +3449,15 @@ pub async fn save_settings(let _ = state.db.set_setting(super::waiting::HOURS_SETTING, &h.to_string()).await;state.scheduler_wake.notify_one();}+ if let Some(on) = payload.decide_first {+ let _ = state.db.set_setting(super::decide::SETTING, if on { "true" } else { "false" }).await;+ }+ if let Some(on) = payload.work_ahead {+ let _ = state.db.set_setting(super::decide::WORK_AHEAD_SETTING, if on { "true" } else { "false" }).await;+ }+ if let Some(n) = payload.work_ahead_daily_cap {+ let _ = state.db.set_setting(super::decide::WORK_AHEAD_CAP_SETTING, &n.to_string()).await;+ }if let Some(on) = payload.agent_tools {let _ = state.db.set_setting("agent_tools", if on { "on" } else { "off" }).await;}diff --git a/src/server/sse.rs b/src/server/sse.rsindex 3a577d4f..282c9069 100644--- a/src/server/sse.rs+++ b/src/server/sse.rs@@ -104,6 +104,7 @@ pub fn owners(event: &RuntimeEvent) -> Vec<Owner> {E::DiscussionTurnStarted { speaker_id, .. } => contexts([&Some(speaker_id.clone())]),E::DiscussionCompleted { context_id, .. } | E::RoutingStarted { context_id, .. } => contexts([context_id]),E::RoutingDecided { context_id, kwant_id, .. } => contexts([context_id, &Some(kwant_id.clone())]),+ E::DecideUpdated { kwant_id, context_id, thread_id, .. } => contexts([context_id, thread_id, &Some(kwant_id.clone())]),E::Error { kwant_id, .. } => contexts([kwant_id]),E::RoutineRun { routine_id, .. } => vec![Owner::Routine(routine_id.clone())],E::Notify { space_id, kwant_id, channel_id, .. } => {@@ -267,6 +268,15 @@ mod tests {matched_terms: vec![],basis: None,},+ E::DecideUpdated {+ kwant_id: s("k"),+ context_id: Some(s("c")),+ thread_id: None,+ state: s("deciding"),+ held_turn_id: s("x"),+ consulted: vec![],+ outcome: None,+ },E::Error { code: s("x"), message: s("x"), kwant_id: Some(s("k")) },E::MemoryChanged { kwant_id: s("k") },E::RoutineRun { routine_id: s("r"), run_id: s("x"), status: s("ok") },@@ -314,6 +324,7 @@ mod tests {| E::SandboxStatusChanged { .. }| E::RoutingStarted { .. }| E::RoutingDecided { .. }+ | E::DecideUpdated { .. }| E::Error { .. }| E::MemoryChanged { .. }| E::RoutineRun { .. }diff --git a/src/server/turns.rs b/src/server/turns.rsindex cef8e849..f0e499a2 100644--- a/src/server/turns.rs+++ b/src/server/turns.rs@@ -29,6 +29,8 @@ struct Job {token: CancellationToken,/// Fresh tokens (see [`crate::drivers::TurnUsage::fresh`]) its turns used so far.fresh_tokens: u64,+ /// A reply in it already went through the decide-first gate (see [`super::decide`]).+ decided: bool,}/// A turn the UI can show: running, or waiting for a slot.@@ -41,6 +43,9 @@ pub struct ActiveTurn {/// "queued" or "running".pub state: String,pub since: chrono::DateTime<chrono::Utc>,+ /// "decide" for the hidden decide-first round's turns (see [`super::decide`]).+ #[serde(skip_serializing_if = "Option::is_none")]+ pub purpose: Option<String>,}#[derive(Default)]@@ -90,7 +95,7 @@ impl TurnRegistry {let token = CancellationToken::new();let mut keys: Vec<String> = keys.into_iter().map(Into::into).filter(|k: &String| !k.is_empty()).collect();keys.push(id.clone());- self.lock().jobs.insert(id.clone(), Job { keys, token: token.clone(), fresh_tokens: 0 });+ self.lock().jobs.insert(id.clone(), Job { keys, token: token.clone(), fresh_tokens: 0, decided: false });JobGuard { registry: self.clone(), id, token }}@@ -112,6 +117,18 @@ impl TurnRegistry {}}+ /// Whether a reply in the job already went through the decide-first gate.+ pub fn job_decided(&self, job_id: &str) -> bool {+ self.lock().jobs.get(job_id).is_some_and(|j| j.decided)+ }++ /// Marks the job as through the decide-first gate.+ pub fn mark_decided(&self, job_id: &str) {+ if let Some(job) = self.lock().jobs.get_mut(job_id) {+ job.decided = true;+ }+ }+/// Fresh tokens a job's turns used so far (0 for a finished job).pub fn job_tokens(&self, job_id: &str) -> u64 {self.lock().jobs.get(job_id).map_or(0, |j| j.fresh_tokens)@@ -176,6 +193,7 @@ impl TurnRegistry {thread_id: tag.thread_id.clone(),state: "queued".into(),since: chrono::Utc::now(),+ purpose: None,});let _ = events.send(RuntimeEvent::TurnQueued {turn_id: tag.turn_id.clone(),diff --git a/tests/app_update_test.rs b/tests/app_update_test.rsindex 379ed0a6..a379c143 100644--- a/tests/app_update_test.rs+++ b/tests/app_update_test.rs@@ -258,12 +258,12 @@ fn kinds(list: &[&str]) -> Vec<String> {}#[tokio::test]-async fn app_update_is_on_for_lists_saved_before_it_existed() {+async fn app_update_and_work_ahead_are_on_for_lists_saved_before_they_existed() {let e = setup(Some(Arc::new(FakeUpdater::default()))).await;// What a person who saved their notification settings before #78 has storede.state.db.set_setting("notify_on", r#"["turn_finished","approval_needed"]"#).await.unwrap();let on = continuity::notify_on(&e.state).await;- assert_eq!(on, kinds(&["turn_finished", "approval_needed", "app_update"]));+ assert_eq!(on, kinds(&["turn_finished", "approval_needed", "app_update", "work_ahead"]));assert!(update_notification_delivered(&e, "0.1.2").await);let (_, s) = call(&e.app, "GET", "/api/settings", None).await;assert!(s["notify_on"].as_array().unwrap().contains(&json!("app_update")), "the switch shows on: {s}");diff --git a/tests/approvals_off_test.rs b/tests/approvals_off_test.rsindex 4299a3fc..48847f86 100644--- a/tests/approvals_off_test.rs+++ b/tests/approvals_off_test.rs@@ -112,6 +112,7 @@ async fn turn_with(e: &Env, bot: &Kwant, always_ask: bool) -> (String, String, Tthread_id: None,state: "running".into(),since: Utc::now(),+ purpose: None,});(turn_id, token, folder)}diff --git a/tests/ask_user_test.rs b/tests/ask_user_test.rsindex e05e33f9..9dfab079 100644--- a/tests/ask_user_test.rs+++ b/tests/ask_user_test.rs@@ -12,7 +12,10 @@ use serde_json::{json, Value};use std::time::Duration;fn ask_marker(question: &str, choices: &[&str]) -> String {- call_tool_marker("ask_user", json!({"question": question, "choices": choices}))+ call_tool_marker(+ "ask_user",+ json!({"question": question, "choices": choices, "why_you": "irreversible", "checked": "Read the release notes."}),+ )}/// Waits until `ctx` has an open question, and returns it.@@ -51,6 +54,8 @@ async fn ask_pauses_the_turn_and_a_choice_resumes_it() {assert_eq!(meta["kind"], "ask_user");assert_eq!(meta["question_id"], id.as_str());assert_eq!(meta["status"], "open");+ assert_eq!((meta["why_you"].as_str(), meta["checked"].as_str()), (Some("irreversible"), Some("Read the release notes.")));+ assert_eq!(q["why_you"], "irreversible");let (s, v) = call(&env.app, "POST", &format!("/api/questions/{id}/answer"), Some(json!({"choice": 1}))).await;assert_eq!(s, StatusCode::OK, "{v}");@@ -218,13 +223,30 @@ async fn answers_and_tool_input_are_validated() {("v3", json!({"question": "Six?", "choices": ["a", "b", "c", "d", "e", "f"]})),("v4", json!({"question": "", "choices": ["a", "b"]})),] {+ let args = json!({"why_you": "irreversible", "checked": "x", "question": args["question"], "choices": args["choices"]});send_direct(&env, &env.b, &format!("{} REPLYTAG:{tag}", call_tool_marker("ask_user", args)), json!({})).await;let r = wait_reply(&env, &env.b, &format!("answer {tag}")).await;assert!(r.text.contains("TOOLERROR"), "{}", r.text);}+ // Without a reason only the person can answer, the bot is told to decide itself+ for (tag, args) in [+ ("v5", json!({"question": "Which colour?", "choices": ["red", "blue"]})),+ ("v6", json!({"question": "Which colour?", "choices": ["red", "blue"], "why_you": "because", "checked": "x"})),+ ("v7", json!({"question": "Which colour?", "choices": ["red", "blue"], "why_you": "irreversible", "checked": " "})),+ ] {+ send_direct(&env, &env.b, &format!("{} REPLYTAG:{tag}", call_tool_marker("ask_user", args)), json!({})).await;+ let r = wait_reply(&env, &env.b, &format!("answer {tag}")).await;+ assert!(r.text.contains("TOOLERROR") && r.text.contains("decide it yourself"), "{}", r.text);+ }let (_, open) = call(&env.app, "GET", &format!("/api/questions?context_id={}", env.b), None).await;assert!(open.as_array().unwrap().is_empty());+ // With decide-first off, a question needs no reason+ call(&env.app, "POST", "/api/settings", Some(json!({"decide_first": false}))).await;+ send_direct(&env, &env.b, &format!("{} REPLYTAG:v8", call_tool_marker("ask_user", json!({"question": "Red?", "choices": ["yes", "no"]}))), json!({})).await;+ let q = open_question(&env, &env.b).await;+ assert_eq!(q["why_you"], Value::Null);+// Outside a live chat turn the tool isn't offeredenv.state.self_toolsdiff --git a/tests/away_test.rs b/tests/away_test.rsindex 00036441..24d00b90 100644--- a/tests/away_test.rs+++ b/tests/away_test.rs@@ -392,6 +392,7 @@ async fn live_approval(app: &Router, state: &AppState, kwant: &kwnt::db::models:thread_id: place.1.map(Into::into),state: "running".into(),since: Utc::now(),+ purpose: None,});let ask = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "approve","arguments": {"tool_name": tool, "input": input, "tool_use_id": "tu_1"}}});diff --git a/tests/builtin_tools_test.rs b/tests/builtin_tools_test.rsindex 176d819a..01f27817 100644--- a/tests/builtin_tools_test.rs+++ b/tests/builtin_tools_test.rs@@ -193,6 +193,7 @@ async fn turn_in_thread(state: &AppState, bot: &kwnt::db::models::Kwant, turn_idthread_id: Some(thread.into()),state: "running".into(),since: chrono::Utc::now(),+ purpose: None,});let scope = SelfScope { kwant_id: bot.id.clone(), kwant_name: bot.name.clone(), ..Default::default() };mcp_runtime::prepare_turn_with_self(state, bot, Some(turn_id.into()), None, Some(scope)).await.unwrap().1diff --git a/tests/continuity_test.rs b/tests/continuity_test.rsindex d6067539..e1285813 100644--- a/tests/continuity_test.rs+++ b/tests/continuity_test.rs@@ -1564,7 +1564,7 @@ async fn webhook_setting_is_https_only_and_masked() {assert_eq!(s["notify_webhook_url"], "");assert_eq!(s["notify_on"],- json!(["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled", "skill_proposed", "question_asked", "loose_ends", "human_step", "app_update"])+ json!(["turn_finished", "approval_needed", "routine_failed", "delegation_finished", "delegation_stalled", "skill_proposed", "question_asked", "loose_ends", "human_step", "app_update", "work_ahead"]));let (status, _) = req(diff --git a/tests/decide_first_test.rs b/tests/decide_first_test.rsnew file mode 100644index 00000000..3c17c505--- /dev/null+++ b/tests/decide_first_test.rs@@ -0,0 +1,263 @@+//! Decide first: a reply that ends by asking the person to pick between reversible options is held,+//! the bot hears a teammate and decides, and one decided reply reaches the person, with a Change+//! that keeps a note of how the person decides. A fake claude CLI answers by keyword. Its own test+//! binary: it changes PATH.++use axum::{+ body::{to_bytes, Body},+ http::{Request, StatusCode},+ Router,+};+use kwnt::{+ broker::PermissionBroker,+ config::Config,+ db::{models::Message, spaces::SpaceId, Database},+ router::LayaRouter,+ server::{create_router, AppState},+ tools::ToolRunner,+ RuntimeEvent,+};+use serde_json::{json, Value};+use std::path::PathBuf;+use std::sync::OnceLock;+use std::time::Duration;+use tower::ServiceExt;++/// - the hidden round's prompt: a decided reply with a [DECISIONS] block;+/// - a teammate's view: "I'd pick B";+/// - CHOICE: the screenshot's ending ("A, B or C?"), naming Bob;+/// - SEND: an ask about sending an email;+/// - anything else: "answer".+const FAKE_CLAUDE: &str = r#"#!/bin/sh+case "$1" in+ auth) echo '{"loggedIn":true}'; exit 0 ;;+esac+for a; do last="$a"; done+case "$last" in+ *"[Decide first] Your last reply"*)+ out='I checked contrast on A and C and went with B: Wax seal. Change it any time.\n\n[DECISIONS]\nquestion: Which direction? | options: A: Classic; B: Wax seal; C: Green desk | picked: B: Wax seal | why: reads best\n[/DECISIONS]' ;;+ *"[Decide first]"*) out="I'd pick B: it reads best." ;;+ *CHOICE*) out='Three directions are ready. Bob only looked at B; nobody looked at A and C.\n\nTwo decisions for you:\n1. A, B or C?\n2. FM monogram or plain?' ;;+ *SEND*) out='The draft is ready.\n\nShould I send the email to Mia now, or wait until Monday?' ;;+ *) out="answer" ;;+esac+printf '%s\n' "{\"type\":\"result\",\"is_error\":false,\"num_turns\":1,\"result\":\"$out\",\"usage\":{\"input_tokens\":10,\"cache_creation_input_tokens\":0,\"cache_read_input_tokens\":0,\"output_tokens\":90}}"+"#;++fn fake_cli() {+ static DONE: OnceLock<PathBuf> = OnceLock::new();+ DONE.get_or_init(|| {+ let bin = tempfile::tempdir().unwrap().keep().join("bin");+ std::fs::create_dir_all(&bin).unwrap();+ let fake = bin.join("claude");+ std::fs::write(&fake, FAKE_CLAUDE).unwrap();+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();+ }+ std::env::set_var("PATH", format!("{}:{}", bin.display(), std::env::var("PATH").unwrap_or_default()));+ bin+ });+}++async fn call(app: &Router, method: &str, uri: &str, body: Option<Value>) -> (StatusCode, Value) {+ let req = Request::builder().method(method).uri(uri).header("content-type", "application/json");+ let body = body.map(|v| Body::from(v.to_string())).unwrap_or_else(Body::empty);+ let resp = app.clone().oneshot(req.body(body).unwrap()).await.unwrap();+ let s = resp.status();+ let bytes = to_bytes(resp.into_body(), usize::MAX).await.unwrap();+ (s, serde_json::from_slice(&bytes).unwrap_or_else(|_| Value::String(String::from_utf8_lossy(&bytes).into())))+}++async fn ok(app: &Router, method: &str, uri: &str, body: Option<Value>) -> Value {+ let (s, v) = call(app, method, uri, body).await;+ assert!(s.is_success(), "{method} {uri}: {s} {v}");+ v+}++struct Env {+ app: Router,+ state: AppState,+ channel: String,+ _tmp: tempfile::TempDir,+}++/// Ann and Bob on the fake claude in one channel; Ann leads.+async fn setup() -> Env {+ fake_cli();+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ let config = Config {+ data_dir: tmp.path().to_path_buf(),+ laya_url: "http://127.0.0.1:9".into(),+ browser_cdp_url: Some("http://127.0.0.1:9".into()),+ ..Config::default()+ };+ let state = AppState::new(+ config.clone(),+ db,+ ToolRunner::new(tmp.path().join("workspace")),+ PermissionBroker::new(),+ LayaRouter::new(config.laya_url.clone()),+ );+ let app = create_router(state.clone());+ let bot = |name: &str| {+ json!({"name": name, "title": format!("{name} the tester"), "persona_prompt": "Test persona",+ "avatar_sprite": "s", "driver_type": "cli", "preferred_model": "claude"})+ };+ let ann = ok(&app, "POST", "/api/kwants", Some(bot("Ann"))).await["id"].as_str().unwrap().to_string();+ let bob = ok(&app, "POST", "/api/kwants", Some(bot("Bob"))).await["id"].as_str().unwrap().to_string();+ let c = ok(&app, "POST", "/api/channels", Some(json!({"name": "desk", "lead_kwant_id": ann, "member_kwants": [bob]}))).await;+ Env { app, state, channel: c["id"].as_str().unwrap().to_string(), _tmp: tmp }+}++impl Env {+ async fn say(&self, prompt: &str) {+ ok(&self.app, "POST", "/api/chat/send", Some(json!({"channel_id": self.channel, "prompt": prompt, "sender_id": "user"}))).await;+ }++ async fn messages(&self) -> Vec<Message> {+ self.state.db.list_messages(&self.channel, 100).await.unwrap()+ }++ async fn replies(&self) -> Vec<Message> {+ self.messages().await.into_iter().filter(|m| m.sender_role == "kwant").collect()+ }++ async fn wait_for_reply(&self) -> Message {+ for _ in 0..200 {+ if let Some(m) = self.replies().await.pop() {+ // Let anything still on its way arrive+ tokio::time::sleep(Duration::from_millis(1500)).await;+ let all = self.replies().await;+ assert_eq!(all.len(), 1, "{:#?}", all.iter().map(|m| (&m.sender_id, &m.text)).collect::<Vec<_>>());+ return all.into_iter().next().unwrap_or(m);+ }+ tokio::time::sleep(Duration::from_millis(100)).await;+ }+ panic!("no reply: {:#?}", self.messages().await.iter().map(|m| (&m.sender_id, &m.text)).collect::<Vec<_>>());+ }+}++fn meta(m: &Message) -> Value {+ m.meta.as_deref().and_then(|s| serde_json::from_str(s).ok()).unwrap_or(Value::Null)+}++#[tokio::test]+async fn a_reply_asking_to_pick_is_decided_with_a_teammate_and_can_be_changed() {+ let env = setup().await;+ let mut rx = env.state.event_sender.subscribe();+ env.say("@Ann make three directions for the hero CHOICE").await;+ let reply = env.wait_for_reply().await;++ // Only the decided reply reached the chat, without the block; the choices are in meta+ assert_eq!(reply.sender_id, "Ann");+ assert_eq!(reply.text, "I checked contrast on A and C and went with B: Wax seal. Change it any time.");+ let m = meta(&reply);+ assert_eq!(m["decisions"][0]["picked"], "B: Wax seal");+ assert_eq!(m["decisions"][0]["options"], json!(["A: Classic", "B: Wax seal", "C: Green desk"]));+ assert_eq!(m["decisions"][0]["status"], "decided");+ assert_eq!(m["decide_first"]["consulted"], json!(["Bob"]), "Bob was named in the held reply");++ let (mut deciding, mut done) = (false, None);+ while let Ok(e) = rx.try_recv() {+ if let RuntimeEvent::DecideUpdated { state, outcome, consulted, .. } = e.unscoped() {+ match state.as_str() {+ "deciding" => {+ deciding = true;+ assert_eq!(consulted, &vec!["Bob".to_string()]);+ }+ _ => done = outcome.clone(),+ }+ }+ }+ assert!(deciding);+ assert_eq!(done.as_deref(), Some("decided"));++ // Change: bad picks are refused, a good one marks it and returns the prompt to send+ let url = format!("/api/messages/{}/decisions/0/change", reply.id);+ for bad in [json!({"picked": "D: Neon"}), json!({"picked": "B: Wax seal"}), json!({})] {+ let (s, v) = call(&env.app, "POST", &url, Some(bad.clone())).await;+ assert_eq!(s, StatusCode::BAD_REQUEST, "{bad}: {v}");+ }+ let (s, _) = call(&env.app, "POST", &format!("/api/messages/{}/decisions/5/change", reply.id), Some(json!({"picked": "A: Classic"}))).await;+ assert_eq!(s, StatusCode::NOT_FOUND);+ let (s, _) = call(&env.app, "POST", "/api/messages/nope/decisions/0/change", Some(json!({"picked": "A: Classic"}))).await;+ assert_eq!(s, StatusCode::NOT_FOUND);+ let v = ok(&env.app, "POST", &url, Some(json!({"picked": "A: Classic"}))).await;+ assert_eq!(+ v["prompt"],+ "@Ann Change of decision: for “Which direction?” use “A: Classic” instead of “B: Wax seal”. Redo what depended on it."+ );+ let changed: Value = serde_json::from_str(v["message"]["meta"].as_str().unwrap()).unwrap();+ assert_eq!((changed["decisions"][0]["status"].as_str(), changed["decisions"][0]["changed_to"].as_str()), (Some("changed"), Some("A: Classic")));+ let (s, _) = call(&env.app, "POST", &url, Some(json!({"picked": "C: Green desk"}))).await;+ assert_eq!(s, StatusCode::CONFLICT, "one change per decision");++ // Notes: the bot's pick and the person's change; the prompt block shows the change+ let space = SpaceId::default_space();+ let notes = env.state.db.list_decision_notes(&space, &[], 10).await.unwrap();+ let sources: Vec<&str> = notes.iter().map(|n| n.source.as_str()).collect();+ assert_eq!(sources, vec!["changed", "bot"]);+ assert_eq!(notes[0].bot_pick.as_deref(), Some("B: Wax seal"));+ assert_eq!(env.state.db.decision_keep_rate(&space, 20).await.unwrap(), (0, 1));+ let block = kwnt::server::decide::prompt_block(&env.state, &space).await;+ assert!(block.contains("[How the person usually decides]"), "{block}");+ assert!(block.contains("changed the bot's “B: Wax seal” to “A: Classic”"), "{block}");+ assert!(block.len() <= kwnt::server::decide::MAX_BLOCK_BYTES);+}++#[tokio::test]+async fn an_ask_about_sending_is_posted_as_is() {+ let env = setup().await;+ env.say("@Ann draft the email to Mia SEND").await;+ let reply = env.wait_for_reply().await;+ assert!(reply.text.ends_with("Should I send the email to Mia now, or wait until Monday?"), "{}", reply.text);+ assert!(meta(&reply).get("decide_first").is_none());+}++#[tokio::test]+async fn the_person_asking_to_pick_gets_the_options() {+ let env = setup().await;+ env.say("@Ann give me three directions, let me pick CHOICE").await;+ let reply = env.wait_for_reply().await;+ assert!(reply.text.ends_with("2. FM monogram or plain?"), "{}", reply.text);+ assert!(meta(&reply).get("decide_first").is_none());+}++#[tokio::test]+async fn over_the_budget_the_original_reply_is_posted() {+ let env = setup().await;+ // The first turn fits; the hidden round's reserve doesn't+ ok(&env.app, "POST", "/api/settings", Some(json!({"chain_token_budget": 1000}))).await;+ env.say("@Ann make three directions CHOICE").await;+ let reply = env.wait_for_reply().await;+ assert!(reply.text.ends_with("2. FM monogram or plain?"), "{}", reply.text);+ assert_eq!(meta(&reply)["decide_first"]["outcome"], "posted_original");+}++#[tokio::test]+async fn with_decide_first_off_nothing_is_held() {+ let env = setup().await;+ ok(&env.app, "POST", "/api/settings", Some(json!({"decide_first": false}))).await;+ env.say("@Ann make three directions CHOICE").await;+ let reply = env.wait_for_reply().await;+ assert!(reply.text.ends_with("2. FM monogram or plain?"), "{}", reply.text);+ assert!(meta(&reply).get("decide_first").is_none());+}++#[tokio::test]+async fn the_settings_round_trip_and_are_validated() {+ let env = setup().await;+ let s = ok(&env.app, "GET", "/api/settings", None).await;+ assert_eq!((s["decide_first"].as_bool(), s["work_ahead"].as_bool(), s["work_ahead_daily_cap"].as_u64()), (Some(true), Some(true), Some(3)));+ ok(&env.app, "POST", "/api/settings", Some(json!({"decide_first": false, "work_ahead": false, "work_ahead_daily_cap": 7}))).await;+ let s = ok(&env.app, "GET", "/api/settings", None).await;+ assert_eq!((s["decide_first"].as_bool(), s["work_ahead"].as_bool(), s["work_ahead_daily_cap"].as_u64()), (Some(false), Some(false), Some(7)));+ for bad in [0, 11] {+ let (s, v) = call(&env.app, "POST", "/api/settings", Some(json!({"work_ahead_daily_cap": bad}))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+ assert_eq!(v["error"], "work_ahead_daily_cap must be 1–10");+ }+}diff --git a/tests/kwant_delete_test.rs b/tests/kwant_delete_test.rsindex ed77bc51..2df1dd39 100644--- a/tests/kwant_delete_test.rs+++ b/tests/kwant_delete_test.rs@@ -102,6 +102,7 @@ async fn the_person_deletes_any_bot_with_its_history() {thread_id: None,state: "running".into(),since: chrono::Utc::now(),+ purpose: None,});let (s, v) = call_as(&app, "DELETE", &format!("/api/kwants/{}", bot.id), Some(state.api_token.reveal()), None).await;assert_eq!(s, StatusCode::CONFLICT);diff --git a/tests/smart_approvals_test.rs b/tests/smart_approvals_test.rsindex 54455a66..dd712faf 100644--- a/tests/smart_approvals_test.rs+++ b/tests/smart_approvals_test.rs@@ -124,6 +124,7 @@ async fn ask(e: &Env, tool: &str, input: impl FnOnce(&Path) -> Value) -> Outcomethread_id: None,state: "running".into(),since: Utc::now(),+ purpose: None,});let mut events = e.state.event_sender.subscribe();let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "approve",