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
Router: learn from corrections, Concierge suggests a hire
Lin (kwant bot)5e6eb94e768c
diff --git a/docs/channel-routing.md b/docs/channel-routing.mdindex 6b227cab..0d6d083e 100644--- a/docs/channel-routing.md+++ b/docs/channel-routing.md@@ -41,3 +41,23 @@ Returns `{status: "dispatched", user_message_id, kwant, kwant_id}`; the eventA routed bot can call `hand_back {reason}` ("not my area"). The message goes on once (basis`handback`, with `handed_back_by`) to the next member that fits (fit ≥ 0.6), else the Concierge,else the lead. A message takes at most one hop; a second `hand_back` is refused.++## Learning from the person++`POST /api/route-corrections {message_id, kwant_id}` (person only): "this should have gone to X".+The message must be the person's own, in a channel (not a thread), and X a bot that answers there;+otherwise 400. Returns `{status: "learned", message_id, kwant_id, kwant}`; nothing is rerun. A pick on+an ask card (not "Answer generally") is saved the same way.++A later message that shares at least two words and 60% of the shorter message's words with a saved+one goes to that bot (basis `learned`, fit 0.6–1.0), unless its avoids list matches or the message+@names someone. A space keeps its latest 200 examples.++## The Concierge suggests a hire++Every message the Concierge answers is counted. On the third similar one (same word test) within+14 days, `meta.routing.similar_requests` lists the three message ids, oldest first, and the+Concierge's turn asks it to call `propose_hire` once with `evidence: {basis: "repeated",+similar_requests}`. The usual hire policy applies (a role the person denied is refused, the card+asks). Those messages aren't counted again, and nothing is suggested while a Concierge proposal is+pending.diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rsindex 738d317a..ff29f745 100644--- a/src/db/bot_actions.rs+++ b/src/db/bot_actions.rs@@ -353,6 +353,7 @@ impl Database {"DELETE FROM api_contexts WHERE kwant_id = ?1","DELETE FROM model_usage WHERE kwant_id = ?1","DELETE FROM kwant_scope WHERE kwant_id = ?1",+ "DELETE FROM route_examples WHERE kwant_id = ?1",] {sqlx::query(sql).bind(id).execute(&mut *tx).await?;}diff --git a/src/db/routing.rs b/src/db/routing.rsindex d6367f70..14aa35c4 100644--- a/src/db/routing.rs+++ b/src/db/routing.rs@@ -12,6 +12,29 @@ use uuid::Uuid;pub const MAX_SCOPE_ENTRIES: usize = 20;/// Characters one entry keeps.pub const MAX_SCOPE_ENTRY_CHARS: usize = 60;+/// Examples of each kind a space keeps; past it, the oldest go.+pub const MAX_ROUTE_EXAMPLES: i64 = 200;+/// Characters of a message an example keeps.+const MAX_EXAMPLE_CHARS: usize = 500;++/// A person's message and the bot that should answer it, or that the Concierge did answer.+#[derive(Debug, Clone, Serialize, FromRow, PartialEq)]+pub struct RouteExample {+ pub id: String,+ pub space_id: String,+ pub message_id: String,+ pub text: String,+ pub kwant_id: String,+ /// "correction" (the person said who should have answered), "ask" (the person chose on a+ /// card) or "concierge" (no specialist fit; counted for hire suggestions).+ pub source: String,+ /// When a hire was suggested from this request; it isn't counted again.+ pub hire_suggested_at: Option<DateTime<Utc>>,+ pub created_at: DateTime<Utc>,+}++/// What routing learns from: corrections and choices the person made.+pub const LEARNED_SOURCES: [&str; 2] = ["correction", "ask"];/// What a bot is for and not for, in the person's words ("restaurants", "travel"). Empty lists/// leave routing as it was.@@ -101,6 +124,19 @@ impl Database {reason TEXT NOT NULL,created_at TIMESTAMP NOT NULL)",+ // What the person taught routing, and what the Concierge answered (for hire suggestions)+ "CREATE TABLE IF NOT EXISTS route_examples (+ id TEXT PRIMARY KEY,+ space_id TEXT NOT NULL,+ message_id TEXT NOT NULL,+ text TEXT NOT NULL,+ kwant_id TEXT NOT NULL,+ source TEXT NOT NULL CHECK (source IN ('correction', 'ask', 'concierge')),+ hire_suggested_at TIMESTAMP,+ created_at TIMESTAMP NOT NULL,+ UNIQUE (message_id, source)+ )",+ "CREATE INDEX IF NOT EXISTS idx_route_examples_space ON route_examples (space_id, source, created_at)",] {sqlx::query(stmt).execute(&self.pool).await?;}@@ -201,6 +237,66 @@ impl Database {Ok(done.rows_affected() == 1)}+ /// Records `message_id` → `kwant_id` (a later one for the same message and kind replaces it),+ /// then drops the space's oldest examples of that kind past [`MAX_ROUTE_EXAMPLES`].+ pub async fn add_route_example(&self, space_id: &str, message_id: &str, text: &str, kwant_id: &str, source: &str) -> Result<(), DbError> {+ let text: String = text.chars().take(MAX_EXAMPLE_CHARS).collect();+ sqlx::query(+ "INSERT INTO route_examples (id, space_id, message_id, text, kwant_id, source, created_at) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)+ ON CONFLICT(message_id, source) DO UPDATE SET kwant_id = ?5, text = ?4, created_at = ?7",+ )+ .bind(Uuid::new_v4().to_string())+ .bind(space_id)+ .bind(message_id)+ .bind(&text)+ .bind(kwant_id)+ .bind(source)+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ let kinds: &[&str] = if source == "concierge" { &["concierge"] } else { &LEARNED_SOURCES };+ let placeholders = vec!["?"; kinds.len()].join(", ");+ let sql = format!(+ "DELETE FROM route_examples WHERE id IN (SELECT id FROM route_examples WHERE space_id = ? AND source IN ({placeholders})+ ORDER BY created_at DESC LIMIT -1 OFFSET ?)"+ );+ let mut q = sqlx::query(&sql).bind(space_id);+ for k in kinds {+ q = q.bind(*k);+ }+ q.bind(MAX_ROUTE_EXAMPLES).execute(&self.pool).await?;+ Ok(())+ }++ /// The space's corrections and choices, newest first.+ pub async fn learned_examples(&self, space_id: &str) -> Result<Vec<RouteExample>, DbError> {+ Ok(sqlx::query_as("SELECT * FROM route_examples WHERE space_id = ?1 AND source IN ('correction', 'ask') ORDER BY created_at DESC")+ .bind(space_id)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Requests the Concierge answered in the space since `since`, newest first.+ pub async fn concierge_examples(&self, space_id: &str, since: DateTime<Utc>) -> Result<Vec<RouteExample>, DbError> {+ Ok(sqlx::query_as("SELECT * FROM route_examples WHERE space_id = ?1 AND source = 'concierge' AND created_at >= ?2 ORDER BY created_at DESC")+ .bind(space_id)+ .bind(since)+ .fetch_all(&self.pool)+ .await?)+ }++ /// Marks the Concierge requests a hire was suggested from.+ pub async fn mark_hire_suggested(&self, message_ids: &[String]) -> Result<(), DbError> {+ for id in message_ids {+ sqlx::query("UPDATE route_examples SET hire_suggested_at = ?2 WHERE message_id = ?1 AND source = 'concierge'")+ .bind(id)+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ }+ Ok(())+ }+pub async fn handed_back(&self, user_message_id: &str) -> Result<bool, DbError> {let row: Option<(String,)> =sqlx::query_as("SELECT id FROM route_handbacks WHERE user_message_id = ?1").bind(user_message_id).fetch_optional(&self.pool).await?;@@ -220,4 +316,23 @@ mod tests {let many: Vec<String> = (0..21).map(|i| format!("t{i}")).collect();assert!(clean_scope_list(&many).is_err());}++ #[tokio::test]+ async fn examples_are_capped_per_space_and_kind() {+ let tmp = tempfile::tempdir().unwrap();+ let db = Database::init(tmp.path()).await.unwrap();+ for i in 0..(MAX_ROUTE_EXAMPLES + 5) {+ db.add_route_example("s1", &format!("m{i}"), "corn dogs", "k1", if i % 2 == 0 { "correction" } else { "ask" }).await.unwrap();+ }+ db.add_route_example("s1", "c1", "corn dogs", "conc", "concierge").await.unwrap();+ db.add_route_example("s2", "o1", "tax", "k2", "correction").await.unwrap();+ let learned = db.learned_examples("s1").await.unwrap();+ assert_eq!(learned.len() as i64, MAX_ROUTE_EXAMPLES);+ assert!(!learned.iter().any(|e| e.message_id == "m0"), "the oldest went");+ assert_eq!(db.concierge_examples("s1", Utc::now() - chrono::Duration::days(14)).await.unwrap().len(), 1);+ assert_eq!(db.learned_examples("s2").await.unwrap().len(), 1);+ // A second correction of the same message replaces the first+ db.add_route_example("s2", "o1", "tax", "k3", "correction").await.unwrap();+ assert_eq!(db.learned_examples("s2").await.unwrap()[0].kwant_id, "k3");+ }}diff --git a/src/router/team.rs b/src/router/team.rsindex 27fef70b..4a1d092d 100644--- a/src/router/team.rs+++ b/src/router/team.rs@@ -607,6 +607,49 @@ pub fn pick_member_after<'a>(pub struct Hints {/// Each bot's covers/avoids lists, by bot id. A bot without one routes as before.pub scopes: std::collections::HashMap<String, crate::db::routing::Scope>,+ /// Messages the person said should go to a bot (a correction or a choice on a card), newest first.+ pub learned: Vec<Learned>,+}++/// A message routing learned: its words and the bot it belongs to.+#[derive(Debug, Clone)]+pub struct Learned {+ pub kwant_id: String,+ pub words: Vec<String>,+}++impl Learned {+ pub fn new(kwant_id: &str, text: &str) -> Self {+ Learned { kwant_id: kwant_id.to_string(), words: content_words(text) }+ }+}++/// How much of the shorter message's words the longer one has, from 0 to 1, and how many words they+/// share; [`LEARNED_AT`] and two shared words make two messages alike.+pub fn word_overlap(a: &[String], b: &[String]) -> (f32, usize) {+ let shared = a.iter().filter(|w| b.contains(w)).count();+ let shorter = a.len().min(b.len());+ if shorter == 0 {+ return (0.0, 0);+ }+ (shared as f32 / shorter as f32, shared)+}++/// Two messages are alike: they share at least two words and [`LEARNED_AT`] of the shorter one's.+pub fn alike(a: &[String], b: &[String]) -> bool {+ let (overlap, shared) = word_overlap(a, b);+ shared >= 2 && overlap >= LEARNED_AT+}++/// Share of words a message must have in common with a learned one to route like it.+pub const LEARNED_AT: f32 = 0.6;++/// A message's words for comparing it with another: no filler, plurals folded, each once.+pub fn content_words(text: &str) -> Vec<String> {+ let mut w = scope_words(text);+ w.sort();+ w.dedup();+ w}impl Hints {@@ -615,6 +658,28 @@ impl Hints {self.scopes.get(&kwant.id).map(|s| s.covers.iter().filter(|e| entry_in(e, words)).map(|e| e.to_lowercase()).collect()).unwrap_or_default()}+ /// The member the most alike learned message belongs to, with how alike (see [`alike`]).+ fn learned_pick<'a>(&self, prompt: &str, members: &'a [Kwant]) -> Option<(&'a Kwant, f32)> {+ if self.learned.is_empty() {+ return None;+ }+ let words = content_words(prompt);+ let scoped = scope_words(prompt);+ let mut best: Option<(&'a Kwant, f32, usize)> = None;+ for l in &self.learned {+ let Some(k) = members.iter().find(|k| k.id == l.kwant_id) else { continue };+ if !alike(&words, &l.words) || self.avoids(k, &scoped) {+ continue;+ }+ let (overlap, shared) = word_overlap(&words, &l.words);+ // Newest first, so an equal match keeps the latest correction+ if best.is_none_or(|(_, o, s)| (overlap, shared) > (o, s)) {+ best = Some((k, overlap, shared));+ }+ }+ best.map(|(k, o, _)| (k, o))+ }+/// The message has every word of an entry in `kwant`'s avoids list.fn avoids(&self, kwant: &Kwant, words: &[String]) -> bool {self.scopes.get(&kwant.id).is_some_and(|s| s.avoids.iter().any(|e| entry_in(e, words)))@@ -716,6 +781,14 @@ pub fn pick_member_hinted<'a>(return Some(Pick { kwant: lead, basis: "team", reason, terms: vec![], fit: 1.0, choices: vec![] });}+ // 2b. The person said a message like this one should go to a bot (a correction or a choice on+ // a card): that bot, unless its avoids list keeps it out+ if let Some((k, overlap)) = hints.learned_pick(prompt, members) {+ let reason = format!("{} ({}) answers messages like this one: you chose it for a similar message", k.name, k.title);+ let fit = (ROUTE_AT + (1.0 - ROUTE_AT) * overlap).min(1.0);+ return Some(Pick { kwant: k, basis: "learned", reason, terms: vec![], fit, choices: vec![] });+ }+// 3. The request's words belong to a rolelet role_words = role_words(prompt);let scope_words = scope_words(prompt);@@ -1627,7 +1700,7 @@ mod fit_tests {covers: covers.iter().map(|s| s.to_string()).collect(),avoids: avoids.iter().map(|s| s.to_string()).collect(),};- Hints { scopes: [(id.to_string(), scope)].into_iter().collect() }+ Hints { scopes: [(id.to_string(), scope)].into_iter().collect(), ..Hints::default() }}/// Two bots with the same role and the same words: a close call, so the person is asked to@@ -1675,4 +1748,26 @@ mod fit_tests {let p = pick_member_hinted("Scriptwriter, a hook for this fantasy book", "k-lead", &members, None, "channel lead", None, &h).unwrap();assert_eq!(p.kwant.id, "k-script", "{p:?}");}++ /// The person chose the Scriptwriter for a message no title points to: a similar one routes+ /// there too (basis "learned"), an unlike one doesn't, and @naming another bot still wins.+ #[test]+ fn a_learned_example_routes_a_similar_message() {+ let members = general();+ let learned = Hints { learned: vec![Learned::new("k-script", "Can you draft the monthly book club newsletter?")], ..Hints::default() };+ let prompt = "Draft this month's book club newsletter please";+ let before = pick_member_hinted(prompt, "k-lead", &members, None, "channel lead", None, &Hints::default()).unwrap();+ assert_ne!(before.kwant.id, "k-script", "{before:?}");+ let p = pick_member_hinted(prompt, "k-lead", &members, None, "channel lead", None, &learned).unwrap();+ assert_eq!((p.kwant.id.as_str(), p.basis), ("k-script", "learned"), "{p:?}");+ assert!(p.fit >= ROUTE_AT, "{p:?}");+ let p = pick_member_hinted("Why do the book pages load slowly?", "k-lead", &members, None, "channel lead", None, &learned).unwrap();+ assert_ne!(p.basis, "learned", "{p:?}");+ let p = pick_member_hinted("@Atlas draft the book club newsletter", "k-lead", &members, None, "channel lead", None, &learned).unwrap();+ assert_eq!(p.kwant.id, "k-seo");+ // A bot that isn't in the channel isn't picked+ let without = [members[0].clone(), members[2].clone()];+ let p = pick_member_hinted(prompt, "k-lead", &without, None, "channel lead", None, &learned).unwrap();+ assert_ne!(p.basis, "learned");+ }}diff --git a/src/server/concierge.rs b/src/server/concierge.rsindex a4e2dfa3..e4c3874f 100644--- a/src/server/concierge.rs+++ b/src/server/concierge.rs@@ -118,3 +118,92 @@ pub async fn for_no_match(app: &AppState, space: &SpaceId, channel_id: &str, alltracing::info!(kwant_id = %id, space = %space.as_str(), "made the Concierge for a message no specialist fits");app.db.get_kwant(&id).await.ok().flatten()}++/// Similar requests the Concierge must have had (this one included) within [`SIMILAR_WINDOW_DAYS`]+/// before it suggests a specialist.+pub const SIMILAR_FOR_HIRE: usize = 3;+pub const SIMILAR_WINDOW_DAYS: i64 = 14;++/// Records that the Concierge answers `message_id` and, when it is the [`SIMILAR_FOR_HIRE`]th+/// similar request in [`SIMILAR_WINDOW_DAYS`] days, returns their ids, oldest first, for one hire+/// suggestion (see [`hire_note`]). Requests a hire was already suggested from don't count again,+/// and nothing is suggested while a Concierge proposal is pending.+pub async fn similar_requests(app: &AppState, space: &SpaceId, message_id: &str, text: &str, concierge_id: &str) -> Option<Vec<String>> {+ if let Err(e) = app.db.add_route_example(space.as_str(), message_id, text, concierge_id, "concierge").await {+ tracing::warn!(error = %e, "could not save the Concierge request");+ return None;+ }+ let since = chrono::Utc::now() - chrono::Duration::days(SIMILAR_WINDOW_DAYS);+ let recent = app.db.concierge_examples(space.as_str(), since).await.ok()?;+ let ids = similar_ids(text, message_id, &recent);+ if ids.len() < SIMILAR_FOR_HIRE {+ return None;+ }+ let pending = app.db.list_hires(space, Some("pending")).await.unwrap_or_default();+ if pending.iter().any(|h| h.kwant_id == concierge_id) {+ return None;+ }+ let _ = app.db.mark_hire_suggested(&ids).await;+ Some(ids)+}++/// `message_id` and the earlier requests in `recent` (newest first) that are like `text` and no+/// hire was suggested from, oldest first.+pub fn similar_ids(text: &str, message_id: &str, recent: &[crate::db::routing::RouteExample]) -> Vec<String> {+ let words = crate::router::team::content_words(text);+ let mut ids: Vec<String> = recent+ .iter()+ .filter(|e| e.message_id != message_id && e.hire_suggested_at.is_none())+ .filter(|e| crate::router::team::alike(&words, &crate::router::team::content_words(&e.text)))+ .map(|e| e.message_id.clone())+ .collect();+ ids.reverse();+ ids.push(message_id.to_string());+ ids+}++/// Added to the Concierge's turn when similar requests keep coming: answer, then suggest one+/// specialist through the hire policy, which still refuses a role the person turned down.+pub fn hire_note(ids: &[&str]) -> String {+ format!(+ "(kwnt routing note: this is request {} of a kind you have answered in the last {SIMILAR_WINDOW_DAYS} days; message \+ ids: {}. Answer it first. Then, if one specialist bot would clearly do this kind of request better, call \+ propose_hire once with evidence {{\"basis\": \"repeated\", \"similar_requests\": [those ids]}}. Check hire_status \+ first and don't propose a role the person turned down. If propose_hire refuses, don't retry.)",+ ids.len(),+ ids.join(", ")+ )+}++#[cfg(test)]+mod hire_tests {+ use super::*;+ use crate::db::routing::RouteExample;++ fn ex(id: &str, text: &str, suggested: bool) -> RouteExample {+ RouteExample {+ id: format!("e-{id}"),+ space_id: "s".into(),+ message_id: id.into(),+ text: text.into(),+ kwant_id: "conc".into(),+ source: "concierge".into(),+ hire_suggested_at: suggested.then(chrono::Utc::now),+ created_at: chrono::Utc::now(),+ }+ }++ /// The third similar request makes the count; unlike ones and ones already suggested from don't.+ #[test]+ fn the_third_similar_request_suggests_a_hire() {+ let now = "Best street food stalls in Munich this weekend?";+ let one = vec![ex("m1", "Where is the best street food in Munich?", false), ex("m0", "What's the weather tomorrow?", false)];+ assert_eq!(similar_ids(now, "m3", &one), vec!["m1", "m3"]);+ assert!(similar_ids(now, "m3", &one).len() < SIMILAR_FOR_HIRE);+ let two = [vec![ex("m2", "Good street food markets in Munich?", false)], one.clone()].concat();+ assert_eq!(similar_ids(now, "m3", &two), vec!["m1", "m2", "m3"]);+ let done = [vec![ex("m2", "Good street food markets in Munich?", true)], one].concat();+ assert_eq!(similar_ids(now, "m3", &done).len(), 2, "a request a hire was suggested from counts once");+ assert!(hire_note(&["m1", "m2", "m3"]).contains("\"similar_requests\""));+ }+}diff --git a/src/server/mod.rs b/src/server/mod.rsindex 1902e668..0630e52f 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -328,6 +328,7 @@ pub fn create_router(state: AppState) -> Router {.route("/api/bot-actions/:id/confirm", post(bot_actions::confirm)).route("/api/bot-actions/:id/decline", post(bot_actions::decline)).route("/api/route-choices/:id/resolve", post(rerouting::resolve_route))+ .route("/api/route-corrections", post(rerouting::correct_route)).route("/api/hires", get(hires::list)).route("/api/hires/:id/accept", post(hires::accept_route)).route("/api/hires/:id/deny", post(hires::deny_route))diff --git a/src/server/rerouting.rs b/src/server/rerouting.rsindex 75e441a7..c4795897 100644--- a/src/server/rerouting.rs+++ b/src/server/rerouting.rs@@ -15,7 +15,7 @@ use crate::db::models::{Kwant, MessageExtra, NewMessage};use crate::db::routing::RouteChoice;use crate::db::spaces::SpaceId;use crate::drivers::events::RuntimeEvent;-use crate::router::team::{Hints, ROUTE_AT};+use crate::router::team::{Hints, Learned, ROUTE_AT};use axum::{extract::{Path, State},http::{HeaderMap, StatusCode},@@ -27,10 +27,19 @@ use serde_json::{json, Value};pub const HAND_BACK: &str = "hand_back";-/// The space's covers/avoids lists for routing among `members`.-pub(super) async fn hints_for(state: &AppState, members: &[Kwant]) -> Hints {+/// The space's covers/avoids lists for routing among `members`, and what the person taught it.+pub(super) async fn hints_for(state: &AppState, space: &SpaceId, members: &[Kwant]) -> Hints {let ids: Vec<String> = members.iter().map(|k| k.id.clone()).collect();- Hints { scopes: state.db.scopes_for(&ids).await.unwrap_or_default() }+ let learned = state+ .db+ .learned_examples(space.as_str())+ .await+ .unwrap_or_default()+ .into_iter()+ .filter(|e| ids.contains(&e.kwant_id))+ .map(|e| Learned::new(&e.kwant_id, &e.text))+ .collect();+ Hints { scopes: state.db.scopes_for(&ids).await.unwrap_or_default(), learned }}fn error(status: StatusCode, msg: &str) -> Response {@@ -190,6 +199,10 @@ pub async fn resolve_route(State(state): State<AppState>, headers: HeaderMap, Palet _ = state.db.set_message_meta(mid, &meta).await;}let _ = state.event_sender.send(RuntimeEvent::RouteChoiceUpdated { choice: meta });+ // The person's pick teaches routing (a general answer says nothing about the bots)+ if !body.general {+ learn(&state, &space, &c.user_message_id, &kwant.id, "ask").await;+ }let candidates = offered.len() + 1;let mut routing = super::routes::routing_meta(&kwant, &reason, candidates, false, &[], "ask");routing["route_choice_id"] = json!(c.id);@@ -202,6 +215,48 @@ pub async fn resolve_route(State(state): State<AppState>, headers: HeaderMap, PaJson(json!({"status": "dispatched", "user_message_id": c.user_message_id, "kwant": kwant.name, "kwant_id": kwant.id})).into_response()}+/// Saves "messages like `message_id` go to `kwant_id`" for routing to learn from.+async fn learn(state: &AppState, space: &SpaceId, message_id: &str, kwant_id: &str, source: &str) {+ let Ok(Some(m)) = state.db.get_message(message_id).await else { return };+ if let Err(e) = state.db.add_route_example(space.as_str(), message_id, &m.text, kwant_id, source).await {+ tracing::warn!(error = %e, "could not save a routing example");+ }+}++#[derive(Debug, Deserialize)]+pub struct CorrectionBody {+ pub message_id: String,+ pub kwant_id: String,+}++/// `POST /api/route-corrections` `{message_id, kwant_id}`: the person says who should have+/// answered their channel message; similar messages go to that bot from now on (basis+/// "learned"). Person only. It doesn't rerun the message.+pub async fn correct_route(State(state): State<AppState>, headers: HeaderMap, Json(body): Json<CorrectionBody>) -> Response {+ if let Err(r) = super::mcp_suggest::refuse_agent_tokens(&state, &headers, "only the person corrects routing").await {+ return r;+ }+ let msg = match state.db.get_message(&body.message_id).await {+ Ok(Some(m)) => m,+ _ => return error(StatusCode::NOT_FOUND, "no such message"),+ };+ let (Some(channel_id), None, "user") = (msg.channel_id.as_deref(), msg.thread_id.as_deref(), msg.sender_role.as_str()) else {+ return error(StatusCode::BAD_REQUEST, "only your own messages in a channel can be corrected");+ };+ let Ok(Some(channel)) = state.db.get_channel(channel_id).await else {+ return error(StatusCode::NOT_FOUND, "the channel is gone");+ };+ let space = SpaceId::new(&channel.space_id);+ let all = state.db.list_kwants(&space).await.unwrap_or_default();+ let concierge = super::concierge::id(&state, &space, &all).await;+ let members = super::routes::routing_members(&channel, &all, concierge.as_deref());+ let Some(kwant) = members.iter().find(|k| k.id == body.kwant_id) else {+ return error(StatusCode::BAD_REQUEST, "that bot doesn't answer in this channel");+ };+ learn(&state, &space, &msg.id, &kwant.id, "correction").await;+ Json(json!({"status": "learned", "message_id": msg.id, "kwant_id": kwant.id, "kwant": kwant.name})).into_response()+}+pub fn tool() -> Value {json!({"name": HAND_BACK,@@ -302,7 +357,7 @@ async fn next_after_handback(concierge: Option<&str>,) -> Option<(Kwant, f32)> {if !members.is_empty() {- let hints = hints_for(state, members).await;+ let hints = hints_for(state, space, members).await;let lead = if channel.lead_kwant_id == from.id { members[0].id.clone() } else { channel.lead_kwant_id.clone() };let route = state.router.route_channel_query_hinted(text, &channel.name, &lead, members, None, &hints).await;if route.fit >= ROUTE_AT {diff --git a/src/server/routes.rs b/src/server/routes.rsindex b7435225..d3cb0881 100644--- a/src/server/routes.rs+++ b/src/server/routes.rs@@ -899,6 +899,9 @@ fn execute_single_turn(// as its own specialty (the saved message stays as the person wrote it)let turn_prompt = if routing.as_ref().is_some_and(|r| r["basis"] == "team") {format!("{prompt}\n\n{}", crate::router::team::TEAM_BUILDING_NOTE)+ } else if let Some(ids) = routing.as_ref().and_then(|r| r["similar_requests"].as_array()) {+ let ids: Vec<&str> = ids.iter().filter_map(serde_json::Value::as_str).collect();+ format!("{prompt}\n\n{}", super::concierge::hire_note(&ids))} else {prompt.clone()};@@ -3306,7 +3309,7 @@ async fn send_chat_inner(let members = routing_members(&channel, &all_kwants, concierge.as_deref());if channel.routing_mode == "auto" && members.len() > 1 {- let hints = super::rerouting::hints_for(&state, &members).await;+ let hints = super::rerouting::hints_for(&state, &space, &members).await;let context_id = payload.channel_id.clone();let _ = state.event_sender.send(RuntimeEvent::RoutingStarted {context_id: context_id.clone(),@@ -3332,6 +3335,8 @@ async fn send_chat_inner(// #general leans to the Concierge when nothing fits (made now, the first time,// unless the person removed it); anywhere else the pick standslet mut route = route;+ // Earlier requests like this one the Concierge answered, when it should suggest a hire+ let mut similar: Option<Vec<String>> = None;let mut chosen = members.iter().find(|k| k.id == route.kwant_id).cloned().or(lead);let removed = matches!(super::concierge::state(&state, &space, &all_kwants).await, super::concierge::State::Removed);match crate::router::team::settle(&route, general, !removed) {@@ -3343,6 +3348,7 @@ async fn send_chat_inner();route.basis = "concierge".into();route.kwant_id = c.id.clone();+ similar = super::concierge::similar_requests(&state, &space, &saved_user_msg.id, &payload.prompt, &c.id).await;chosen = Some(c);}}@@ -3364,6 +3370,9 @@ async fn send_chat_inner(routing = Some(routing_meta(k, &route.reason, members.len(), route.fallback, &route.matched_terms, &route.basis));if let Some(m) = routing.as_mut() {m["fit"] = json!(route.fit);+ if let Some(ids) = similar.take() {+ m["similar_requests"] = json!(ids);+ }}let _ = state.event_sender.send(RuntimeEvent::RoutingDecided {context_id,diff --git a/tests/concierge_test.rs b/tests/concierge_test.rsindex 42b23ae6..c39f3766 100644--- a/tests/concierge_test.rs+++ b/tests/concierge_test.rs@@ -2,7 +2,8 @@//! with a card the person can undo), a clear specialist message doesn't, and once the person//! removes it, it is never made again. A fake claude CLI answers turns.//! Also the close calls the person settles on a card, a bot handing a message back, and the-//! covers/avoids lists on the bot routes.+//! covers/avoids lists on the bot routes; routing learning from the person's corrections and+//! choices, and the Concierge suggesting a hire when similar requests keep coming.//! Its own test binary: it changes PATH.use axum::{@@ -261,24 +262,25 @@ async fn a_close_call_asks_and_the_choice_answers() {let (s, _) = call_as(&app, &uri, &token, json!({"kwant_id": web})).await;assert_eq!(s, StatusCode::FORBIDDEN);+ // "Answer generally" in #general: the Concierge, made nowlet mut events = state.event_sender.subscribe();- let v = ok(&app, "POST", &uri, Some(json!({"kwant_id": web}))).await;- assert_eq!((v["status"].as_str(), v["kwant_id"].as_str()), (Some("dispatched"), Some(web.as_str())));+ let v = ok(&app, "POST", &uri, Some(json!({"general": true}))).await;+ let made = concierges(&state).await;+ assert_eq!(made.len(), 1);+ assert_eq!((v["status"].as_str(), v["kwant_id"].as_str()), (Some("dispatched"), Some(made[0].as_str())));let routing = next_reply_routing(&state, &mut events, &general).await;- assert_eq!((routing["basis"].as_str(), routing["kwant_id"].as_str()), (Some("ask"), Some(web.as_str())), "{routing}");+ assert_eq!(routing["basis"], "ask", "{routing}");let (s, _) = call(&app, "POST", &uri, Some(json!({"kwant_id": fe}))).await;assert_eq!(s, StatusCode::CONFLICT, "a second tap does nothing");- // "Answer generally" in #general: the Concierge, made now+ // A general answer teaches routing nothing, so a similar message asks again; the pick answerslet v = ok(&app, "POST", "/api/chat/send", Some(json!({"channel_id": general, "prompt": "Is the CSS grid off on the button?", "sender_id": "user"}))).await;assert_eq!(v["status"], "asking", "{v}");let mut events = state.event_sender.subscribe();- let v = ok(&app, "POST", &format!("/api/route-choices/{}/resolve", v["route_choice_id"].as_str().unwrap()), Some(json!({"general": true}))).await;- let made = concierges(&state).await;- assert_eq!(made.len(), 1);- assert_eq!(v["kwant_id"].as_str(), Some(made[0].as_str()));+ let v = ok(&app, "POST", &format!("/api/route-choices/{}/resolve", v["route_choice_id"].as_str().unwrap()), Some(json!({"kwant_id": web}))).await;+ assert_eq!((v["status"].as_str(), v["kwant_id"].as_str()), (Some("dispatched"), Some(web.as_str())));let routing = next_reply_routing(&state, &mut events, &general).await;- assert_eq!(routing["basis"], "ask", "{routing}");+ assert_eq!((routing["basis"].as_str(), routing["kwant_id"].as_str()), (Some("ask"), Some(web.as_str())), "{routing}");assert_eq!(state.db.get_scope(&made[0]).await.unwrap().covers.len(), kwnt::server::concierge::COVERS.len());}@@ -332,3 +334,89 @@ async fn covers_and_avoids_are_read_and_updated() {let listed = list.as_array().unwrap().iter().find(|k| k["id"] == id).unwrap().clone();assert_eq!(listed["avoids"], json!(["wine"]));}++/// The person's last message in `channel`.+async fn last_user_message(state: &AppState, channel: &str) -> String {+ let msgs = state.db.list_messages(channel, 50).await.unwrap();+ msgs.iter().rev().find(|m| m.sender_role == "user").expect("a message").id.clone()+}++/// "This should have gone to X": a similar message goes to X from now on (basis "learned"), and so+/// does one like a message the person settled on a card.+#[tokio::test]+async fn corrections_and_choices_teach_routing() {+ let (app, state, _tmp) = setup().await;+ let script = ok(&app, "POST", "/api/kwants", Some(specialist("Scriptwriter", "TikTok Scriptwriter", "Scripts and hooks for book videos."))).await["id"].as_str().unwrap().to_string();+ let atlas = ok(&app, "POST", "/api/kwants", Some(specialist("Atlas", "Technical SEO", "Crawl errors and sitemaps."))).await["id"].as_str().unwrap().to_string();+ only(&app, &state, &[&script, &atlas]).await;+ let general = state.db.general_channel(&SpaceId::default_space()).await.unwrap().expect("#general").id;++ let (to, _) = routed_to(&app, &state, &general, "Can you draft the monthly book club newsletter?").await;+ assert_ne!(to, script);+ let msg = last_user_message(&state, &general).await;+ // Person only, own channel messages only, bots of the channel only+ let token = turn_token(&state, &atlas, &general).await;+ let (s, _) = call_as(&app, "/api/route-corrections", &token, json!({"message_id": msg, "kwant_id": script})).await;+ assert_eq!(s, StatusCode::FORBIDDEN);+ let reply = state.db.list_messages(&general, 50).await.unwrap().into_iter().rev().find(|m| m.sender_role == "kwant").unwrap().id;+ let (s, _) = call(&app, "POST", "/api/route-corrections", Some(json!({"message_id": reply, "kwant_id": script}))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+ let (s, _) = call(&app, "POST", "/api/route-corrections", Some(json!({"message_id": msg, "kwant_id": "nope"}))).await;+ assert_eq!(s, StatusCode::BAD_REQUEST);+ let v = ok(&app, "POST", "/api/route-corrections", Some(json!({"message_id": msg, "kwant_id": script}))).await;+ assert_eq!((v["status"].as_str(), v["kwant"].as_str()), (Some("learned"), Some("Scriptwriter")));++ let (to, basis) = routed_to(&app, &state, &general, "Draft this month's book club newsletter please").await;+ assert_eq!((to.as_str(), basis.as_deref()), (script.as_str(), Some("learned")));+ let (to, basis) = routed_to(&app, &state, &general, "Best place to eat corn dogs in Munich tomorrow?").await;+ assert_ne!(to, script, "an unlike message isn't affected");+ assert_eq!(basis.as_deref(), Some("concierge"));++ // A choice on a card teaches it too+ let fe = ok(&app, "POST", "/api/kwants", Some(specialist("Bea", "Frontend engineer", "You build the app's pages."))).await["id"].as_str().unwrap().to_string();+ let web = ok(&app, "POST", "/api/kwants", Some(specialist("Cy", "Web developer", "You build websites."))).await["id"].as_str().unwrap().to_string();+ let v = ok(&app, "POST", "/api/chat/send", Some(json!({"channel_id": general, "prompt": "The button CSS is off on mobile Safari", "sender_id": "user"}))).await;+ assert_eq!(v["status"], "asking", "{v}");+ let mut events = state.event_sender.subscribe();+ ok(&app, "POST", &format!("/api/route-choices/{}/resolve", v["route_choice_id"].as_str().unwrap()), Some(json!({"kwant_id": web}))).await;+ next_reply_routing(&state, &mut events, &general).await;+ let (to, basis) = routed_to(&app, &state, &general, "The button CSS looks off on Safari again").await;+ assert_eq!((to.as_str(), basis.as_deref()), (web.as_str(), Some("learned")));+ let _ = fe;+}++/// The third similar request the Concierge gets in 14 days carries the ids of all three+/// (`meta.routing.similar_requests`) so it can propose one hire; the fourth doesn't ask again.+#[tokio::test]+async fn the_concierge_suggests_a_hire_on_the_third_similar_request() {+ let (app, state, _tmp) = setup().await;+ let script = ok(&app, "POST", "/api/kwants", Some(specialist("Scriptwriter", "TikTok Scriptwriter", "Scripts and hooks for book videos."))).await["id"].as_str().unwrap().to_string();+ let atlas = ok(&app, "POST", "/api/kwants", Some(specialist("Atlas", "Technical SEO", "Crawl errors and sitemaps."))).await["id"].as_str().unwrap().to_string();+ only(&app, &state, &[&script, &atlas]).await;+ let general = state.db.general_channel(&SpaceId::default_space()).await.unwrap().expect("#general").id;++ let mut ids = Vec::new();+ for (i, prompt) in [+ "Where is the best street food in Munich?",+ "What's the weather tomorrow?",+ "Good street food markets in Munich?",+ "Best street food stalls in Munich this weekend?",+ "Any street food festival in Munich soon?",+ ]+ .into_iter()+ .enumerate()+ {+ let mut events = state.event_sender.subscribe();+ ok(&app, "POST", "/api/chat/send", Some(json!({"channel_id": general, "prompt": prompt, "sender_id": "user"}))).await;+ let routing = next_reply_routing(&state, &mut events, &general).await;+ assert_eq!(routing["basis"], "concierge", "{prompt}: {routing}");+ let similar = &routing["similar_requests"];+ if i != 1 {+ ids.push(last_user_message(&state, &general).await);+ }+ match i {+ 3 => assert_eq!(similar, &json!(ids), "the third similar request"),+ _ => assert!(similar.is_null(), "{prompt}: {routing}"),+ }+ }+}