aien-sovereign-core-mv
AienOS host runtime: inference scheduling, paged KV state, the aien CLI and Spark verification tooling. Its inference engine is in alpha testing (DGX Spark GB10); Omega is the implementation destination.
Brought by drakestapleton
aien-sovereign-core-mv / crates / aien-cli / src / science_context.rs
| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright 2026 Drake Stapleton (AIEN / aien-dev) |
| 3 | // |
| 4 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | // you may not use this file except in compliance with the License. |
| 6 | // You may obtain a copy of the License at |
| 7 | // |
| 8 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | // |
| 10 | // Unless required by applicable law or agreed to in writing, software |
| 11 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | // See the License for the specific language governing permissions and |
| 14 | // limitations under the License. |
| 15 | |
| 16 | use serde_json::{json, Value}; |
| 17 | use std::fs; |
| 18 | use std::path::{Path, PathBuf}; |
| 19 | use std::process::Command; |
| 20 | use std::sync::OnceLock; |
| 21 | |
| 22 | const DEFAULT_SCIENCE_TOKENS: usize = 700; |
| 23 | const MAX_SCIENCE_RESULTS: usize = 4; |
| 24 | |
| 25 | #[derive(Debug, Clone)] |
| 26 | struct ScienceNote { |
| 27 | id: String, |
| 28 | title: String, |
| 29 | content: String, |
| 30 | } |
| 31 | |
| 32 | #[derive(Debug, Clone, Default)] |
| 33 | struct ScienceIndex { |
| 34 | revision: String, |
| 35 | notes: Vec<ScienceNote>, |
| 36 | } |
| 37 | |
| 38 | static SCIENCE_INDEX: OnceLock<ScienceIndex> = OnceLock::new(); |
| 39 | |
| 40 | fn default_repo_path() -> PathBuf { |
| 41 | crate::platform::PlatformContext::detect() |
| 42 | .home_dir |
| 43 | .join("workspace/atlas-forgejo/data/git/repositories/drake/cortex.git") |
| 44 | } |
| 45 | |
| 46 | fn read_science_source(repo: &Path) -> Option<(String, String)> { |
| 47 | if repo.is_file() { |
| 48 | return fs::read_to_string(repo) |
| 49 | .ok() |
| 50 | .map(|content| ("working-tree".to_string(), content)); |
| 51 | } |
| 52 | if !repo.is_dir() { |
| 53 | return None; |
| 54 | } |
| 55 | let source = Command::new("git") |
| 56 | .arg(format!("--git-dir={}", repo.display())) |
| 57 | .args(["show", "HEAD:src/lib/brain-seed.ts"]) |
| 58 | .output() |
| 59 | .ok()?; |
| 60 | if !source.status.success() { |
| 61 | return None; |
| 62 | } |
| 63 | let revision = Command::new("git") |
| 64 | .arg(format!("--git-dir={}", repo.display())) |
| 65 | .args(["rev-parse", "--short", "HEAD"]) |
| 66 | .output() |
| 67 | .ok() |
| 68 | .filter(|output| output.status.success()) |
| 69 | .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_string()) |
| 70 | .unwrap_or_else(|| "unknown".to_string()); |
| 71 | Some(( |
| 72 | revision, |
| 73 | String::from_utf8_lossy(&source.stdout).into_owned(), |
| 74 | )) |
| 75 | } |
| 76 | |
| 77 | fn parse_notes(source: &str) -> Vec<ScienceNote> { |
| 78 | let mut notes = Vec::new(); |
| 79 | let mut id = String::new(); |
| 80 | let mut title = String::new(); |
| 81 | let mut string_args = Vec::new(); |
| 82 | let mut in_note = false; |
| 83 | let mut in_content = false; |
| 84 | let mut content = String::new(); |
| 85 | |
| 86 | for line in source.lines() { |
| 87 | let trimmed = line.trim(); |
| 88 | if !in_note && trimmed == "note(" { |
| 89 | in_note = true; |
| 90 | string_args.clear(); |
| 91 | continue; |
| 92 | } |
| 93 | if !in_note { |
| 94 | continue; |
| 95 | } |
| 96 | if !in_content { |
| 97 | if trimmed.starts_with('`') { |
| 98 | in_content = true; |
| 99 | content.clear(); |
| 100 | content.push_str(trimmed.trim_start_matches('`')); |
| 101 | content.push('\n'); |
| 102 | continue; |
| 103 | } |
| 104 | if let Some(value) = trimmed |
| 105 | .strip_prefix('"') |
| 106 | .and_then(|value| value.strip_suffix("\",")) |
| 107 | { |
| 108 | string_args.push(value.to_string()); |
| 109 | if string_args.len() == 1 { |
| 110 | id = value.to_string(); |
| 111 | } else if string_args.len() == 2 { |
| 112 | title = value.to_string(); |
| 113 | } |
| 114 | } |
| 115 | continue; |
| 116 | } |
| 117 | |
| 118 | if trimmed == "`," { |
| 119 | if !id.is_empty() && !title.is_empty() && !content.trim().is_empty() { |
| 120 | notes.push(ScienceNote { |
| 121 | id: std::mem::take(&mut id), |
| 122 | title: std::mem::take(&mut title), |
| 123 | content: content.trim().to_string(), |
| 124 | }); |
| 125 | } |
| 126 | in_note = false; |
| 127 | in_content = false; |
| 128 | content.clear(); |
| 129 | } else { |
| 130 | content.push_str(line); |
| 131 | content.push('\n'); |
| 132 | } |
| 133 | } |
| 134 | notes |
| 135 | } |
| 136 | |
| 137 | fn index() -> &'static ScienceIndex { |
| 138 | SCIENCE_INDEX.get_or_init(|| { |
| 139 | let configured = std::env::var("AIEN_CORTEX_SCIENCE_REPO") |
| 140 | .map(PathBuf::from) |
| 141 | .unwrap_or_else(|_| default_repo_path()); |
| 142 | let Some((revision, source)) = read_science_source(&configured) else { |
| 143 | return ScienceIndex::default(); |
| 144 | }; |
| 145 | ScienceIndex { |
| 146 | revision, |
| 147 | notes: parse_notes(&source), |
| 148 | } |
| 149 | }) |
| 150 | } |
| 151 | |
| 152 | fn query_terms(query: &str) -> Vec<String> { |
| 153 | const STOP_WORDS: &[&str] = &[ |
| 154 | "about", "after", "again", "could", "from", "have", "into", "more", "some", "that", |
| 155 | "theory", "their", "there", "these", "they", "this", "what", "when", "where", "which", |
| 156 | "with", "would", "your", |
| 157 | ]; |
| 158 | query |
| 159 | .split(|ch: char| !ch.is_alphanumeric() && ch != '-') |
| 160 | .map(|term| term.to_lowercase()) |
| 161 | .filter(|term| term.len() >= 3 && !STOP_WORDS.contains(&term.as_str())) |
| 162 | .collect() |
| 163 | } |
| 164 | |
| 165 | fn best_paragraph(note: &ScienceNote, terms: &[String]) -> String { |
| 166 | note.content |
| 167 | .split("\n\n") |
| 168 | .max_by_key(|paragraph| { |
| 169 | let lower = paragraph.to_lowercase(); |
| 170 | terms |
| 171 | .iter() |
| 172 | .map(|term| lower.matches(term).count()) |
| 173 | .sum::<usize>() |
| 174 | }) |
| 175 | .unwrap_or(¬e.content) |
| 176 | .trim() |
| 177 | .to_string() |
| 178 | } |
| 179 | |
| 180 | fn truncate_words(text: &str, limit: usize) -> String { |
| 181 | let mut words = text.split_whitespace(); |
| 182 | let selected: Vec<&str> = words.by_ref().take(limit).collect(); |
| 183 | let suffix = if words.next().is_some() { " ..." } else { "" }; |
| 184 | format!("{}{}", selected.join(" "), suffix) |
| 185 | } |
| 186 | |
| 187 | pub fn search_foundation_science(query: &str, limit: usize) -> Vec<Value> { |
| 188 | let terms = query_terms(query); |
| 189 | if terms.is_empty() { |
| 190 | return Vec::new(); |
| 191 | } |
| 192 | let index = index(); |
| 193 | let mut ranked: Vec<(usize, &ScienceNote)> = index |
| 194 | .notes |
| 195 | .iter() |
| 196 | .filter_map(|note| { |
| 197 | let title = note.title.to_lowercase(); |
| 198 | let content = note.content.to_lowercase(); |
| 199 | let score = terms |
| 200 | .iter() |
| 201 | .map(|term| title.matches(term).count() * 8 + content.matches(term).count()) |
| 202 | .sum::<usize>(); |
| 203 | (score > 0).then_some((score, note)) |
| 204 | }) |
| 205 | .collect(); |
| 206 | ranked.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| a.1.title.cmp(&b.1.title))); |
| 207 | |
| 208 | let result_limit = limit.clamp(1, MAX_SCIENCE_RESULTS); |
| 209 | let words_per_result = DEFAULT_SCIENCE_TOKENS / result_limit; |
| 210 | ranked |
| 211 | .into_iter() |
| 212 | .take(result_limit) |
| 213 | .map(|(score, note)| { |
| 214 | json!({ |
| 215 | "source": format!("cortex-founding-science:{}@{}", note.id, index.revision), |
| 216 | "title": note.title, |
| 217 | "score": score, |
| 218 | "content": truncate_words(&best_paragraph(note, &terms), words_per_result) |
| 219 | }) |
| 220 | }) |
| 221 | .collect() |
| 222 | } |
| 223 | |
| 224 | pub fn render_foundation_science(query: &str, limit: usize) -> Option<String> { |
| 225 | let results = search_foundation_science(query, limit); |
| 226 | if results.is_empty() { |
| 227 | return None; |
| 228 | } |
| 229 | let entries = results |
| 230 | .iter() |
| 231 | .map(|item| { |
| 232 | format!( |
| 233 | "[{}] {}\n{}", |
| 234 | item["source"].as_str().unwrap_or("cortex-founding-science"), |
| 235 | item["title"].as_str().unwrap_or("Untitled"), |
| 236 | item["content"].as_str().unwrap_or("") |
| 237 | ) |
| 238 | }) |
| 239 | .collect::<Vec<_>>() |
| 240 | .join("\n\n"); |
| 241 | Some(format!( |
| 242 | "<CORTEX_FOUNDING_SCIENCE>\nRetrieved neuroscience context from the original Cortex repository. Cite the source IDs when used.\n{}\n</CORTEX_FOUNDING_SCIENCE>", |
| 243 | entries |
| 244 | )) |
| 245 | } |
| 246 | |
| 247 | #[cfg(test)] |
| 248 | mod tests { |
| 249 | use super::*; |
| 250 | |
| 251 | #[test] |
| 252 | fn parses_seed_notes() { |
| 253 | let source = r#" |
| 254 | note( |
| 255 | "ca1", |
| 256 | "CA1", |
| 257 | "Structures", |
| 258 | "structure", |
| 259 | "detail", |
| 260 | null, |
| 261 | ["hippocampus"], |
| 262 | `# CA1 |
| 263 | |
| 264 | Comparator circuit for prediction error. |
| 265 | `, |
| 266 | ), |
| 267 | "#; |
| 268 | let notes = parse_notes(source); |
| 269 | assert_eq!(notes.len(), 1); |
| 270 | assert_eq!(notes[0].id, "ca1"); |
| 271 | assert!(notes[0].content.contains("prediction error")); |
| 272 | } |
| 273 | |
| 274 | #[test] |
| 275 | fn query_terms_drop_common_words() { |
| 276 | assert_eq!( |
| 277 | query_terms("what is hippocampal prediction"), |
| 278 | ["hippocampal", "prediction"] |
| 279 | ); |
| 280 | } |
| 281 | } |