trusty_code/intent/mod.rs
1//! Intent classification for PM orchestrator fast-pathing.
2//!
3//! Why: The PM system prompt instructs "always use delegate_to_agent", which
4//! means even trivial conversational inputs like "Hello" trigger sub-agent
5//! spawning — a 60-90s round trip for what should be a sub-second reply.
6//! Research questions ("explain X", "what does Y do") similarly don't need
7//! the full prescriptive subprocess pipeline — they can run in-process with
8//! tools. Classifying input cheaply (no network) lets the controller route
9//! each intent to its lowest-cost path.
10//! What: A pure-Rust heuristic classifier returning `IntentClass::Conversational`,
11//! `IntentClass::Research`, or `IntentClass::Implementation`. No regex crate,
12//! no LLM — just lowercased string matching and word-count gates. Slash
13//! commands are always Implementation so the user can force the full pipeline.
14//! Test: `cargo test intent::` exercises greetings, closings, self-questions,
15//! research verbs, question words, action-verb tasks, and edge cases.
16//! See `tests` module below — fixes #199, #203.
17
18/// Classification of user input for PM fast-pathing.
19///
20/// Why: Distinguishes conversational chatter (no work) from research questions
21/// (in-process with tools) from implementation requests (full prescriptive
22/// subprocess pipeline) so the controller routes each to its lowest-cost path.
23/// What: `Conversational` -> reply directly, no tools.
24/// `Research` -> in-process PM loop with `delegate_to_agent` available.
25/// `Implementation` -> full subprocess prescriptive workflow.
26/// Test: Pattern-match in `submit_task` + `run_pm_task_with_session`; covered
27/// by `tests::*` below.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub enum IntentClass {
30 /// Greeting, thanks, or simple self-referential question — answer directly.
31 Conversational,
32 /// Research/explain/analyze — in-process PM loop with tools.
33 Research,
34 /// Action request — route through the full prescriptive subprocess pipeline.
35 Implementation,
36}
37
38/// Action verbs that strongly indicate an implementation request.
39///
40/// Why: Centralizing the verb list as a constant keeps the classifier honest
41/// — any change to "what counts as a task verb" lives in one place.
42/// What: Lowercase verb tokens; matched as whole words against normalized input.
43const ACTION_VERBS: &[&str] = &[
44 "write",
45 "create",
46 "build",
47 "run",
48 "fix",
49 "implement",
50 "add",
51 "update",
52 "delete",
53 "test",
54 "deploy",
55 "generate",
56 "show",
57 "list",
58 "find",
59 "search",
60 "refactor",
61 "remove",
62 "rename",
63 "install",
64 "compile",
65 "debug",
66 "check",
67];
68
69/// Research verbs that signal "explain / analyze / investigate" intent.
70///
71/// Why: Research questions don't need the prescriptive subprocess pipeline.
72/// They benefit from PM's tool-armed in-process loop (delegate to a sub-agent
73/// only when needed) for fast turnaround on read-only tasks.
74/// What: Lowercase verb tokens; matched as whole words against normalized input.
75/// Note: An ACTION_VERB elsewhere in the input wins over a research verb
76/// (e.g. "explain how to fix this" -> Implementation, because "fix" is
77/// concrete work).
78const RESEARCH_VERBS: &[&str] = &[
79 "explain",
80 "analyze",
81 "analyse",
82 "investigate",
83 "review",
84 "examine",
85 "explore",
86 "describe",
87 "summarize",
88 "summarise",
89 "understand",
90 "diagnose",
91 "audit",
92 "assess",
93 "evaluate",
94 "compare",
95];
96
97/// Question words that signal an interrogative (research) intent.
98///
99/// Why: When input starts with a question word and lacks an action verb, it's
100/// almost always a research question (e.g. "what does X do", "why is Y slow").
101/// What: Lowercase tokens; matched only as the FIRST word of normalized input.
102const QUESTION_WORDS: &[&str] = &[
103 "what", "why", "how", "when", "where", "which", "who", "whose", "whom", "does", "is", "are",
104 "can", "could", "would", "should",
105];
106
107/// Greeting prefixes that signal a conversational opener.
108///
109/// Why: Recognized as whole-message matches OR as the first word of a short
110/// input. Kept as a constant so additions (e.g. "salutations") are a one-liner.
111/// What: Lowercase, punctuation-stripped greeting tokens.
112const GREETINGS: &[&str] = &[
113 "hello",
114 "hi",
115 "hey",
116 "howdy",
117 "greetings",
118 "sup",
119 "yo",
120 "good morning",
121 "good afternoon",
122 "good evening",
123 "hey there",
124 "hi there",
125 "hello there",
126];
127
128/// Closing / gratitude phrases.
129///
130/// Why: Same rationale as `GREETINGS` — single source of truth.
131const CLOSINGS: &[&str] = &[
132 "bye",
133 "goodbye",
134 "thanks",
135 "thank you",
136 "cheers",
137 "later",
138 "see ya",
139 "see you",
140 "ok thanks",
141 "thx",
142 "ty",
143];
144
145/// Self-referential conversational questions.
146///
147/// Why: Users frequently probe "what can you do?" before delegating real work.
148/// Answering directly (≤2 sentences from the PM) is faster than spawning an agent.
149const SELF_QUESTIONS: &[&str] = &[
150 "how are you",
151 "what are you",
152 "who are you",
153 "what can you do",
154 "what is trusty-code",
155 "what is trusty code",
156 "what do you do",
157 "what's your name",
158 "whats your name",
159 "are you there",
160 "you there",
161];
162
163/// Strip surrounding/embedded punctuation for matching.
164///
165/// Why: Users write "Hello!" / "hi." / "hey," — comparing to plain "hello"
166/// requires normalization. We keep apostrophes (so "what's" stays whole)
167/// and internal hyphens (so "trusty-code" stays whole).
168/// What: Lowercases and replaces ASCII punctuation (except `'`, `-`, `_`)
169/// with spaces, then collapses runs of whitespace. Underscores are preserved
170/// so identifiers like `run_pm_task_with_session` remain a single token
171/// rather than fragmenting into "run" / "task" (which would falsely match
172/// ACTION_VERBS).
173/// Test: Covered indirectly by classifier tests — "Hello!!!" must classify
174/// the same as "hello".
175fn normalize(input: &str) -> String {
176 let mut out = String::with_capacity(input.len());
177 for ch in input.chars() {
178 if ch.is_alphanumeric() || ch == '\'' || ch == '-' || ch == '_' || ch.is_whitespace() {
179 for low in ch.to_lowercase() {
180 out.push(low);
181 }
182 } else {
183 out.push(' ');
184 }
185 }
186 // Collapse whitespace.
187 out.split_whitespace().collect::<Vec<_>>().join(" ")
188}
189
190/// Classify a user input string into a coarse intent class.
191///
192/// Why: Lets `submit_task` and `run_pm_task_with_session` route each input
193/// to its cheapest viable path — direct reply (Conversational), in-process
194/// tool-armed loop (Research), or full subprocess pipeline (Implementation).
195/// What: Applies heuristics in priority order — empty, slash command, greeting,
196/// closing, self-question, research-question, action-verb scan, length-based
197/// fallback.
198/// Test: `tests::*` below covers greetings, closings, self-questions, research
199/// verbs, question words, clear task verbs, slash commands, and edge cases.
200pub fn classify_intent(input: &str) -> IntentClass {
201 let trimmed = input.trim();
202
203 // Empty / whitespace-only -> conversational (the caller will produce a
204 // friendly default; no point in calling the LLM for "").
205 if trimmed.is_empty() {
206 return IntentClass::Conversational;
207 }
208
209 // Slash commands always go through the full pipeline. They have explicit
210 // semantics and the user is signaling intent unambiguously.
211 if trimmed.starts_with('/') {
212 return IntentClass::Implementation;
213 }
214
215 let normalized = normalize(trimmed);
216 if normalized.is_empty() {
217 // All punctuation — nothing actionable.
218 return IntentClass::Conversational;
219 }
220
221 // Whole-message matches against canned phrase lists. These are the
222 // strongest signals: "hello.", "thanks!", "what can you do?" etc.
223 if GREETINGS.iter().any(|g| &normalized == g) {
224 return IntentClass::Conversational;
225 }
226 if CLOSINGS.iter().any(|c| &normalized == c) {
227 return IntentClass::Conversational;
228 }
229 if SELF_QUESTIONS.iter().any(|q| &normalized == q) {
230 return IntentClass::Conversational;
231 }
232
233 // Prefix matches for greetings — "hello there friend" still reads as a
234 // greeting; "hello, can you write a script" should NOT (action verb wins).
235 let words: Vec<&str> = normalized.split_whitespace().collect();
236 let word_count = words.len();
237
238 let has_action_verb = words.iter().any(|w| ACTION_VERBS.contains(w));
239 let has_research_verb = words.iter().any(|w| RESEARCH_VERBS.contains(w));
240 let starts_with_question_word = words
241 .first()
242 .map(|w| QUESTION_WORDS.contains(w))
243 .unwrap_or(false);
244 let ends_with_question_mark = trimmed.ends_with('?');
245
246 // Greeting prefix on a short message (no action/research verb) -> conversational.
247 if !has_action_verb && !has_research_verb && !starts_with_question_word {
248 for g in GREETINGS {
249 if normalized.starts_with(g)
250 && (normalized.len() == g.len()
251 || normalized.as_bytes().get(g.len()) == Some(&b' '))
252 && word_count <= 6
253 {
254 return IntentClass::Conversational;
255 }
256 }
257 for c in CLOSINGS {
258 if normalized.starts_with(c)
259 && (normalized.len() == c.len()
260 || normalized.as_bytes().get(c.len()) == Some(&b' '))
261 && word_count <= 6
262 {
263 return IntentClass::Conversational;
264 }
265 }
266 }
267
268 // Action verbs ALWAYS win — even over question words and research verbs.
269 // "how do I fix this bug" -> Implementation (because "fix" is concrete work).
270 // "explain how to write a test" -> Implementation (because "write" wins).
271 if has_action_verb {
272 return IntentClass::Implementation;
273 }
274
275 // Research signal: starts with question word OR contains a research verb,
276 // and lacks an action verb (checked above).
277 if starts_with_question_word || has_research_verb {
278 return IntentClass::Research;
279 }
280
281 // Question mark on a short input with no action verb -> Research
282 // (e.g. "is bedrock enabled?", "does this support tokio?").
283 if ends_with_question_mark && word_count <= 15 {
284 return IntentClass::Research;
285 }
286
287 // "help me ..." is an implementation request even though "help" alone
288 // isn't a verb we list (to avoid catching "help?").
289 if normalized.starts_with("help me ") || normalized == "help me" {
290 return IntentClass::Implementation;
291 }
292
293 // Short input, no action/research/question signal -> probably conversational.
294 if word_count <= 4 {
295 return IntentClass::Conversational;
296 }
297
298 // Long input without action verbs but past the threshold -> Implementation.
299 if word_count > 10 {
300 return IntentClass::Implementation;
301 }
302
303 // Ambiguous middle range (5-10 words, no action verb): treat as
304 // conversational. The user can re-issue with an action verb if they
305 // actually wanted delegation.
306 IntentClass::Conversational
307}
308
309#[cfg(test)]
310#[path = "classifier_tests.rs"]
311mod classifier_tests;
312
313#[cfg(test)]
314#[path = "classifier_tests_2.rs"]
315mod classifier_tests_2;
316
317#[cfg(test)]
318#[path = "classifier_property_tests.rs"]
319mod classifier_property_tests;
320
321#[cfg(test)]
322#[path = "unit_tests.rs"]
323mod tests;