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.

Routing follow-ups: QA test plans, possessive/hyphen/version keywords, no bare 'private', title-only roles

Lin (kwant bot)790993b18228
diff --git a/src/router/fallback.rs b/src/router/fallback.rs
index 9c58840a..7b8bb72f 100644
--- a/src/router/fallback.rs
+++ b/src/router/fallback.rs
@@ -9,7 +9,7 @@ const DEEP_SIGNALS: &[&str] = &[
"optimise", "optimized", "optimised", "optimizing", "optimising", "optimization", "optimisation",
"investigate", "investigating", "investigation", "root cause", "root-cause", "tradeoff", "trade-off",
"trade off", "monolith", "monolithic", "microservice", "migrate", "migrated", "migrating", "migration",
- "postmortem", "post-mortem",
+ "postmortem", "post-mortem", "deep analysis", "think deeply", "think hard", "go deep", "dig deep",
];
/// Everyday phrases that contain a deep signal but ask for nothing deep.
@@ -18,25 +18,38 @@ const NOT_DEEP: &[&str] = &["security guard", "security deposit", "social securi
/// Words that, just before a signal, say the person doesn't want it ("don't refactor anything").
const NEGATIONS: &[&str] = &["don't", "dont", "do not", "not", "no", "never", "without"];
-/// Lower-case words of `text`. Hyphens and apostrophes stay inside a word ("trade-off", "don't"), and
-/// are trimmed from its ends ("'deep copy'").
+/// After a negation, these turn it back into a request: "don't ignore security warnings" wants them looked at.
+const UNDO_NEGATION: &[&str] = &["ignore", "skip", "forget", "overlook", "neglect", "miss", "underestimate"];
+
+/// Lower-case words of `text`. Apostrophes stay inside a word ("don't") but a possessive "'s" is
+/// dropped ("Rust's" is "rust"). Hyphens split a word ("code-review" is "code review"), and keyword
+/// phrases are split the same way, so "trade-off" still matches "trade-off" and "trade off".
pub(crate) fn words(text: &str) -> Vec<String> {
text.to_lowercase()
.replace('\u{2019}', "'")
- .split(|c: char| !c.is_alphanumeric() && c != '-' && c != '\'')
- .map(|w| w.trim_matches(|c| c == '-' || c == '\''))
+ .split(|c: char| !c.is_alphanumeric() && c != '\'')
+ .map(|w| w.trim_matches('\''))
+ .map(|w| w.strip_suffix("'s").unwrap_or(w))
.filter(|w| !w.is_empty())
.map(str::to_string)
.collect()
}
-/// Where `phrase` (one or more words) starts in `words`. A word also matches its plural ("tradeoffs").
+/// Where `phrase` (one or more words) starts in `words`. A word also matches its plural ("tradeoffs")
+/// and a version number after it ("python3").
fn phrase_at(words: &[String], phrase: &str) -> Vec<usize> {
- let parts: Vec<&str> = phrase.split(' ').collect();
+ let parts: Vec<&str> = phrase.split([' ', '-']).filter(|p| !p.is_empty()).collect();
if parts.is_empty() || words.len() < parts.len() {
return Vec::new();
}
- let same = |w: &str, p: &str| w == p || w.strip_suffix('s').is_some_and(|x| x == p) || w.strip_suffix("es").is_some_and(|x| x == p);
+ let unversioned = |w: &str| {
+ let stem = w.trim_end_matches(|c: char| c.is_ascii_digit());
+ if stem.len() >= 4 && stem.chars().all(char::is_alphabetic) { stem.to_string() } else { w.to_string() }
+ };
+ let same = |w: &str, p: &str| {
+ let w = unversioned(w);
+ w == p || w.strip_suffix('s').is_some_and(|x| x == p) || w.strip_suffix("es").is_some_and(|x| x == p)
+ };
(0..=words.len() - parts.len())
.filter(|&i| parts.iter().enumerate().all(|(j, p)| same(&words[i + j], p)))
.collect()
@@ -55,7 +68,7 @@ fn has_any(words: &[String], phrases: &[&str]) -> bool {
fn has_deep_signal(text: &str) -> bool {
let mut ws = words(text);
for idiom in NOT_DEEP {
- let len = idiom.split(' ').count();
+ let len = idiom.split([' ', '-']).count();
for i in phrase_at(&ws, idiom) {
for w in &mut ws[i..i + len] {
w.clear();
@@ -64,7 +77,7 @@ fn has_deep_signal(text: &str) -> bool {
}
let negated = |i: usize| {
let before = &ws[i.saturating_sub(2)..i];
- NEGATIONS.iter().any(|n| has_phrase(before, n))
+ NEGATIONS.iter().any(|n| has_phrase(before, n)) && !has_any(before, UNDO_NEGATION)
};
DEEP_SIGNALS.iter().any(|s| phrase_at(&ws, s).into_iter().any(|i| !negated(i)))
}
@@ -127,11 +140,12 @@ pub fn blend_effort(prompt: &str, laya_effort: &str) -> String {
}
}
-/// Asks to keep the work on this machine. Bare "local" is not one of them: "localhost", "locale" and
-/// "my local coffee shop" aren't private.
+/// Asks to keep the work on this machine. Bare "local" and "private" are not among them: "localhost",
+/// "my local coffee shop", "Safari private mode" and "a private method" aren't about where it runs.
const PRIVATE: &[&str] = &[
- "private", "confidential", "sensitive", "offline", "ollama", "local model", "local llm", "locally",
- "on-device", "on device", "on my machine", "private data",
+ "confidential", "sensitive", "offline", "ollama", "local model", "local llm", "locally", "on-device",
+ "on my machine", "private data", "private files", "private documents", "private info",
+ "private information", "my private", "keep it private", "keep this private",
];
/// Needs long reasoning or writing.
@@ -142,7 +156,8 @@ const REASONING: &[&str] = &[
/// Asks for code.
const CODING: &[&str] = &[
- "python", "rust", "javascript", "typescript", "code", "script", "regex", "algorithm", "function",
+ "python", "rust", "javascript", "typescript", "code", "codebase", "coding", "script", "scripting",
+ "regex", "algorithm", "function",
];
/// Evaluates a prompt using local keyword scoring heuristics when Laya is offline.
diff --git a/src/router/team.rs b/src/router/team.rs
index e98adcfd..bc978663 100644
--- a/src/router/team.rs
+++ b/src/router/team.rs
@@ -329,10 +329,14 @@ const ROLES: &[Role] = &[
],
},
Role {
- titles: &["qa", "quality", "test", "tests", "testing", "tester", "verification"],
+ titles: &["qa", "q-a", "quality", "test", "tests", "testing", "tester", "verification", "sdet"],
signals: &[
("tests", 2), ("testing", 2), ("qa", 2), ("e2e", 2), ("regression", 2), ("coverage", 2),
("flaky", 2), ("test", 1), ("verify", 1), ("bug", 1), ("repro", 2),
+ // Phrases only QA writes. Weight 1 so they don't outvote another role's clear words ("a test
+ // plan for our ad campaign" is marketing's), but see NAMES_THE_WORK.
+ ("test-plan", 1), ("test-plans", 1), ("test-case", 1), ("test-cases", 1), ("acceptance-test", 1),
+ ("acceptance-tests", 1),
],
},
Role {
@@ -359,7 +363,9 @@ const ROLES: &[Role] = &[
("campaigns", 2), ("ad", 2), ("ads", 2), ("tweet", 2), ("tweets", 2), ("newsletter", 2), ("blog", 2),
("tagline", 2), ("slogan", 2), ("headline", 2), ("headlines", 2), ("announcement", 2),
("instagram", 2), ("tiktok", 2), ("linkedin", 2), ("copy", 1), ("launch", 1), ("social", 1),
- ("audience", 1), ("conversion", 1), ("post", 1),
+ ("audience", 1), ("conversion", 1), ("post", 1), ("seo-strategy", 2), ("keyword-strategy", 2),
+ ("content-strategy", 2), ("marketing-strategy", 2), ("growth-strategy", 2), ("brand-strategy", 2),
+ ("social-strategy", 2), ("launch-strategy", 2), ("a-b-test", 1), ("a-b-tests", 1), ("a-b-testing", 1),
],
},
Role {
@@ -381,8 +387,22 @@ const GENERIC_ENGINEER_TITLES: &[&str] = &[
"engineer", "engineering", "developer", "dev", "software", "full-stack", "fullstack", "programmer", "coder", "swe",
];
-/// Two words that mean something else together: a landing page is marketing, not a UI page.
-const COMPOUNDS: &[(&str, &str)] = &[("landing", "page"), ("market", "size"), ("market", "research")];
+/// Two words that mean something else together: a landing page is marketing, not a UI page, an SEO
+/// strategy isn't a trading strategy, and an A/B test is a marketing experiment. A pair can extend an
+/// earlier one ("a-b" then "test").
+const COMPOUNDS: &[(&str, &str)] = &[
+ ("landing", "page"), ("market", "size"), ("market", "research"), ("test", "plan"), ("test", "plans"),
+ ("test", "case"), ("test", "cases"), ("acceptance", "test"), ("acceptance", "tests"), ("seo", "strategy"),
+ ("keyword", "strategy"), ("content", "strategy"), ("marketing", "strategy"), ("growth", "strategy"),
+ ("brand", "strategy"), ("social", "strategy"), ("launch", "strategy"), ("front", "end"), ("back", "end"),
+ ("q", "a"), ("a", "b"), ("a-b", "test"), ("a-b", "tests"), ("a-b", "testing"),
+];
+
+/// A matched role phrase such as "test plan" names the work as plainly as a title does, so a confident
+/// Laya pick of another bot doesn't override it (a QA bot's own "test plan", not a guess from its persona).
+fn names_the_work(term: &str) -> bool {
+ term.contains('-') && COMPOUNDS.iter().any(|(a, b)| term == format!("{a}-{b}"))
+}
/// [`tokens`] with [`COMPOUNDS`] joined by a hyphen, for role matching.
fn role_words(text: &str) -> Vec<String> {
@@ -407,16 +427,9 @@ fn tokens(text: &str) -> Vec<String> {
.collect()
}
-fn roles_of(kwant: &Kwant) -> Vec<&'static Role> {
- let mut own = tokens(&kwant.title);
- own.extend(tokens(&kwant.name));
- if kwant.title.trim().is_empty() {
- own = tokens(&kwant.name);
- let first = tokens(kwant.persona_prompt.split(['.', '\n']).next().unwrap_or(""));
- if !ROLES.iter().any(|r| r.titles.iter().any(|t| own.iter().any(|o| o == t))) {
- own = first;
- }
- }
+/// The roles that `text`'s words (a title, a name or a persona's first line) name.
+fn roles_named_by(text: &str) -> Vec<&'static Role> {
+ let own = role_words(text);
let roles: Vec<&Role> = ROLES.iter().filter(|r| r.titles.iter().any(|t| own.iter().any(|o| o == t))).collect();
if roles.is_empty() && own.iter().any(|o| GENERIC_ENGINEER_TITLES.contains(&o.as_str())) {
return ROLES.iter().filter(|r| r.titles.contains(&"backend")).collect();
@@ -424,6 +437,21 @@ fn roles_of(kwant: &Kwant) -> Vec<&'static Role> {
roles
}
+/// A bot's roles come from its title. Its name only counts when the title names no role (a bot named
+/// "Art" titled "Software Engineer" writes code, it isn't a designer), and the persona's first line
+/// only when there is no title and the name names no role.
+fn roles_of(kwant: &Kwant) -> Vec<&'static Role> {
+ let from_title = roles_named_by(&kwant.title);
+ if !from_title.is_empty() {
+ return from_title;
+ }
+ let from_name = roles_named_by(&kwant.name);
+ if !from_name.is_empty() || !kwant.title.trim().is_empty() {
+ return from_name;
+ }
+ roles_named_by(kwant.persona_prompt.split(['.', '\n']).next().unwrap_or(""))
+}
+
/// The request words that belong to `kwant`'s role, and their weight.
fn role_score(words: &[String], kwant: &Kwant) -> (usize, Vec<String>) {
let mut score = 0;
@@ -557,7 +585,7 @@ pub fn pick_member<'a>(
.map(|((m, (_, rs, rt)), terms)| {
let own: Vec<&(String, usize)> = terms.iter().filter(|(t, _)| !shared(t)).collect();
let s = own.iter().map(|(_, s)| s).sum::<usize>();
- let named = own.iter().any(|(_, s)| *s >= 2);
+ let named = own.iter().any(|(_, s)| *s >= 2) || rt.iter().any(|t| names_the_work(t));
let mut t: Vec<String> = own.iter().map(|(t, _)| t.clone()).collect();
for w in rt {
if !t.contains(w) {
diff --git a/tests/router_test.rs b/tests/router_test.rs
index 5f315fda..5a5b2209 100644
--- a/tests/router_test.rs
+++ b/tests/router_test.rs
@@ -713,3 +713,109 @@ fn a_clear_laya_pick_beats_words_only_in_a_persona() {
// A word in a bot's title still beats Laya: that is the role the person named
assert_eq!(route("Ask the designer about this", &laya_says("Mia")).0, "Dana");
}
+
+// Follow-ups from Rigel's PR #28 review (laya-eval/rigel-check-28.md); h/hb ids are from eval-holdout.json.
+
+#[test]
+fn whole_word_keywords_still_match_possessives_hyphens_and_versions() {
+ for (prompt, model) in [
+ ("Explain Rust's borrow checker", "codex"),
+ ("Why is Python's GIL a problem here?", "codex"),
+ ("python3 is failing to import my module", "codex"),
+ ("Explain this codebase to me", "codex"),
+ ("I'm scripting a nightly backup", "codex"),
+ ("Do a code-review of this diff", "codex"),
+ ("Use Ollama's smallest model for this", "local_ollama"),
+ ("Run it on-device, please", "local_ollama"),
+ ] {
+ assert_eq!(offline_model(prompt), model, "{prompt}");
+ }
+ use kwnt::router::fallback::heuristic_effort;
+ assert_eq!(heuristic_effort("Give me a deep analysis of our churn", "chat"), "high");
+ assert_eq!(heuristic_effort("Think deeply about this design", "chat"), "high");
+ assert_eq!(heuristic_effort("Let's do a deep-dive on the auth flow", "chat"), "high");
+ // The #28 traps stay fixed
+ assert_ne!(offline_model("Open localhost:3000 and tell me why the proxy returns 502"), "local_ollama", "h01");
+ assert_ne!(offline_model("Keep the app local-first and sync later"), "local_ollama");
+ assert_eq!(offline_model("Write a punchy product description for our candle shop"), "claude", "m11");
+ assert_eq!(heuristic_effort("Explain what a 'deep copy' is in Python in one line", "chat"), "low", "a03");
+}
+
+#[test]
+fn a_private_browser_mode_is_not_a_request_for_the_local_model() {
+ assert_ne!(
+ offline_model("localStorage.setItem throws in Safari private mode. Can you review the code and fix the bug?"),
+ "local_ollama",
+ "h16"
+ );
+ assert_ne!(offline_model("Why is this Kotlin method private?"), "local_ollama");
+ // The person's own private data still stays here
+ assert_eq!(offline_model("Summarize my private medical lab results: total cholesterol 240, LDL 160, HDL 38"), "local_ollama", "m14");
+ assert_eq!(offline_model("This is private data, keep it on this machine"), "local_ollama");
+}
+
+#[test]
+fn a_negation_that_asks_not_to_skip_something_still_counts() {
+ use kwnt::router::fallback::{blend_effort, heuristic_effort};
+ assert_eq!(heuristic_effort("Don't ignore security warnings from npm audit", "chat"), "high");
+ assert_eq!(blend_effort("Don't ignore security warnings from npm audit", "medium"), "high");
+ assert_eq!(heuristic_effort("Please don't refactor anything, just tell me what time zone Paris is in", "chat"), "low", "a01");
+ assert_ne!(heuristic_effort("Don't refactor the module yet, just rename it", "chat"), "high");
+}
+
+fn qa_team() -> Vec<Kwant> {
+ let bot = |name: &str, title: &str, persona: &str| {
+ let mut k = agent(&name.to_lowercase(), name, title);
+ k.persona_prompt = persona.into();
+ k
+ };
+ vec![
+ bot("Sam", "Software Engineer", "You build and maintain backend and frontend features."),
+ bot("Quincy", "QA Engineer", "You test software, find defects and write test plans."),
+ bot("Pia", "Product Designer", "You design screens and user flows."),
+ ]
+}
+
+#[test]
+fn a_test_plan_goes_to_qa_even_when_laya_is_sure_it_is_the_engineers() {
+ let members = qa_team();
+ // Laya's real answer for hb17: Sam 0.58, Quincy 0.29
+ let laya = json!({"answers": {"lead_kwant": {"choice": "Sam", "probabilities": {"Sam": 0.58, "Quincy": 0.29, "Pia": 0.13}}}});
+ let route = |prompt: &str| {
+ let guess = kwnt::router::team::laya_guess(&laya, &members);
+ kwnt::router::team::pick_member(prompt, "sam", &members, guess, "channel lead").unwrap().kwant.name.clone()
+ };
+ assert_eq!(route("Write a test plan for the payment feature"), "Quincy", "hb17");
+ assert_eq!(route("Write test cases for the password reset flow"), "Quincy");
+ assert_eq!(route("Draft acceptance tests for the refund flow"), "Quincy");
+ // Code work still goes to the engineer
+ assert_eq!(route("Implement pagination in the users API"), "Sam", "hb16");
+ // #28's protection holds: a word only in a persona doesn't beat a confident Laya
+ let members = eval_team();
+ let mia = json!({"answers": {"lead_kwant": {"choice": "Mia", "probabilities": {"Mia": 0.6, "Dev": 0.1, "Remy": 0.1, "Dana": 0.1, "Quinn": 0.1}}}});
+ let guess = kwnt::router::team::laya_guess(&mia, &members);
+ let pick = |p: &str| kwnt::router::team::pick_member(p, "dev", &members, guess, "channel lead").unwrap().kwant.name.clone();
+ assert_eq!(pick("Plan our content calendar for next month"), "Mia");
+ assert_eq!(pick("Write a test plan for our ad campaign A/B test"), "Mia", "x02");
+}
+
+#[test]
+fn roles_come_from_titles_in_any_spelling_not_from_names() {
+ let pick = |members: &[Kwant], prompt: &str| {
+ let lead = members.last().unwrap().id.clone();
+ kwnt::router::team::pick_member(prompt, &lead, members, None, "channel lead").unwrap().kwant.name.clone()
+ };
+ let mia = agent("mia", "Mia", "Marketing Manager");
+ let sam = agent("sam", "Sam", "Software Engineer");
+ assert_eq!(pick(&[agent("zed", "Zed", "Front End Developer"), mia.clone()], "Fix the button css layout"), "Zed");
+ assert_eq!(pick(&[agent("zed", "Zed", "SDET"), sam.clone()], "Write regression tests for checkout"), "Zed");
+ assert_eq!(pick(&[agent("zed", "Zed", "Q.A. Engineer"), sam.clone()], "Write regression tests for checkout"), "Zed");
+ // A bot named Art is a software engineer by title, not a designer by name
+ assert_eq!(pick(&[agent("art", "Art", "Software Engineer"), mia.clone()], "Fix the crash in the parser"), "Art");
+ // A name still counts when the title names no role
+ assert_eq!(pick(&[agent("ui", "Frontend", "Helper"), mia.clone()], "Fix the button css layout"), "Frontend");
+ // "strategy" next to a marketing word is a marketing strategy, not a trading one (hb05)
+ let members = eval_team();
+ let p = kwnt::router::team::pick_member("Plan our SEO keyword strategy for Q4", "dev", &members, None, "channel lead").unwrap();
+ assert_eq!(p.kwant.name, "Mia", "hb05");
+}