1#![allow(unused_imports)]
2use std::collections::{BTreeMap, HashMap};
3use std::path::{Path, PathBuf};
4use super::*;
5
6#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
11pub struct RuntimeScriptInput {
12 pub runtime: String,
13 pub script: String,
14 #[serde(default)]
15 pub env: HashMap<String, String>,
16 #[serde(default)]
17 pub entry_point: String,
18 #[serde(default)]
19 pub cargo_test: String,
20 #[serde(default)]
21 pub args: Vec<String>,
22 #[serde(default)]
23 pub clm_root: String,
24 #[serde(default)]
25 pub source_file: Option<String>,
26 #[serde(default)]
27 pub source_name: Option<String>,
28 #[serde(default)]
29 pub theorem_name: Option<String>,
30 #[serde(default)]
31 pub profile_id: Option<String>,
32 #[serde(default)]
33 pub config_file: Option<String>,
34 #[serde(default)]
35 pub staged_files: BTreeMap<String, String>,
36 #[serde(default)]
37 pub strict: bool,
38 #[serde(default)]
39 pub isolated_empty_path: bool,
40}
41
42#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
44pub struct RuntimeScriptOutput {
45 pub exit_code: i32,
46 pub stdout: String,
47 pub stderr: String,
48}
49
50#[cfg(feature = "native")]
51fn dispatch_formal_input(
52 runtime: &str,
53 input: &RuntimeScriptInput,
54 clm_root: &str,
55) -> Result<crate::layer4::FormalDispatchOutcome, String> {
56 let target = crate::layer4::formal_contract::resolve_formal_target(
57 runtime,
58 input.profile_id.as_deref(),
59 None,
60 None,
61 clm_root,
62 )?;
63 let ep_raw = input.entry_point.as_str();
64 let (prof_id, ep_opt) = if let Some(p) = input.profile_id.as_deref().filter(|s| !s.is_empty()) {
65 (Some(p.to_string()), (!ep_raw.is_empty()).then(|| ep_raw.to_string()))
66 } else if !ep_raw.is_empty() && target.known_profiles.contains(ep_raw) {
67 (Some(ep_raw.to_string()), None)
68 } else {
69 (None, (!ep_raw.is_empty()).then(|| ep_raw.to_string()))
70 };
71 let (src_file, src_text, src_name, extra_args) =
72 if let Some(sf) = input.source_file.as_deref().filter(|s| !s.is_empty()) {
73 (Some(sf.to_string()), None, None, input.args.clone())
74 } else if !input.script.is_empty() || input.source_name.as_deref().is_some_and(|s| !s.is_empty()) {
75 let sname = input
76 .source_name
77 .as_deref()
78 .filter(|s| !s.is_empty())
79 .map(String::from)
80 .unwrap_or_else(|| format!("Spec{}", target.default_extension));
81 (None, Some(input.script.clone()), Some(sname), input.args.clone())
82 } else if let Some((first, rest)) = input.args.split_first() {
83 (Some(first.clone()), None, None, rest.to_vec())
84 } else {
85 return Err("Formal oracle requires script content or source file path".to_string());
86 };
87 let req = crate::layer4::FormalExecutionRequest {
88 runtime_id: runtime.to_string(),
89 profile_id: prof_id,
90 source_file: src_file,
91 source_text: src_text,
92 source_name: src_name,
93 theorem_name: input.theorem_name.clone(),
94 entry_point: ep_opt,
95 extra_args,
96 config_file: input.config_file.clone(),
97 staged_files: input.staged_files.clone(),
98 strict: input.strict,
99 isolated_empty_path: input.isolated_empty_path,
100 clm_root: clm_root.to_string(),
101 ..Default::default()
102 };
103 let env_ref = if input.env.is_empty() && !input.isolated_empty_path { None } else { Some(&input.env) };
104 crate::layer4::formal_oracle_runner::execute_formal_request(&req, env_ref)
105}
106
107pub fn exec_runtime_script(input: &RuntimeScriptInput) -> Result<RuntimeScriptOutput, String> {
109 let clm_root = if input.clm_root.is_empty() {
110 crate::layer0::environment::var(crate::layer0::vocabulary_env::ENV_CLM_ROOT).unwrap_or_default()
111 } else {
112 input.clm_root.clone()
113 };
114
115 let runtime_norm = input.runtime.trim().to_ascii_lowercase();
116 let runtime = runtime_norm.as_str();
117 let script_content = input.script.as_str();
118 let entry_point = input.entry_point.as_str();
119 let cargo_test_name = input.cargo_test.as_str();
120 let pos_args = &input.args;
121
122 let (code, out, err) = match runtime {
123 "shell" => {
124 let entry_call = if !entry_point.is_empty() {
125 let mut call = format!("{} ", entry_point);
126 for a in pos_args {
127 call.push_str(&format!("\"{}\" ", a.replace('"', "\\\"")));
128 }
129 call
130 } else {
131 String::new()
132 };
133 let full_script = format!("{}\n{}", script_content, entry_call);
134 let mut cmd = create_sandboxed_command(
135 &crate::fs_utils::get_bash_command(),
136 &["-c".to_string(), full_script],
137 &input.env,
138 &clm_root,
139 );
140 let output = cmd.output().map_err(|e| format!("Failed to spawn bash: {}", e))?;
141 (
142 output.status.code().unwrap_or(0),
143 String::from_utf8_lossy(&output.stdout).into_owned(),
144 String::from_utf8_lossy(&output.stderr).into_owned(),
145 )
146 }
147 "python" => {
148 let py_cmd = resolve_python_cmd(&clm_root);
149 let mut cmd_args = vec!["-c".to_string(), script_content.to_string()];
150 cmd_args.extend(pos_args.clone());
151 let mut py_env = input.env.clone();
152 py_env.insert("PYTHONPATH".to_string(), format!("{}/kernel/clm_py_core", clm_root));
153 let mut cmd = create_sandboxed_command(&py_cmd, &cmd_args, &py_env, &clm_root);
154 let output = cmd.output().map_err(|e| format!("Failed to spawn python: {}", e))?;
155 (
156 output.status.code().unwrap_or(0),
157 String::from_utf8_lossy(&output.stdout).into_owned(),
158 String::from_utf8_lossy(&output.stderr).into_owned(),
159 )
160 }
161 "node" => {
162 let rand_id = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
163 let temp_dir = std::env::temp_dir().join("clm_execution_logs/.tmp");
164 let _ = std::fs::create_dir_all(&temp_dir);
165 let temp_file = temp_dir.join(format!("clm_node_inline_{}_{}.cjs", rand_id, std::process::id()));
166 std::fs::write(&temp_file, script_content).map_err(|e| format!("Failed to write node inline script: {}", e))?;
167 let mut cmd_args = vec!["--trace-uncaught".to_string(), temp_file.to_string_lossy().to_string()];
168 cmd_args.extend(pos_args.clone());
169 let mut cmd = create_sandboxed_command("node", &cmd_args, &input.env, &clm_root);
170 let output = cmd.output();
171 let _ = std::fs::remove_file(&temp_file);
172 let output = output.map_err(|e| format!("Failed to spawn node: {}", e))?;
173 (
174 output.status.code().unwrap_or(0),
175 String::from_utf8_lossy(&output.stdout).into_owned(),
176 String::from_utf8_lossy(&output.stderr).into_owned(),
177 )
178 }
179 "rust" => {
180 if !cargo_test_name.is_empty() {
181 let self_exe = resolve_self_exe(&clm_root);
182 let mut cmd = create_sandboxed_command(
183 &self_exe.to_string_lossy(),
184 &["run-test".to_string(), cargo_test_name.to_string()],
185 &input.env,
186 &clm_root,
187 );
188 cmd.current_dir(Path::new(&clm_root).join("kernel/clm_rust_core"));
189 let output = cmd.output().map_err(|e| format!("Failed to spawn clm_rust_core: {}", e))?;
190 (
191 output.status.code().unwrap_or(if output.status.success() { 0 } else { 1 }),
192 String::from_utf8_lossy(&output.stdout).into_owned(),
193 String::from_utf8_lossy(&output.stderr).into_owned(),
194 )
195 } else {
196 let rand_id = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0);
197 let pid = std::process::id();
198 let temp_dir = std::env::temp_dir().join("clm_execution_logs/.tmp");
199 let _ = std::fs::create_dir_all(&temp_dir);
200 let src_file = temp_dir.join(format!("clm_rust_inline_{}_{}.rs", rand_id, pid));
201 let bin_file = temp_dir.join(format!("clm_rust_bin_{}_{}", rand_id, pid));
202 let full_rust_src = if !script_content.contains("fn main") {
203 format!("use std::io::{{self, Read}};\nfn main() {{\n{}\n}}", script_content)
204 } else {
205 script_content.to_string()
206 };
207 std::fs::write(&src_file, full_rust_src).map_err(|e| format!("Failed to write rust inline source: {}", e))?;
208 let compile_output = std::process::Command::new("rustc").arg("-O").arg("-o").arg(&bin_file).arg(&src_file).output();
209 let _ = std::fs::remove_file(&src_file);
210 let compile_res = compile_output.map_err(|e| format!("Failed to run rustc: {}", e))?;
211 if !compile_res.status.success() {
212 return Ok(RuntimeScriptOutput {
213 exit_code: 1,
214 stdout: String::new(),
215 stderr: format!("Rust compilation failed:\n{}", String::from_utf8_lossy(&compile_res.stderr)),
216 });
217 }
218 let mut cmd = std::process::Command::new(&bin_file);
219 cmd.args(pos_args).envs(&input.env).current_dir(&clm_root);
220 let output = cmd.output();
221 let _ = std::fs::remove_file(&bin_file);
222 let output = output.map_err(|e| format!("Failed to run rust binary: {}", e))?;
223 (
224 output.status.code().unwrap_or(0),
225 String::from_utf8_lossy(&output.stdout).into_owned(),
226 String::from_utf8_lossy(&output.stderr).into_owned(),
227 )
228 }
229 }
230 #[cfg(feature = "native")]
231 "lean" | "coq" | "rocq" | "julia" | "tlaplus" | "tla" | "tlc" | "apalache" | "java" => {
232 let outcome = dispatch_formal_input(runtime, input, &clm_root)?;
233 (outcome.exit_code, outcome.stdout, outcome.stderr)
234 }
235 _ => return Err(format!("Unsupported runtime: {}", input.runtime)),
236 };
237
238 Ok(RuntimeScriptOutput { exit_code: code, stdout: out, stderr: err })
239}
240
241#[cfg(all(test, feature = "native"))]
242mod formal_dispatch_tests {
243 use super::*;
244
245 #[test]
246 fn test_formal_oracle_dispatches_native() {
247 let valid_input = RuntimeScriptInput {
248 runtime: "lean".to_string(),
249 script: "theorem clc02_rust_bridge_ok : 2 + 2 = 4 := rfl\n".to_string(),
250 ..Default::default()
251 };
252 let valid_out = exec_runtime_script(&valid_input).expect("native formal dispatch");
253 let valid_witness: crate::layer4::OracleWitness = serde_json::from_str(&valid_out.stdout).expect("witness json");
254 assert_eq!(valid_out.exit_code, 0);
255 assert_eq!(valid_witness.status, crate::layer4::OracleWitnessStatus::Verified);
256 assert_eq!(valid_witness.argv, vec!["lean", "--json", "Spec.lean"]);
257
258 let sorry_input = RuntimeScriptInput {
259 runtime: "lean".to_string(),
260 script: "theorem clc02_rust_bridge_sorry : 1 = 1 := by sorry\n".to_string(),
261 ..Default::default()
262 };
263 let sorry_out = exec_runtime_script(&sorry_input).expect("native formal sorry dispatch");
264 let sorry_witness: crate::layer4::OracleWitness = serde_json::from_str(&sorry_out.stdout).expect("sorry witness json");
265 assert_eq!(sorry_out.exit_code, 1);
266 assert_eq!(sorry_witness.status, crate::layer4::OracleWitnessStatus::Refuted);
267
268 let tla_isolated = RuntimeScriptInput {
269 runtime: "tla".to_string(),
270 script: "---- MODULE M ----\n====\n".to_string(),
271 source_name: Some("M.tla".to_string()),
272 isolated_empty_path: true,
273 ..Default::default()
274 };
275 let tla_out = exec_runtime_script(&tla_isolated).expect("tla alias dispatch");
276 let tla_w: crate::layer4::OracleWitness = serde_json::from_str(&tla_out.stdout).expect("tla witness json");
277 assert_eq!(tla_w.runtime_id, "tlaplus");
278 assert_eq!(tla_w.profile_id, "tlc");
279 assert_eq!(tla_w.status, crate::layer4::OracleWitnessStatus::SkippedUnavailable);
280 }
281}