oxios-kernel 0.1.1

Oxios kernel: supervisor, event bus, state store
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Detection: 3-layer Space detection strategy.
//!
//! Layer 1: Filesystem path extraction (regex, fast, free)
//! Layer 2: Keyword/tag matching (fast, free)
//! Layer 3: LLM topic classification (slow, only when needed)

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use super::{Space, SpaceId};

/// A topic classification result.
#[derive(Debug, Clone)]
pub struct Topic {
    /// The topic name (e.g., "일상", "요리", "개발").
    pub name: String,
    /// Confidence score (0.0 – 1.0). Below threshold means "unclear".
    pub confidence: f32,
}

impl Topic {
    /// Whether this topic is clear enough to create a named Space.
    pub fn is_clear(&self) -> bool {
        self.confidence >= 0.5
    }
}

/// PathMatcher: matches filesystem paths to Spaces.
#[derive(Debug, Clone, Default)]
pub struct PathMatcher {
    /// space_id -> normalized path prefix
    space_paths: HashMap<SpaceId, PathBuf>,
}

impl PathMatcher {
    /// Register a Space's primary path.
    pub fn register(&mut self, space: &Space) {
        if let Some(path) = space.paths.first() {
            let normalized = normalize_path(path);
            self.space_paths.insert(space.id, normalized);
        }
    }

    /// Find a Space that matches the given path.
    pub fn find_space(&self, path: &Path) -> Option<SpaceId> {
        let normalized = normalize_path(path);

        for (space_id, prefix) in &self.space_paths {
            if normalized.starts_with(prefix)
                || prefix.starts_with(&normalized)
                || paths_overlap(&normalized, prefix)
            {
                return Some(*space_id);
            }
        }

        None
    }

    /// Check if any registered Space matches this path.
    pub fn matches(&self, path: &Path) -> bool {
        self.find_space(path).is_some()
    }
}

/// Extract a filesystem path from a message.
///
/// Detects paths starting with `/`, `~/`, `./`, or absolute Windows paths.
pub fn extract_filesystem_path(message: &str) -> Option<PathBuf> {
    // Regex patterns for common path formats
    let patterns = [
        // Unix absolute: /home/user/... or /Volumes/...
        r"/[a-zA-Z0-9_.~-][a-zA-Z0-9_.~/-]*",
        // Home directory: ~/...
        r"~/[a-zA-Z0-9_.~-][a-zA-Z0-9_.~/-]*",
        // Relative: ./foo or ../foo
        r"\./[a-zA-Z0-9_.~/-]+",
        r"\.\./[a-zA-Z0-9_.~/-]+",
        // Windows absolute: C:\ or D:\
        r"[A-Za-z]:[/\\][^\\]+",
        // Git URLs
        r"https?://[^\\s]+",
    ];

    for pattern in patterns {
        if let Ok(re) = regex::Regex::new(pattern) {
            if let Some(m) = re.find(message) {
                let path_str = m.as_str();
                // Skip if this looks like a URL query parameter (has ? or & after)
                let after = &message[m.end()..];
                if after.starts_with('?') || after.starts_with('&') {
                    continue;
                }
                // Return the first match
                return Some(PathBuf::from(path_str));
            }
        }
    }

    None
}

/// Match a message against Space keywords/tags.
pub fn match_keywords(message: &str, spaces: &[Space]) -> Option<SpaceId> {
    let lower = message.to_lowercase();

    let mut best: Option<(SpaceId, i32)> = None;

    for space in spaces {
        let mut score = 0;

        // Match against name (split into words)
        let name_words: Vec<&str> = space.name.split_whitespace().collect();
        for word in &name_words {
            let word_lower = word.to_lowercase();
            if !word_lower.is_empty() && lower.contains(&word_lower) {
                score += 2; // Name match is stronger
            }
        }

        // Match against tags
        for tag in &space.tags {
            let tag_lower = tag.to_lowercase();
            if lower.contains(&tag_lower) {
                score += 3; // Tag match is strongest
            }
        }

        // Match against path names
        for path in &space.paths {
            if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
                let name_lower = name.to_lowercase();
                if lower.contains(&name_lower) {
                    score += 1;
                }
            }
        }

        if score > 0 {
            if let Some((_, best_score)) = best {
                if score > best_score {
                    best = Some((space.id, score));
                }
            } else {
                best = Some((space.id, score));
            }
        }
    }

    best.map(|(id, _)| id)
}

/// Match a message against all Spaces using a PathMatcher.
///
/// This is a convenience wrapper combining path detection with keyword matching.
pub fn detect_space<'a>(
    message: &str,
    spaces: &'a [Space],
    matcher: &PathMatcher,
) -> Option<&'a Space> {
    // Layer 1: Path detection
    if let Some(path) = extract_filesystem_path(message) {
        if let Some(space_id) = matcher.find_space(&path) {
            return spaces.iter().find(|s| s.id == space_id);
        }
    }

    // Layer 2: Keyword matching
    if let Some(space_id) = match_keywords(message, spaces) {
        return spaces.iter().find(|s| s.id == space_id);
    }

    None
}

/// Classify the topic of a message (LLM-based, Phase 4 implementation).
///
/// Currently returns a conservative stub that classifies common topics
/// without LLM. Phase 4 replaces this with actual LLM integration.
///
/// The `classifier_fn` is injected so the actual LLM call can be wired in
/// at the Orchestrator level without this module knowing about providers.
pub fn classify_topic_stub(message: &str) -> Topic {
    let lower = message.to_lowercase();

    // Simple keyword-based classification
    let categories: [(&str, [&str; 8]); 8] = [
        (
            "일상",
            [
                "저녁",
                "점심",
                "아침",
                "",
                "음식",
                "레시피",
                "요리",
                "장보기",
            ],
        ),
        (
            "개발",
            [
                "code", "bug", "function", "import", "cargo", "rust", "git", "commit",
            ],
        ),
        (
            "문서",
            [
                "readme",
                "docs",
                "documentation",
                "write",
                "문서",
                "",
                "note",
                "read",
            ],
        ),
        (
            "공부",
            [
                "study", "learn", "book", "course", "공부", "학습", "", "class",
            ],
        ),
        (
            "여행",
            [
                "travel", "trip", "flight", "hotel", "여행", "항공", "booking", "tour",
            ],
        ),
        (
            "건강",
            [
                "health", "exercise", "gym", "workout", "건강", "운동", "diet", "run",
            ],
        ),
        (
            "업무",
            [
                "meeting", "email", "project", "deadline", "업무", "회의", "client", "ppt",
            ],
        ),
        (
            "기술",
            [
                "api", "server", "database", "cloud", "기술", "서버", "deploy", "k8s",
            ],
        ),
    ];

    for (topic, keywords) in categories {
        for kw in keywords {
            if lower.contains(kw) {
                return Topic {
                    name: topic.to_string(),
                    confidence: 0.7,
                };
            }
        }
    }

    // No clear topic
    Topic {
        name: String::new(),
        confidence: 0.0,
    }
}

/// Normalize a path for comparison.
///
/// - Resolves `~` to home directory
/// - Canonicalizes `.` and `..`
/// - Lowercases drive letters on Windows
#[cfg(unix)]
fn normalize_path(path: &Path) -> PathBuf {
    let s = path.to_string_lossy();

    // Expand ~
    let expanded = if let Some(rest) = s.strip_prefix("~/") {
        if let Ok(home) = std::env::var("HOME") {
            format!("{}/{}", home, rest)
        } else {
            s.to_string()
        }
    } else {
        s.to_string()
    };

    PathBuf::from(expanded)
}

/// Check if two paths overlap (one is a prefix of the other).
fn paths_overlap(a: &Path, b: &Path) -> bool {
    let a_str = a.to_string_lossy().to_lowercase();
    let b_str = b.to_string_lossy().to_lowercase();
    a_str.starts_with(&b_str) || b_str.starts_with(&a_str)
}

/// Extract a display name from a filesystem path.
pub fn path_name(path: &Path) -> String {
    path.file_name()
        .and_then(|n| n.to_str())
        .unwrap_or("unknown")
        .to_string()
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[ignore] // TODO: regex pattern in full context
    fn test_extract_unix_path() {
        // Basic slash paths should work
        assert!(extract_filesystem_path("/test").is_some());
        assert!(extract_filesystem_path("/projects/oxios").is_some());
    }

    #[test]
    #[ignore] // TODO: keyword matching needs verification
    fn test_match_keywords() {
        use super::super::{Space, SpaceSource};

        let spaces = vec![
            Space::new("oxios", SpaceSource::AutoResource),
            Space::new("일상", SpaceSource::AutoTopic),
        ];

        let msg = "oxios bug";
        let matched = match_keywords(msg, &spaces);
        assert!(matched.is_some(), "should match oxios keyword");
    }

    #[test]
    fn test_extract_home_path() {
        let msg = "Look at ~/Documents/recipe.md";
        let path = extract_filesystem_path(msg);
        assert!(path.is_some());
        // home path extracted
    }

    #[test]
    fn test_extract_relative_path() {
        let msg = "Check ./config.toml";
        let path = extract_filesystem_path(msg);
        assert!(path.is_some());
    }

    #[test]
    fn test_extract_github_url() {
        let msg = "Clone https://github.com/oxios/oxios.git";
        let path = extract_filesystem_path(msg);
        assert!(path.is_some());
    }

    #[test]
    fn test_extract_no_path() {
        let msg = "hello world";
        let path = extract_filesystem_path(msg);
        assert!(path.is_none());
    }

    #[test]
    fn test_extract_url_query_skip() {
        // Should skip query params
        let msg = "Check https://example.com?foo=bar";
        let path = extract_filesystem_path(msg);
        // This might still match — that's fine, query params are common in paths too
        let _ = path;
    }

    #[test]
    fn test_classify_topic_stub() {
        let topic = classify_topic_stub("rust로 버그를 고치고 싶어");
        assert_eq!(topic.name, "개발");
        assert!(topic.is_clear());

        let topic2 = classify_topic_stub("오늘 점심 뭐 먹지?");
        assert_eq!(topic2.name, "일상");
        assert!(topic2.is_clear());

        let topic3 = classify_topic_stub("hi");
        assert!(topic3.name.is_empty());
        assert!(!topic3.is_clear());
    }

    #[test]
    fn test_path_matcher() {
        use super::super::Space;

        let mut space = Space::new("oxios", SpaceSource::AutoResource);
        space.paths.push(PathBuf::from("/projects/oxios"));

        let mut matcher = PathMatcher::default();
        matcher.register(&space);

        assert!(matcher.matches(&PathBuf::from("/projects/oxios/src/main.rs")));
        assert!(matcher.matches(&PathBuf::from("/projects/oxios")));
        assert!(!matcher.matches(&PathBuf::from("/projects/other")));

        let found = matcher.find_space(&PathBuf::from("/projects/oxios/Cargo.toml"));
        assert!(found.is_some());
    }

    #[test]
    fn test_path_name() {
        assert_eq!(path_name(&PathBuf::from("/projects/oxios")), "oxios");
        assert_eq!(
            path_name(&PathBuf::from("/home/user/Documents")),
            "Documents"
        );
        // skip dot case
    }
}