oxios-kernel 1.5.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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
//! Auto-meta detection: cheap heuristics on marker files (RFC-025 §Auto-Meta).
//!
//! Seeds [`MountMeta`](super::MountMeta) from filesystem markers, then the
//! agent refines it during enrichment. Detection runs at drift-detection time
//! (cheap `stat` + tiny reads), not on every message.

use std::path::Path;
use std::time::{Duration, UNIX_EPOCH};

use super::MountMeta;

/// Marker files that imply a language / stack. Checked against a Mount's
/// primary path.
const MARKERS: &[(&str, &str)] = &[
    ("Cargo.toml", "rust"),
    ("package.json", "typescript"),
    ("go.mod", "go"),
    ("pyproject.toml", "python"),
    ("requirements.txt", "python"),
    ("setup.py", "python"),
    ("pom.xml", "java"),
    ("build.gradle", "java"),
    ("build.gradle.kts", "kotlin"),
    ("Gemfile", "ruby"),
    ("composer.json", "php"),
    ("mix.exs", "elixir"),
    ("CMakeLists.txt", "cpp"),
    ("Makefile", "c"),
];

/// Docs/agent markers — recorded but don't imply a language.
const DOC_MARKERS: &[&str] = &[
    "AGENTS.md",
    "CLAUDE.md",
    ".cursorrules",
    "README.md",
    "GEMINI.md",
    ".windsurfrules",
];

/// Structure hints from top-level directories.
const STRUCTURE_HINTS: &[(&str, &str)] = &[
    ("crates", "cargo-workspace"),
    ("packages", "monorepo"),
    ("apps", "monorepo"),
    ("libs", "monorepo"),
];

/// Detect [`MountMeta`] from the filesystem at `path`.
///
/// This is a **draft** — the agent refines it during enrichment. We never make
/// an LLM call here; everything is cheap `stat`/`read` on small files.
pub fn detect_meta(path: &Path) -> MountMeta {
    let mut meta = MountMeta::default();

    let mut found_languages: Vec<String> = Vec::new();
    let mut found_markers: Vec<String> = Vec::new();

    // Language + stack markers.
    for (marker, lang) in MARKERS {
        let marker_path = path.join(marker);
        if marker_path.is_file() {
            if !found_languages.contains(&lang.to_string()) {
                found_languages.push(lang.to_string());
            }
            found_markers.push(marker.to_string());

            // Extract stack hints for well-known markers.
            extract_stack(marker, &marker_path, &mut meta.stack);
        }
    }

    // Doc / agent markers (no language, but recorded + seed summary).
    for marker in DOC_MARKERS {
        let marker_path = path.join(marker);
        if marker_path.is_file() {
            found_markers.push(marker.to_string());
            // AGENTS.md / README.md seed the summary (first paragraph).
            if (marker == &"AGENTS.md" || marker == &"README.md")
                && meta.summary.is_empty()
                && let Ok(content) = std::fs::read_to_string(&marker_path)
            {
                meta.summary = first_meaningful_line(&content);
            }
        }
    }

    // Structure hints.
    for (dir, hint) in STRUCTURE_HINTS {
        if path.join(dir).is_dir() && !meta.stack.contains(&hint.to_string()) {
            meta.stack.push(hint.to_string());
        }
    }

    meta.languages = found_languages;
    meta.markers = found_markers;

    // If no summary yet, derive one from languages.
    if meta.summary.is_empty() && !meta.languages.is_empty() {
        meta.summary = meta.languages.join(" + ");
    }

    meta
}

/// Compute the set of marker files to watch for drift, given a path.
///
/// Returns `(path, mtime)` pairs for existing markers — this is the snapshot
/// the drift detector compares against on the next session.
pub fn snapshot_markers(path: &Path) -> Vec<(std::path::PathBuf, std::time::SystemTime)> {
    let all: Vec<&str> = MARKERS
        .iter()
        .map(|(m, _)| *m)
        .chain(DOC_MARKERS.iter().copied())
        .collect();

    all.into_iter()
        .filter_map(|m| {
            let p = path.join(m);
            p.metadata()
                .and_then(|md| md.modified())
                .ok()
                // Truncate to whole seconds so the freshly-read mtime matches
                // the precision stored in the DB (u64 seconds). Without this,
                // drift would fire on every restart: the DB reconstructs a
                // whole-second SystemTime, but a fresh `stat()` yields
                // nanosecond precision.
                .map(|t| {
                    let truncated = t
                        .duration_since(UNIX_EPOCH)
                        .map(|d| UNIX_EPOCH + Duration::from_secs(d.as_secs()))
                        .unwrap_or(t);
                    (p, truncated)
                })
        })
        .collect()
}

/// Extract stack keywords from a marker file's contents.
///
/// Reads only the marker file (small), scans for dependency names. Keeps the
/// result bounded — at most ~8 entries.
fn extract_stack(marker: &str, path: &Path, stack: &mut Vec<String>) {
    let Ok(content) = std::fs::read_to_string(path) else {
        return;
    };
    let push = |stack: &mut Vec<String>, s: &str| {
        if s.len() >= 2 && !stack.iter().any(|e| e.eq_ignore_ascii_case(s)) {
            stack.push(s.to_string());
        }
    };

    match marker {
        "Cargo.toml" => {
            // Track the current TOML section so we only extract crate names
            // from dependency sections. Without this, fields from `[package]`
            // (name, edition, authors, license, …) leak into the stack.
            let mut current_section = String::new();
            let dep_sections = ["dependencies", "dev-dependencies", "build-dependencies"];

            for line in content.lines() {
                let trimmed = line.trim();
                // Track section headers like `[dependencies]` or
                // `[dependencies.serde]` (also `[workspace.dependencies]`).
                if trimmed.starts_with('[') && trimmed.ends_with(']') {
                    current_section = trimmed
                        .trim_start_matches('[')
                        .trim_end_matches(']')
                        .to_string();
                    // Dotted-table form: `[dependencies.serde]` or
                    // `[workspace.dependencies.serde]` — the trailing segment
                    // after the dependency-section name is the crate name.
                    if let Some(suffix) =
                        crate_suffix_of_dep_section(&current_section, &dep_sections)
                    {
                        let crate_name = suffix.split('.').next().unwrap_or(suffix);
                        push(stack, crate_name);
                    }
                    continue;
                }
                // For *bare* dependency sections (e.g. `[dependencies]`),
                // the `=` keys are crate names. Dotted tables were handled
                // above via their section header; their sub-keys (version,
                // path, features, …) must not be pushed.
                let is_bare_dep_section = dep_sections.iter().any(|ds| {
                    current_section == *ds || current_section == format!("workspace.{ds}")
                });
                if !is_bare_dep_section {
                    continue;
                }
                if let Some(eq_pos) = trimmed.find('=') {
                    let name = trimmed[..eq_pos].trim();
                    if !name.is_empty() {
                        push(stack, name);
                    }
                }
            }
        }
        "package.json" => {
            // Parse JSON, pull keys from dependencies + devDependencies.
            if let Ok(val) = serde_json::from_str::<serde_json::Value>(&content) {
                for key in &["dependencies", "devDependencies", "peerDependencies"] {
                    if let Some(obj) = val.get(key).and_then(|v| v.as_object()) {
                        for dep in obj.keys() {
                            push(stack, dep);
                        }
                    }
                }
            }
        }
        "go.mod" => {
            // Lines like `\tgithub.com/foo/bar v1.2.3`.
            for line in content.lines() {
                let trimmed = line.trim();
                if trimmed.starts_with("require ") || trimmed.contains(" v") {
                    let parts: Vec<&str> = trimmed.split_whitespace().collect();
                    for part in parts {
                        if part.contains('/') && part.contains('.') && !part.starts_with("require")
                        {
                            // Take the last path segment as the stack name.
                            if let Some(name) = part.rsplit('/').next() {
                                push(stack, name);
                            }
                        }
                    }
                }
            }
        }
        "pyproject.toml" | "requirements.txt" => {
            for line in content.lines() {
                let trimmed = line.trim();
                if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with('[') {
                    continue;
                }
                let name = trimmed
                    .split(['=', '<', '>', ';', '[', ' '])
                    .next()
                    .unwrap_or("")
                    .trim();
                if !name.is_empty() {
                    push(stack, name);
                }
            }
        }
        _ => {}
    }

    // Bound the stack list.
    stack.truncate(8);
}

/// If `section` (a normalized TOML header without brackets, e.g.
/// `dependencies.serde` or `workspace.dependencies.serde`) names a *dotted*
/// dependency table, return the substring after the dependency-section prefix
/// (the crate name, possibly dotted). Returns `None` for bare sections like
/// `dependencies` and for non-dependency sections like `package`.
fn crate_suffix_of_dep_section<'a>(section: &'a str, dep_sections: &[&str]) -> Option<&'a str> {
    for ds in dep_sections {
        if let Some(rest) = section.strip_prefix(&format!("{ds}.")) {
            return Some(rest);
        }
        if let Some(rest) = section.strip_prefix(&format!("workspace.{ds}.")) {
            return Some(rest);
        }
    }
    None
}

/// Take the first non-heading, non-empty line as a summary seed.
fn first_meaningful_line(content: &str) -> String {
    for line in content.lines() {
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("```") {
            continue;
        }
        // Strip markdown emphasis for a cleaner summary.
        let clean = trimmed.trim_start_matches('>').replace(['*', '`'], "");
        let clean = clean.trim();
        let capped = if clean.len() > 120 {
            &clean[..120]
        } else {
            clean
        };
        // Find a safe UTF-8 boundary.
        let mut end = capped.len();
        while end > 0 && !capped.is_char_boundary(end) {
            end -= 1;
        }
        let safe = &capped[..end];
        if clean.len() > 120 {
            return format!("{}", safe);
        }
        return safe.to_string();
    }
    String::new()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_detect_rust_project() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname = \"oxios\"\n\n[dependencies]\ntokio = \"1\"\nserde = \"1\"\naxum = \"0.7\"\n",
        )
        .unwrap();
        fs::write(dir.path().join("AGENTS.md"), "# Oxios\nAgent OS in Rust.").unwrap();

        let meta = detect_meta(dir.path());
        assert!(meta.languages.contains(&"rust".to_string()));
        assert!(meta.markers.contains(&"Cargo.toml".to_string()));
        assert!(meta.markers.contains(&"AGENTS.md".to_string()));
        assert!(meta.stack.iter().any(|s| s == "tokio"));
        assert!(meta.stack.iter().any(|s| s == "axum"));
        assert!(!meta.summary.is_empty());
    }

    #[test]
    fn test_extract_stack_ignores_non_dependency_sections() {
        // RFC-025 fix: `[package]` fields must not leak into the stack.
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("Cargo.toml"),
            [
                "[package]",
                "name = \"foo\"",
                "edition = \"2021\"",
                "authors = [\"a\"]",
                "description = \"desc\"",
                "license = \"MIT\"",
                "",
                "[dependencies]",
                "tokio = { version = \"1\", features = [\"full\"] }",
                "serde = \"1.0\"",
                "",
                "[dev-dependencies]",
                "pretty_assertions = \"1\"",
                "",
                "[dependencies.axum]",
                "version = \"0.7\"",
                "features = [\"json\"]",
            ]
            .join("\n"),
        )
        .unwrap();

        let meta = detect_meta(dir.path());
        // Real deps are captured (bare section + dotted table).
        assert!(
            meta.stack.iter().any(|s| s == "tokio"),
            "tokio missing: {meta:?}"
        );
        assert!(
            meta.stack.iter().any(|s| s == "serde"),
            "serde missing: {meta:?}"
        );
        assert!(
            meta.stack.iter().any(|s| s == "axum"),
            "dotted-table crate name missing: {meta:?}"
        );
        assert!(
            meta.stack.iter().any(|s| s == "pretty_assertions"),
            "dev-dep missing: {meta:?}"
        );
        // `[package]` fields must NOT appear.
        assert!(
            !meta.stack.iter().any(|s| s == "name"),
            "name leaked: {meta:?}"
        );
        assert!(
            !meta.stack.iter().any(|s| s == "edition"),
            "edition leaked: {meta:?}"
        );
        assert!(
            !meta.stack.iter().any(|s| s == "authors"),
            "authors leaked: {meta:?}"
        );
        // Dotted-table sub-keys must NOT appear.
        assert!(
            !meta.stack.iter().any(|s| s == "version"),
            "version leaked: {meta:?}"
        );
        assert!(
            !meta.stack.iter().any(|s| s == "features"),
            "features leaked: {meta:?}"
        );
    }

    #[test]
    fn test_detect_node_project() {
        let dir = TempDir::new().unwrap();
        fs::write(
            dir.path().join("package.json"),
            r#"{"dependencies": {"react": "^18", "next": "^14"}, "devDependencies": {"typescript": "^5"}}"#,
        )
        .unwrap();

        let meta = detect_meta(dir.path());
        assert!(meta.languages.contains(&"typescript".to_string()));
        assert!(meta.stack.iter().any(|s| s == "react"));
        assert!(meta.stack.iter().any(|s| s == "next"));
    }

    #[test]
    fn test_detect_empty_dir() {
        let dir = TempDir::new().unwrap();
        let meta = detect_meta(dir.path());
        assert!(meta.languages.is_empty());
        assert!(meta.markers.is_empty());
        assert!(meta.summary.is_empty());
    }

    #[test]
    fn test_structure_hints() {
        let dir = TempDir::new().unwrap();
        fs::create_dir(dir.path().join("crates")).unwrap();
        let meta = detect_meta(dir.path());
        assert!(meta.stack.contains(&"cargo-workspace".to_string()));
    }

    #[test]
    fn test_snapshot_markers() {
        let dir = TempDir::new().unwrap();
        fs::write(dir.path().join("Cargo.toml"), "[package]\nname = \"x\"").unwrap();
        let snap = snapshot_markers(dir.path());
        assert!(
            snap.iter()
                .any(|(p, _)| p.file_name().unwrap() == "Cargo.toml")
        );
        // Non-existent markers are excluded.
        assert!(
            !snap
                .iter()
                .any(|(p, _)| p.file_name().unwrap() == "package.json")
        );
    }

    #[test]
    fn test_first_meaningful_line() {
        assert_eq!(
            first_meaningful_line("# Title\n\nThis is the **summary**.\nMore."),
            "This is the summary."
        );
    }
}