1use crate::layer0::vocabulary::{HANDLE_VCARD};
2use std::fs;
3use clap::Subcommand;
4use std::path::Path;
5
6pub fn compile_evaluator_cache(_clm_root: &Path, _quiet: bool) -> Result<(), String> {
7 Ok(())
10}
11
12pub fn extract_bootstrap_script(clm_root: &Path) -> Result<String, String> {
13 let self_clm = clm_root.join("computable_knowledge/Abstract/layer5_system/bootstrap/evaluator/clmEval.yaml");
14 if !self_clm.exists() {
15 return Err(format!("clmEval.yaml not found at {:?}", self_clm));
16 }
17 let content = fs::read_to_string(&self_clm)
18 .map_err(|e| format!("Failed to read clmEval.yaml: {}", e))?;
19
20 let data: serde_yaml::Value = serde_yaml::from_str(&content)
21 .map_err(|e| format!("Failed to parse clmEval.yaml: {}", e))?;
22
23 let clm_data = data.get("clm").unwrap_or(&data);
24 let concrete_impl = clm_data.get("concrete_impl").ok_or("No concrete_impl in clmEval.yaml")?;
25 let process = concrete_impl.get("process").ok_or("No process in clmEval.yaml")?;
26
27 let script = match process {
28 serde_yaml::Value::Mapping(map) => {
29 map.get("script").and_then(|v| v.as_str()).map(|s| s.to_string())
30 }
31 serde_yaml::Value::Sequence(seq) => {
32 let mut s = None;
33 for val in seq {
34 if let serde_yaml::Value::Mapping(map) = val
35 && map.get("type").and_then(|v| v.as_str()) == Some("shell") {
36 s = map.get("script").and_then(|v| v.as_str()).map(|s| s.to_string());
37 break;
38 }
39 }
40 s
41 }
42 _ => None,
43 };
44
45 script.ok_or_else(|| "Could not extract shell bootstrap script from clmEval.yaml".to_string())
46}
47
48#[derive(Subcommand, Debug, Clone)]
49pub enum ToolCommands {
50 #[command(name = "run")]
51 Run {
52 tool_handle: String,
53 #[arg(long)]
54 source_dir: Option<String>,
55 #[arg(num_args = 0..)]
56 args: Vec<String>,
57 },
58 #[command(name = "document")]
59 Document,
60}
61
62#[derive(Subcommand, Debug, Clone)]
63pub enum EvolveCommands {
64 #[command(name = "status")]
65 Status {
66 #[arg(long)]
67 timeslot: Option<String>,
68 },
69 #[command(name = "step")]
70 Step,
71 #[command(name = "report")]
72 Report,
73}
74
75pub fn run_tool_dispatcher(cmd: ToolCommands, clm_root: &str) -> Result<String, String> {
76 match cmd {
77 ToolCommands::Run { tool_handle, source_dir, args } => {
78 let clm_path = Path::new(clm_root);
79
80 let yaml_filename = format!("{}.yaml", tool_handle.replace(":", "_"));
82 let yaml_path = clm_path.join("types/governance").join(&yaml_filename);
83
84 if !yaml_path.exists() {
85 return Err(format!("[ERROR] Tool spec not found: {:?}", yaml_path));
86 }
87
88 let yaml_content = std::fs::read_to_string(&yaml_path).map_err(|e| e.to_string())?;
89 let spec: serde_yaml::Value = serde_yaml::from_str(&yaml_content).map_err(|e| e.to_string())?;
90
91 let script_val = spec.get("clm")
92 .and_then(|v| v.get("concrete_impl"))
93 .and_then(|v| v.get("process"))
94 .and_then(|v| v.get("script"))
95 .and_then(|v| v.as_str());
96
97 if let Some(script_rel_path) = script_val {
98 let script_path = clm_path.join(script_rel_path);
99 if !script_path.exists() {
100 return Err(format!("[ERROR] Script not found: {:?}", script_path));
101 }
102
103 let mut cmd = std::process::Command::new("python3");
104 cmd.arg(&script_path);
105
106 if let Some(dir) = source_dir {
107 cmd.arg("--source_dir");
108 cmd.arg(&dir);
109 }
110 for arg in args {
111 cmd.arg(&arg);
112 }
113
114 let res = cmd.output().map_err(|e| e.to_string())?;
115 let mut out = format!("[TOOL DISPATCHER] Executed tool: {}\n", tool_handle);
116 out.push_str(&String::from_utf8_lossy(&res.stdout));
117 if !res.stderr.is_empty() {
118 out.push_str("\n[STDERR]\n");
119 out.push_str(&String::from_utf8_lossy(&res.stderr));
120 }
121 Ok(out)
122 } else {
123 Err(format!("[ERROR] Invalid tool spec in {:?}: missing clm.concrete_impl.process.script", yaml_path))
124 }
125 }
126 ToolCommands::Document => {
127 Ok("# CLM Executable Tools Registry\n\n- `tool:layer_boundary_checker`: Verifies layer boundaries across the Rust workspace.\n- `tool:rust_interpreter_reporter`: Analyzes the Rust CLM Interpreter and generates an architecture report.\n".to_string())
128 }
129 }
130}
131
132pub fn run_evolve_dispatcher(cmd: EvolveCommands, clm_root: &str) -> Result<String, String> {
133 match cmd {
134 EvolveCommands::Status { timeslot } => {
135 let slot = timeslot.unwrap_or_else(|| {
136 let now = chrono::Local::now();
137 let iso_week = chrono::Datelike::iso_week(&now);
138 format!("{:04}_w{:02}", iso_week.year(), iso_week.week())
139 });
140 let db_name = format!("pkc_evol_{}.db", slot);
141
142 let count = if let Ok(conn) = crate::db::get_connection("evolution", clm_root) {
143 conn.query_row(
144 "SELECT COUNT(*) FROM handle_registry WHERE handle LIKE 'run:evolution:transition:%'",
145 [],
146 |row| row.get::<_, i64>(0)
147 ).unwrap_or(0)
148 } else {
149 0
150 };
151
152 Ok(format!(
153 "[EVOLVE STATUS] Active Time-Slot: {}\nDatabase: {}\nVerified Transitions: {}\nStatus: Ready for next step.\n",
154 slot, db_name, count
155 ))
156 }
157 EvolveCommands::Step => {
158 let gov_dir = Path::new(clm_root).join("types/governance");
159 if !gov_dir.exists() {
160 return Err(format!("Governance directory not found: {:?}", gov_dir));
161 }
162
163 let mut executed_count = 0;
164 let mut failed_count = 0;
165 let mut skipped_count = 0;
166
167 for entry in fs::read_dir(&gov_dir).map_err(|e| e.to_string())? {
168 let entry = entry.map_err(|e| e.to_string())?;
169 let path = entry.path();
170 let file_name = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
171
172 if file_name.starts_with("b_mcard_") && file_name.ends_with(".yaml") {
173 let b_mcard_name = file_name.trim_start_matches("b_mcard_").trim_end_matches(".yaml");
174 let handle_name = format!("run:evolution:transition:{}", b_mcard_name);
175
176 if let Ok(Some(_)) = crate::db::resolve_handle_hash("evolution", clm_root, &handle_name) {
177 skipped_count += 1;
178 continue;
179 }
180
181 let path_str = path.to_string_lossy().to_string();
182 let val = match crate::parser::parse_manifest(&path_str) {
183 Ok(v) => v,
184 Err(e) => {
185 failed_count += 1;
186 println!("[EVOLVE STEP] Failed to parse B-MCard {:?}: {}", path, e);
187 continue;
188 }
189 };
190
191 let polyglot_cases = val.pointer("/clm/balanced_exp/polyglot_cases")
192 .and_then(|v| v.as_array());
193
194 if let Some(cases) = polyglot_cases {
195 let mut b_mcard_ok = true;
196 println!("[EVOLVE STEP] Verifying transition '{}'...", b_mcard_name);
197
198 for case in cases {
199 let name = case.get("name").and_then(|v| v.as_str()).unwrap_or("unnamed");
200 let assertions = case.get("then").and_then(|v| v.as_array());
201
202 if let Some(asserts) = assertions {
203 for assertion in asserts {
204 if let Some(cmd_str) = assertion.get("assert_success").and_then(|v| v.as_str()) {
205 let shell = if cfg!(windows) { crate::fs_utils::get_bash_command() } else { "sh".to_string() };
207 let mut command = std::process::Command::new(shell);
208 command.arg("-c").arg(cmd_str);
209 let output = match command.output() {
210 Ok(out) => out,
211 Err(e) => {
212 b_mcard_ok = false;
213 println!(" ❌ Case '{}' failed: could not execute: {}", name, e);
214 break;
215 }
216 };
217 if !output.status.success() {
218 b_mcard_ok = false;
219 println!(" ❌ Case '{}' failed (exit code = {}).", name, output.status.code().unwrap_or(1));
220 let stderr = String::from_utf8_lossy(&output.stderr);
221 if !stderr.is_empty() {
222 println!(" Stderr: {}", stderr.trim());
223 }
224 break;
225 } else {
226 println!(" ✅ Case '{}' assertion passed.", name);
227 }
228 }
229 }
230 }
231 if !b_mcard_ok {
232 break;
233 }
234 }
235
236 if b_mcard_ok {
237 let g_time = crate::fs_utils::compute_g_time();
238 let sponsor_did = crate::layer0::environment::var("ACTIVE_AGENT_DID").unwrap_or_else(|_| crate::layer0::vocabulary_identities::DID_PKC_CA_DARWIN_ROOT_AGENT.to_string());
239 let pre_hash = val.pointer("/clm/abstract_spec/invariants/preconditions")
240 .and_then(|v| v.as_array())
241 .map(|a| crate::fs_utils::compute_content_hash(&format!("{:?}", a)))
242 .unwrap_or_default();
243 let post_hash = val.pointer("/clm/abstract_spec/invariants/postconditions")
244 .and_then(|v| v.as_array())
245 .map(|a| crate::fs_utils::compute_content_hash(&format!("{:?}", a)))
246 .unwrap_or_default();
247
248 let vcard_content = format!(
249 "{HANDLE_VCARD}\n g_time: \"{}\"\n transition: \"{}\"\n status: \"VERIFIED\"\n pre_hash: \"{}\"\n post_hash: \"{}\"\n sponsor_did: \"{}\"\n",
250 g_time, b_mcard_name, pre_hash, post_hash, sponsor_did
251 );
252 let content_hash = crate::fs_utils::compute_content_hash(&vcard_content);
253
254 if let Err(e) = crate::db::handle_register_batch(
255 "evolution",
256 clm_root,
257 &handle_name,
258 &crate::hash::prefixed(&content_hash),
259 &vcard_content,
260 ) {
261 failed_count += 1;
262 println!("[EVOLVE STEP] Failed to register transition handle: {}", e);
263 } else {
264 executed_count += 1;
265 println!("[EVOLVE STEP] Verified and registered transition '{}'.", b_mcard_name);
266 }
267 } else {
268 failed_count += 1;
269 }
270 }
271 }
272 }
273
274 Ok(format!(
275 "[EVOLVE STEP] Completed. Executed: {}, Skipped: {}, Failed: {}\n",
276 executed_count, skipped_count, failed_count
277 ))
278 }
279 EvolveCommands::Report => {
280 generate_evolution_audit_report(clm_root)
281 }
282 }
283}
284
285pub fn generate_evolution_audit_report(clm_root: &str) -> Result<String, String> {
286 let mut table_rows = Vec::new();
287
288 if let Ok(conn) = crate::db::get_connection("evolution", clm_root) {
289 let mut stmt = match conn.prepare(
290 "SELECT hr.handle, hr.current_hash, hr.updated_at, c.content \
291 FROM handle_registry hr \
292 JOIN card c ON hr.current_hash = c.hash \
293 WHERE hr.handle LIKE 'run:evolution:transition:%' \
294 ORDER BY hr.updated_at ASC;"
295 ) {
296 Ok(s) => s,
297 Err(e) => return Err(e.to_string()),
298 };
299
300 let mut rows = match stmt.query([]) {
301 Ok(r) => r,
302 Err(e) => return Err(e.to_string()),
303 };
304
305 while let Ok(Some(row)) = rows.next() {
306 let handle: String = row.get(0).unwrap_or_default();
307 let _current_hash: String = row.get(1).unwrap_or_default();
308 let updated_at: String = row.get(2).unwrap_or_default();
309 let content: String = row.get(3).unwrap_or_default();
310
311 let mut transition = handle.trim_start_matches("run:evolution:transition:").to_string();
312 let mut status = "UNKNOWN".to_string();
313 let mut sponsor_did = "UNKNOWN".to_string();
314 let mut pre_hash = "UNKNOWN".to_string();
315 let mut post_hash = "UNKNOWN".to_string();
316
317 for line in content.lines() {
318 let line_trimmed = line.trim();
319 if line_trimmed.starts_with("transition:") {
320 transition = line_trimmed.trim_start_matches("transition:").trim_matches('"').trim().to_string();
321 } else if line_trimmed.starts_with("status:") {
322 status = line_trimmed.trim_start_matches("status:").trim_matches('"').trim().to_string();
323 } else if line_trimmed.starts_with("sponsor_did:") {
324 sponsor_did = line_trimmed.trim_start_matches("sponsor_did:").trim_matches('"').trim().to_string();
325 } else if line_trimmed.starts_with("pre_hash:") {
326 pre_hash = line_trimmed.trim_start_matches("pre_hash:").trim_matches('"').trim().to_string();
327 } else if line_trimmed.starts_with("post_hash:") {
328 post_hash = line_trimmed.trim_start_matches("post_hash:").trim_matches('"').trim().to_string();
329 }
330 }
331
332 table_rows.push(format!(
333 "| {} | {} | {} | {} | `{}` | `{}` |",
334 updated_at, transition, status, sponsor_did, pre_hash, post_hash
335 ));
336 }
337 }
338
339 let rows_str = if table_rows.is_empty() {
340 "No transitions recorded in the current epoch.\n".to_string()
341 } else {
342 let mut table = "| Timestamp | Transition | Status | Sponsor DID | Pre Ingress Hash | Post Egress Hash |\n".to_string();
343 table.push_str("| --- | --- | --- | --- | --- | --- |\n");
344 for r in table_rows {
345 table.push_str(&r);
346 table.push('\n');
347 }
348 table
349 };
350
351 let report_content = format!(
352 "# CLM Evolution Audit Report\n\n\
353 Generated: {}\n\n\
354 ## Verified Transitions\n\n\
355 {}\n",
356 chrono::Local::now().to_rfc2822(),
357 rows_str
358 );
359
360 let path = Path::new(clm_root).join("docs/spec/consensus_audit_report.md");
361 if let Some(parent) = path.parent() {
362 std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
363 }
364 std::fs::write(&path, &report_content).map_err(|e| e.to_string())?;
365
366 Ok(format!("Evolution audit report generated at: {:?}", path))
367}