Skip to content

armgit / kwant

Public Imported from GitHub
0

Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.

Router: no specialist question falls to the Concierge; eval runs in CI

Lin (kwant bot)6021b56ffbab
diff --git a/docs/channel-routing.md b/docs/channel-routing.md
index 0d6d083e..5fbc889d 100644
--- a/docs/channel-routing.md
+++ b/docs/channel-routing.md
@@ -11,11 +11,21 @@ Each pick has a `fit` from 0 to 1, saved on the reply as `meta.routing.fit`.
|---|---|
| ≥ 0.6 | Routed to the best member |
| 0.4–0.6, two candidates | The person is asked (basis `ask`), in any channel. Never for @mentions or DMs |
-| < 0.4 in #general | The Concierge answers (basis `concierge`), made on first need |
-| < 0.4 elsewhere | The channel's own members, as before (lead or last speaker) |
+| Anything else in #general | The Concierge answers (basis `concierge`), made on first need |
+| Anything else elsewhere | The channel's own members, as before (lead or last speaker) |
Laya's titles-only guess is a tiebreaker only; it no longer picks a bot on its own.
+- A word of the message in only one bot's name, title or description, with no runner-up, routes
+ to it (fit 0.6): "How many calories are in a corn dog?" goes to the Nutritionist. A weak role
+ hint alone ("report", "error") doesn't.
+- A greeting, thank-you or go-ahead ("ok go ahead") stays with the bot that spoke last before any
+ word matching (basis `last`). "go" is not a role word.
+- Bots that share a role word ("tiktok") are told apart by a word in just one of their names or
+ titles ("hook" for the TikTok Scriptwriter & Hook Specialist); without one it is a close call.
+- `tests/router_eval/` holds 47 messages with their expected routing; `router_eval_must_pass` in
+ `tests/router_eval_test.rs` runs in CI.
+
## covers / avoids
`GET /api/kwants`, `GET /api/kwants/:id` and `PUT /api/kwants/:id` carry `covers: [string]` and
diff --git a/src/router/team.rs b/src/router/team.rs
index 4a1d092d..6fe023a4 100644
--- a/src/router/team.rs
+++ b/src/router/team.rs
@@ -404,7 +404,7 @@ const ROLES: &[Role] = &[
("backend", 2), ("back-end", 2), ("api", 2), ("endpoint", 2), ("database", 2), ("schema", 2),
("migration", 2), ("server", 2), ("service", 1), ("strategy", 2), ("strategies", 2), ("backtest", 2),
("trading", 2), ("indicator", 2), ("order", 1), ("orders", 1), ("algorithm", 2), ("query", 1),
- ("sql", 2), ("golang", 2), ("go", 1), ("rust", 1), ("function", 1), ("cli", 1), ("parser", 2),
+ ("sql", 2), ("golang", 2), ("rust", 1), ("function", 1), ("cli", 1), ("parser", 2),
("python", 1), ("script", 2), ("scripts", 2), ("scrape", 2), ("scraper", 2), ("crash", 2),
("crashes", 2), ("crashing", 2), ("traceback", 2), ("exception", 2), ("error", 1),
],
@@ -771,6 +771,17 @@ pub fn pick_member_hinted<'a>(
return Some(chosen(k, vec![k.name.trim().to_lowercase()], "was named in your message", 1.0));
}
+ // 1b. A greeting, thank-you or go-ahead ("ok go ahead") carries on with the bot that spoke last
+ // before any word matching: its everyday words name no one's work
+ let scope_words = scope_words(prompt);
+ let avoided = |k: &Kwant| hints.avoids(k, &scope_words);
+ if is_small_talk(prompt) {
+ if let Some(k) = last_speaker.and_then(|id| members.iter().find(|m| m.id == id)).filter(|k| !avoided(k)) {
+ let reason = format!("Nothing in your message named a role, so {} ({}), who spoke last here, carries on", k.name, k.title);
+ return Some(Pick { kwant: k, basis: "last", reason, terms: vec![], fit: ROUTE_AT, choices: vec![] });
+ }
+ }
+
// 2. A request to put a team of bots together is no one specialist's work: the lead proposes
// the bots on one hire card (see TEAM_BUILDING_NOTE)
if is_team_building_request(prompt) {
@@ -791,8 +802,6 @@ pub fn pick_member_hinted<'a>(
// 3. The request's words belong to a role
let role_words = role_words(prompt);
- let scope_words = scope_words(prompt);
- let avoided = |k: &Kwant| hints.avoids(k, &scope_words);
let roles: Vec<(&Kwant, usize, Vec<String>)> = members
.iter()
.map(|m| (m, if avoided(m) { (0, vec![]) } else { role_score(&role_words, m) }))
@@ -830,6 +839,26 @@ pub fn pick_member_hinted<'a>(
}
}
}
+ if same_role_tie {
+ // Bots sharing one role: a word of the message in just one of their own names or
+ // titles settles it ("hook" for the "TikTok Scriptwriter & Hook Specialist")
+ let titled: Vec<(&Kwant, Vec<String>)> = matched
+ .iter()
+ .map(|m| (*m, relevance_terms(prompt, m).into_iter().filter(|(t, s)| *s >= 2 && !terms.contains(t)).map(|(t, _)| t).collect::<Vec<_>>()))
+ .collect();
+ let own = |k: &Kwant, t: &String| titled.iter().all(|(o, ts)| o.id == k.id || !ts.contains(t));
+ let deciders: Vec<(&Kwant, Vec<String>)> = titled
+ .iter()
+ .map(|(k, ts)| (*k, ts.iter().filter(|t| own(k, t)).cloned().collect::<Vec<_>>()))
+ .filter(|(_, ts)| !ts.is_empty())
+ .collect();
+ if let [(k, extra)] = deciders.as_slice() {
+ let mut t = terms.clone();
+ t.extend(extra.iter().cloned());
+ let how = format!("does this kind of work: your message mentions {}", t.join(", "));
+ return Some(chosen(k, t, &how, ROUTE_AT + 0.1));
+ }
+ }
let mut p = to_lead(matched.clone(), terms);
if same_role_tie {
// Two bots with the same role: a close call between them, not multi-role work
@@ -903,14 +932,19 @@ pub fn pick_member_hinted<'a>(
if let [i] = best.as_slice() {
let (k, s, terms, named) = &scored[*i];
let how = format!("shares words with your message: {}", terms.join(", "));
- // One word only in a description is a hint (0.5); a word in the name or title, or two
- // description words, is enough to route
+ // One word only in a description is a hint (0.5) when another bot also matched; a word in
+ // the name or title, or two description words, is enough to route
let base = (0.4 + 0.1 * *s as f32 + if *named { 0.1 } else { 0.0 }).min(0.95);
- let mut p = chosen(k, terms.clone(), &how, base);
let runner_up = (0..scored.len())
.filter(|&j| j != *i && scored[j].1 > 0)
.max_by_key(|&j| scored[j].1)
.map(|j| scored[j].0);
+ // With no runner-up there is no one to ask about: words of the message in only this bot's
+ // name, title or description (not just a weak role hint) are enough to route
+ // ("calories" for the Nutritionist), rather than drop to the Concierge
+ let own_words = matches[*i].iter().any(|(t, _)| !shared(t));
+ let base = if runner_up.is_none() && own_words { base.max(ROUTE_AT) } else { base };
+ let mut p = chosen(k, terms.clone(), &how, base);
p.choices = std::iter::once(*k).chain(runner_up).collect();
return Some(p);
}
@@ -1675,15 +1709,76 @@ mod fit_tests {
#[test]
fn laya_only_nudges_a_pick_with_word_evidence() {
let members = general();
- // One description-only word is a hint below the bar; Laya agreeing tips it over
+ // One description-only word that no other bot has routes; Laya agreeing raises the fit
let prompt = "any thoughts on scroll-stopping openers?";
let alone = pick_member_after(prompt, "k-lead", &members, None, "channel lead", None).unwrap();
let agreed = pick_member_after(prompt, "k-lead", &members, Some(LayaGuess { kwant: &members[1], confident: true }), "channel lead", None).unwrap();
assert_eq!(alone.kwant.id, "k-script", "{alone:?}");
- assert!(alone.fit < ROUTE_AT && alone.fit >= ASK_FROM, "{alone:?}");
+ assert_eq!(alone.fit, ROUTE_AT, "{alone:?}");
assert!(agreed.fit > alone.fit, "{agreed:?}");
}
+ fn kitchen() -> Vec<Kwant> {
+ vec![
+ bot("k-tl", "TechLead", "Tech Lead", "Leads engineering and coordinates the team"),
+ bot("k-chef", "HeadChef", "Head Chef", "Runs the kitchen: menus, techniques, recipes and cooking questions"),
+ bot("k-nutri", "Nutritionist", "Nutritionist", "Nutrition, calories, macros, diets and meal plans"),
+ bot("k-pastry", "Pastry", "Pastry Chef", "Pastry, bread, dough and desserts"),
+ bot("k-tiktok", "TikTokLead", "TikTok Lead", "Plans the TikTok channel and content calendar"),
+ bot("k-script", "Scriptwriter", "TikTok Scriptwriter & Hook Specialist", "Writes TikTok scripts and hooks"),
+ bot("k-comm", "Community", "Community Manager", "Answers followers and moderates the community"),
+ bot("k-data", "Analyst", "Data Analyst", "Analyses sales, churn and retention numbers"),
+ ]
+ }
+
+ /// The first fit score sent a specialist question with one word only its bot has, and no
+ /// runner-up, to the Concierge (0.5, nobody to ask about). Corn dogs still have no fit.
+ #[test]
+ fn a_word_only_one_bot_has_routes_to_it_not_the_concierge() {
+ let members = kitchen();
+ for (prompt, want) in [
+ ("How many calories are in a corn dog?", "k-nutri"),
+ ("Which dough is better for croissants, laminated or puff?", "k-pastry"),
+ ("Which dishes should go on tonight's menu?", "k-chef"),
+ ] {
+ let p = pick_member_after(prompt, "k-tl", &members, None, "channel lead", None).unwrap();
+ assert_eq!(p.kwant.id, want, "{prompt}: {p:?}");
+ assert_eq!(settle(&route_of(&p), true, true), Settle::Route, "{prompt}: {p:?}");
+ }
+ let p = pick_member_after("Best place to eat corn dogs in Munich tomorrow?", "k-tl", &members, None, "channel lead", None).unwrap();
+ assert_eq!(settle(&route_of(&p), true, true), Settle::Concierge, "{p:?}");
+ }
+
+ /// "go" in "ok go ahead" counted as a Backend word, so the go-ahead went to the Concierge.
+ #[test]
+ fn a_go_ahead_carries_on_with_the_last_speaker_before_word_matching() {
+ let members = vec![
+ bot("k-be", "Backend", "Backend Engineer", "Builds APIs and services"),
+ bot("k-fe", "Frontend", "Frontend Engineer", "Builds the web interface"),
+ bot("k-mk", "Marketer", "Growth Marketer", "Campaigns, copy and launches"),
+ ];
+ for last in ["k-be", "k-fe"] {
+ let p = pick_member_after("ok go ahead", "k-be", &members, None, "channel lead", Some(last)).unwrap();
+ assert_eq!((p.kwant.id.as_str(), p.basis), (last, "last"), "{p:?}");
+ assert_eq!(settle(&route_of(&p), true, true), Settle::Route);
+ }
+ // "go" as a verb names no one's work
+ let p = pick_member_after("Where should we go for the team dinner in Lisbon?", "k-be", &members, None, "channel lead", None).unwrap();
+ assert_eq!(settle(&route_of(&p), true, true), Settle::Concierge, "{p:?}");
+ }
+
+ /// Bots sharing a role word ("tiktok") are told apart by a word in just one of their titles.
+ #[test]
+ fn a_title_word_settles_a_tie_between_bots_of_one_role() {
+ let members = kitchen();
+ let p = pick_member_after("Write a TikTok hook about corn dogs", "k-tl", &members, None, "channel lead", None).unwrap();
+ assert_eq!(p.kwant.id, "k-script", "{p:?}");
+ assert_eq!(settle(&route_of(&p), true, true), Settle::Route);
+ // Without such a word it stays a close call
+ let p = pick_member_after("Ideas for our TikTok this week?", "k-tl", &members, None, "channel lead", None).unwrap();
+ assert!(matches!(settle(&route_of(&p), true, true), Settle::Ask(_)), "{p:?}");
+ }
+
#[test]
fn follow_ups_and_greetings_stay_with_the_last_speaker() {
let members = general();
diff --git a/tests/concierge_test.rs b/tests/concierge_test.rs
index c39f3766..d41501c2 100644
--- a/tests/concierge_test.rs
+++ b/tests/concierge_test.rs
@@ -387,6 +387,8 @@ async fn corrections_and_choices_teach_routing() {
/// 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.
+/// The Concierge's proposal with those ids is a pending hire card, and once the person denies it
+/// the same kind of bot is refused.
#[tokio::test]
async fn the_concierge_suggests_a_hire_on_the_third_similar_request() {
let (app, state, _tmp) = setup().await;
@@ -419,4 +421,54 @@ async fn the_concierge_suggests_a_hire_on_the_third_similar_request() {
_ => assert!(similar.is_null(), "{prompt}: {routing}"),
}
}
+
+ // The Concierge acts on it: propose_hire with exactly those ids puts a pending hire card up
+ let space = SpaceId::default_space();
+ let concierge = concierges(&state).await.pop().expect("the Concierge");
+ let guide = json!({
+ "name": "Foodie",
+ "role": "Local food guide",
+ "instructions": "You recommend street food, markets and places to eat.",
+ "reason": "Street food questions keep coming and none of the specialists here covers them.",
+ "evidence": {"basis": "repeated", "similar_requests": ids},
+ });
+ let (text, is_error) = propose_hire(&app, &state, &concierge, &general, 1, guide.clone()).await;
+ assert!(!is_error, "{text}");
+ let pending = state.db.list_hires(&space, Some("pending")).await.unwrap();
+ let [card] = pending.as_slice() else { panic!("one pending hire card: {pending:?}") };
+ assert_eq!(card.kwant_id, concierge);
+ let evidence: Value = serde_json::from_str(&card.evidence).unwrap();
+ assert_eq!(evidence["basis"], "repeated");
+ let on_card: Vec<&str> = evidence["similar_requests"].as_array().unwrap().iter().map(|r| r["message_id"].as_str().unwrap()).collect();
+ assert_eq!(on_card, ids.iter().map(String::as_str).collect::<Vec<_>>());
+ let msgs = state.db.list_messages(&general, 100).await.unwrap();
+ assert!(
+ msgs.iter().any(|m| m.meta.as_deref().is_some_and(|x| x.contains("hire_proposal") && x.contains(&card.id))),
+ "the hire card is posted in #general"
+ );
+
+ // The person turns it down: the same kind of bot isn't proposed again
+ ok(&app, "POST", &format!("/api/hires/{}/deny", card.id), None).await;
+ let (text, is_error) = propose_hire(&app, &state, &concierge, &general, 2, guide).await;
+ assert!(is_error, "a denied role is refused: {text}");
+ assert!(state.db.list_hires(&space, Some("pending")).await.unwrap().is_empty());
+ assert_eq!(state.db.list_hires(&space, None).await.unwrap().len(), 1, "nothing new was saved");
+}
+
+/// `bot` calls propose_hire in its own turn number `turn` in `channel`; the tool's text and isError.
+async fn propose_hire(app: &Router, state: &AppState, bot: &str, channel: &str, turn: u32, args: Value) -> (String, bool) {
+ let k = state.db.get_kwant(bot).await.unwrap().unwrap();
+ let turn_id = format!("turn-{bot}-{turn}");
+ let scope = SelfScope {
+ kwant_id: k.id.clone(),
+ kwant_name: k.name.clone(),
+ origin: Some(TurnOrigin { channel_id: Some(channel.into()), ..Default::default() }),
+ turn_id: Some(turn_id.clone()),
+ ..Default::default()
+ };
+ let token = mcp_runtime::prepare_turn_with_self(state, &k, Some(turn_id), None, Some(scope)).await.unwrap().1;
+ let rpc = json!({"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "propose_hire", "arguments": args}});
+ let (s, v) = call_as(app, "/api/mcp/self", &token, rpc).await;
+ assert_eq!(s, StatusCode::OK, "{v}");
+ (v["result"]["content"][0]["text"].as_str().unwrap_or("").to_string(), v["result"]["isError"].as_bool().unwrap_or(false))
}
diff --git a/tests/router_eval/README.md b/tests/router_eval/README.md
index 3000a10e..a3e04cb4 100644
--- a/tests/router_eval/README.md
+++ b/tests/router_eval/README.md
@@ -11,4 +11,7 @@ for the wrong stated reason, reported separately.
`expect.route` is a member name, `concierge` or `ask`. `expect.basis` lists accepted bases (omitted = any).
`laya` fixes a confident titles-only Laya guess (case 1 reproduces the screenshot). `channel` is `general`,
-a members' channel name or `dm`; the runner passes it once the router takes a channel kind (see `route_case`).
+a members' channel name or `dm`: the runner picks, then settles on fit as the server does, with a Concierge
+in #general; a DM goes to its pick (see `route_case`).
+
+`router_eval_must_pass` runs in CI and fails if any case in its `MUST_PASS` list misroutes.
diff --git a/tests/router_eval_test.rs b/tests/router_eval_test.rs
index 64da36a5..c2b69e8e 100644
--- a/tests/router_eval_test.rs
+++ b/tests/router_eval_test.rs
@@ -2,8 +2,9 @@
//! a live Laya (a case may carry a fixed Laya guess), and reports the misroute rate per space.
//!
//! * `router_eval_cases_are_well_formed` runs in CI: the data parses and every name resolves.
-//! * `router_eval` is `#[ignore]`d, because expected values for routes that don't exist yet
-//! (`concierge`, `ask`) fail by design. Run it on a branch with:
+//! * `router_eval_must_pass` runs in CI: the cases in `MUST_PASS` route where expected.
+//! * `router_eval` is `#[ignore]`d: it reports every case, including ones still known to fail.
+//! Run it with:
//!
//! cargo test --test router_eval_test router_eval -- --ignored --nocapture
//!
@@ -13,10 +14,10 @@
//! A *misroute* is a wrong destination. A *basis mismatch* is the right destination for the wrong
//! stated reason (basis); it is reported apart, not counted as a misroute.
//!
-//! When the router's signature changes (a channel kind, a Concierge), only `route_case` needs to change.
+//! `route_case` routes as the server does: pick, then settle on fit (#general has a Concierge).
use kwnt::db::models::Kwant;
-use kwnt::router::team::{pick_member_after, LayaGuess};
+use kwnt::router::team::{pick_member_hinted, settle, ChannelRoute, Hints, LayaGuess, Settle};
use serde::Deserialize;
use std::collections::BTreeMap;
@@ -94,15 +95,28 @@ fn route_case(case: &Case, space: &Space, members: &[Kwant]) -> (String, String)
let by_name = |n: &str| members.iter().find(|m| m.name == n).unwrap_or_else(|| panic!("case {}: no member {n}", case.id));
let laya = case.laya.as_ref().map(|l| LayaGuess { kwant: by_name(&l.pick), confident: l.confident });
let last = case.last_speaker.as_ref().map(|n| by_name(n).id.clone());
- // main: no channel kind and no Concierge yet, so `case.channel` is not passed.
- let pick = pick_member_after(&case.message, &by_name(&space.lead).id, members, laya, "channel lead", last.as_deref())
+ // As the server does (routes.rs): pick, then settle on fit. A DM goes to its bot as picked; in
+ // #general the Concierge exists (it is made on the first no-match unless the person removed it).
+ let pick = pick_member_hinted(&case.message, &by_name(&space.lead).id, members, laya, "channel lead", last.as_deref(), &Hints::default())
.expect("a pick");
- let dest = match pick.basis {
- "concierge" => "concierge".to_string(),
- "ask" => "ask".to_string(),
- _ => pick.kwant.name.clone(),
+ if std::env::var("ROUTER_EVAL_DEBUG").is_ok() { eprintln!("DEBUG #{} pick={} basis={} fit={:.2} choices={:?} terms={:?}", case.id, pick.kwant.name, pick.basis, pick.fit, pick.choices.iter().map(|k| &k.name).collect::<Vec<_>>(), pick.terms); }
+ if case.channel == "dm" {
+ return (pick.kwant.name.clone(), pick.basis.to_string());
+ }
+ let route = ChannelRoute {
+ kwant_id: pick.kwant.id.clone(),
+ reason: pick.reason.clone(),
+ fallback: laya.is_none(),
+ matched_terms: pick.terms.clone(),
+ basis: pick.basis.into(),
+ fit: pick.fit,
+ choices: pick.choices.iter().map(|k| k.id.clone()).collect(),
};
- (dest, pick.basis.to_string())
+ match settle(&route, case.channel == "general", true) {
+ Settle::Concierge => ("concierge".into(), "concierge".into()),
+ Settle::Ask(_) => ("ask".into(), "ask".into()),
+ Settle::Route => (pick.kwant.name.clone(), pick.basis.to_string()),
+ }
}
#[test]
@@ -165,3 +179,23 @@ fn router_eval() {
assert!(m as f64 / t as f64 <= max, "misroute rate {:.3} above {max}", m as f64 / t as f64);
}
}
+
+/// Cases the router must get right, checked in CI: every no-match case (to the Concierge in
+/// #general), the specialist questions and the go-ahead that main already routed right and the
+/// first fit score broke (#12, #13, #16, #17, #40), and #35, where "go" made Backend a runner-up.
+const MUST_PASS: &[u32] = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 16, 17, 20, 35, 36, 40, 44, 45];
+
+#[test]
+fn router_eval_must_pass() {
+ let f = load();
+ let mut failures = Vec::new();
+ for id in MUST_PASS {
+ let c = f.cases.iter().find(|c| c.id == *id).unwrap_or_else(|| panic!("no case #{id}"));
+ let space = &f.spaces[&c.space];
+ let (dest, basis) = route_case(c, space, &kwants(space));
+ if dest != c.expect.route {
+ failures.push(format!("#{id} {:?}: expected {}, got {dest} (basis {basis})", c.message, c.expect.route));
+ }
+ }
+ assert!(failures.is_empty(), "must-pass routing cases failed:\n{}", failures.join("\n"));
+}