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

193 lines · 7625 bytes Raw Blame History
1//! The canary adapter manifest: what a target repository ships to declare how its built
2//! artifact can be exercised as a worker. A target without one is not eligible for canary and
3//! fails closed. The manifest names the executable and arguments; it never names the workload
4//! content or any passing criterion, which belong to the operator's pinned workload.
5
6use super::{sha256_hex, ADAPTER_MANIFEST_VERSION, CANARY_PROTOCOL_VERSION};
7use serde::{Deserialize, Serialize};
8use std::path::{Component, Path, PathBuf};
9
10/// File name at the root of the target repository (and so of the evaluated tree).
11pub const ADAPTER_MANIFEST_FILE: &str = "canary-adapter.toml";
12/// The only response format of protocol version 1: the worker answers with UTF-8 text that
13/// must equal the expected output byte for byte.
14pub const RESPONSE_FORMAT_UTF8_EXACT: &str = "utf8-exact";
15
16#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17#[serde(deny_unknown_fields)]
18pub struct CanaryAdapterManifest {
19 pub manifest_version: u16,
20 pub protocol_version: u16,
21 /// Path of the executable relative to the build output root the engine passes. Never
22 /// absolute, never climbing.
23 pub executable: String,
24 #[serde(default)]
25 pub args: Vec<String>,
26 /// Must equal the `workload_id` of the operator's pinned workload.
27 pub workload_id: String,
28 pub response_format: String,
29}
30
31/// A manifest read from a tree together with the digest of its exact bytes.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct LoadedAdapterManifest {
34 pub manifest: CanaryAdapterManifest,
35 pub digest: String,
36 pub path: PathBuf,
37}
38
39impl CanaryAdapterManifest {
40 pub fn parse(text: &str) -> Result<Self, String> {
41 let manifest: Self = toml::from_str(text)
42 .map_err(|e| format!("canary adapter manifest does not parse: {}", e))?;
43 manifest.validate()?;
44 Ok(manifest)
45 }
46
47 pub fn validate(&self) -> Result<(), String> {
48 if self.manifest_version != ADAPTER_MANIFEST_VERSION {
49 return Err(format!(
50 "canary adapter manifest version {} is not supported (expected {})",
51 self.manifest_version, ADAPTER_MANIFEST_VERSION
52 ));
53 }
54 if self.protocol_version != CANARY_PROTOCOL_VERSION {
55 return Err(format!(
56 "canary adapter protocol version {} is not supported (expected {})",
57 self.protocol_version, CANARY_PROTOCOL_VERSION
58 ));
59 }
60 validate_relative_executable(&self.executable)?;
61 for arg in &self.args {
62 if arg.contains('\0') {
63 return Err("canary adapter argument contains NUL".to_string());
64 }
65 }
66 if self.workload_id.trim().is_empty() || self.workload_id.chars().any(char::is_control) {
67 return Err("canary adapter workload id is required and must be printable".to_string());
68 }
69 if self.response_format != RESPONSE_FORMAT_UTF8_EXACT {
70 return Err(format!(
71 "canary adapter response format {:?} is not supported (expected {:?})",
72 self.response_format, RESPONSE_FORMAT_UTF8_EXACT
73 ));
74 }
75 Ok(())
76 }
77
78 /// Whether `tree_root` declares an adapter at all. Declared is not the same as valid.
79 pub fn is_declared(tree_root: &Path) -> bool {
80 tree_root.join(ADAPTER_MANIFEST_FILE).is_file()
81 }
82
83 /// Reads and validates the manifest at the root of `tree_root`. A missing manifest is an
84 /// error: the target is not eligible for canary.
85 pub fn load_from_tree(tree_root: &Path) -> Result<LoadedAdapterManifest, String> {
86 let path = tree_root.join(ADAPTER_MANIFEST_FILE);
87 if !path.is_file() {
88 return Err(format!(
89 "target {:?} ships no {}: not eligible for canary",
90 tree_root, ADAPTER_MANIFEST_FILE
91 ));
92 }
93 let text =
94 std::fs::read_to_string(&path).map_err(|e| format!("cannot read {:?}: {}", path, e))?;
95 let manifest = Self::parse(&text)?;
96 Ok(LoadedAdapterManifest {
97 manifest,
98 digest: sha256_hex(text.as_bytes()),
99 path,
100 })
101 }
102
103 /// Digest of the exact manifest bytes.
104 pub fn digest_of_text(text: &str) -> String {
105 sha256_hex(text.as_bytes())
106 }
107
108 /// Where the declared executable is expected inside `build_output_root`.
109 pub fn executable_path(&self, build_output_root: &Path) -> PathBuf {
110 build_output_root.join(&self.executable)
111 }
112}
113
114fn validate_relative_executable(executable: &str) -> Result<(), String> {
115 if executable.trim().is_empty() {
116 return Err("canary adapter executable is required".to_string());
117 }
118 if executable.contains('\\') || executable.contains('\0') {
119 return Err("canary adapter executable contains a backslash or NUL".to_string());
120 }
121 let path = Path::new(executable);
122 if path.is_absolute() {
123 return Err(format!(
124 "canary adapter executable {:?} must be relative to the build output",
125 executable
126 ));
127 }
128 for comp in path.components() {
129 match comp {
130 Component::Normal(_) => {}
131 _ => {
132 return Err(format!(
133 "canary adapter executable {:?} must not climb or use special components",
134 executable
135 ))
136 }
137 }
138 }
139 Ok(())
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145
146 const VALID: &str = r#"
147manifest_version = 1
148protocol_version = 1
149executable = "release/rsi-canary-fixture"
150args = ["--adapter"]
151workload_id = "fixture-v1"
152response_format = "utf8-exact"
153"#;
154
155 #[test]
156 fn parses_a_valid_manifest() {
157 let m = CanaryAdapterManifest::parse(VALID).unwrap();
158 assert_eq!(m.executable, "release/rsi-canary-fixture");
159 assert_eq!(m.args, vec!["--adapter".to_string()]);
160 assert_eq!(
161 m.executable_path(Path::new("/tmp/out")),
162 PathBuf::from("/tmp/out/release/rsi-canary-fixture")
163 );
164 }
165
166 #[test]
167 fn refuses_absolute_climbing_unknown_and_wrong_versions() {
168 let abs = VALID.replace("release/rsi-canary-fixture", "/usr/bin/true");
169 assert!(CanaryAdapterManifest::parse(&abs).is_err());
170 let climb = VALID.replace("release/rsi-canary-fixture", "../outside");
171 assert!(CanaryAdapterManifest::parse(&climb).is_err());
172 let inner_climb = VALID.replace("release/rsi-canary-fixture", "release/../x");
173 assert!(CanaryAdapterManifest::parse(&inner_climb).is_err());
174 let fmt = VALID.replace("utf8-exact", "anything-goes");
175 assert!(CanaryAdapterManifest::parse(&fmt).is_err());
176 let proto = VALID.replace("protocol_version = 1", "protocol_version = 2");
177 assert!(CanaryAdapterManifest::parse(&proto).is_err());
178 let criteria = format!("{}\npass_if = \"always\"\n", VALID);
179 assert!(CanaryAdapterManifest::parse(&criteria).is_err());
180 }
181
182 #[test]
183 fn missing_manifest_is_not_eligible() {
184 let tmp = tempfile::tempdir().unwrap();
185 assert!(!CanaryAdapterManifest::is_declared(tmp.path()));
186 let err = CanaryAdapterManifest::load_from_tree(tmp.path()).unwrap_err();
187 assert!(err.contains("not eligible for canary"));
188
189 std::fs::write(tmp.path().join(ADAPTER_MANIFEST_FILE), VALID).unwrap();
190 let loaded = CanaryAdapterManifest::load_from_tree(tmp.path()).unwrap();
191 assert_eq!(loaded.digest, CanaryAdapterManifest::digest_of_text(VALID));
192 }
193}