Skip to main content

qualia_core_db/poet_host/invoke/agent/
mod.rs

1//! Agent orchestration invoke family.
2//!
3//! Contains the DAG executor (R3), agent context builder, and stalk
4//! isolation. These are the wiring layers that connect VibeScript agent
5//! primitives (A1–A9) to the host capability dispatch and blackboard.
6
7pub mod dag_executor;
8pub mod orchestration;
9pub mod runtime;
10
11use crate::modalities::blackboard::BlackboardBus;
12use crate::NQuin;
13use dag_executor::{execute_pipeline, NodeExecutor};
14use std::collections::HashMap;
15use vibe::dag::{DagEdge, DagNode, DagPipeline, NodeEffect};
16use vibe::{DiagCode, Diagnostic, Span, Value};
17
18fn parse_node_effect(s: &str) -> NodeEffect {
19    match s.to_ascii_lowercase().as_str() {
20        "pure" => NodeEffect::Pure,
21        "hot" => NodeEffect::Hot,
22        "cold" => NodeEffect::Cold,
23        "async" => NodeEffect::Async,
24        "external" => NodeEffect::External,
25        _ => NodeEffect::Cold,
26    }
27}
28
29/// Parses `dag-node`.
30pub fn parse_dag_node(val: &Value, span: Span) -> Result<(DagNode, Vec<u32>), Diagnostic> {
31    match val {
32        Value::Record(map) => {
33            let id = map
34                .get("id")
35                .and_then(|v| match v {
36                    Value::I64(n) => Some(*n as u32),
37                    Value::U64(n) => Some(*n as u32),
38                    _ => None,
39                })
40                .unwrap_or(0);
41
42            let name = map
43                .get("name")
44                .and_then(|v| match v {
45                    Value::String(s) => Some(s.clone()),
46                    _ => None,
47                })
48                .unwrap_or_else(|| format!("node_{id}"));
49
50            let effect = map
51                .get("effect")
52                .and_then(|v| match v {
53                    Value::String(s) => Some(parse_node_effect(s)),
54                    _ => None,
55                })
56                .unwrap_or(NodeEffect::Cold);
57
58            let mut node = DagNode::new(id, &name, effect);
59
60            if let Some(Value::List(caps)) = map.get("capabilities") {
61                for c in caps {
62                    if let Value::String(s) = c {
63                        node.capabilities.push(s.clone());
64                    }
65                }
66            }
67
68            if let Some(Value::List(inputs)) = map.get("inputs") {
69                for inp in inputs {
70                    if let Value::String(s) = inp {
71                        node.inputs.push(s.clone());
72                    }
73                }
74            }
75
76            if let Some(Value::List(outputs)) = map.get("outputs") {
77                for out in outputs {
78                    if let Value::String(s) = out {
79                        node.outputs.push(s.clone());
80                    }
81                }
82            }
83
84            if let Some(b) = map.get("budget").and_then(|v| match v {
85                Value::I64(n) => Some(*n as u32),
86                Value::U64(n) => Some(*n as u32),
87                _ => None,
88            }) {
89                node.budget = b;
90            }
91
92            let mut deps = Vec::new();
93            if let Some(Value::List(d_list)) = map.get("depends_on") {
94                for d in d_list {
95                    if let Value::I64(n) = d {
96                        deps.push(*n as u32);
97                    } else if let Value::U64(n) = d {
98                        deps.push(*n as u32);
99                    }
100                }
101            }
102
103            Ok((node, deps))
104        }
105        _ => Err(Diagnostic::new(
106            DiagCode::E100,
107            span,
108            "expected Record for DAG node definition",
109        )),
110    }
111}
112
113/// Builds `pipeline-from-value`.
114pub fn build_pipeline_from_value(args: &Value, span: Span) -> Result<DagPipeline, Diagnostic> {
115    let mut pipeline = DagPipeline::new();
116    let (node_values, edge_values) = match args {
117        Value::List(nodes) => (nodes.as_slice(), None),
118        Value::Record(map) => {
119            let nodes = match map.get("nodes") {
120                Some(Value::List(n)) => n.as_slice(),
121                _ => {
122                    return Err(Diagnostic::new(
123                        DiagCode::E100,
124                        span,
125                        "DAG pipeline record must contain 'nodes' List",
126                    ));
127                }
128            };
129            let edges = match map.get("edges") {
130                Some(Value::List(e)) => Some(e.as_slice()),
131                _ => None,
132            };
133            (nodes, edges)
134        }
135        _ => {
136            return Err(Diagnostic::new(
137                DiagCode::E100,
138                span,
139                "DAG pipeline expects a List of nodes or a Record with 'nodes'",
140            ));
141        }
142    };
143
144    let mut all_deps = Vec::new();
145    let mut channel_producers: HashMap<String, u32> = HashMap::new();
146
147    for nv in node_values {
148        let (node, deps) = parse_dag_node(nv, span)?;
149        let id = node.id;
150        for out in &node.outputs {
151            channel_producers.insert(out.clone(), id);
152        }
153        all_deps.push((id, node.inputs.clone(), deps));
154        pipeline
155            .add_node(node)
156            .map_err(|e| Diagnostic::new(DiagCode::E100, span, format!("DAG node error: {e:?}")))?;
157    }
158
159    if let Some(edges) = edge_values {
160        for ev in edges {
161            if let Value::List(pair) = ev {
162                if pair.len() == 2 {
163                    if let (Some(from), Some(to)) = (
164                        pair[0].as_i64().map(|n| n as u32),
165                        pair[1].as_i64().map(|n| n as u32),
166                    ) {
167                        pipeline.add_edge(DagEdge::new(from, to)).map_err(|e| {
168                            Diagnostic::new(DiagCode::E100, span, format!("DAG edge error: {e:?}"))
169                        })?;
170                    }
171                }
172            }
173        }
174    } else {
175        for (id, inputs, deps) in all_deps {
176            for dep in deps {
177                let _ = pipeline.add_edge(DagEdge::new(dep, id));
178            }
179            for inp in inputs {
180                if let Some(&producer_id) = channel_producers.get(&inp) {
181                    if producer_id != id {
182                        let _ = pipeline.add_edge(DagEdge::new(producer_id, id));
183                    }
184                }
185            }
186        }
187    }
188
189    Ok(pipeline)
190}
191
192struct NoopNodeExecutor;
193
194impl NodeExecutor for NoopNodeExecutor {
195    fn execute(
196        &mut self,
197        _node_id: u32,
198        _node_name: &str,
199        _inputs: &[(String, Vec<NQuin>)],
200        _capabilities: &[String],
201    ) -> Result<Vec<(String, Vec<NQuin>)>, Diagnostic> {
202        Ok(Vec::new())
203    }
204}
205
206/// Execute a DAG pipeline via capability.invoke (R3).
207pub fn dag_execute(args: &Value, span: Span) -> Result<Value, Diagnostic> {
208    let pipeline = build_pipeline_from_value(args, span)?;
209    let mut bus = BlackboardBus::new();
210    let mut executor = NoopNodeExecutor;
211    let result = execute_pipeline(&pipeline, &mut bus, None, &mut executor).map_err(|e| {
212        Diagnostic::new(DiagCode::E600, span, format!("DAG execution error: {e:?}"))
213    })?;
214    Ok(Value::String(result.summary()))
215}
216
217/// Validate a DAG pipeline via capability.invoke (R3).
218pub fn dag_validate(args: &Value, span: Span) -> Result<Value, Diagnostic> {
219    let pipeline = build_pipeline_from_value(args, span)?;
220    pipeline.validate(&[]).map_err(|e| {
221        Diagnostic::new(DiagCode::E100, span, format!("DAG validation error: {e:?}"))
222    })?;
223    Ok(Value::Bool(true))
224}
225
226/// Status of a DAG pipeline via capability.invoke (R3).
227/// Returns a record describing the pipeline's node count, edge count, and
228/// validation status. If a pipeline is passed, it validates and reports;
229/// if null is passed, it reports the executor's readiness.
230pub fn dag_status(args: &Value, span: Span) -> Result<Value, Diagnostic> {
231    if matches!(args, Value::Null) {
232        let mut rec = std::collections::BTreeMap::new();
233        rec.insert("status".into(), Value::String("ready".into()));
234        return Ok(Value::Record(rec));
235    }
236    let pipeline = build_pipeline_from_value(args, span)?;
237    let node_count = pipeline.node_count();
238    let edge_count = pipeline.edge_count();
239    let valid = pipeline.validate(&[]).is_ok();
240    let mut rec = std::collections::BTreeMap::new();
241    rec.insert("nodes".into(), Value::U64(node_count as u64));
242    rec.insert("edges".into(), Value::U64(edge_count as u64));
243    rec.insert("valid".into(), Value::Bool(valid));
244    rec.insert(
245        "status".into(),
246        Value::String(if valid {
247            "valid".into()
248        } else {
249            "invalid".into()
250        }),
251    );
252    Ok(Value::Record(rec))
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258    use std::collections::BTreeMap;
259
260    fn make_node(id: i64, name: &str, inputs: &[&str], outputs: &[&str], budget: i64) -> Value {
261        let mut map = BTreeMap::new();
262        map.insert("id".into(), Value::I64(id));
263        map.insert("name".into(), Value::String(name.into()));
264        map.insert("effect".into(), Value::String("Cold".into()));
265        map.insert(
266            "inputs".into(),
267            Value::List(inputs.iter().map(|s| Value::String((*s).into())).collect()),
268        );
269        map.insert(
270            "outputs".into(),
271            Value::List(outputs.iter().map(|s| Value::String((*s).into())).collect()),
272        );
273        map.insert("budget".into(), Value::I64(budget));
274        Value::Record(map)
275    }
276
277    #[test]
278    fn dag_execute_single_node() {
279        let node = make_node(0, "researcher", &[], &["summary"], 100);
280        let args = Value::List(vec![node]);
281        let res = dag_execute(&args, Span::point(0)).unwrap();
282        match res {
283            Value::String(s) => {
284                assert!(s.contains("success=true"));
285                assert!(s.contains("nodes=1/1"));
286            }
287            _ => panic!("expected String result"),
288        }
289    }
290
291    #[test]
292    fn dag_validate_cycle() {
293        let mut map = BTreeMap::new();
294        let n0 = make_node(0, "node_a", &["ch_b"], &["ch_a"], 100);
295        let n1 = make_node(1, "node_b", &["ch_a"], &["ch_b"], 100);
296        map.insert("nodes".into(), Value::List(vec![n0, n1]));
297        map.insert(
298            "edges".into(),
299            Value::List(vec![
300                Value::List(vec![Value::I64(0), Value::I64(1)]),
301                Value::List(vec![Value::I64(1), Value::I64(0)]),
302            ]),
303        );
304        let args = Value::Record(map);
305        let err = dag_validate(&args, Span::point(0));
306        assert!(err.is_err());
307        let diag = err.unwrap_err();
308        assert!(
309            diag.message.contains("CycleDetected") || diag.message.contains("DAG validation error")
310        );
311    }
312
313    #[test]
314    fn dag_execute_sequential() {
315        let n0 = make_node(0, "step1", &[], &["step1_out"], 100);
316        let n1 = make_node(1, "step2", &["step1_out"], &["step2_out"], 100);
317        let args = Value::List(vec![n0, n1]);
318
319        let res = dag_execute(&args, Span::point(0)).unwrap();
320        match res {
321            Value::String(s) => {
322                assert!(s.contains("success=true"));
323                assert!(s.contains("nodes=2/2"));
324            }
325            _ => panic!("expected String result"),
326        }
327    }
328}