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 / propose / mod.rs

234 lines · 8260 bytes Raw Blame History
1pub mod cortex;
2pub mod diagnose;
3pub mod hypothesis;
4pub mod kernel_autotune;
5pub mod model_seat;
6
7pub use cortex::CortexExperienceClient;
8pub use diagnose::{DefectCategory, DiagnosticContext};
9pub use hypothesis::{HypothesisContract, ProtectedMetric};
10pub use kernel_autotune::{KernelAutotuneManager, PagedAttentionConfig};
11pub use model_seat::{ChatMessage, ModelSeatClient};
12
13use crate::models::{ImprovementProposal, ProposalKind};
14use std::fs;
15use std::path::{Path, PathBuf};
16use uuid::Uuid;
17
18pub struct ProposalGenerator;
19
20impl ProposalGenerator {
21 pub fn create_proposal(
22 title: &str,
23 description: &str,
24 target_file: &str,
25 proposed_patch: &str,
26 kind: ProposalKind,
27 ) -> ImprovementProposal {
28 let id = format!("prop-{}", Uuid::new_v4().simple());
29 ImprovementProposal {
30 id,
31 title: title.to_string(),
32 description: description.to_string(),
33 target_file: target_file.to_string(),
34 proposed_patch: proposed_patch.to_string(),
35 kind,
36 created_at: chrono::Utc::now().to_rfc3339(),
37 sandbox_path: None,
38 operator_signature: None,
39 }
40 }
41
42 /// Prepares an isolated sandbox worktree directory to evaluate the proposal safely.
43 pub fn stage_in_sandbox(
44 proposal: &mut ImprovementProposal,
45 repo_root: &Path,
46 sandbox_base: &Path,
47 ) -> Result<PathBuf, String> {
48 let sandbox_dir = sandbox_base.join(&proposal.id);
49 if sandbox_dir.exists() {
50 let _ = fs::remove_dir_all(&sandbox_dir);
51 }
52 fs::create_dir_all(&sandbox_dir)
53 .map_err(|e| format!("Failed to create sandbox dir: {}", e))?;
54
55 // Copy source files excluding target and .git
56 copy_dir_recursive(repo_root, &sandbox_dir, 0)?;
57
58 // Apply proposed patch to target file in sandbox
59 let target_in_sandbox = sandbox_dir.join(&proposal.target_file);
60 if let Some(parent) = target_in_sandbox.parent() {
61 let _ = fs::create_dir_all(parent);
62 }
63
64 fs::write(&target_in_sandbox, &proposal.proposed_patch)
65 .map_err(|e| format!("Failed to write proposed patch in sandbox: {}", e))?;
66
67 proposal.sandbox_path = Some(sandbox_dir.display().to_string());
68 Ok(sandbox_dir)
69 }
70
71 /// Automatically inspects a repository for unslop violations and proposes atomic sanitization.
72 pub fn scan_and_propose_unslop(repo_root: &Path) -> Option<ImprovementProposal> {
73 let candidate_files = ["README.md", "docs/PHILOSOPHY.md", "CONTRIBUTING.md"];
74 for rel in &candidate_files {
75 let full_path = repo_root.join(rel);
76 if full_path.exists() {
77 if let Ok(content) = fs::read_to_string(&full_path) {
78 if content.contains('\u{2014}') || content.contains('\u{2013}') {
79 let cleaned = content.replace('\u{2014}', ", ").replace('\u{2013}', "-");
80 return Some(Self::create_proposal(
81 &format!("sanitize unslop punctuation in {}", rel),
82 "Remove em dashes and en dashes in accordance with unslop standard",
83 rel,
84 &cleaned,
85 ProposalKind::UnslopSanitization,
86 ));
87 }
88 }
89 }
90 }
91 None
92 }
93
94 /// Extracts clean replacement file content from markdown code fences
95 pub fn extract_code_block(raw: &str) -> String {
96 let trimmed = raw.trim();
97 if let Some(start) = trimmed.find("```") {
98 let after_fence = &trimmed[start + 3..];
99 let code_start = if let Some(newline) = after_fence.find('\n') {
100 newline + 1
101 } else {
102 0
103 };
104 let rest = &after_fence[code_start..];
105 if let Some(end) = rest.rfind("```") {
106 return rest[..end].trim().to_string();
107 }
108 return rest.trim().to_string();
109 }
110 if trimmed.starts_with("Here")
111 || trimmed.starts_with("I ")
112 || trimmed.starts_with("Sure")
113 || trimmed.starts_with("Let")
114 || trimmed.contains("thinking process:")
115 {
116 return String::new();
117 }
118 trimmed.to_string()
119 }
120
121 /// Generates a proposal by prompting the local model seat with a diagnostic context
122 pub async fn propose_from_diagnosis(
123 model_seat: &ModelSeatClient,
124 diag: &DiagnosticContext,
125 ) -> Result<ImprovementProposal, String> {
126 let (sys, user) = diag.build_prompts();
127 let messages = vec![
128 ChatMessage {
129 role: "system".to_string(),
130 content: sys,
131 },
132 ChatMessage {
133 role: "user".to_string(),
134 content: user,
135 },
136 ];
137
138 let raw_completion = model_seat
139 .complete(&messages, 1536, 0.2)
140 .await
141 .map_err(|e| format!("Model seat diagnosis proposal generation failed: {}", e))?;
142
143 let cleaned_patch = Self::extract_code_block(&raw_completion);
144 if cleaned_patch.is_empty() {
145 return Err("Model seat generated an empty patch".to_string());
146 }
147
148 // Validate unslop invariant on generated patch
149 if cleaned_patch.contains('\u{2014}') || cleaned_patch.contains('\u{2013}') {
150 let sanitized = cleaned_patch
151 .replace('\u{2014}', ", ")
152 .replace('\u{2013}', "-");
153 return Ok(Self::create_proposal(
154 &format!("resolve {:?} in {}", diag.primary_defect, diag.target_file),
155 &format!(
156 "Automated model seat repair with unslop sanitization for cycle {}",
157 diag.cycle_id
158 ),
159 &diag.target_file,
160 &sanitized,
161 ProposalKind::InvariantFix,
162 ));
163 }
164
165 Ok(Self::create_proposal(
166 &format!("resolve {:?} in {}", diag.primary_defect, diag.target_file),
167 &format!("Automated model seat repair for cycle {}", diag.cycle_id),
168 &diag.target_file,
169 &cleaned_patch,
170 ProposalKind::InvariantFix,
171 ))
172 }
173}
174
175fn copy_dir_recursive(src: &Path, dst: &Path, depth: usize) -> Result<(), String> {
176 if depth > 8 {
177 return Ok(());
178 }
179 if !dst.exists() {
180 fs::create_dir_all(dst).map_err(|e| format!("Failed to create dir {:?}: {}", dst, e))?;
181 }
182 let entries = fs::read_dir(src).map_err(|e| format!("Failed to read dir {:?}: {}", src, e))?;
183 for entry in entries.flatten() {
184 let path = entry.path();
185 let file_name = entry.file_name();
186 let name = file_name.to_str().unwrap_or_default();
187
188 if name == "target" || name == ".git" || name.starts_with(".") {
189 continue;
190 }
191
192 let target_path = dst.join(&file_name);
193 if path.is_dir() {
194 copy_dir_recursive(&path, &target_path, depth + 1)?;
195 } else if path.is_file() {
196 let _ = fs::copy(&path, &target_path);
197 }
198 }
199 Ok(())
200}
201
202#[cfg(test)]
203mod tests {
204 use super::*;
205
206 #[test]
207 fn test_create_proposal() {
208 let prop = ProposalGenerator::create_proposal(
209 "add verified test",
210 "Improve verification test coverage",
211 "tests/verify.rs",
212 "// new test content",
213 ProposalKind::Refactor,
214 );
215 assert!(prop.id.starts_with("prop-"));
216 assert_eq!(prop.kind, ProposalKind::Refactor);
217 }
218
219 #[test]
220 fn test_extract_code_block() {
221 let raw = "```rust\npub fn hello() -> &'static str {\n \"world\"\n}\n```";
222 let extracted = ProposalGenerator::extract_code_block(raw);
223 assert_eq!(
224 extracted,
225 "pub fn hello() -> &'static str {\n \"world\"\n}"
226 );
227
228 let raw_plain = "pub fn simple() {}";
229 assert_eq!(
230 ProposalGenerator::extract_code_block(raw_plain),
231 "pub fn simple() {}"
232 );
233 }
234}