Skip to main content

clm_rust_core/layer1/
action.rs

1//! Layer 1: Declarative Action Manifest Engine & Baldwin Modularity Manipulators
2//! Canonical Path: kernel/clm_rust_core/src/layer1/action.rs
3
4use std::collections::HashMap;
5use std::path::Path;
6use serde::{Deserialize, Serialize};
7use serde_json::{json, Value};
8
9/// Format of data processed by an Action
10#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
11#[serde(rename_all = "lowercase")]
12pub enum ActionFormat {
13    Csv,
14    Json,
15    Yaml,
16    Markdown,
17    Text,
18    Binary,
19    Media,
20}
21
22/// Baldwin modularity operators (Baldwin & Clark, 2000)
23#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "lowercase")]
25pub enum BaldwinOperator {
26    Split,
27    Substitute,
28    Augment,
29    Exclude,
30    Invert,
31    Port,
32    Custom,
33}
34
35impl std::fmt::Display for BaldwinOperator {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        match self {
38            BaldwinOperator::Split => write!(f, "split"),
39            BaldwinOperator::Substitute => write!(f, "substitute"),
40            BaldwinOperator::Augment => write!(f, "augment"),
41            BaldwinOperator::Exclude => write!(f, "exclude"),
42            BaldwinOperator::Invert => write!(f, "invert"),
43            BaldwinOperator::Port => write!(f, "port"),
44            BaldwinOperator::Custom => write!(f, "custom"),
45        }
46    }
47}
48
49#[derive(Debug, Clone, Serialize, Deserialize)]
50pub struct ActionMetadata {
51    #[serde(default = "default_action_type")]
52    pub r#type: String,
53    pub name: String,
54    #[serde(skip_serializing_if = "Option::is_none")]
55    pub description: Option<String>,
56    #[serde(default = "default_face")]
57    pub face: String,
58    pub operator: BaldwinOperator,
59    #[serde(default = "default_author")]
60    pub author: String,
61}
62
63fn default_action_type() -> String { "action".to_string() }
64fn default_face() -> String { "C".to_string() }
65fn default_author() -> String { crate::layer0::vocabulary_identities::DID_CLM_SYSTEM.to_string() }
66
67#[derive(Debug, Clone, Serialize, Deserialize)]
68pub struct ActionInput {
69    pub name: String,
70    #[serde(skip_serializing_if = "Option::is_none")]
71    pub uri: Option<String>,
72    #[serde(skip_serializing_if = "Option::is_none")]
73    pub format: Option<String>,
74    #[serde(default = "default_true")]
75    pub required: bool,
76    #[serde(skip_serializing_if = "Option::is_none")]
77    pub description: Option<String>,
78}
79
80fn default_true() -> bool { true }
81
82#[derive(Debug, Clone, Serialize, Deserialize)]
83pub struct ActionPrecondition {
84    pub invariant: String,
85    pub rule: String,
86    #[serde(skip_serializing_if = "Option::is_none")]
87    pub schema_ref: Option<String>,
88    #[serde(skip_serializing_if = "Option::is_none")]
89    pub description: Option<String>,
90}
91
92#[derive(Debug, Clone, Serialize, Deserialize)]
93pub struct ActionOperation {
94    pub operator: BaldwinOperator,
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub strategy: Option<String>,
97    #[serde(default)]
98    pub parameters: HashMap<String, Value>,
99    #[serde(default = "default_runtime")]
100    pub runtime: String,
101}
102
103fn default_runtime() -> String { "builtin".to_string() }
104
105#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct ActionPostcondition {
107    pub invariant: String,
108    pub rule: String,
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub schema_ref: Option<String>,
111    #[serde(skip_serializing_if = "Option::is_none")]
112    pub description: Option<String>,
113}
114
115#[derive(Debug, Clone, Serialize, Deserialize)]
116pub struct ActionOutput {
117    pub name: String,
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub handle: Option<String>,
120    #[serde(skip_serializing_if = "Option::is_none")]
121    pub format: Option<String>,
122    #[serde(skip_serializing_if = "Option::is_none")]
123    pub description: Option<String>,
124}
125
126#[derive(Debug, Clone, Serialize, Deserialize)]
127pub struct ActionManifest {
128    #[serde(default = "default_version")]
129    pub version: String,
130    pub clm: ActionMetadata,
131    pub inputs: Vec<ActionInput>,
132    #[serde(default)]
133    pub preconditions: Vec<ActionPrecondition>,
134    pub operation: ActionOperation,
135    #[serde(default)]
136    pub postconditions: Vec<ActionPostcondition>,
137    pub outputs: Vec<ActionOutput>,
138}
139
140fn default_version() -> String { "1.0".to_string() }
141
142impl ActionManifest {
143    pub fn from_yaml_str(yaml_str: &str) -> Result<Self, String> {
144        let manifest: ActionManifest = serde_yaml::from_str(yaml_str)
145            .map_err(|e| format!("Failed to parse YAML ActionManifest: {}", e))?;
146        if manifest.clm.operator != manifest.operation.operator {
147            return Err(format!(
148                "Operator mismatch: clm.operator='{}' != operation.operator='{}'",
149                manifest.clm.operator, manifest.operation.operator
150            ));
151        }
152        Ok(manifest)
153    }
154
155    pub fn from_yaml_file<P: AsRef<Path>>(path: P) -> Result<Self, String> {
156        let content = std::fs::read_to_string(path.as_ref())
157            .map_err(|e| format!("Cannot read file {}: {}", path.as_ref().display(), e))?;
158        Self::from_yaml_str(&content)
159    }
160
161    pub fn to_canonical_json_value(&self) -> Value {
162        serde_json::to_value(self).unwrap_or(Value::Null)
163    }
164}
165
166// ── Canonical Hashing Helpers ────────────────────────────────────────────────
167
168pub use crate::layer0::codec::sort_json_value;
169
170pub fn compute_canonical_serialized(val: &Value) -> String {
171    crate::layer0::codec::canonical_json(val).unwrap_or_default()
172}
173
174pub fn compute_canonical_hash(val: &Value) -> String {
175    let s = compute_canonical_serialized(val);
176    blake3::hash(s.as_bytes()).to_hex().to_string()
177}
178
179pub fn clm_hash_string(s: &str) -> String {
180    blake3::hash(s.as_bytes()).to_hex().to_string()
181}
182
183// ── Modality Manipulators ───────────────────────────────────────────────────
184
185pub struct TabularManipulator;
186
187impl TabularManipulator {
188    pub fn parse_csv(text: &str) -> (Vec<String>, Vec<Vec<String>>) {
189        let mut lines = text.lines().filter(|l| !l.trim().is_empty());
190        let header_line = match lines.next() {
191            Some(h) => h,
192            None => return (vec![], vec![]),
193        };
194        let headers: Vec<String> = header_line.split(',').map(|s| s.trim().to_string()).collect();
195        let mut rows = Vec::new();
196        for line in lines {
197            let row: Vec<String> = line.split(',').map(|s| s.trim().to_string()).collect();
198            rows.push(row);
199        }
200        (headers, rows)
201    }
202
203    pub fn render_csv(headers: &[String], rows: &[Vec<String>]) -> String {
204        let mut out = String::new();
205        if !headers.is_empty() {
206            out.push_str(&headers.join(","));
207            out.push('\n');
208        }
209        for r in rows {
210            out.push_str(&r.join(","));
211            out.push('\n');
212        }
213        out
214    }
215
216    pub fn split(data: &str, params: &HashMap<String, Value>) -> Result<HashMap<String, String>, String> {
217        let (headers, rows) = Self::parse_csv(data);
218        if rows.is_empty() {
219            let mut res = HashMap::new();
220            res.insert("part_1".to_string(), Self::render_csv(&headers, &[]));
221            res.insert("part_2".to_string(), Self::render_csv(&headers, &[]));
222            return Ok(res);
223        }
224
225        if let Some(Value::Object(ratios)) = params.get("ratios") {
226            let total = rows.len();
227            let mut partitions = HashMap::new();
228            let mut current_idx = 0;
229            let ratio_list: Vec<(&String, f64)> = ratios
230                .iter()
231                .map(|(k, v)| (k, v.as_f64().unwrap_or(0.0)))
232                .collect();
233
234            for (i, (name, ratio)) in ratio_list.iter().enumerate() {
235                let part_rows = if i == ratio_list.len() - 1 {
236                    &rows[current_idx..]
237                } else {
238                    let count = (total as f64 * ratio).round() as usize;
239                    let end = (current_idx + count).min(total);
240                    let slice = &rows[current_idx..end];
241                    current_idx = end;
242                    slice
243                };
244                partitions.insert((*name).clone(), Self::render_csv(&headers, part_rows));
245            }
246            return Ok(partitions);
247        }
248
249        let mid = rows.len() / 2;
250        let mut partitions = HashMap::new();
251        partitions.insert("part_1".to_string(), Self::render_csv(&headers, &rows[..mid]));
252        partitions.insert("part_2".to_string(), Self::render_csv(&headers, &rows[mid..]));
253        Ok(partitions)
254    }
255
256    pub fn substitute(data: &str, params: &HashMap<String, Value>) -> Result<String, String> {
257        let (mut headers, rows) = Self::parse_csv(data);
258        if let (Some(target), Some(replacement)) = (
259            params.get("target_column").and_then(|v| v.as_str()),
260            params.get("replacement_column").and_then(|v| v.as_str()),
261        ) {
262            for h in &mut headers {
263                if h == target {
264                    *h = replacement.to_string();
265                }
266            }
267        } else if let Some(Value::Object(rename)) = params.get("rename_columns") {
268            for h in &mut headers {
269                if let Some(new_name) = rename.get(h).and_then(|v| v.as_str()) {
270                    *h = new_name.to_string();
271                }
272            }
273        }
274        Ok(Self::render_csv(&headers, &rows))
275    }
276
277    pub fn augment(data: &str, params: &HashMap<String, Value>) -> Result<String, String> {
278        let (mut headers, rows) = Self::parse_csv(data);
279        let col_name = params.get("column_name")
280            .or_else(|| params.get("target_column"))
281            .and_then(|v| v.as_str())
282            .unwrap_or("augmented_col");
283        let default_val = params.get("default_value")
284            .or_else(|| params.get("constant_value"))
285            .map(|v| match v {
286                Value::String(s) => s.clone(),
287                other => other.to_string(),
288            })
289            .unwrap_or_else(|| "active".to_string());
290
291        headers.push(col_name.to_string());
292        let mut new_rows = Vec::new();
293        for r in rows {
294            let mut nr = r;
295            nr.push(default_val.clone());
296            new_rows.push(nr);
297        }
298        Ok(Self::render_csv(&headers, &new_rows))
299    }
300
301    pub fn exclude(data: &str, params: &HashMap<String, Value>) -> Result<String, String> {
302        let (headers, rows) = Self::parse_csv(data);
303        let mut drop_cols = Vec::new();
304        if let Some(Value::Array(cols)) = params.get("columns").or_else(|| params.get("target_columns")) {
305            for c in cols {
306                if let Some(s) = c.as_str() {
307                    drop_cols.push(s.to_string());
308                }
309            }
310        }
311
312        let keep_indices: Vec<usize> = headers
313            .iter()
314            .enumerate()
315            .filter(|(_, h)| !drop_cols.contains(h))
316            .map(|(i, _)| i)
317            .collect();
318
319        let new_headers: Vec<String> = keep_indices.iter().map(|&i| headers[i].clone()).collect();
320        let mut new_rows = Vec::new();
321        for r in rows {
322            let nr: Vec<String> = keep_indices.iter().filter(|&&i| i < r.len()).map(|&i| r[i].clone()).collect();
323            new_rows.push(nr);
324        }
325        Ok(Self::render_csv(&new_headers, &new_rows))
326    }
327
328    pub fn invert(data: &str, params: &HashMap<String, Value>) -> Result<String, String> {
329        let (headers, mut rows) = Self::parse_csv(data);
330        let strategy = params.get("strategy").and_then(|v| v.as_str()).unwrap_or("reverse_rows");
331        if strategy == "transpose" && !headers.is_empty() {
332            let mut matrix = vec![headers];
333            matrix.extend(rows);
334            let cols = matrix[0].len();
335            let mut transposed = Vec::new();
336            for c in 0..cols {
337                let mut row = Vec::new();
338                for r in 0..matrix.len() {
339                    if c < matrix[r].len() {
340                        row.push(matrix[r][c].clone());
341                    }
342                }
343                transposed.push(row);
344            }
345            let new_headers = transposed.first().cloned().unwrap_or_default();
346            let new_rows = if transposed.len() > 1 { transposed[1..].to_vec() } else { vec![] };
347            return Ok(Self::render_csv(&new_headers, &new_rows));
348        }
349        rows.reverse();
350        Ok(Self::render_csv(&headers, &rows))
351    }
352
353    pub fn port(data: &str, params: &HashMap<String, Value>) -> Result<String, String> {
354        let (headers, rows) = Self::parse_csv(data);
355        let target_format = params.get("target_format").and_then(|v| v.as_str()).unwrap_or("json").to_lowercase();
356        if target_format == "json" {
357            let mut records = Vec::new();
358            for r in rows {
359                let mut obj = serde_json::Map::new();
360                for (i, h) in headers.iter().enumerate() {
361                    let val = if i < r.len() { r[i].clone() } else { String::new() };
362                    obj.insert(h.clone(), Value::String(val));
363                }
364                records.push(Value::Object(obj));
365            }
366            return serde_json::to_string_pretty(&records).map_err(|e| e.to_string());
367        }
368        Ok(Self::render_csv(&headers, &rows))
369    }
370}
371
372
373#[path = "action_manipulators.rs"]
374mod action_manipulators;
375#[allow(unused_imports)]
376pub use action_manipulators::*;
377#[path = "action_rules.rs"]
378mod action_rules;
379#[allow(unused_imports)]
380pub use action_rules::*;
381#[path = "action_sandwich.rs"]
382mod action_sandwich;
383#[allow(unused_imports)]
384pub use action_sandwich::*;