use serde::Serialize;
use crate::search::tokenize;
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct IntentMatch {
pub workflow: String,
pub score: f32,
pub signals: Vec<String>,
}
const MIN_SCORE: f32 = 4.0;
type Signals = &'static [(&'static str, f32)];
const ENTRANCES: &[(&str, Signals)] = &[
(
"local-handoff",
&[
("handoff", 3.0),
("handover", 3.0),
("hand off", 3.0),
("hand over", 3.0),
("hand it over", 3.0),
("custody", 3.0),
("shift change", 3.0),
("work order", 3.0),
("pass on", 2.0),
("take over", 2.0),
("equipment", 2.0),
("asset", 2.0),
("technician", 2.0),
("engineer", 2.0),
("crew", 2.0),
("inspection", 2.0),
("reconcil*", 2.0),
("acknowledg*", 2.0),
("sign off", 2.0),
("dispatch*", 2.0),
("operator", 1.0),
("field", 1.0),
("durable", 1.0),
("persist*", 1.0),
("backend", 1.0),
("job", 1.0),
("task", 1.0),
("shift", 1.0),
("workflow", 1.0),
("accept*", 1.0),
],
),
(
"backend-delivery",
&[
("telemetry", 3.0),
("sensor", 3.0),
("store and forward", 3.0),
("outage", 3.0),
("ingest*", 3.0),
("system of record", 3.0),
("outbox", 3.0),
("reading", 2.0),
("measurement", 2.0),
("metric", 2.0),
("iot", 2.0),
("retain*", 2.0),
("retention", 2.0),
("buffer*", 2.0),
("queue", 2.0),
("backlog", 2.0),
("upload*", 2.0),
("idempoten*", 2.0),
("at least once", 2.0),
("exactly once", 2.0),
("collector", 2.0),
("gateway", 2.0),
("kafka", 2.0),
("confluent", 2.0),
("backend", 1.0),
("server", 1.0),
("cloud", 1.0),
("api", 1.0),
("database", 1.0),
("deliver*", 1.0),
("accept*", 1.0),
("retry", 1.0),
("event", 1.0),
("durable", 1.0),
("persist*", 1.0),
("connectivity", 1.0),
],
),
(
"nearby-service",
&[
("invoke", 3.0),
("invocation", 3.0),
("rpc", 3.0),
("remote procedure", 3.0),
("service discovery", 3.0),
("request response", 3.0),
("provider", 3.0),
("meshservice", 3.0),
("service", 2.0),
("capabilit*", 2.0),
("advertis*", 2.0),
("authoriz*", 2.0),
("permission", 2.0),
("allowlist", 2.0),
("approved", 2.0),
("existing app", 2.0),
("existing application", 2.0),
("integrate", 2.0),
("printer", 2.0),
("scanner", 2.0),
("diagnostic", 2.0),
("kiosk", 2.0),
("discover", 1.0),
("call", 1.0),
("nearby", 1.0),
("api", 1.0),
],
),
];
const CONSUMER: Signals = &[
("game", 3.0),
("play", 3.0),
("player", 3.0),
("multiplayer", 3.0),
("ludo", 3.0),
("chess", 3.0),
("checker", 3.0),
("battleship", 3.0),
("tic tac", 3.0),
("board game", 3.0),
("chat", 3.0),
("messenger", 3.0),
("messaging app", 3.0),
("group chat", 3.0),
("dm", 3.0),
("social", 3.0),
("feed", 3.0),
("friend", 3.0),
("follower", 3.0),
("community", 3.0),
("dating", 3.0),
("poll", 2.0),
("vote", 2.0),
("photo", 2.0),
];
fn stem(token: &str) -> String {
let mut t = token
.replace("authoris", "authoriz")
.replace("organis", "organiz")
.replace("acknowledgement", "acknowledgment");
if t.len() > 4 && t.ends_with("ies") {
t.truncate(t.len() - 3);
t.push('y');
} else if t.len() > 4 && (t.ends_with("ches") || t.ends_with("shes") || t.ends_with("sses")) {
t.truncate(t.len() - 2);
} else if t.len() > 3 && t.ends_with('s') && !t.ends_with("ss") && !t.ends_with("us") {
t.truncate(t.len() - 1);
}
t
}
fn normalize(prompt: &str) -> (Vec<String>, String) {
let lower = prompt
.to_lowercase()
.replace("hand-off", "handoff")
.replace("hand-over", "handover")
.replace("back-end", "backend")
.replace("back end", "backend");
let tokens: Vec<String> = tokenize(&lower).iter().map(|t| stem(t)).collect();
let joined = format!(" {} ", tokens.join(" "));
(tokens, joined)
}
fn score(signals: Signals, tokens: &[String], joined: &str) -> (f32, Vec<String>) {
let mut total = 0.0;
let mut hits = Vec::new();
for (signal, weight) in signals {
let matched = if signal.contains(' ') {
let phrase: Vec<String> = signal.split(' ').map(stem).collect();
let phrase = phrase.join(" ");
joined.contains(&format!(" {phrase} ")).then_some(phrase)
} else if let Some(prefix) = signal.strip_suffix('*') {
tokens.iter().find(|t| t.starts_with(prefix)).cloned()
} else {
tokens.iter().find(|t| t == signal).cloned()
};
if let Some(word) = matched {
total += weight;
if !hits.contains(&word) {
hits.push(word);
}
}
}
(total, hits)
}
pub fn entrance_scores(prompt: &str) -> Vec<IntentMatch> {
let (tokens, joined) = normalize(prompt);
let mut out: Vec<IntentMatch> = ENTRANCES
.iter()
.map(|(workflow, signals)| {
let (score, signals) = score(signals, &tokens, &joined);
IntentMatch {
workflow: (*workflow).to_string(),
score,
signals,
}
})
.filter(|m| m.score > 0.0)
.collect();
out.sort_by(|a, b| {
b.score
.partial_cmp(&a.score)
.unwrap_or(std::cmp::Ordering::Equal)
});
out
}
pub fn consumer_score(prompt: &str) -> f32 {
let (tokens, joined) = normalize(prompt);
score(CONSUMER, &tokens, &joined).0
}
pub fn classify_entrance(prompt: &str) -> Option<IntentMatch> {
let best = entrance_scores(prompt).into_iter().next()?;
(best.score >= MIN_SCORE && best.score > consumer_score(prompt)).then_some(best)
}
pub fn mentions_existing_app(prompt: &str) -> bool {
let (_, joined) = normalize(prompt);
[
" existing app",
" existing application",
" existing codebase",
" existing project",
" current app",
" into our app",
" into my app",
" to our app",
" to my app",
" in our app",
" in my app",
]
.iter()
.any(|p| joined.contains(p))
}
#[cfg(test)]
mod tests {
use super::*;
fn entrance(prompt: &str) -> Option<String> {
classify_entrance(prompt).map(|m| m.workflow)
}
#[test]
fn stems_paraphrases() {
assert_eq!(stem("handoffs"), "handoff");
assert_eq!(stem("authorised"), "authorized");
assert_eq!(stem("capabilities"), "capability");
assert_eq!(stem("readings"), "reading");
assert_eq!(stem("access"), "access");
assert_eq!(stem("status"), "status");
}
#[test]
fn founder_review_prompts_select_their_entrance() {
assert_eq!(
entrance("Durable equipment handoff between field engineers, with persistence and backend reconciliation").as_deref(),
Some("local-handoff")
);
assert_eq!(
entrance("Retain sensor telemetry during outages and deliver it to a backend with explicit acceptance").as_deref(),
Some("backend-delivery")
);
assert_eq!(
entrance(
"Discover and invoke an authorised nearby service from an existing application"
)
.as_deref(),
Some("nearby-service")
);
}
#[test]
fn explicit_consumer_requests_keep_their_workflows() {
for prompt in [
"Build a tic tac toe game two phones can play over BLE",
"Nearby BLE group chat without accounts",
"Build an offline social network with feed",
"offline Ludo for two phones",
"local event chat app",
] {
assert_eq!(entrance(prompt), None, "{prompt}");
}
}
#[test]
fn weak_evidence_does_not_route() {
assert_eq!(entrance("an offline app"), None);
assert_eq!(entrance("live poll at an event over BLE"), None);
assert_eq!(
entrance("Nearby file transfer app to share photos offline"),
None
);
}
#[test]
fn detects_existing_apps() {
assert!(mentions_existing_app(
"Discover and invoke an authorised nearby service from an existing application"
));
assert!(mentions_existing_app("add store and forward into our app"));
assert!(!mentions_existing_app("new equipment handoff app"));
}
}