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

336 lines · 12706 bytes Raw Blame History
1use serde::{Deserialize, Serialize};
2
3#[derive(Debug, Clone, Serialize, Deserialize)]
4pub struct TelemetrySnapshot {
5 pub repo_path: String,
6 pub git_branch: String,
7 pub git_clean: bool,
8 pub uncommitted_files: Vec<String>,
9 pub crumbs_detected: usize,
10 pub tests_passing: bool,
11 pub soul_tension: SoulTension,
12 pub timestamp: String,
13}
14
15#[derive(Debug, Clone, Serialize, Deserialize)]
16pub struct SoulTension {
17 pub drive_score: f64,
18 pub humanity_score: f64,
19 pub drive_terms_matched: Vec<String>,
20 pub humanity_terms_matched: Vec<String>,
21 pub tension_ratio: f64,
22 pub state: String,
23}
24
25#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
26#[serde(rename_all = "snake_case")]
27pub enum ProposalKind {
28 Refactor,
29 Documentation,
30 Optimization,
31 UnslopSanitization,
32 InvariantFix,
33 MetaEngineImprovement,
34}
35
36#[derive(Debug, Clone, Serialize, Deserialize)]
37pub struct ImprovementProposal {
38 pub id: String,
39 pub title: String,
40 pub description: String,
41 pub target_file: String,
42 pub proposed_patch: String,
43 pub kind: ProposalKind,
44 pub created_at: String,
45 pub sandbox_path: Option<String>,
46 #[serde(default)]
47 pub operator_signature: Option<String>,
48}
49
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct InvariantReport {
52 pub passed: bool,
53 pub unslop_clean: bool,
54 pub em_dash_detected: usize,
55 pub en_dash_detected: usize,
56 pub forbidden_buzzwords_detected: Vec<String>,
57 pub antithesis_tropes_detected: Vec<String>,
58 pub zero_disk_secrets_clean: bool,
59 pub secret_leaks: Vec<String>,
60 pub compilation_passed: bool,
61 pub compilation_error: Option<String>,
62 pub tests_passed: bool,
63 pub test_output_summary: Option<String>,
64 pub notes: Vec<String>,
65}
66
67#[derive(Debug, Clone, Serialize, Deserialize)]
68pub struct BalanceVerdict {
69 pub kernel: String,
70 pub mode: String,
71 pub drive: f64,
72 pub humanity: f64,
73 pub ratio: f64,
74 pub score: f64,
75 pub verdict: String,
76 pub guidance: String,
77}
78
79#[derive(Debug, Clone, Serialize, Deserialize)]
80pub struct RatificationRecord {
81 pub proposal_id: String,
82 pub commit_hash: Option<String>,
83 /// Review branch holding the candidate commit. Never the default branch.
84 #[serde(default)]
85 pub branch: Option<String>,
86 /// PR-ready patch (git format-patch) of the candidate commit.
87 #[serde(default)]
88 pub patch_path: Option<String>,
89 pub author: String,
90 pub cortex_receipt_id: Option<String>,
91 pub cortex_recorded: bool,
92 pub timestamp: String,
93 pub status: String,
94 pub message: String,
95}
96
97#[derive(Debug, Clone, Serialize, Deserialize)]
98pub struct RsiConfig {
99 pub target_repo: String,
100 pub cortex_url: String,
101 pub cortex_space: String,
102 pub loop_interval_secs: u64,
103 pub sandbox_root: String,
104 #[serde(default = "default_rsi_root")]
105 pub rsi_root: String,
106 #[serde(default)]
107 pub holdouts_dir: Option<String>,
108 #[serde(default)]
109 pub signing_key_hex: Option<String>,
110 #[serde(default)]
111 pub require_latency_improvement: bool,
112 /// OpenAI-compatible chat completions endpoint of the local model seat.
113 /// Configs written before 2026-10-15 named this `max_url`; that key is still read.
114 #[serde(default = "default_model_url", alias = "max_url")]
115 pub model_url: String,
116 /// Model id sent to the local model seat. Older configs named this `max_model`.
117 #[serde(default = "default_model_id", alias = "max_model")]
118 pub model_id: String,
119 #[serde(default = "default_canary_target")]
120 pub canary_target: u64,
121 #[serde(default)]
122 pub operator_key_hex: Option<String>,
123 #[serde(default)]
124 pub non_inferiority_margin: Option<f64>,
125 /// Repository-relative roots a proposal may change. Anything else is refused.
126 #[serde(default = "crate::diff_gate::default_ratify_roots")]
127 pub ratify_roots: Vec<String>,
128 /// Directory holding a DUAL price vector (`price_vector.bin`, `*.constraint.bin`,
129 /// optional `price_vector.sha256`). Read as a diagnostic signal only (ADR 0031
130 /// section 7.5); it grants no authority and changes no gate. None = not configured.
131 #[serde(default)]
132 pub dual_price_vector_dir: Option<String>,
133 /// SEC1 hex public key of the separate judge. Promotion requires a version 2 receipt signed
134 /// by this key; it must differ from the daemon's own key. None = promotion fails closed.
135 #[serde(default)]
136 pub judge_public_key_hex: Option<String>,
137 /// Operator-owned evaluation policy the judge receipt must be bound to. None = fails closed.
138 #[serde(default)]
139 pub judge_policy_file: Option<String>,
140 /// Minimum compatible completed samples a stage needs before its latency counts as measured.
141 #[serde(default = "default_measure_min_samples")]
142 pub measure_min_samples: usize,
143 /// How many of the most recent compatible completed cycles are considered per stage.
144 #[serde(default = "default_measure_window_cycles")]
145 pub measure_window_cycles: usize,
146 /// Minimum valid compatible samples before an empirical p95 is reported.
147 #[serde(default = "default_measure_p95_min_samples")]
148 pub measure_p95_min_samples: usize,
149 /// Operator-declared latency goal, in percent below the measured median. A goal, not a forecast.
150 #[serde(default = "default_measure_target_improvement_pct")]
151 pub measure_target_improvement_pct: f64,
152 /// Where the operator's canary workload lives. None = `<rsi_root>/canary/workload.json`.
153 /// The candidate never writes it: it is read from the operator's state directory, not from
154 /// the evaluated tree.
155 #[serde(default)]
156 pub canary_workload_path: Option<String>,
157 /// SHA-256 pin of the canary workload (the digest `CanaryWorkloadManifest::digest` reports).
158 /// None = canary admission fails closed: the operator must pin the workload.
159 #[serde(default)]
160 pub canary_workload_sha256: Option<String>,
161 /// Canary applicability policy. A change that is executable (a target file ending in `.rs`,
162 /// `.toml` or `Cargo.lock`, or a tree that builds an executable or declares a canary
163 /// adapter) always goes through canary admission, whatever its kind. Only kinds listed here
164 /// are exempt, and only when the change is not executable. The default is empty: nothing is
165 /// exempt. An exempt change still goes through the safety envelope and the promotion gate.
166 #[serde(default)]
167 pub canary_exempt_kinds: Vec<ProposalKind>,
168}
169
170fn default_model_url() -> String {
171 "http://127.0.0.1:18006/v1".to_string()
172}
173
174fn default_model_id() -> String {
175 "atlas-lightning-omni".to_string()
176}
177
178fn default_rsi_root() -> String {
179 ".rsi".to_string()
180}
181
182fn default_canary_target() -> u64 {
183 5000
184}
185
186fn default_measure_min_samples() -> usize {
187 3
188}
189
190fn default_measure_window_cycles() -> usize {
191 20
192}
193
194fn default_measure_p95_min_samples() -> usize {
195 20
196}
197
198fn default_measure_target_improvement_pct() -> f64 {
199 5.0
200}
201
202impl Default for RsiConfig {
203 fn default() -> Self {
204 Self {
205 target_repo: ".".to_string(),
206 cortex_url: "http://127.0.0.1:18080".to_string(),
207 cortex_space: "atlas-memory".to_string(),
208 loop_interval_secs: 60,
209 sandbox_root: "/tmp/spark-rsi-sandbox".to_string(),
210 rsi_root: ".rsi".to_string(),
211 holdouts_dir: None,
212 signing_key_hex: None,
213 require_latency_improvement: false,
214 model_url: default_model_url(),
215 model_id: default_model_id(),
216 canary_target: 5000,
217 operator_key_hex: None,
218 non_inferiority_margin: None,
219 ratify_roots: crate::diff_gate::default_ratify_roots(),
220 dual_price_vector_dir: None,
221 judge_public_key_hex: None,
222 judge_policy_file: None,
223 measure_min_samples: default_measure_min_samples(),
224 measure_window_cycles: default_measure_window_cycles(),
225 measure_p95_min_samples: default_measure_p95_min_samples(),
226 measure_target_improvement_pct: default_measure_target_improvement_pct(),
227 canary_workload_path: None,
228 canary_workload_sha256: None,
229 canary_exempt_kinds: Vec::new(),
230 }
231 }
232}
233
234/// What the supervisor-driven run did, copied from the executor's summary.
235#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
236pub struct CanaryExecutionRecord {
237 pub requests_planned: usize,
238 pub issued: usize,
239 pub verified_success: usize,
240 pub wrong_result: usize,
241 pub timeout: usize,
242 pub invalid_response: usize,
243 pub connection_closed: usize,
244 pub rejections: usize,
245 pub ready: bool,
246 pub reverted: bool,
247 pub first_failure: Option<String>,
248}
249
250/// The quota validator's decision: counted against target, or the refusal reason.
251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
252pub struct QuotaDecisionRecord {
253 pub admitted: bool,
254 pub counted: Option<u64>,
255 pub target: u64,
256 pub refusal: Option<String>,
257}
258
259/// A pass or refusal of one gate, with the detail the gate gave.
260#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
261pub struct GateDecisionRecord {
262 pub passed: bool,
263 pub detail: String,
264}
265
266/// The reference-backend caveat recorded with every safety envelope decision.
267pub const ENVELOPE_REFERENCE_NOTE: &str = "the safety envelope evaluated through aien_probe::DeterministicReferenceBackend; this is a reference evaluation and does not establish production safety";
268
269/// Canary admission as one cycle saw it. Every digest is lowercase hex SHA-256.
270#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
271pub struct CanarySummary {
272 /// Canary admission applied to the change (false only for a configured exemption).
273 pub applicable: bool,
274 /// Why the change was exempt, when it was.
275 pub exemption: Option<String>,
276 /// The target ships a valid adapter manifest and the operator's workload is pinned.
277 pub eligible: bool,
278 /// Why the candidate was refused before or during execution, when it was.
279 pub refusal: Option<String>,
280 pub identity_binding_digest: Option<String>,
281 pub executable_digest: Option<String>,
282 pub workload_digest: Option<String>,
283 pub log_digest: Option<String>,
284 /// Hash of the ledger block that committed the sealed log before admission.
285 pub commitment_block_hash: Option<String>,
286 pub execution: Option<CanaryExecutionRecord>,
287 pub quota: Option<QuotaDecisionRecord>,
288 pub envelope: Option<GateDecisionRecord>,
289 /// Present whenever the envelope ran: it is a reference evaluation, not production safety.
290 pub envelope_note: Option<String>,
291 pub promotion_gate: Option<GateDecisionRecord>,
292}
293
294#[derive(Debug, Clone, Serialize, Deserialize)]
295pub struct RsiCycleResult {
296 pub cycle_id: String,
297 pub telemetry: TelemetrySnapshot,
298 pub proposal: Option<ImprovementProposal>,
299 pub invariants: Option<InvariantReport>,
300 pub balance: Option<BalanceVerdict>,
301 pub receipt: Option<crate::evaluator::EvaluationReceipt>,
302 pub generation: Option<crate::supervisor::GenerationInfo>,
303 pub ledger_block: Option<crate::ledger::LedgerBlock>,
304 pub ratification: Option<RatificationRecord>,
305 pub success: bool,
306 pub elapsed_ms: f64,
307 /// DUAL scarcity reading (ADR 0031 section 7.5). Diagnostic only: it never
308 /// enters bottleneck ranking, hard invariants, admission, ratification or
309 /// promotion. Defaults to `Unavailable { Missing }` when not configured.
310 #[serde(default)]
311 pub scarcity: crate::dual::ScarcityDiagnostic,
312 /// Canary admission summary. None when no candidate reached the canary stage.
313 #[serde(default)]
314 pub canary: Option<CanarySummary>,
315}
316
317#[cfg(test)]
318mod tests {
319 use super::*;
320
321 #[test]
322 fn config_written_with_the_old_endpoint_keys_still_loads() {
323 let old = serde_json::json!({
324 "target_repo": ".", "cortex_url": "http://127.0.0.1:18080", "cortex_space": "s",
325 "mojo_kernel_path": "mojo/balance_bin", "loop_interval_secs": 60,
326 "sandbox_root": "/tmp/spark-rsi-sandbox",
327 "max_url": "http://127.0.0.1:9/v1", "max_model": "old-model"
328 });
329 let cfg: RsiConfig = serde_json::from_value(old).unwrap();
330 assert_eq!(cfg.model_url, "http://127.0.0.1:9/v1");
331 assert_eq!(cfg.model_id, "old-model");
332 let new = serde_json::to_value(&cfg).unwrap();
333 assert!(new.get("model_url").is_some() && new.get("max_url").is_none());
334 assert!(new.get("mojo_kernel_path").is_none());
335 }
336}