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

1104 lines · 49645 bytes Raw Blame History
1use crate::actor::judge::BlindJudge;
2use crate::balance::BalanceKernel;
3use crate::canary::identity::{digest_file, tree_digest};
4use crate::canary::{
5 admit_sealed_quota, CanaryAdapterManifest, CanaryWorkloadManifest, CandidateIdentity,
6 LoadedAdapterManifest, PinnedWorkload,
7};
8use crate::dual::ScarcityDiagnostic;
9use crate::evaluator::EvaluationReceipt;
10use crate::isolation::BuildJail;
11use crate::ledger::{BlockType, ImprovementLedger, LedgerBlock};
12use crate::measure::{
13 build_capability_graph, check_claim, measure_stages, CycleSampleRecord, MeasureContext,
14 SampleLog, Stage, StageClock, StageMeasurement, StageOutcome, SCHEMA_VERSION,
15};
16use crate::models::{
17 CanaryExecutionRecord, CanarySummary, GateDecisionRecord, QuotaDecisionRecord, RsiConfig,
18 RsiCycleResult, ENVELOPE_REFERENCE_NOTE,
19};
20use crate::observe::observe_codebase;
21use crate::propose::{
22 CortexExperienceClient, DefectCategory, DiagnosticContext, HypothesisContract, ModelSeatClient,
23 ProposalGenerator,
24};
25use crate::ratify::Ratifier;
26use crate::supervisor::canary_exec::{CanaryExecutor, ExecutionOutcome, ExecutorConfig};
27use crate::supervisor::daemon::{resolve_supervisor_secret, SupervisorConfig, SupervisorDaemon};
28use crate::supervisor::{GenerationInfo, GenerationState};
29use crate::verifier::InvariantVerifier;
30use sha2::Digest;
31use std::path::{Path, PathBuf};
32use std::time::Instant;
33use uuid::Uuid;
34
35pub struct RsiEngine;
36
37impl RsiEngine {
38 /// Runs one cycle and records its stage samples. A cycle that returns an error is a partial
39 /// cycle: its samples go to the partial-cycle log and are never ranked. A cycle that ends
40 /// early for a normal reason (no candidate, judge refused, canary quota refused) is complete
41 /// for the stages it ran.
42 pub async fn run_cycle(config: &RsiConfig) -> Result<RsiCycleResult, String> {
43 let cycle_id = format!("cycle-{}", Uuid::new_v4().simple());
44 let repo_path = Path::new(&config.target_repo);
45 let rsi_root = repo_path.join(&config.rsi_root);
46 let ctx = MeasureContext::for_config(config, repo_path);
47 let mut clock = StageClock::new();
48 let result = Self::run_cycle_inner(config, &cycle_id, &ctx, &mut clock).await;
49 Self::record_stage_samples(&rsi_root, &cycle_id, &ctx, &clock, result.is_ok());
50 result
51 }
52
53 fn record_stage_samples(
54 rsi_root: &Path,
55 cycle_id: &str,
56 ctx: &MeasureContext,
57 clock: &StageClock,
58 completed: bool,
59 ) {
60 if clock.is_empty() {
61 return;
62 }
63 let record = CycleSampleRecord {
64 schema_version: SCHEMA_VERSION,
65 cycle_id: cycle_id.to_string(),
66 workload_key: ctx.workload_key.clone(),
67 execution_profile_fingerprint: ctx.fingerprint.clone(),
68 execution_profile: ctx.profile.clone(),
69 stages: clock.samples(),
70 source_commit: ctx.source_commit.clone(),
71 recorded_at: chrono::Utc::now().to_rfc3339(),
72 };
73 let log = SampleLog::new(rsi_root);
74 let written = if completed {
75 log.append_complete(&record)
76 } else {
77 log.append_partial(&record)
78 };
79 if let Err(e) = written {
80 tracing::warn!("stage samples for {} were not recorded: {}", cycle_id, e);
81 }
82 }
83
84 async fn run_cycle_inner(
85 config: &RsiConfig,
86 cycle_id: &str,
87 ctx: &MeasureContext,
88 clock: &mut StageClock,
89 ) -> Result<RsiCycleResult, String> {
90 let start = Instant::now();
91 let cycle_id = cycle_id.to_string();
92 let repo_path = Path::new(&config.target_repo);
93 let rsi_root = repo_path.join(&config.rsi_root);
94
95 // 1. Immutable Provenance: Fail closed if ledger cannot be opened
96 let ledger = ImprovementLedger::open(&rsi_root).map_err(|e| {
97 format!(
98 "Fatal: Improvement Ledger must be active and accessible at {:?}: {}",
99 rsi_root, e
100 )
101 })?;
102
103 // 2. Strict Holdouts: Fail closed if holdout test suite is missing
104 let holdouts_path = config
105 .holdouts_dir
106 .as_ref()
107 .map(PathBuf::from)
108 .unwrap_or_else(|| rsi_root.join("holdouts"));
109
110 if !holdouts_path.exists() {
111 return Err(format!(
112 "Fatal: Missing holdouts directory at {:?}. Production evaluation fails closed.",
113 holdouts_path
114 ));
115 }
116
117 // 3. Cryptographic Signer: Fail closed if signing key is missing or invalid
118 let signing_key_hex = config.signing_key_hex.as_ref().ok_or_else(|| {
119 "Fatal: Missing cryptographic signing key (signing_key_hex). Production evaluation fails closed.".to_string()
120 })?;
121 let key_bytes = hex::decode(signing_key_hex)
122 .map_err(|e| format!("Fatal: Invalid signing_key_hex: {}", e))?;
123 let signing_key = p256::ecdsa::SigningKey::from_slice(&key_bytes)
124 .map_err(|e| format!("Fatal: Invalid P-256 signing key: {}", e))?;
125
126 // 4. Telemetry Ingestion & CapabilityGraph Population
127 let observe_guard = clock.guard(Stage::Observe);
128 let telemetry = observe_codebase(repo_path)?;
129 observe_guard.complete(StageOutcome::Ok);
130
131 // Ranking reads measurements from completed prior cycles only. This cycle's own samples
132 // are appended after it ends, and its id is excluded as well.
133 let measurements = measure_stages(
134 SampleLog::new(&rsi_root).read_complete(),
135 &cycle_id,
136 ctx,
137 config,
138 );
139 let graph = build_capability_graph(&measurements)?;
140 let top_bottleneck = graph.top_bottleneck();
141 let diagnosis_measured = top_bottleneck.as_ref().is_some_and(|b| {
142 Stage::ALL.iter().any(|s| {
143 s.id() == b.node_id
144 && matches!(measurements.get(s), Some(StageMeasurement::Measured { .. }))
145 })
146 });
147
148 // 4b. DUAL scarcity reading (ADR 0031 section 7.5). Diagnostic only: read
149 // after ranking, never fed into rank_bottlenecks, hard invariants,
150 // admission, ratification or promotion. Unconfigured = Unavailable(Missing).
151 let scarcity = match config.dual_price_vector_dir.as_deref() {
152 Some(dir) => ScarcityDiagnostic::load_from_dir(Path::new(dir)),
153 None => ScarcityDiagnostic::default(),
154 };
155
156 // 5. Bottleneck Hypothesis Contract & Cortex Recall
157 let hypothesis = top_bottleneck.as_ref().map(|b| {
158 HypothesisContract::from_bottleneck(
159 &format!("hypo-{}", Uuid::new_v4().simple()),
160 &cycle_id,
161 b,
162 config.measure_target_improvement_pct,
163 )
164 .with_protected_metric("correctness", 0.0)
165 .with_falsification_test("assert!(receipt.passed_all_hard_invariants)")
166 });
167
168 let propose_started = Instant::now();
169 let mut propose_outcome = StageOutcome::Ok;
170
171 let cortex =
172 CortexExperienceClient::new(&config.cortex_url).with_space(&config.cortex_space);
173 let cortex_query = if let Some(ref h) = hypothesis {
174 format!("{} {}", h.observed_problem, h.suspected_root_cause)
175 } else {
176 "performance bottleneck repair".to_string()
177 };
178 let past_lessons = cortex.recall_lessons(&cortex_query, 3).await;
179
180 // 6. Proposer: local model seat proposer and constrained candidates
181 let mut candidates = Vec::new();
182 let model_seat = ModelSeatClient::new(&config.model_url, &config.model_id);
183
184 if model_seat.is_available().await {
185 let target_file = "src/lib.rs";
186 let full_path = repo_path.join(target_file);
187 let content = std::fs::read_to_string(&full_path).unwrap_or_default();
188
189 let mut diag = DiagnosticContext::from_violations(
190 &cycle_id,
191 target_file,
192 &content,
193 DefectCategory::PerformanceRegression,
194 {
195 let mut violations = vec![format!(
196 "Bottleneck identified at {:?}",
197 top_bottleneck.as_ref().map(|b| &b.node_name)
198 )];
199 // Rationale text only, and only when a price vector is configured.
200 if config.dual_price_vector_dir.is_some() {
201 violations.push(format!(
202 "DUAL scarcity reading (diagnostic only, no authority): {}",
203 scarcity.summary()
204 ));
205 }
206 violations
207 },
208 past_lessons.clone(),
209 );
210 if let Some(h) = hypothesis.clone() {
211 diag = diag.with_hypothesis(h);
212 }
213
214 match ProposalGenerator::propose_from_diagnosis(&model_seat, &diag).await {
215 Ok(prop) => candidates.push(prop),
216 Err(_) => propose_outcome = StageOutcome::Failed,
217 }
218 }
219
220 if let Some(prop) = ProposalGenerator::scan_and_propose_unslop(repo_path) {
221 candidates.push(prop);
222 }
223 clock.record(Stage::Propose, propose_started.elapsed(), propose_outcome);
224
225 let mut maybe_invariants = None;
226 let mut maybe_balance = None;
227 let mut maybe_receipt: Option<EvaluationReceipt> = None;
228 let mut maybe_generation: Option<GenerationInfo> = None;
229 let mut maybe_ledger_block: Option<LedgerBlock> = None;
230 let mut maybe_ratification = None;
231 let mut winning_proposal: Option<crate::models::ImprovementProposal> = None;
232 let mut success = true;
233 let mut canary_summary: Option<CanarySummary> = None;
234 let mut canary_build: Option<(LoadedAdapterManifest, PathBuf)> = None;
235 let mut winning_build_output: Option<tempfile::TempDir> = None;
236 let mut pinned_workload: Option<PinnedWorkload> = None;
237
238 let sandbox_base = Path::new(&config.sandbox_root);
239
240 for mut candidate in candidates {
241 // Claim policy: a performance claim needs a measured diagnosis. Refused before
242 // anything is staged.
243 if let Err(e) = check_claim(
244 &candidate.kind,
245 config.require_latency_improvement,
246 diagnosis_measured,
247 ) {
248 let _ = ledger.append_block(BlockType::Evaluation, e, vec![]);
249 continue;
250 }
251
252 // Declared-target gate before anything is staged: normalized path,
253 // no `..`, inside the declared roots, not a root-of-trust file.
254 if let Err(e) = crate::diff_gate::check_declared_target(
255 &candidate.target_file,
256 &config.ratify_roots,
257 ) {
258 let _ = ledger.append_block(
259 BlockType::Evaluation,
260 format!("Declared target refused: {}", e),
261 vec![],
262 );
263 continue;
264 }
265
266 // Tier Governance: Check candidate tier and boundaries
267 let tier = crate::meta::TierGovernance::classify_proposal(&candidate);
268 if tier == crate::meta::CandidateTier::Tier2Engine {
269 if config.operator_key_hex.is_none() {
270 // Engine changes need operator authorization; no key means no authorization.
271 let _ = ledger.append_block(
272 BlockType::Evaluation,
273 "Tier 2 candidate refused: no operator key configured".to_string(),
274 vec![],
275 );
276 continue;
277 }
278 if let Err(e) = crate::meta::TierGovernance::validate_tier2_candidate_boundaries(
279 &candidate.target_file,
280 ) {
281 let _ = ledger.append_block(
282 BlockType::Evaluation,
283 format!("Tier 2 Invariant Rejected: {}", e),
284 vec![],
285 );
286 continue;
287 }
288 if let Some(ref op_key_hex) = config.operator_key_hex {
289 let key_bytes = match hex::decode(op_key_hex) {
290 Ok(b) => b,
291 Err(_) => {
292 let _ = ledger.append_block(
293 BlockType::Evaluation,
294 "Invalid operator_key_hex".to_string(),
295 vec![],
296 );
297 continue;
298 }
299 };
300 let op_key = match p256::ecdsa::VerifyingKey::from_sec1_bytes(&key_bytes) {
301 Ok(k) => k,
302 Err(_) => {
303 let _ = ledger.append_block(
304 BlockType::Evaluation,
305 "Invalid operator verifying key".to_string(),
306 vec![],
307 );
308 continue;
309 }
310 };
311 let digest = sha2::Sha256::digest(candidate.proposed_patch.as_bytes());
312 let sig = candidate.operator_signature.as_deref().unwrap_or_default();
313 if crate::meta::TierGovernance::verify_operator_authorization(
314 &digest, sig, &op_key,
315 )
316 .is_err()
317 {
318 let _ = ledger.append_block(
319 BlockType::Evaluation,
320 "Operator signature unauthorized".to_string(),
321 vec![],
322 );
323 continue;
324 }
325 }
326 }
327
328 let sandbox_dir = match ProposalGenerator::stage_in_sandbox(
329 &mut candidate,
330 repo_path,
331 sandbox_base,
332 ) {
333 Ok(dir) => dir,
334 Err(e) => {
335 let _ = ledger.append_block(
336 BlockType::Evaluation,
337 format!("Stage failed: {}", e),
338 vec![],
339 );
340 continue;
341 }
342 };
343 // Output must not alias the read-only candidate tree or another candidate's cache.
344 let build_output = tempfile::tempdir()
345 .map_err(|e| format!("Cannot create private build output: {}", e))?;
346
347 // Canary applicability. An executable change always goes through canary admission;
348 // only a kind the operator listed in `canary_exempt_kinds` can skip it, and only
349 // when nothing executable is involved.
350 let is_code_change = candidate.target_file.ends_with(".rs")
351 || candidate.target_file.ends_with(".toml")
352 || candidate.target_file.ends_with("Cargo.lock");
353 let adapter_declared = CanaryAdapterManifest::is_declared(&sandbox_dir);
354 let heuristic_build = sandbox_dir.join("Cargo.toml").exists()
355 && (!sandbox_dir.join("spark-rsi").exists()
356 || candidate.target_file.ends_with(".rs"));
357 let executable_change = is_code_change || heuristic_build || adapter_declared;
358 let exempt = !executable_change && config.canary_exempt_kinds.contains(&candidate.kind);
359 let mut cand_summary = CanarySummary {
360 applicable: !exempt,
361 exemption: exempt.then(|| {
362 format!(
363 "kind {:?} is exempt by configuration and the change is not executable",
364 candidate.kind
365 )
366 }),
367 ..Default::default()
368 };
369 // 6b. Eligibility, fail closed before any worker starts: the evaluated tree must
370 // ship a valid adapter manifest, the operator's workload must be pinned and match,
371 // and the adapter must name that workload. An ineligible candidate still runs the
372 // judge so its evaluation is on record, then is refused at the canary stage.
373 let mut canary_target_build: Option<(LoadedAdapterManifest, PathBuf)> = None;
374 if !exempt {
375 'eligibility: {
376 let adapter = match CanaryAdapterManifest::load_from_tree(&sandbox_dir) {
377 Ok(a) => a,
378 Err(e) => {
379 let _ = ledger.append_block(
380 BlockType::Evaluation,
381 format!("Canary refused, candidate not eligible: {}", e),
382 vec![],
383 );
384 cand_summary.refusal = Some(e);
385 break 'eligibility;
386 }
387 };
388 if pinned_workload.is_none() {
389 match load_pinned_workload(config, &rsi_root) {
390 Ok(w) => pinned_workload = Some(w),
391 Err(e) => {
392 let _ = ledger.append_block(
393 BlockType::Evaluation,
394 format!("Canary workload refused: {}", e),
395 vec![],
396 );
397 return Err(format!("Fatal: canary workload refused: {}", e));
398 }
399 }
400 }
401 let workload = pinned_workload.as_ref().expect("loaded above");
402 cand_summary.workload_digest = Some(workload.digest.clone());
403 if adapter.manifest.workload_id != workload.manifest.workload_id {
404 let e = format!(
405 "adapter names workload {:?}, the pinned workload is {:?}",
406 adapter.manifest.workload_id, workload.manifest.workload_id
407 );
408 let _ = ledger.append_block(
409 BlockType::Evaluation,
410 format!("Canary refused, candidate not eligible: {}", e),
411 vec![],
412 );
413 cand_summary.refusal = Some(e);
414 break 'eligibility;
415 }
416 let built = adapter
417 .manifest
418 .executable_path(&build_output.path().join("target"));
419 cand_summary.eligible = true;
420 canary_target_build = Some((adapter, built));
421 }
422 }
423
424 // 7. Jail 1 Build: Compile candidate artifact strictly in isolated Build Jail. The
425 // `spark-rsi` heuristic never decides this for a canary-eligible tree: it is always
426 // built, so the adapter executable exists fresh from this exact tree.
427 let needs_build = heuristic_build || canary_target_build.is_some();
428 if needs_build {
429 let build_started = Instant::now();
430 let build_jail = BuildJail::new(
431 "spark-rsi-builder:latest",
432 &sandbox_dir,
433 build_output.path(),
434 );
435 let (build_success, build_stdout, build_stderr) = match build_jail.execute_bwrap(&[
436 "cargo",
437 "build",
438 "--release",
439 "--offline",
440 "--locked",
441 "-j2",
442 ]) {
443 Ok(res) => res,
444 Err(e) => {
445 clock.record(
446 Stage::BuildJail,
447 build_started.elapsed(),
448 StageOutcome::Failed,
449 );
450 let _ = ledger.append_block(
451 BlockType::Evaluation,
452 format!("Build Jail exec error: {}", e),
453 vec![],
454 );
455 continue;
456 }
457 };
458
459 clock.record(
460 Stage::BuildJail,
461 build_started.elapsed(),
462 if build_success {
463 StageOutcome::Ok
464 } else {
465 StageOutcome::Failed
466 },
467 );
468 if !build_success {
469 let err_msg = format!(
470 "Candidate failed to compile in Build Jail:
471{}",
472 build_stderr
473 );
474 let raw_err = serde_json::to_string(&serde_json::json!({
475 "proposal_id": candidate.id,
476 "stage": "build_jail",
477 "error": err_msg,
478 "stdout": build_stdout,
479 }))
480 .unwrap_or_default();
481 let _ = ledger.append_block(BlockType::Evaluation, raw_err, vec![]);
482 continue;
483 }
484 }
485 let built_missing = canary_target_build.as_ref().and_then(|(_, built)| {
486 let is_file = built
487 .symlink_metadata()
488 .map(|m| m.file_type().is_file())
489 .unwrap_or(false);
490 (!is_file).then(|| {
491 format!(
492 "the build did not produce the adapter executable {:?}; not eligible for canary",
493 built
494 )
495 })
496 });
497 if let Some(e) = built_missing {
498 let _ = ledger.append_block(BlockType::Evaluation, e.clone(), vec![]);
499 cand_summary.eligible = false;
500 cand_summary.refusal = Some(e);
501 canary_target_build = None;
502 }
503
504 // The JudgeEvaluation stage covers invariant verification, the balance reading and the
505 // judge's evaluation of this candidate.
506 let eval_started = Instant::now();
507 // 8. Invariant Verification in isolated sandbox
508 // Non-code proposals skip compile and test gates: the sandbox cannot
509 // resolve sibling path dependencies and markdown carries no build risk.
510 let inv_report =
511 InvariantVerifier::run_full_verification_scoped(&sandbox_dir, is_code_change);
512 let passed = inv_report.passed;
513
514 // 9. Balance: evaluate soul tension via the native balance kernel
515 let balance_verdict = BalanceKernel::evaluate(
516 telemetry.soul_tension.drive_score,
517 telemetry.soul_tension.humanity_score,
518 );
519 let is_balanced = balance_verdict.verdict == "balanced";
520
521 if !passed || !is_balanced {
522 clock.record(
523 Stage::JudgeEvaluation,
524 eval_started.elapsed(),
525 StageOutcome::Refused,
526 );
527 let raw_fail = serde_json::to_string(&serde_json::json!({
528 "proposal_id": candidate.id,
529 "invariants_passed": passed,
530 "is_balanced": is_balanced,
531 "notes": inv_report.notes,
532 "compile_error": inv_report.compilation_error,
533 "test_summary": inv_report.test_output_summary,
534 }))
535 .unwrap_or_default();
536 let _ = ledger.append_block(BlockType::Evaluation, raw_fail, vec![]);
537 continue;
538 }
539
540 // 10. Objective Evaluation via BlindJudge with holdouts and cryptographic signing key
541 let output_dir = Path::new(&config.sandbox_root).join("eval_outputs");
542 let mut judge = BlindJudge::new(holdouts_path.clone(), output_dir)
543 .with_signing_key(signing_key.clone())
544 .with_non_inferiority_margin(config.non_inferiority_margin.unwrap_or(5.0));
545 judge.require_latency_improvement = config.require_latency_improvement;
546 judge.require_build_verification = is_code_change;
547
548 let receipt = match judge.evaluate_cycle(
549 &cycle_id,
550 &candidate.id,
551 "parent",
552 &sandbox_dir,
553 repo_path,
554 ) {
555 Ok(rcpt) => rcpt,
556 Err(e) => {
557 clock.record(
558 Stage::JudgeEvaluation,
559 eval_started.elapsed(),
560 StageOutcome::Failed,
561 );
562 let _ = ledger.append_block(
563 BlockType::Evaluation,
564 format!("Judge evaluation error: {}", e),
565 vec![],
566 );
567 continue;
568 }
569 };
570
571 let raw_json = serde_json::to_vec(&receipt).unwrap_or_default();
572 let blk = ledger
573 .append_evaluation(&receipt, Some(&raw_json))
574 .map_err(|e| format!("Fatal: Failed to append evaluation to ledger: {}", e))?;
575 let ledger_hash = blk.block_hash.clone();
576 let judge_admitted = receipt.admitted;
577 clock.record(
578 Stage::JudgeEvaluation,
579 eval_started.elapsed(),
580 if judge_admitted {
581 StageOutcome::Ok
582 } else {
583 StageOutcome::Refused
584 },
585 );
586
587 if !judge_admitted {
588 let _ = Ratifier::record_cortex_lesson(
589 &candidate,
590 None,
591 Some(&ledger_hash),
592 &config.cortex_url,
593 &config.cortex_space,
594 )
595 .await;
596 continue;
597 }
598
599 maybe_invariants = Some(inv_report);
600 maybe_balance = Some(balance_verdict);
601 maybe_receipt = Some(receipt);
602 maybe_ledger_block = Some(blk);
603 canary_summary = Some(cand_summary);
604 canary_build = canary_target_build;
605 winning_build_output = Some(build_output);
606 winning_proposal = Some(candidate);
607 break;
608 }
609
610 let canary_started = Instant::now();
611 if let Some(ref proposal) = winning_proposal {
612 let sandbox_dir = sandbox_base.join(&proposal.id);
613 // 11. Supervisor-driven canary and admission. Sequence: Collect -> Seal -> Verify ->
614 // Quota admission -> Safety envelope -> Judge / promotion gate -> Durable.
615 let supervisor_sock = rsi_root.join("supervisor.sock");
616 let active_link = rsi_root.join("active.sock");
617 let supervisor_config = SupervisorConfig {
618 rsi_root: rsi_root.clone(),
619 socket_path: supervisor_sock.clone(),
620 memory_limit_mb: 49152,
621 canary_target: config.canary_target,
622 max_latency_us: 1_000_000,
623 max_error_rate: 0.0,
624 shared_secret: resolve_supervisor_secret(),
625 };
626 let supervisor_daemon = SupervisorDaemon::new(supervisor_config.clone());
627 let mut summary = canary_summary.take().unwrap_or_default();
628 let receipt_digest = maybe_receipt.as_ref().unwrap().receipt_digest.clone();
629 let judge_ledger_hash = maybe_ledger_block.as_ref().map(|b| b.block_hash.clone());
630
631 // Stage canary generation
632 let mut gen_info = supervisor_daemon
633 .stage_canary(&proposal.id, &sandbox_dir, &receipt_digest)
634 .await?;
635
636 let patch_bytes = proposal.proposed_patch.as_bytes();
637 let patch_digest: [u8; 32] = sha2::Sha256::digest(patch_bytes).into();
638 let candidate_digest = hex::encode(patch_digest);
639
640 let admitted = Self::admit_canary(
641 config,
642 &ledger,
643 proposal,
644 &sandbox_dir,
645 &patch_digest,
646 canary_build.as_ref(),
647 pinned_workload.as_ref(),
648 &supervisor_daemon,
649 &supervisor_config,
650 &mut gen_info,
651 &mut summary,
652 )
653 .await;
654 drop(winning_build_output);
655
656 // The subject of the envelope is the candidate identity binding (or, for a
657 // configured exemption, the patch digest). Quota refusal rolls back here.
658 let subject_digest = match admitted {
659 Ok(digest) => Some(digest),
660 Err(reason) => {
661 success = false;
662 Self::roll_back(&supervisor_daemon, &active_link, &ledger, proposal, &reason)
663 .await?;
664 Self::record_decision(&ledger, &proposal.id, &summary);
665 let _ = Ratifier::record_cortex_lesson(
666 proposal,
667 None,
668 judge_ledger_hash.as_deref(),
669 &config.cortex_url,
670 &config.cortex_space,
671 )
672 .await;
673 None
674 }
675 };
676
677 if let Some(subject_digest) = subject_digest {
678 // Safety envelope gate: no promotion without a signed canary
679 // evaluation receipt from the production signer. Fails closed. It evaluates
680 // through the deterministic reference backend, which is recorded as such.
681 let envelope_signer = std::sync::Arc::new(
682 aien_evaluation_protocol::SoftwareP256Signer::new(signing_key.clone()),
683 );
684 use aien_evaluation_protocol::VerifierSigner as _RsiEnvelopeSignerExt;
685 let envelope_verifier = aien_evaluation_protocol::VerifierIdentity {
686 principal_id: "rsi-production-daemon".to_string(),
687 key_id: envelope_signer.key_fingerprint(),
688 trust_epoch: 1,
689 trusted_build_digest: aien_protocol_types::Digest32(subject_digest),
690 policy_bundle_digest: aien_protocol_types::Digest32({
691 let mut h = sha2::Sha256::new();
692 h.update(
693 format!("rsi-production-policy:{}", config.canary_target).as_bytes(),
694 );
695 h.finalize().into()
696 }),
697 };
698 let envelope = crate::safety_envelope::CanarySafetyEnvelope::new(
699 envelope_verifier,
700 envelope_signer,
701 );
702 let subject = aien_protocol_types::ArtifactRef {
703 artifact_id: Uuid::new_v4(),
704 digest: aien_protocol_types::Digest32(subject_digest),
705 media_type: "application/rust-patch".to_string(),
706 byte_size: patch_bytes.len() as u64,
707 };
708 let started_at = aien_protocol_types::Timestamp(
709 std::time::SystemTime::now()
710 .duration_since(std::time::UNIX_EPOCH)
711 .unwrap_or_default()
712 .as_millis() as u64,
713 );
714 summary.envelope_note = Some(ENVELOPE_REFERENCE_NOTE.to_string());
715 if let Err(e) = envelope
716 .evaluate_and_enforce(&subject, "rsi-production", started_at, || async {
717 Ok(())
718 })
719 .await
720 {
721 success = false;
722 summary.envelope = Some(GateDecisionRecord {
723 passed: false,
724 detail: e.to_string(),
725 });
726 let reason = format!("Safety envelope rejected promotion: {}", e);
727 Self::roll_back(&supervisor_daemon, &active_link, &ledger, proposal, &reason)
728 .await?;
729 Self::record_decision(&ledger, &proposal.id, &summary);
730 let _ = Ratifier::record_cortex_lesson(
731 proposal,
732 None,
733 judge_ledger_hash.as_deref(),
734 &config.cortex_url,
735 &config.cortex_space,
736 )
737 .await;
738 } else {
739 summary.envelope = Some(GateDecisionRecord {
740 passed: true,
741 detail: "signed canary evaluation receipt issued".to_string(),
742 });
743 let gate = crate::promotion_gate::check_v2_promotion(
744 maybe_receipt.as_ref().unwrap(),
745 config.judge_public_key_hex.as_deref(),
746 signing_key.verifying_key(),
747 config.judge_policy_file.as_deref(),
748 &crate::promotion_gate::PromotionSubject {
749 // The parent this daemon handed its judge (a label, not a commit), so
750 // only a receipt for this cycle's own tree can match.
751 parent_id: "parent",
752 path: &proposal.target_file,
753 content_sha256: &candidate_digest,
754 // Re-read the generation the swap promotes, right before the swap;
755 // unreadable never matches.
756 disk_sha256: &crate::actor::judge::sha256_file(
757 &supervisor_daemon
758 .supervisor
759 .generations_root
760 .join(&proposal.id)
761 .join(&proposal.target_file),
762 )
763 .unwrap_or_else(|e| format!("unreadable: {}", e)),
764 },
765 );
766 if let Err(e) = gate {
767 // No promotion without a version 2 receipt from the separate judge that
768 // binds this exact change. Version 1 receipts are history, never authority.
769 success = false;
770 summary.promotion_gate = Some(GateDecisionRecord {
771 passed: false,
772 detail: e.to_string(),
773 });
774 let reason = format!("Promotion gate refused: {}", e);
775 Self::roll_back(
776 &supervisor_daemon,
777 &active_link,
778 &ledger,
779 proposal,
780 &reason,
781 )
782 .await?;
783 Self::record_decision(&ledger, &proposal.id, &summary);
784 } else {
785 summary.promotion_gate = Some(GateDecisionRecord {
786 passed: true,
787 detail: "version 2 judge receipt accepted".to_string(),
788 });
789 Self::record_decision(&ledger, &proposal.id, &summary);
790 // Quota, envelope and promotion gate all passed. Only now is the
791 // generation Durable.
792 supervisor_daemon
793 .supervisor
794 .atomic_symlink_swap(&proposal.id)?;
795 gen_info.state = GenerationState::Durable;
796
797 let prom_blk = ledger
798 .append_promotion(&gen_info, &receipt_digest)
799 .map_err(|e| {
800 format!("Fatal: Failed to append promotion to ledger: {}", e)
801 })?;
802 let prom_hash = prom_blk.block_hash.clone();
803 maybe_ledger_block = Some(prom_blk);
804 maybe_generation = Some(gen_info);
805
806 // 12. Ratify proposal onto a review branch + patch (never the default branch), and record in Cortex memory tied to ledger hash
807 let commit_started = Instant::now();
808 let rat = Ratifier::ratify_proposal(
809 proposal,
810 maybe_invariants.as_ref().unwrap(),
811 repo_path,
812 &config.ratify_roots,
813 &Path::new(&config.rsi_root).join("patches"),
814 Some(&prom_hash),
815 &config.cortex_url,
816 &config.cortex_space,
817 )
818 .await?;
819 clock.record(
820 Stage::CortexCommit,
821 commit_started.elapsed(),
822 if rat.cortex_recorded {
823 StageOutcome::Ok
824 } else {
825 StageOutcome::Failed
826 },
827 );
828 maybe_ratification = Some(rat);
829 }
830 }
831 }
832 canary_summary = Some(summary);
833 } else {
834 let balance_verdict = BalanceKernel::evaluate(
835 telemetry.soul_tension.drive_score,
836 telemetry.soul_tension.humanity_score,
837 );
838 maybe_balance = Some(balance_verdict);
839 }
840 if winning_proposal.is_some() {
841 // The canary stage is the supervised block minus the CortexCommit time inside it.
842 let canary_time = canary_started
843 .elapsed()
844 .saturating_sub(clock.duration(Stage::CortexCommit));
845 clock.record(
846 Stage::SupervisorCanary,
847 canary_time,
848 if success {
849 StageOutcome::Ok
850 } else {
851 StageOutcome::Refused
852 },
853 );
854 }
855 // Checkpoint ledger Merkle root with TPM signer
856 let _ = ledger.checkpoint(Some(&signing_key));
857
858 let elapsed_ms = start.elapsed().as_secs_f64() * 1000.0;
859
860 Ok(RsiCycleResult {
861 cycle_id,
862 telemetry,
863 proposal: winning_proposal,
864 invariants: maybe_invariants,
865 balance: maybe_balance,
866 receipt: maybe_receipt,
867 generation: maybe_generation,
868 ledger_block: maybe_ledger_block,
869 ratification: maybe_ratification,
870 success,
871 elapsed_ms,
872 scarcity,
873 canary: canary_summary,
874 })
875 }
876
877 /// Rolls the staged generation back through the supervisor and records the reason.
878 async fn roll_back(
879 supervisor_daemon: &SupervisorDaemon,
880 active_link: &Path,
881 ledger: &ImprovementLedger,
882 proposal: &crate::models::ImprovementProposal,
883 reason: &str,
884 ) -> Result<(), String> {
885 supervisor_daemon
886 .trigger_instant_rollback(active_link)
887 .await?;
888 let _ = ledger.append_rollback(&proposal.id, reason);
889 Ok(())
890 }
891
892 /// Records the quota, envelope and promotion gate decisions for the generation. The
893 /// envelope entry carries the reference-backend note.
894 fn record_decision(ledger: &ImprovementLedger, generation_id: &str, summary: &CanarySummary) {
895 let payload = serde_json::json!({
896 "canary_decision": {
897 "generation_id": generation_id,
898 "identity_binding_digest": summary.identity_binding_digest,
899 "log_digest": summary.log_digest,
900 "commitment_block_hash": summary.commitment_block_hash,
901 "quota": summary.quota,
902 "envelope": summary.envelope,
903 "envelope_note": summary.envelope_note,
904 "promotion_gate": summary.promotion_gate,
905 }
906 });
907 let _ = ledger.append_block(BlockType::Evaluation, payload.to_string(), vec![]);
908 }
909
910 /// Runs the supervisor-driven canary for the staged generation and the quota decision.
911 /// Returns the digest the safety envelope takes as its subject, or the refusal reason; the
912 /// caller rolls back on `Err`. A configured exemption skips the canary and returns the
913 /// patch digest.
914 #[allow(clippy::too_many_arguments)]
915 async fn admit_canary(
916 config: &RsiConfig,
917 ledger: &ImprovementLedger,
918 proposal: &crate::models::ImprovementProposal,
919 sandbox_dir: &Path,
920 patch_digest: &[u8; 32],
921 build: Option<&(LoadedAdapterManifest, PathBuf)>,
922 workload: Option<&PinnedWorkload>,
923 supervisor_daemon: &SupervisorDaemon,
924 supervisor_config: &SupervisorConfig,
925 gen_info: &mut GenerationInfo,
926 summary: &mut CanarySummary,
927 ) -> Result<[u8; 32], String> {
928 if let Some(refusal) = summary.refusal.as_ref().filter(|_| summary.applicable) {
929 return Err(format!(
930 "canary refused, candidate not eligible: {}",
931 refusal
932 ));
933 }
934 if !summary.applicable {
935 return Ok(*patch_digest);
936 }
937 let (Some((adapter, built)), Some(workload)) = (build, workload) else {
938 return Err(
939 "canary applies but no adapter or pinned workload was resolved".to_string(),
940 );
941 };
942
943 // Identity chain: patch, evaluated tree, built executable, generation.
944 let evaluated_tree = tree_digest(sandbox_dir)?;
945 let staged_tree = tree_digest(&gen_info.installed_path)?;
946 if staged_tree != evaluated_tree {
947 return Err(format!(
948 "staged tree digest {} differs from the evaluated tree digest {}",
949 staged_tree, evaluated_tree
950 ));
951 }
952 let exe_name = built
953 .file_name()
954 .ok_or_else(|| format!("adapter executable path {:?} has no file name", built))?;
955 let exe_dir = gen_info.installed_path.join(".rsi-canary");
956 std::fs::create_dir_all(&exe_dir)
957 .map_err(|e| format!("cannot create {:?}: {}", exe_dir, e))?;
958 let staged_exe = exe_dir.join(exe_name);
959 std::fs::copy(built, &staged_exe)
960 .map_err(|e| format!("cannot stage executable {:?}: {}", built, e))?;
961 let identity = CandidateIdentity::new(
962 &hex::encode(patch_digest),
963 &evaluated_tree,
964 &digest_file(&staged_exe)?,
965 &proposal.id,
966 );
967 identity.validate()?;
968 let binding = identity.binding_digest();
969 summary.identity_binding_digest = Some(binding.clone());
970 summary.executable_digest = Some(identity.executable_digest.clone());
971
972 // Collect and seal: the supervisor issues every request and measures every answer.
973 let executor = CanaryExecutor::new(
974 &supervisor_daemon.supervisor,
975 supervisor_config.clone(),
976 workload.clone(),
977 identity.clone(),
978 staged_exe,
979 adapter.manifest.args.clone(),
980 ExecutorConfig::default(),
981 );
982 let (sealed, exec_summary) = match executor.run(gen_info).await? {
983 ExecutionOutcome::Sealed { sealed, summary } => (sealed, summary),
984 ExecutionOutcome::Halted { .. } => {
985 return Err("canary run halted without sealing; refusing".to_string())
986 }
987 };
988 summary.execution = Some(CanaryExecutionRecord {
989 requests_planned: exec_summary.requests_planned,
990 issued: exec_summary.issued,
991 verified_success: exec_summary.verified_success,
992 wrong_result: exec_summary.wrong_result,
993 timeout: exec_summary.timeout,
994 invalid_response: exec_summary.invalid_response,
995 connection_closed: exec_summary.connection_closed,
996 rejections: exec_summary.rejections,
997 ready: exec_summary.ready,
998 reverted: exec_summary.reverted,
999 first_failure: exec_summary.first_failure.clone(),
1000 });
1001 summary.log_digest = Some(sealed.seal.log_digest.clone());
1002
1003 // The ledger holds the commitment before quota admission runs.
1004 let commitment = serde_json::json!({
1005 "canary_commitment": {
1006 "generation_id": identity.generation_id,
1007 "patch_digest": identity.patch_digest,
1008 "tree_digest": identity.tree_digest,
1009 "executable_digest": identity.executable_digest,
1010 "identity_binding_digest": binding,
1011 "workload_id": workload.manifest.workload_id,
1012 "workload_digest": workload.digest,
1013 "adapter_manifest_digest": adapter.digest,
1014 "sealed_log_path": sealed.path.as_ref().map(|p| p.display().to_string()),
1015 "log_digest": sealed.seal.log_digest,
1016 "observation_count": sealed.seal.observation_count,
1017 "qualifying_count": sealed.seal.qualifying_count,
1018 "rejection_count": sealed.rejections.len(),
1019 }
1020 });
1021 let block = ledger
1022 .append_block(BlockType::Evaluation, commitment.to_string(), vec![])
1023 .map_err(|e| format!("cannot commit the sealed log to the ledger: {}", e))?;
1024 summary.commitment_block_hash = Some(block.block_hash);
1025
1026 // Quota admission: the one authority on evidence sufficiency.
1027 match admit_sealed_quota(&sealed, &identity, &workload.manifest, config.canary_target) {
1028 Ok(decision) => {
1029 summary.quota = Some(QuotaDecisionRecord {
1030 admitted: true,
1031 counted: Some(decision.counted),
1032 target: decision.target,
1033 refusal: None,
1034 });
1035 }
1036 Err(reason) => {
1037 let reason = match exec_summary.first_failure {
1038 Some(f) => format!("{} (first failure: {})", reason, f),
1039 None => reason,
1040 };
1041 summary.quota = Some(QuotaDecisionRecord {
1042 admitted: false,
1043 counted: None,
1044 target: config.canary_target,
1045 refusal: Some(reason.clone()),
1046 });
1047 return Err(reason);
1048 }
1049 }
1050
1051 let mut subject = [0u8; 32];
1052 hex::decode_to_slice(&binding, &mut subject)
1053 .map_err(|e| format!("identity binding digest is not 32 bytes of hex: {}", e))?;
1054 Ok(subject)
1055 }
1056
1057 pub async fn run_daemon(config: RsiConfig) -> Result<(), String> {
1058 tracing::info!(
1059 "Starting continuous RSI daemon for repository {:?} with interval {}s",
1060 config.target_repo,
1061 config.loop_interval_secs
1062 );
1063
1064 loop {
1065 match Self::run_cycle(&config).await {
1066 Ok(res) => {
1067 tracing::info!(
1068 "RSI cycle {} completed in {:.2}ms (success: {}, proposed: {}, admitted: {})",
1069 res.cycle_id,
1070 res.elapsed_ms,
1071 res.success,
1072 res.proposal.is_some(),
1073 res.receipt.as_ref().map(|r| r.admitted).unwrap_or(true)
1074 );
1075 if config.dual_price_vector_dir.is_some() {
1076 tracing::info!(
1077 "DUAL scarcity reading (diagnostic only): {}",
1078 res.scarcity.summary()
1079 );
1080 }
1081 }
1082 Err(e) => {
1083 tracing::error!("RSI cycle failed with error: {}", e);
1084 }
1085 }
1086
1087 tokio::time::sleep(tokio::time::Duration::from_secs(config.loop_interval_secs)).await;
1088 }
1089 }
1090}
1091
1092/// Loads the operator's canary workload. The digest pin is mandatory: an unpinned workload fails
1093/// closed, and a workload that does not hash to the pin is refused.
1094fn load_pinned_workload(config: &RsiConfig, rsi_root: &Path) -> Result<PinnedWorkload, String> {
1095 let pin = config.canary_workload_sha256.as_deref().ok_or_else(|| {
1096 "canary_workload_sha256 is not set: the operator must pin the canary workload".to_string()
1097 })?;
1098 let path = config
1099 .canary_workload_path
1100 .as_ref()
1101 .map(PathBuf::from)
1102 .unwrap_or_else(|| rsi_root.join("canary").join("workload.json"));
1103 CanaryWorkloadManifest::load_pinned(&path, pin)
1104}