spark-rsi-mv
Native Rust recursive self-improvement engine with paired bootstrap evaluation and cryptographic ledger
Brought by drakestapleton
GitHub aien-dev/spark-rsi-mv#14 (code only)
Apply it
git checkout -b patch-ec434b604f46d4c6 b53bb4f457a660b5547895eb177282d7f7832bb4 curl -fsSL https://interplane.io/drakestapleton/spark-rsi-mv/patches/ec434b604f46d4c6.patch | git am
Provenance
github-import 1
aien-dev/spark-rsi-mv
14
68713b887cf64fb1cd0fc9c3b0aa99afba4010a9
{"kind":"github-import","owner":"aien-dev","repo":"spark-rsi-mv","number":14,"url":"https://github.com/aien-dev/spark-rsi-mv/pull/14","export_sha256":"967c79e26a893657b5cdaa45efd442be5dbd2ecfe68e25f9a8c1b5da4d60d452","imported_utc":"2026-11-18T16:40:17Z","metadata":"unavailable","state_derived":true}
Changes
diff --git a/src/daemon.rs b/src/daemon.rs index 9344597..8e49ca2 100644 --- a/src/daemon.rs +++ b/src/daemon.rs @@ -4,7 +4,7 @@ use crate::evaluator::EvaluationReceipt; use crate::ledger::{ImprovementLedger, LedgerBlock}; use crate::models::{RsiConfig, RsiCycleResult}; use crate::observe::observe_codebase; -use crate::propose::ProposalGenerator; +use crate::propose::{CortexExperienceClient, DefectCategory, DiagnosticContext, MaxClient, ProposalGenerator}; use crate::ratify::Ratifier; use crate::supervisor::{GenerationInfo, HostSupervisor}; use crate::verifier::InvariantVerifier; @@ -32,6 +32,72 @@ impl RsiEngine { // 2. Propose improvement let mut maybe_proposal = ProposalGenerator::scan_and_propose_unslop(repo_path); + // If no heuristic unslop proposal, attempt autonomous diagnosis and repair via MAX + if maybe_proposal.is_none() { + let max_client = MaxClient::new(&config.max_url, &config.max_model); + if max_client.is_available().await { + // Check for prior failed receipts in eval_outputs + let eval_dir = rsi_root.join("eval_outputs"); + let mut prior_failure = None; + if eval_dir.exists() { + if let Ok(entries) = std::fs::read_dir(&eval_dir) { + for entry in entries.flatten() { + let p = entry.path(); + if p.is_file() && p.extension().and_then(|s| s.to_str()) == Some("json") { + if let Ok(receipt) = EvaluationReceipt::load_from_file(&p) { + if !receipt.admitted { + prior_failure = Some(receipt); + break; + } + } + } + } + } + } + + if let Some(ref receipt) = prior_failure { + let cortex = CortexExperienceClient::new(&config.cortex_url) + .with_space(&config.cortex_space); + let lessons = cortex.recall_lessons("holdout assertion defect", 3).await; + let target_file = "src/lib.rs"; + let full_path = repo_path.join(target_file); + let content = std::fs::read_to_string(&full_path).unwrap_or_default(); + + let diag = DiagnosticContext::from_receipt( + &cycle_id, + receipt, + target_file, + &content, + lessons, + ); + + if let Ok(prop) = ProposalGenerator::propose_from_diagnosis(&max_client, &diag).await { + maybe_proposal = Some(prop); + } + } else if telemetry.soul_tension.drive_score > 0.8 { + let cortex = CortexExperienceClient::new(&config.cortex_url) + .with_space(&config.cortex_space); + let lessons = cortex.recall_lessons("soul tension drive balance", 2).await; + let target_file = "README.md"; + let full_path = repo_path.join(target_file); + let content = std::fs::read_to_string(&full_path).unwrap_or_default(); + + let diag = DiagnosticContext::from_violations( + &cycle_id, + target_file, + &content, + DefectCategory::SoulTensionDominance, + vec![format!("Drive dominance detected: score={:.2} > 0.80", telemetry.soul_tension.drive_score)], + lessons, + ); + + if let Ok(prop) = ProposalGenerator::propose_from_diagnosis(&max_client, &diag).await { + maybe_proposal = Some(prop); + } + } + } + } + let mut maybe_invariants = None; let maybe_balance; let mut maybe_receipt: Option<EvaluationReceipt> = None; diff --git a/src/main.rs b/src/main.rs index 5272bc1..eaba585 100644 --- a/src/main.rs +++ b/src/main.rs @@ -149,6 +149,10 @@ enum Commands { kernel: String, #[arg(long, default_value = "http://127.0.0.1:18080")] cortex_url: String, + #[arg(long, default_value = "http://127.0.0.1:18006/v1")] + max_url: String, + #[arg(long, default_value = "atlas-lightning-omni")] + max_model: String, }, /// Run the continuous recursive self-improvement daemon loop Daemon { @@ -160,6 +164,10 @@ enum Commands { kernel: String, #[arg(long, default_value = "http://127.0.0.1:18080")] cortex_url: String, + #[arg(long, default_value = "http://127.0.0.1:18006/v1")] + max_url: String, + #[arg(long, default_value = "atlas-lightning-omni")] + max_model: String, }, /// Manage the append-only cryptographic improvement ledger Ledger { @@ -268,7 +276,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> { let res = spark_rsi::evaluate_holdout_case(&input); println!("{}", res); } - Commands::Cycle { path, kernel, cortex_url } => { + Commands::Cycle { path, kernel, cortex_url, max_url, max_model } => { let config = RsiConfig { target_repo: path, cortex_url, @@ -280,11 +288,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> { holdouts_dir: None, signing_key_hex: None, require_latency_improvement: false, + max_url, + max_model, }; let result = RsiEngine::run_cycle(&config).await?; println!("{}", serde_json::to_string_pretty(&result)?); } - Commands::Daemon { path, interval, kernel, cortex_url } => { + Commands::Daemon { path, interval, kernel, cortex_url, max_url, max_model } => { let config = RsiConfig { target_repo: path, cortex_url, @@ -296,6 +306,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> { holdouts_dir: None, signing_key_hex: None, require_latency_improvement: false, + max_url, + max_model, }; RsiEngine::run_daemon(config).await?; } diff --git a/src/models.rs b/src/models.rs index 6174b9c..ed3664a 100644 --- a/src/models.rs +++ b/src/models.rs @@ -101,6 +101,18 @@ pub struct RsiConfig { pub signing_key_hex: Option<String>, #[serde(default)] pub require_latency_improvement: bool, + #[serde(default = "default_max_url")] + pub max_url: String, + #[serde(default = "default_max_model")] + pub max_model: String, +} + +fn default_max_url() -> String { + "http://127.0.0.1:18006/v1".to_string() +} + +fn default_max_model() -> String { + "atlas-lightning-omni".to_string() } fn default_rsi_root() -> String { @@ -120,6 +132,8 @@ impl Default for RsiConfig { holdouts_dir: None, signing_key_hex: None, require_latency_improvement: false, + max_url: default_max_url(), + max_model: default_max_model(), } } } diff --git a/src/propose/cortex.rs b/src/propose/cortex.rs new file mode 100644 index 0000000..973f999 --- /dev/null +++ b/src/propose/cortex.rs @@ -0,0 +1,111 @@ +use serde::{Deserialize, Serialize}; +use std::fs; +use std::path::PathBuf; +use std::time::Duration; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CortexSearchResult { + pub id: String, + #[serde(default, rename = "canonicalName")] + pub canonical_name: Option<String>, + pub content: String, + #[serde(default)] + pub score: Option<f64>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +struct CortexSearchEnvelope { + #[serde(default)] + pub results: Vec<CortexSearchResult>, +} + +#[derive(Debug, Clone)] +pub struct CortexExperienceClient { + pub base_url: String, + pub space: String, + pub token: Option<String>, + client: reqwest::Client, +} + +impl CortexExperienceClient { + pub fn new(base_url: &str) -> Self { + let token = Self::resolve_token(); + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(10)) + .build() + .unwrap_or_default(); + + Self { + base_url: base_url.trim_end_matches('/').to_string(), + space: "atlas-memory".to_string(), + token, + client, + } + } + + pub fn with_space(mut self, space: &str) -> Self { + self.space = space.to_string(); + self + } + + pub fn with_token(mut self, token: &str) -> Self { + self.token = Some(token.to_string()); + self + } + + fn resolve_token() -> Option<String> { + if let Ok(tok) = std::env::var("CORTEX_TOKEN") { + let t = tok.trim().to_string(); + if !t.is_empty() { + return Some(t); + } + } + + let home = std::env::var("HOME").unwrap_or_else(|_| "/home/drakestapleton".to_string()); + let token_path = PathBuf::from(home).join(".config/cortex/token"); + if token_path.exists() { + if let Ok(content) = fs::read_to_string(&token_path) { + let t = content.trim().to_string(); + if !t.is_empty() { + return Some(t); + } + } + } + None + } + + pub async fn recall_lessons(&self, query: &str, limit: usize) -> Vec<String> { + let url = format!("{}/api/cortex/search", self.base_url); + let limit_str = limit.to_string(); + let mut req = self.client.get(&url).query(&[ + ("q", query), + ("space", &self.space), + ("limit", &limit_str), + ]); + + if let Some(ref tok) = self.token { + req = req.bearer_auth(tok); + } + + match req.send().await { + Ok(resp) if resp.status().is_success() => { + if let Ok(envelope) = resp.json::<CortexSearchEnvelope>().await { + envelope + .results + .into_iter() + .map(|r| { + if let Some(ref name) = r.canonical_name { + format!("[{}] {}", name, r.content) + } else { + r.content + } + }) + .collect() + } else { + Vec::new() + } + } + _ => Vec::new(), + } + } +} diff --git a/src/propose/diagnose.rs b/src/propose/diagnose.rs new file mode 100644 index 0000000..1e5b01a --- /dev/null +++ b/src/propose/diagnose.rs @@ -0,0 +1,149 @@ +use crate::evaluator::EvaluationReceipt; +use serde::{Deserialize, Serialize}; + +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +pub enum DefectCategory { + CompilationFailure, + HoldoutFailure, + InvariantViolation, + PerformanceRegression, + ResourceViolation, + StyleViolation, + SoulTensionDominance, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct DiagnosticContext { + pub cycle_id: String, + pub target_file: String, + pub current_content: String, + pub primary_defect: DefectCategory, + pub violations: Vec<String>, + pub past_lessons: Vec<String>, +} + +impl DiagnosticContext { + pub fn from_receipt( + cycle_id: &str, + receipt: &EvaluationReceipt, + target_file: &str, + current_content: &str, + past_lessons: Vec<String>, + ) -> Self { + let mut violations = Vec::new(); + let mut primary_defect = DefectCategory::HoldoutFailure; + + for layer in &receipt.layer_results { + if !layer.passed { + match layer.layer_name.as_str() { + "Correctness" => { + primary_defect = DefectCategory::CompilationFailure; + } + "Security" => { + primary_defect = DefectCategory::InvariantViolation; + } + "Style" => { + primary_defect = DefectCategory::StyleViolation; + } + "Performance" => { + primary_defect = DefectCategory::PerformanceRegression; + } + "ResourceEfficiency" => { + primary_defect = DefectCategory::ResourceViolation; + } + "LongitudinalReplay" => { + primary_defect = DefectCategory::HoldoutFailure; + } + _ => {} + } + for v in &layer.violations { + violations.push(format!("[{}] {}", layer.layer_name, v)); + } + } + } + + if violations.is_empty() && !receipt.admitted { + violations.push("Evaluator rejected candidate without explicit layer violations.".to_string()); + } + + Self { + cycle_id: cycle_id.to_string(), + target_file: target_file.to_string(), + current_content: current_content.to_string(), + primary_defect, + violations, + past_lessons, + } + } + + pub fn from_violations( + cycle_id: &str, + target_file: &str, + current_content: &str, + primary_defect: DefectCategory, + violations: Vec<String>, + past_lessons: Vec<String>, + ) -> Self { + Self { + cycle_id: cycle_id.to_string(), + target_file: target_file.to_string(), + current_content: current_content.to_string(), + primary_defect, + violations, + past_lessons, + } + } + + pub fn build_prompts(&self) -> (String, String) { + let system_prompt = "You are the autonomous recursive code synthesizer for spark-rsi on NVIDIA DGX Spark. +Your role: generate a clean, compiling, verified replacement for the target file that resolves diagnosed defects. + +CRITICAL INVARIANTS: +1. Output MUST contain ONLY the complete replacement file inside a single fenced code block (e.g. ```rust ... ```). +2. Do NOT provide conversational filler, pleasantries, explanations, or text outside the code block. +3. Anti-Slop Standard: ZERO em dashes (\u{2014}), ZERO en dashes (\u{2013}), ZERO marketing adjectives or decorative adjectives. +4. Preserve existing public APIs and invariants.".to_string(); + + let mut user_prompt = format!( + "TARGET FILE: {} +PRIMARY DEFECT: {:?} + +DIAGNOSTIC VIOLATIONS DETECTED BY EVALUATOR: +", + self.target_file, self.primary_defect + ); + + if self.violations.is_empty() { + user_prompt.push_str("- No explicit violations recorded; optimize code for robustness and efficiency. +"); + } else { + for v in &self.violations { + user_prompt.push_str(&format!("- {} +", v)); + } + } + + if !self.past_lessons.is_empty() { + user_prompt.push_str(" +CANONICAL LESSONS FROM SPARK CORTEX (ATLAS-MEMORY): +"); + for lesson in &self.past_lessons { + user_prompt.push_str(&format!("* {} +", lesson)); + } + } + + user_prompt.push_str(&format!( + " +CURRENT FILE CONTENT: +``` +{} +``` + +Generate the updated file resolving the above defects:", + self.current_content + )); + + (system_prompt, user_prompt) + } +} diff --git a/src/propose/max_client.rs b/src/propose/max_client.rs new file mode 100644 index 0000000..e4b7ae2 --- /dev/null +++ b/src/propose/max_client.rs @@ -0,0 +1,125 @@ +use serde::{Deserialize, Serialize}; +use std::time::Duration; + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ChatMessage { + pub role: String, + pub content: String, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ChatCompletionRequest { + pub model: String, + pub messages: Vec<ChatMessage>, + #[serde(skip_serializing_if = "Option::is_none")] + pub max_tokens: Option<usize>, + #[serde(skip_serializing_if = "Option::is_none")] + pub temperature: Option<f32>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ChatMessageResponse { + pub role: String, + #[serde(default)] + pub content: Option<String>, + #[serde(default)] + pub reasoning: Option<String>, + #[serde(default)] + pub reasoning_content: Option<String>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ChatChoice { + pub index: usize, + pub message: ChatMessageResponse, + #[serde(default)] + pub finish_reason: Option<String>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct ChatCompletionResponse { + pub id: String, + pub choices: Vec<ChatChoice>, +} + +#[derive(Debug, Clone)] +pub struct MaxClient { + pub base_url: String, + pub model_id: String, + client: reqwest::Client, +} + +impl MaxClient { + pub fn new(base_url: &str, model_id: &str) -> Self { + let client = reqwest::Client::builder() + .timeout(Duration::from_secs(120)) + .build() + .unwrap_or_default(); + + Self { + base_url: base_url.trim_end_matches('/').to_string(), + model_id: model_id.to_string(), + client, + } + } + + pub async fn is_available(&self) -> bool { + let url = format!("{}/models", self.base_url); + match self.client.get(&url).send().await { + Ok(resp) => resp.status().is_success(), + Err(_) => false, + } + } + + pub async fn complete( + &self, + messages: &[ChatMessage], + max_tokens: usize, + temperature: f32, + ) -> Result<String, String> { + let url = format!("{}/chat/completions", self.base_url); + let req = ChatCompletionRequest { + model: self.model_id.clone(), + messages: messages.to_vec(), + max_tokens: Some(max_tokens), + temperature: Some(temperature), + }; + + let resp = self + .client + .post(&url) + .json(&req) + .send() + .await + .map_err(|e| format!("MAX completion request failed: {}", e))?; + + if !resp.status().is_success() { + let status = resp.status(); + let body = resp.text().await.unwrap_or_default(); + return Err(format!("MAX endpoint returned HTTP {}: {}", status, body)); + } + + let body: ChatCompletionResponse = resp + .json() + .await + .map_err(|e| format!("Failed to parse MAX response: {}", e))?; + + let choice = body + .choices + .first() + .ok_or_else(|| "MAX response returned empty choices array".to_string())?; + + let content = choice + .message + .content + .as_deref() + .unwrap_or_default() + .trim(); + + if content.is_empty() { + return Err("MAX assistant message content is empty".to_string()); + } + + Ok(content.to_string()) + } +} diff --git a/src/propose.rs b/src/propose/mod.rs similarity index 58% rename from src/propose.rs rename to src/propose/mod.rs index f17636a..f425ad7 100644 --- a/src/propose.rs +++ b/src/propose/mod.rs @@ -1,3 +1,11 @@ +pub mod cortex; +pub mod diagnose; +pub mod max_client; + +pub use cortex::CortexExperienceClient; +pub use diagnose::{DefectCategory, DiagnosticContext}; +pub use max_client::{ChatMessage, MaxClient}; + use crate::models::{ImprovementProposal, ProposalKind}; use std::fs; use std::path::{Path, PathBuf}; @@ -79,6 +87,73 @@ impl ProposalGenerator { } None } + + /// Extracts clean replacement file content from markdown code fences + pub fn extract_code_block(raw: &str) -> String { + let trimmed = raw.trim(); + if let Some(start) = trimmed.find("```") { + let after_fence = &trimmed[start + 3..]; + let code_start = if let Some(newline) = after_fence.find('\n') { + newline + 1 + } else { + 0 + }; + let rest = &after_fence[code_start..]; + if let Some(end) = rest.rfind("```") { + return rest[..end].trim().to_string(); + } + return rest.trim().to_string(); + } + trimmed.to_string() + } + + /// Generates a proposal by prompting MAX with a diagnostic context + pub async fn propose_from_diagnosis( + max_client: &MaxClient, + diag: &DiagnosticContext, + ) -> Result<ImprovementProposal, String> { + let (sys, user) = diag.build_prompts(); + let messages = vec![ + ChatMessage { + role: "system".to_string(), + content: sys, + }, + ChatMessage { + role: "user".to_string(), + content: user, + }, + ]; + + let raw_completion = max_client + .complete(&messages, 4096, 0.2) + .await + .map_err(|e| format!("MAX diagnosis proposal generation failed: {}", e))?; + + let cleaned_patch = Self::extract_code_block(&raw_completion); + if cleaned_patch.is_empty() { + return Err("MAX generated an empty patch".to_string()); + } + + // Validate unslop invariant on generated patch + if cleaned_patch.contains('\u{2014}') || cleaned_patch.contains('\u{2013}') { + let sanitized = cleaned_patch.replace('\u{2014}', ", ").replace('\u{2013}', "-"); + return Ok(Self::create_proposal( + &format!("resolve {:?} in {}", diag.primary_defect, diag.target_file), + &format!("Automated MAX repair with unslop sanitization for cycle {}", diag.cycle_id), + &diag.target_file, + &sanitized, + ProposalKind::InvariantFix, + )); + } + + Ok(Self::create_proposal( + &format!("resolve {:?} in {}", diag.primary_defect, diag.target_file), + &format!("Automated MAX repair for cycle {}", diag.cycle_id), + &diag.target_file, + &cleaned_patch, + ProposalKind::InvariantFix, + )) + } } fn copy_dir_recursive(src: &Path, dst: &Path, depth: usize) -> Result<(), String> { @@ -124,4 +199,14 @@ mod tests { assert!(prop.id.starts_with("prop-")); assert_eq!(prop.kind, ProposalKind::Refactor); } + + #[test] + fn test_extract_code_block() { + let raw = "```rust\npub fn hello() -> &'static str {\n \"world\"\n}\n```"; + let extracted = ProposalGenerator::extract_code_block(raw); + assert_eq!(extracted, "pub fn hello() -> &'static str {\n \"world\"\n}"); + + let raw_plain = "pub fn simple() {}"; + assert_eq!(ProposalGenerator::extract_code_block(raw_plain), "pub fn simple() {}"); + } } diff --git a/tests/integration_tests.rs b/tests/integration_tests.rs index 7191a41..f010052 100644 --- a/tests/integration_tests.rs +++ b/tests/integration_tests.rs @@ -120,6 +120,7 @@ async fn test_rsi_cycle_execution() { holdouts_dir: None, signing_key_hex: None, require_latency_improvement: false, + ..Default::default() }; let result = spark_rsi::daemon::RsiEngine::run_cycle(&config) diff --git a/tests/test_cryptographic_improvement_ledger.rs b/tests/test_cryptographic_improvement_ledger.rs index 5bf06a8..9f03e8f 100644 --- a/tests/test_cryptographic_improvement_ledger.rs +++ b/tests/test_cryptographic_improvement_ledger.rs @@ -277,6 +277,7 @@ async fn test_daemon_run_cycle_records_provenance_to_ledger() { holdouts_dir: None, signing_key_hex: None, require_latency_improvement: false, + ..Default::default() }; let result = RsiEngine::run_cycle(&config).await.expect("run_cycle failed"); diff --git a/tests/test_max_inference_and_diagnosis.rs b/tests/test_max_inference_and_diagnosis.rs new file mode 100644 index 0000000..2dfef08 --- /dev/null +++ b/tests/test_max_inference_and_diagnosis.rs @@ -0,0 +1,136 @@ +use spark_rsi::evaluator::layers::LayerResult; +use spark_rsi::evaluator::EvaluationReceipt; +use spark_rsi::models::ProposalKind; +use spark_rsi::propose::cortex::CortexExperienceClient; +use spark_rsi::propose::diagnose::{DefectCategory, DiagnosticContext}; +use spark_rsi::propose::max_client::{ChatMessage, MaxClient}; +use spark_rsi::propose::ProposalGenerator; + +#[tokio::test] +async fn test_max_client_availability_and_completion() { + let client = MaxClient::new("http://127.0.0.1:18006/v1", "atlas-lightning-omni"); + let is_avail = client.is_available().await; + assert!(is_avail, "MAX inference service must be reachable on port 18006"); + + let messages = vec![ + ChatMessage { + role: "system".to_string(), + content: "You are a code synthesis test engine. Respond with: PONG".to_string(), + }, + ChatMessage { + role: "user".to_string(), + content: "ping".to_string(), + }, + ]; + + let resp = client.complete(&messages, 256, 0.0).await.expect("MAX completion failed"); + assert!(resp.contains("PONG"), "Expected PONG in completion, got: {}", resp); +} + +#[test] +fn test_code_block_extraction() { + let raw = "Here is the repaired file:\n```rust\npub fn fixed_logic() -> bool {\n true\n}\n```\nAll done."; + let extracted = ProposalGenerator::extract_code_block(raw); + assert_eq!(extracted, "pub fn fixed_logic() -> bool {\n true\n}"); + + let plain = "pub fn simple() -> bool { false }"; + assert_eq!(ProposalGenerator::extract_code_block(plain), plain); +} + +#[test] +fn test_diagnostic_context_from_failing_receipt() { + let receipt = EvaluationReceipt { + cycle_id: "cycle-test-diag".to_string(), + candidate_id: "cand-test-diag".to_string(), + parent_id: "parent-test".to_string(), + evaluated_at: chrono::Utc::now().to_rfc3339(), + evaluator_version: "0.1.0".to_string(), + passed_all_hard_invariants: false, + passed_statistical_gates: false, + admitted: false, + layer_results: vec![ + LayerResult { + layer_name: "Correctness".to_string(), + is_hard_invariant: true, + passed: false, + score: 0.0, + summary: "Compilation failed".to_string(), + violations: vec!["E0308: mismatched types".to_string()], + }, + LayerResult { + layer_name: "Style".to_string(), + is_hard_invariant: true, + passed: false, + score: 0.0, + summary: "Style violation".to_string(), + violations: vec!["Em dash detected at line 14".to_string()], + }, + ], + metrics_summary: None, + receipt_digest: "abcd1234".to_string(), + signature: None, + }; + + let target_file = "src/example.rs"; + let content = "pub fn example() {}"; + let lessons = vec!["Avoid em dashes in comments".to_string()]; + + let diag = DiagnosticContext::from_receipt( + "cycle-test-diag", + &receipt, + target_file, + content, + lessons, + ); + + assert_eq!(diag.target_file, "src/example.rs"); + assert_eq!(diag.primary_defect, DefectCategory::StyleViolation); + assert_eq!(diag.violations.len(), 2); + assert_eq!(diag.past_lessons.len(), 1); + + let (sys, user) = diag.build_prompts(); + assert!(sys.contains("CRITICAL INVARIANTS")); + assert!(sys.contains("Anti-Slop")); + assert!(user.contains("TARGET FILE: src/example.rs")); + assert!(user.contains("E0308: mismatched types")); + assert!(user.contains("Em dash detected at line 14")); + assert!(user.contains("Avoid em dashes in comments")); +} + +#[tokio::test] +async fn test_cortex_experience_client_query() { + let cortex = CortexExperienceClient::new("http://127.0.0.1:18080"); + let lessons = cortex.recall_lessons("spark-rsi", 3).await; + for l in &lessons { + assert!(!l.is_empty()); + } +} + +#[tokio::test] +async fn test_propose_from_diagnosis_live_max() { + let max = MaxClient::new("http://127.0.0.1:18006/v1", "atlas-lightning-omni"); + if !max.is_available().await { + eprintln!("Skipping live MAX test: service not running"); + return; + } + + let diag = DiagnosticContext::from_violations( + "cycle-diag-live", + "src/calc.rs", + "pub fn add(a: i32, b: i32) -> i32 {\n a - b\n}", + DefectCategory::HoldoutFailure, + vec!["Holdout 'ADD-001' failed: expected 5, got -1".to_string()], + vec!["Verify operator signs in arithmetic functions".to_string()], + ); + + let proposal = ProposalGenerator::propose_from_diagnosis(&max, &diag) + .await + .expect("Failed to generate proposal from diagnosis"); + + assert_eq!(proposal.target_file, "src/calc.rs"); + assert_eq!(proposal.kind, ProposalKind::InvariantFix); + assert!(!proposal.proposed_patch.is_empty()); + // Ensure no forbidden unicode dashes + assert!(!proposal.proposed_patch.contains('\u{2014}')); + assert!(!proposal.proposed_patch.contains('\u{2013}')); +} diff --git a/tests/test_no_synthetic_trust_inputs.rs b/tests/test_no_synthetic_trust_inputs.rs index 3b7d50b..9466183 100644 --- a/tests/test_no_synthetic_trust_inputs.rs +++ b/tests/test_no_synthetic_trust_inputs.rs @@ -232,6 +232,7 @@ async fn test_daemon_run_cycle_promotes_via_host_supervisor() { holdouts_dir: None, signing_key_hex: None, require_latency_improvement: false, + ..Default::default() }; let result = RsiEngine::run_cycle(&config).await.expect("run_cycle failed");