spark-rsi
Resilient systems interface and fault-tolerant agent communication
Brought by drakestapleton
| 1 | use crate::config::SovereignConfig; |
| 2 | use crate::models::{ImprovementProposal, InvariantReport, RatificationRecord}; |
| 3 | use reqwest::Client; |
| 4 | use serde_json::json; |
| 5 | use std::fs; |
| 6 | use std::path::Path; |
| 7 | use std::process::Command; |
| 8 | use uuid::Uuid; |
| 9 | |
| 10 | pub struct Ratifier; |
| 11 | |
| 12 | impl Ratifier { |
| 13 | pub async fn ratify_proposal( |
| 14 | proposal: &ImprovementProposal, |
| 15 | invariants: &InvariantReport, |
| 16 | target_repo: &Path, |
| 17 | cortex_url: &str, |
| 18 | cortex_space: &str, |
| 19 | ) -> Result<RatificationRecord, String> { |
| 20 | let now = chrono::Utc::now().to_rfc3339(); |
| 21 | let config = SovereignConfig::load(); |
| 22 | let author_str = config.author_string(); |
| 23 | |
| 24 | if !invariants.passed { |
| 25 | return Ok(RatificationRecord { |
| 26 | proposal_id: proposal.id.clone(), |
| 27 | commit_hash: None, |
| 28 | author: author_str, |
| 29 | cortex_receipt_id: None, |
| 30 | cortex_recorded: false, |
| 31 | timestamp: now, |
| 32 | status: "Rejected".to_string(), |
| 33 | message: format!("Invariant checks failed: {:?}", invariants.notes), |
| 34 | }); |
| 35 | } |
| 36 | |
| 37 | // 1. Apply patch to target file in repository |
| 38 | let target_file_path = target_repo.join(&proposal.target_file); |
| 39 | if let Some(parent) = target_file_path.parent() { |
| 40 | let _ = fs::create_dir_all(parent); |
| 41 | } |
| 42 | |
| 43 | fs::write(&target_file_path, &proposal.proposed_patch) |
| 44 | .map_err(|e| format!("Failed to apply patch to {:?}: {}", target_file_path, e))?; |
| 45 | |
| 46 | // 2. Commit to git using dynamic operator profile |
| 47 | let commit_msg = format!("rsi: {} ({})", proposal.title, proposal.id); |
| 48 | let _ = Command::new("git") |
| 49 | .arg("-C") |
| 50 | .arg(target_repo) |
| 51 | .args(["add", &proposal.target_file]) |
| 52 | .output(); |
| 53 | |
| 54 | let commit_out = Command::new("git") |
| 55 | .arg("-C") |
| 56 | .arg(target_repo) |
| 57 | .args([ |
| 58 | "-c", |
| 59 | &format!("user.name={}", config.operator.name), |
| 60 | "-c", |
| 61 | &format!("user.email={}", config.operator.email), |
| 62 | "commit", |
| 63 | "-m", |
| 64 | &commit_msg, |
| 65 | ]) |
| 66 | .output(); |
| 67 | |
| 68 | let commit_hash = match commit_out { |
| 69 | Ok(out) if out.status.success() => { |
| 70 | let rev = Command::new("git") |
| 71 | .arg("-C") |
| 72 | .arg(target_repo) |
| 73 | .args(["rev-parse", "--short", "HEAD"]) |
| 74 | .output() |
| 75 | .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string()) |
| 76 | .ok(); |
| 77 | rev |
| 78 | } |
| 79 | _ => None, |
| 80 | }; |
| 81 | |
| 82 | // 3. Record lesson in Cortex memory |
| 83 | let (cortex_receipt_id, cortex_recorded) = |
| 84 | Self::record_cortex_lesson(proposal, commit_hash.as_deref(), cortex_url, cortex_space).await; |
| 85 | |
| 86 | Ok(RatificationRecord { |
| 87 | proposal_id: proposal.id.clone(), |
| 88 | commit_hash, |
| 89 | author: author_str, |
| 90 | cortex_receipt_id, |
| 91 | cortex_recorded, |
| 92 | timestamp: now, |
| 93 | status: "Ratified".to_string(), |
| 94 | message: format!("Proposal '{}' ratified and committed to git.", proposal.title), |
| 95 | }) |
| 96 | } |
| 97 | |
| 98 | async fn record_cortex_lesson( |
| 99 | proposal: &ImprovementProposal, |
| 100 | commit_hash: Option<&str>, |
| 101 | cortex_url: &str, |
| 102 | cortex_space: &str, |
| 103 | ) -> (Option<String>, bool) { |
| 104 | let home = std::env::var("HOME").unwrap_or_else(|_| ".".to_string()); |
| 105 | let token_path = format!("{}/.config/cortex/token", home); |
| 106 | let token = std::env::var("CORTEX_TOKEN") |
| 107 | .unwrap_or_else(|_| fs::read_to_string(&token_path).unwrap_or_default()) |
| 108 | .trim() |
| 109 | .to_string(); |
| 110 | |
| 111 | let client = Client::new(); |
| 112 | let entity_id = format!("lesson-rsi-{}", Uuid::new_v4().simple()); |
| 113 | let canonical_name = format!("RSI Lesson: {}", proposal.title); |
| 114 | let commit_info = commit_hash.unwrap_or("uncommitted"); |
| 115 | let content = format!( |
| 116 | "Proposal ID: {}. Target File: {}. Kind: {:?}. Commit: {}. Description: {}", |
| 117 | proposal.id, proposal.target_file, proposal.kind, commit_info, proposal.description |
| 118 | ); |
| 119 | |
| 120 | let payload = json!({ |
| 121 | "canonicalName": canonical_name, |
| 122 | "entityType": "lesson", |
| 123 | "content": content, |
| 124 | "space": cortex_space, |
| 125 | "confidence": 1.0, |
| 126 | "metadata": { |
| 127 | "proposal_id": proposal.id, |
| 128 | "target_file": proposal.target_file, |
| 129 | "kind": format!("{:?}", proposal.kind), |
| 130 | "commit": commit_info |
| 131 | } |
| 132 | }); |
| 133 | |
| 134 | let url = format!("{}/entities", cortex_url.trim_end_matches('/')); |
| 135 | let mut req = client.post(&url).json(&payload); |
| 136 | if !token.is_empty() { |
| 137 | req = req.header("Authorization", format!("Bearer {}", token)); |
| 138 | } |
| 139 | |
| 140 | match req.send().await { |
| 141 | Ok(resp) if resp.status().is_success() => { |
| 142 | let body: serde_json::Value = resp.json().await.unwrap_or(json!({})); |
| 143 | let receipt_id = body.get("receipt") |
| 144 | .and_then(|r| r.get("id")) |
| 145 | .and_then(|id| id.as_str()) |
| 146 | .map(|s| s.to_string()) |
| 147 | .unwrap_or(entity_id); |
| 148 | (Some(receipt_id), true) |
| 149 | } |
| 150 | _ => (None, false), |
| 151 | } |
| 152 | } |
| 153 | } |