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 / ratify.rs

194 lines · 7539 bytes Raw Blame History
1use crate::config::SovereignConfig;
2use crate::diff_gate;
3use crate::models::{ImprovementProposal, InvariantReport, RatificationRecord};
4use reqwest::Client;
5use serde_json::json;
6use std::fs;
7use std::path::Path;
8use uuid::Uuid;
9
10pub struct Ratifier;
11
12impl Ratifier {
13 /// Turns an admitted proposal into a review branch plus a PR-ready patch.
14 ///
15 /// The ratifier never commits to the target's default branch and never
16 /// touches its working tree or index. It builds the candidate commit with
17 /// a temporary index, runs every protected-file check on the REAL git diff
18 /// of that commit, and only if all checks pass creates `rsi/<proposal id>`
19 /// (create-only) and writes `<patch_dir>/<proposal id>.patch`. A human
20 /// opens and merges the pull request.
21 #[allow(clippy::too_many_arguments)]
22 pub async fn ratify_proposal(
23 proposal: &ImprovementProposal,
24 invariants: &InvariantReport,
25 target_repo: &Path,
26 ratify_roots: &[String],
27 patch_dir: &Path,
28 ledger_block_hash: Option<&str>,
29 cortex_url: &str,
30 cortex_space: &str,
31 ) -> Result<RatificationRecord, String> {
32 let now = chrono::Utc::now().to_rfc3339();
33 let config = SovereignConfig::load();
34 let author_str = config.author_string();
35
36 let rejected = |message: String| RatificationRecord {
37 proposal_id: proposal.id.clone(),
38 commit_hash: None,
39 branch: None,
40 patch_path: None,
41 author: author_str.clone(),
42 cortex_receipt_id: None,
43 cortex_recorded: false,
44 timestamp: now.clone(),
45 status: "Rejected".to_string(),
46 message,
47 };
48
49 if !invariants.passed {
50 return Ok(rejected(format!(
51 "Invariant checks failed: {:?}",
52 invariants.notes
53 )));
54 }
55
56 // 1. Declared target: normalized, inside the declared roots, not protected.
57 let target = match diff_gate::check_declared_target(&proposal.target_file, ratify_roots) {
58 Ok(t) => t,
59 Err(e) => return Ok(rejected(format!("Declared target refused: {}", e))),
60 };
61 let branch = match diff_gate::review_branch_name(&proposal.id) {
62 Ok(b) => b,
63 Err(e) => return Ok(rejected(e)),
64 };
65
66 // 2. Build the candidate commit off to the side. No branch moves.
67 let commit_msg = format!("rsi: {} ({})", proposal.title, proposal.id);
68 let staged = match diff_gate::stage_candidate_commit(
69 target_repo,
70 &target,
71 proposal.proposed_patch.as_bytes(),
72 &config.operator.name,
73 &config.operator.email,
74 &commit_msg,
75 ) {
76 Ok(s) => s,
77 Err(e) => return Ok(rejected(format!("Candidate commit refused: {}", e))),
78 };
79
80 // 3. Protected-file checks on the REAL diff, not the declared name.
81 let violations =
82 diff_gate::check_real_diff(&staged.entries, &staged.patch_text, &target, ratify_roots);
83 if !violations.is_empty() {
84 return Ok(rejected(format!(
85 "Real diff refused: {}",
86 violations.join("; ")
87 )));
88 }
89
90 // 4. Review branch (create-only, never a default branch) and patch file.
91 if let Err(e) = diff_gate::create_review_branch(target_repo, &branch, &staged.commit) {
92 return Ok(rejected(format!("Review branch refused: {}", e)));
93 }
94 let patch = diff_gate::format_patch(target_repo, &staged.commit)?;
95 fs::create_dir_all(patch_dir)
96 .map_err(|e| format!("Failed to create patch dir {:?}: {}", patch_dir, e))?;
97 let patch_path = patch_dir.join(format!("{}.patch", proposal.id));
98 fs::write(&patch_path, format!("{}\n", patch))
99 .map_err(|e| format!("Failed to write patch {:?}: {}", patch_path, e))?;
100
101 // 5. Record lesson in Cortex memory, tied to the review commit.
102 let (cortex_receipt_id, cortex_recorded) = Self::record_cortex_lesson(
103 proposal,
104 Some(&staged.commit),
105 ledger_block_hash,
106 cortex_url,
107 cortex_space,
108 )
109 .await;
110
111 Ok(RatificationRecord {
112 proposal_id: proposal.id.clone(),
113 commit_hash: Some(staged.commit.clone()),
114 branch: Some(branch.clone()),
115 patch_path: Some(patch_path.display().to_string()),
116 author: author_str.clone(),
117 cortex_receipt_id,
118 cortex_recorded,
119 timestamp: now.clone(),
120 status: "ProposedForReview".to_string(),
121 message: format!(
122 "Proposal '{}' is on review branch {} with patch {}. The default branch is unchanged; a human merges it.",
123 proposal.title,
124 branch,
125 patch_path.display()
126 ),
127 })
128 }
129
130 pub async fn record_cortex_lesson(
131 proposal: &ImprovementProposal,
132 commit_hash: Option<&str>,
133 ledger_block_hash: Option<&str>,
134 cortex_url: &str,
135 cortex_space: &str,
136 ) -> (Option<String>, bool) {
137 let home = std::env::var("HOME").unwrap_or_default();
138 let token_path = format!("{}/.config/cortex/token", home);
139 let token = std::env::var("CORTEX_TOKEN")
140 .unwrap_or_else(|_| fs::read_to_string(&token_path).unwrap_or_default())
141 .trim()
142 .to_string();
143
144 let client = Client::new();
145 let entity_id = format!("lesson-rsi-{}", Uuid::new_v4().simple());
146 let canonical_name = format!("RSI Lesson: {}", proposal.title);
147 let commit_info = commit_hash.unwrap_or("uncommitted");
148 let ledger_info = ledger_block_hash.unwrap_or("unrecorded");
149 let content = format!(
150 "Proposal ID: {}. Target File: {}. Kind: {:?}. Commit: {}. Ledger Hash: {}. Description: {}",
151 proposal.id, proposal.target_file, proposal.kind, commit_info, ledger_info, proposal.description
152 );
153
154 let payload = json!({
155 "kind": "entity",
156 "value": {
157 "canonicalName": canonical_name,
158 "content": content,
159 "confidence": 1.0,
160 "metadata": {
161 "proposal_id": proposal.id,
162 "target_file": proposal.target_file,
163 "kind": format!("{:?}", proposal.kind),
164 "commit": commit_info,
165 "ledger_block_hash": ledger_info
166 }
167 }
168 });
169
170 let url = format!(
171 "{}/api/cortex/write?space={}",
172 cortex_url.trim_end_matches('/'),
173 cortex_space
174 );
175 let mut req = client.post(&url).json(&payload);
176 if !token.is_empty() {
177 req = req.header("Authorization", format!("Bearer {}", token));
178 }
179
180 match req.send().await {
181 Ok(resp) if resp.status().is_success() => {
182 let body: serde_json::Value = resp.json().await.unwrap_or(json!({}));
183 let receipt_id = body
184 .get("receipt")
185 .and_then(|r| r.get("id"))
186 .and_then(|id| id.as_str())
187 .map(|s| s.to_string())
188 .unwrap_or(entity_id);
189 (Some(receipt_id), true)
190 }
191 _ => (None, false),
192 }
193 }
194}