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 / canary / mod.rs

170 lines · 6628 bytes Raw Blame History
1//! Supervisor-driven canary contract: the shared definitions every M2 worker builds on.
2//!
3//! Approved plan: docs/plans/2026-10-12-evidence-driven-rsi-cut.md. Glossary: CONTEXT.md.
4//! Format reference: docs/CANARY-CONTRACT.md.
5//!
6//! The one rule above everything: no candidate-controlled statement can independently
7//! establish that a canary passed. The supervisor issues every request, measures the elapsed
8//! time itself, compares the answer against the pinned workload, and durably records the
9//! verified observation. Only such observations reach the quota validator.
10//!
11//! Pieces, in the order a cycle uses them:
12//! - [`adapter`]: the declared canary adapter manifest a target repository ships
13//! (`canary-adapter.toml`). No manifest, no canary: the target fails closed.
14//! - [`workload`]: the digest-pinned request set with expected outcomes and deadlines, owned
15//! by the operator under the RSI state directory, never by the candidate.
16//! - [`identity`]: the bound candidate identity chain (patch, evaluated tree, built
17//! executable, generation).
18//! - the wire protocol: `ExecuteRequest` and `ExecuteResult` in [`crate::supervisor::ipc`].
19//! - [`observation`]: the version 2 observation record, its canonical encoding, digest and
20//! derived identity.
21//! - [`log`]: the per-generation append-only observation log, sealed with a final digest.
22//! - [`admission`]: the hand-off from a sealed log to the quota validator.
23//!
24//! Every digest is lowercase hex SHA-256. Structured digests are domain separated: the domain
25//! string and then each field are written length-prefixed (u64 little endian, then the bytes),
26//! the same scheme as the version 2 evaluation receipt. Canonical JSON is one object with keys
27//! in byte order, no insignificant whitespace, integers only (never floats).
28
29pub mod adapter;
30pub mod admission;
31pub mod identity;
32pub mod log;
33pub mod observation;
34pub mod workload;
35
36pub use adapter::{CanaryAdapterManifest, LoadedAdapterManifest, ADAPTER_MANIFEST_FILE};
37pub use admission::{admit_sealed_quota, SealedQuotaDecision};
38pub use identity::CandidateIdentity;
39pub use log::{
40 AppendOutcome, LogHeader, LogRecord, LogRejection, LogSeal, LogState, ObservationLogWriter,
41 SealedObservationLog,
42};
43pub use observation::{
44 observation_id, result_digest, CanaryObservationV2, Provenance, VerifiedStatus,
45};
46pub use workload::{CanaryRequestSpec, CanaryWorkloadManifest, Nondeterminism, PinnedWorkload};
47
48use sha2::{Digest, Sha256};
49
50/// Version of the supervisor-to-worker execute protocol: `ExecuteRequest`, `ExecuteResult`
51/// and the `protocol_version` a worker states in `Ready`.
52pub const CANARY_PROTOCOL_VERSION: u16 = 1;
53/// Version of [`CanaryObservationV2`]. Version 1 is `crate::canary_observation`, kept as is.
54pub const OBSERVATION_RECORD_VERSION: u16 = 2;
55/// Version of the observation log line format.
56pub const OBSERVATION_LOG_VERSION: u16 = 1;
57/// Version of the workload manifest.
58pub const WORKLOAD_VERSION: u16 = 1;
59/// Version of the adapter manifest.
60pub const ADAPTER_MANIFEST_VERSION: u16 = 1;
61/// Version of the candidate identity chain.
62pub const IDENTITY_VERSION: u16 = 1;
63
64pub(crate) fn sha256_hex(bytes: &[u8]) -> String {
65 hex::encode(Sha256::digest(bytes))
66}
67
68/// Domain-separated, length-prefixed SHA-256 over `fields`.
69pub(crate) fn domain_digest(domain: &str, fields: &[&[u8]]) -> String {
70 let mut h = Sha256::new();
71 crate::evaluator::put_field(&mut h, domain.as_bytes());
72 for f in fields {
73 crate::evaluator::put_field(&mut h, f);
74 }
75 hex::encode(h.finalize())
76}
77
78/// Sixty-four lowercase hex characters.
79pub(crate) fn is_hex_digest(s: &str) -> bool {
80 s.len() == 64 && s.bytes().all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f'))
81}
82
83/// Canonical JSON: keys in byte order at every level, no whitespace, serde_json string
84/// escaping. Independent of serde_json's map ordering feature. Only plain structs of strings,
85/// integers, booleans, enums and vectors are encoded here, so serialization cannot fail.
86pub(crate) fn canonical_json<T: serde::Serialize>(value: &T) -> Vec<u8> {
87 let v = serde_json::to_value(value).expect("canary records serialize to JSON values");
88 let mut out = Vec::new();
89 write_canonical(&v, &mut out);
90 out
91}
92
93fn write_canonical(v: &serde_json::Value, out: &mut Vec<u8>) {
94 use serde_json::Value;
95 match v {
96 Value::Null => out.extend_from_slice(b"null"),
97 Value::Bool(b) => out.extend_from_slice(if *b { b"true" } else { b"false" }),
98 Value::Number(n) => out.extend_from_slice(n.to_string().as_bytes()),
99 Value::String(s) => write_json_string(s, out),
100 Value::Array(items) => {
101 out.push(b'[');
102 for (i, item) in items.iter().enumerate() {
103 if i > 0 {
104 out.push(b',');
105 }
106 write_canonical(item, out);
107 }
108 out.push(b']');
109 }
110 Value::Object(map) => {
111 let mut keys: Vec<&String> = map.keys().collect();
112 keys.sort();
113 out.push(b'{');
114 for (i, k) in keys.iter().enumerate() {
115 if i > 0 {
116 out.push(b',');
117 }
118 write_json_string(k, out);
119 out.push(b':');
120 write_canonical(&map[*k], out);
121 }
122 out.push(b'}');
123 }
124 }
125}
126
127fn write_json_string(s: &str, out: &mut Vec<u8>) {
128 let encoded = serde_json::to_string(s).expect("strings serialize");
129 out.extend_from_slice(encoded.as_bytes());
130}
131
132#[cfg(test)]
133mod tests {
134 use super::*;
135
136 #[test]
137 fn canonical_json_sorts_keys_and_strips_whitespace() {
138 #[derive(serde::Serialize)]
139 struct Rec {
140 zeta: u64,
141 alpha: String,
142 mid: Vec<u16>,
143 }
144 let bytes = canonical_json(&Rec {
145 zeta: 7,
146 alpha: "a\"b\n".into(),
147 mid: vec![2, 1],
148 });
149 assert_eq!(
150 String::from_utf8(bytes).unwrap(),
151 "{\"alpha\":\"a\\\"b\\n\",\"mid\":[2,1],\"zeta\":7}"
152 );
153 }
154
155 #[test]
156 fn hex_digest_check_is_strict() {
157 assert!(is_hex_digest(&sha256_hex(b"x")));
158 assert!(!is_hex_digest(&sha256_hex(b"x").to_uppercase()));
159 assert!(!is_hex_digest("abc"));
160 }
161
162 #[test]
163 fn domain_digest_separates_domains_and_field_boundaries() {
164 assert_ne!(domain_digest("a", &[b"xy"]), domain_digest("b", &[b"xy"]));
165 assert_ne!(
166 domain_digest("a", &[b"x", b"y"]),
167 domain_digest("a", &[b"xy"])
168 );
169 }
170}