interplane.Get Omega
Read in your language

spark-rsi-mv

Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger

Brought by drakestapleton

branch main Branches Tags History

spark-rsi-mv / src / observe.rs

222 lines · 6164 bytes Raw Blame History
1use crate::isolation::sandboxed_cargo;
2use crate::models::{SoulTension, TelemetrySnapshot};
3use std::fs;
4use std::path::Path;
5use std::process::Command;
6
7pub const DRIVE_TERMS: &[&str] = &[
8 "curious",
9 "curiosity",
10 "build",
11 "fix",
12 "finish",
13 "ambitious",
14 "ambition",
15 "forge",
16 "explore",
17 "discover",
18 "improve",
19 "solve",
20 "create",
21 "learn",
22 "question",
23 "truth",
24 "measure",
25 "verify",
26 "optimize",
27 "accelerate",
28];
29
30pub const HUMANITY_TERMS: &[&str] = &[
31 "love",
32 "grief",
33 "honor",
34 "family",
35 "community",
36 "warmth",
37 "care",
38 "kindness",
39 "patience",
40 "humility",
41 "listen",
42 "commitment",
43 "promise",
44 "free",
45 "freedom",
46 "ethics",
47 "discipline",
48 "restraint",
49 "sovereignty",
50];
51
52pub fn scan_terms(text: &str, terms: &[&str]) -> Vec<String> {
53 let lower = text.to_lowercase();
54 terms
55 .iter()
56 .filter(|t| lower.contains(**t))
57 .map(|t| t.to_string())
58 .collect()
59}
60
61pub fn calculate_soul_tension(text: &str) -> SoulTension {
62 let drive_matched = scan_terms(text, DRIVE_TERMS);
63 let humanity_matched = scan_terms(text, HUMANITY_TERMS);
64
65 let drive_score = drive_matched.len() as f64;
66 let humanity_score = humanity_matched.len() as f64;
67
68 let tension_ratio = if humanity_score > 0.0 {
69 drive_score / humanity_score
70 } else if drive_score > 0.0 {
71 999.0
72 } else {
73 0.0
74 };
75
76 let state = if drive_score == 0.0 && humanity_score == 0.0 {
77 "Dormant".to_string()
78 } else if humanity_score == 0.0 || tension_ratio > 2.0 {
79 "DriveDominant".to_string()
80 } else if drive_score == 0.0 || tension_ratio < 0.5 {
81 "HumanityDominant".to_string()
82 } else {
83 "Balanced".to_string()
84 };
85
86 SoulTension {
87 drive_score,
88 humanity_score,
89 drive_terms_matched: drive_matched,
90 humanity_terms_matched: humanity_matched,
91 tension_ratio,
92 state,
93 }
94}
95
96pub fn count_crumbs_recursive(root: &Path) -> usize {
97 let mut count = 0;
98 if let Ok(entries) = fs::read_dir(root) {
99 for entry in entries.flatten() {
100 let path = entry.path();
101 if path.is_dir() {
102 let name = path
103 .file_name()
104 .and_then(|n| n.to_str())
105 .unwrap_or_default();
106 if !name.starts_with('.') && name != "target" {
107 count += count_crumbs_recursive(&path);
108 }
109 } else if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
110 if file_name == ".crumb" || file_name == ".crumb.local" {
111 count += 1;
112 }
113 }
114 }
115 }
116 count
117}
118
119pub fn observe_codebase(repo_dir: &Path) -> Result<TelemetrySnapshot, String> {
120 let git_branch = Command::new("git")
121 .arg("-C")
122 .arg(repo_dir)
123 .args(["rev-parse", "--abbrev-ref", "HEAD"])
124 .output()
125 .map(|out| String::from_utf8_lossy(&out.stdout).trim().to_string())
126 .unwrap_or_else(|_| "unknown".to_string());
127
128 let (git_clean, uncommitted_files) = match Command::new("git")
129 .arg("-C")
130 .arg(repo_dir)
131 .args(["status", "--porcelain"])
132 .output()
133 {
134 Ok(out) => {
135 let s = String::from_utf8_lossy(&out.stdout);
136 let files: Vec<String> = s
137 .lines()
138 .filter(|l| !l.trim().is_empty())
139 .map(|l| l.to_string())
140 .collect();
141 (files.is_empty(), files)
142 }
143 Err(_) => (false, vec!["failed to run git status".to_string()]),
144 };
145
146 let crumbs_detected = count_crumbs_recursive(repo_dir);
147
148 let home = std::env::var("HOME")
149 .or_else(|_| std::env::var("USERPROFILE"))
150 .unwrap_or_else(|_| ".".to_string());
151 // Read soul text from soul.md or docs/PHILOSOPHY.md or README.md
152 let soul_sources = [
153 repo_dir.join("soul.md"),
154 repo_dir.join("docs").join("PHILOSOPHY.md"),
155 repo_dir.join("README.md"),
156 std::path::PathBuf::from(home).join("atlas-prime-workspace/soul.md"),
157 ];
158
159 let mut corpus = String::new();
160 for src in &soul_sources {
161 if src.exists() {
162 if let Ok(content) = fs::read_to_string(src) {
163 corpus.push_str(&content);
164 corpus.push(' ');
165 }
166 }
167 }
168
169 let soul_tension = calculate_soul_tension(&corpus);
170
171 // Check test status without executing candidate build scripts on the host.
172 let tests_passing = fs::canonicalize(repo_dir)
173 .and_then(|source_dir| {
174 let build_dir = tempfile::tempdir()?;
175 sandboxed_cargo(
176 &source_dir,
177 build_dir.path(),
178 &["check", "--offline", "--locked", "-j2"],
179 )
180 .output()
181 })
182 .map(|out| out.status.success())
183 .unwrap_or(false);
184
185 Ok(TelemetrySnapshot {
186 repo_path: repo_dir.display().to_string(),
187 git_branch,
188 git_clean,
189 uncommitted_files,
190 crumbs_detected,
191 tests_passing,
192 soul_tension,
193 timestamp: chrono::Utc::now().to_rfc3339(),
194 })
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200
201 #[test]
202 fn test_soul_tension_calculation() {
203 let text = "We are curious and build tools to fix bugs, solve hard problems, and finish work with love, family, and honor.";
204 let tension = calculate_soul_tension(text);
205 assert!(tension.drive_score > 0.0);
206 assert!(tension.humanity_score > 0.0);
207 assert_eq!(tension.state, "Balanced");
208 }
209
210 #[test]
211 fn test_drive_dominant_detection() {
212 let text = "build fix finish optimize forge solve accelerate truth measure";
213 let tension = calculate_soul_tension(text);
214 assert_eq!(tension.state, "DriveDominant");
215 }
216
217 #[test]
218 fn test_scan_terms_empty() {
219 let matched = scan_terms("random content without keywords", DRIVE_TERMS);
220 assert!(matched.is_empty());
221 }
222}