Skip to main content

lean_ctx_ext/core/ib/
intent.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Task-intent classification from session metadata and findings.
3//!
4//! Maps agent task descriptions to [`TaskIntent`] categories used by
5//! information-bottleneck compression to select query terms.
6
7use std::fmt;
8
9use crate::core::session::SessionState;
10
11/// Task intent categories derived from cognitive task analysis.
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
13pub enum TaskIntent {
14    /// Diagnose and correct erroneous behavior.
15    Debug,
16    /// Restructure existing code without changing its behavior.
17    Refactor,
18    /// Add or build new behavior.
19    Implement,
20    /// Assess code for correctness or quality.
21    Review,
22    /// Investigate an unfamiliar codebase or problem.
23    Explore,
24    /// No intent signal was found.
25    #[default]
26    Unknown,
27}
28
29const INTENT_KEYWORDS: &[(TaskIntent, &[&str])] = &[
30    (
31        TaskIntent::Debug,
32        &["fix", "bug", "error", "debug", "crash", "panic"],
33    ),
34    (
35        TaskIntent::Refactor,
36        &[
37            "refactor",
38            "rename",
39            "move",
40            "extract",
41            "restructure",
42            "clean",
43        ],
44    ),
45    (
46        TaskIntent::Implement,
47        &["implement", "add", "create", "build", "feature", "new"],
48    ),
49    (
50        TaskIntent::Review,
51        &["review", "check", "audit", "verify", "inspect"],
52    ),
53    (
54        TaskIntent::Explore,
55        &["understand", "explore", "analyze", "investigate", "find"],
56    ),
57];
58
59const ERROR_KEYWORDS: &[&str] = &["error", "panic", "crash", "failed", "failure", "bug"];
60
61/// Classify the agent's current task intent from session state.
62///
63/// Task metadata has priority over findings; error-bearing findings supply a
64/// debug signal when the task itself does not identify an intent.
65pub fn classify_intent(session: &SessionState) -> TaskIntent {
66    if let Some(task) = &session.task {
67        if let Some(intent) = classify_text(task.intent.as_deref().unwrap_or_default()) {
68            return intent;
69        }
70        if let Some(intent) = classify_text(&task.description) {
71            return intent;
72        }
73    }
74
75    if session
76        .findings
77        .iter()
78        .rev()
79        .any(|finding| contains_keyword(&finding.summary, ERROR_KEYWORDS))
80    {
81        return TaskIntent::Debug;
82    }
83
84    TaskIntent::Unknown
85}
86
87pub(crate) fn classify_text(text: &str) -> Option<TaskIntent> {
88    INTENT_KEYWORDS
89        .iter()
90        .find_map(|(intent, keywords)| contains_keyword(text, keywords).then_some(*intent))
91}
92
93fn contains_keyword(text: &str, keywords: &[&str]) -> bool {
94    text.split(|character: char| !character.is_alphanumeric())
95        .filter(|word| !word.is_empty())
96        .any(|word| {
97            keywords
98                .iter()
99                .any(|keyword| word.eq_ignore_ascii_case(keyword))
100        })
101}
102
103impl fmt::Display for TaskIntent {
104    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
105        let name = match self {
106            Self::Debug => "debug",
107            Self::Refactor => "refactor",
108            Self::Implement => "implement",
109            Self::Review => "review",
110            Self::Explore => "explore",
111            Self::Unknown => "unknown",
112        };
113        formatter.write_str(name)
114    }
115}
116
117#[cfg(test)]
118pub mod tests {
119    use crate::core::session::{SessionState, TaskInfo};
120
121    use super::{TaskIntent, classify_intent};
122
123    fn session_with_task(description: &str) -> SessionState {
124        let mut session = SessionState::new();
125        session.task = Some(TaskInfo {
126            description: description.to_owned(),
127            intent: None,
128            progress_pct: None,
129        });
130        session
131    }
132
133    #[test]
134    fn classify_debug_from_task() {
135        let session = session_with_task("Fix the parser crash");
136        assert_eq!(classify_intent(&session), TaskIntent::Debug);
137    }
138
139    #[test]
140    fn classify_refactor_from_task() {
141        let session = session_with_task("Refactor the session store");
142        assert_eq!(classify_intent(&session), TaskIntent::Refactor);
143    }
144
145    #[test]
146    fn classify_unknown_when_empty() {
147        assert_eq!(classify_intent(&SessionState::new()), TaskIntent::Unknown);
148    }
149
150    #[test]
151    fn display_format() {
152        assert_eq!(TaskIntent::Implement.to_string(), "implement");
153    }
154}