Skip to main content

multicast_codemode/
workflows.rs

1//! Durable callable workflow definitions and structured child admission.
2use crate::{
3    CapabilitySnapshot, CodeModeRuntime, DispatchResponse, ExecutionState, ExecutionStatus, Snippet,
4};
5use serde::{Deserialize, Serialize};
6use serde_json::{Value, json};
7use sha2::{Digest, Sha256};
8use std::collections::{BTreeMap, BTreeSet};
9
10/// Host-owned limits shared by every descendant of one root execution.
11#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
12pub struct WorkflowLimits {
13    /// Maximum child nesting depth.
14    pub depth: u32,
15    /// Maximum total child admissions, including failed children.
16    pub admissions: u32,
17    /// Maximum simultaneously executing passes; waiting parents release slots.
18    pub concurrency: usize,
19    /// Maximum connector attempts across the entire tree, including retries.
20    pub attempts: u32,
21    /// Maximum retained metadata, execution, and encoded checkpoint bytes per root.
22    pub bytes: usize,
23    /// Absolute root lifetime, including approval waits, in milliseconds.
24    pub lifetime_ms: u64,
25    /// Whether executing programs may publish and delete names.
26    pub allow_publication: bool,
27}
28impl Default for WorkflowLimits {
29    fn default() -> Self {
30        Self {
31            depth: 32,
32            admissions: 256,
33            concurrency: 8,
34            attempts: 1024,
35            bytes: 32 * 1024 * 1024,
36            lifetime_ms: 300_000,
37            allow_publication: true,
38        }
39    }
40}
41impl WorkflowLimits {
42    /// Rejects zero or otherwise invalid host limits before constructing a runtime.
43    pub fn check(&self) -> Result<(), String> {
44        if self.depth == 0
45            || self.admissions == 0
46            || self.concurrency == 0
47            || self.attempts == 0
48            || self.bytes == 0
49            || self.lifetime_ms == 0
50        {
51            return Err("WORKFLOW_LIMITS: host limits must be finite and positive".into());
52        }
53        Ok(())
54    }
55}
56
57/// Portable source and explicit data; no lexical environment is serialized.
58#[derive(Debug, Clone, Serialize, Deserialize)]
59#[serde(deny_unknown_fields)]
60pub struct WorkflowDefinition {
61    /// Async function `(input, bindings, self, peers)`.
62    pub source: String,
63    /// Bounded JSON Schema for input.
64    #[serde(default = "any_schema")]
65    pub input: Value,
66    /// Bounded JSON Schema for output.
67    #[serde(default = "any_schema")]
68    pub output: Value,
69    /// Explicit serializable bindings, including workflow references.
70    #[serde(default = "empty_object")]
71    pub bindings: Value,
72}
73fn any_schema() -> Value {
74    Value::Bool(true)
75}
76fn empty_object() -> Value {
77    json!({})
78}
79
80/// Non-secret, store-qualified immutable workflow identity.
81#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
82#[serde(deny_unknown_fields)]
83pub struct WorkflowReference {
84    /// Owning store identity; this is not an authorization credential.
85    pub store: String,
86    /// Content digest of the complete sealed definition bundle.
87    pub version: String,
88    /// Member name inside that bundle.
89    pub member: String,
90}
91/// Explicit child wait, distinct from approval and uncertain-effect reconciliation.
92#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
93pub struct WorkflowWait {
94    /// Bound execution identifiers, in input order.
95    pub children: Vec<String>,
96    /// Collect failures instead of cancelling siblings on the first failure.
97    pub settle: bool,
98}
99/// Bounded descendant diagnostic; authority and connector arguments stay private.
100#[derive(Debug, Clone, Serialize, Deserialize)]
101pub struct WorkflowChild {
102    /// Stable execution identifier used for approval, inspection, and cancellation.
103    pub id: String,
104    /// Immediate owning execution.
105    pub parent: String,
106    /// Immutable definition identity.
107    pub reference: Option<WorkflowReference>,
108    /// Current child lifecycle state.
109    pub status: ExecutionStatus,
110    /// Pending approval sequence numbers belonging to this child.
111    pub pending: Vec<u64>,
112    /// Terminal diagnostic, when present.
113    pub error: Option<String>,
114}
115#[derive(Debug, Clone, Default, Serialize, Deserialize)]
116pub(crate) struct Catalog {
117    #[serde(default)]
118    abi: u32,
119    store: String,
120    definitions: BTreeMap<String, BTreeMap<String, WorkflowDefinition>>,
121    publications: BTreeMap<String, Publication>,
122    nodes: BTreeMap<String, Node>,
123    roots: BTreeMap<String, Root>,
124    receipts: BTreeMap<String, Receipt>,
125    scopes: BTreeMap<String, Scope>,
126    #[serde(default)]
127    owners: BTreeMap<String, BTreeSet<String>>,
128    #[serde(default)]
129    deleted: BTreeSet<String>,
130}
131#[derive(Debug, Clone, Serialize, Deserialize)]
132struct Publication {
133    reference: WorkflowReference,
134    protected: bool,
135    at: u64,
136    #[serde(default)]
137    legacy: Option<Snippet>,
138}
139#[derive(Debug, Clone, Serialize, Deserialize)]
140struct Root {
141    limits: WorkflowLimits,
142    deadline: u64,
143    admissions: u32,
144    attempts: u32,
145    bytes: usize,
146}
147#[derive(Debug, Clone, Serialize, Deserialize)]
148struct Node {
149    root: String,
150    parent: Option<String>,
151    reference: Option<WorkflowReference>,
152    depth: u32,
153    bound: bool,
154    scope: String,
155    released: BTreeSet<String>,
156    observed: bool,
157    #[serde(default)]
158    dependencies: BTreeSet<String>,
159    #[serde(default)]
160    checkpoint_bytes: usize,
161    #[serde(default)]
162    execution_bytes: usize,
163}
164#[derive(Debug, Clone, Serialize, Deserialize)]
165struct Scope {
166    owner: String,
167    closed: bool,
168}
169#[derive(Debug, Clone, Serialize, Deserialize)]
170struct Receipt {
171    method: String,
172    arguments: Value,
173    result: Value,
174}
175
176fn digest(value: &impl Serialize) -> Result<String, String> {
177    Ok(format!(
178        "{:x}",
179        Sha256::digest(serde_json::to_vec(value).map_err(|e| e.to_string())?)
180    ))
181}
182fn text<'a>(args: &'a Value, key: &str) -> Result<&'a str, String> {
183    args.get(key)
184        .and_then(Value::as_str)
185        .ok_or_else(|| format!("WORKFLOW_ARGUMENT: {key} must be a string"))
186}
187fn reference(value: &Value) -> Result<WorkflowReference, String> {
188    serde_json::from_value(value.get("__workflow_ref").unwrap_or(value).clone())
189        .map_err(|_| "WORKFLOW_REFERENCE: invalid workflow reference".into())
190}
191fn wire(reference: &WorkflowReference) -> Value {
192    json!({"__workflow_ref":reference})
193}
194fn run_wire(store: &str, id: &str) -> Value {
195    json!({"__workflow_run":{"store":store,"id":id}})
196}
197fn run_id<'a>(value: &'a Value, store: &str) -> Result<&'a str, String> {
198    let r = value.get("__workflow_run").unwrap_or(value);
199    if r["store"].as_str() != Some(store) {
200        return Err("WORKFLOW_REFERENCE: foreign run store".into());
201    }
202    text(r, "id")
203}
204fn result(value: Value) -> DispatchResponse {
205    DispatchResponse {
206        result: Some(value),
207        control: None,
208        message: None,
209    }
210}
211fn pause() -> DispatchResponse {
212    DispatchResponse {
213        result: None,
214        control: Some("pause".into()),
215        message: None,
216    }
217}
218
219impl Catalog {
220    fn member(&self, r: &WorkflowReference) -> Result<&WorkflowDefinition, String> {
221        if r.store != self.store {
222            return Err("WORKFLOW_REFERENCE: foreign definition store".into());
223        }
224        self.definitions
225            .get(&r.version)
226            .and_then(|bundle| bundle.get(&r.member))
227            .ok_or_else(|| "WORKFLOW_REFERENCE: released or unknown definition".into())
228    }
229    fn root(&self, id: &str, now: u64) -> Result<&Root, String> {
230        let node = self.nodes.get(id).ok_or("WORKFLOW_ROOT_MISSING")?;
231        let root = self.roots.get(&node.root).ok_or("WORKFLOW_ROOT_MISSING")?;
232        if now >= root.deadline {
233            return Err("WORKFLOW_DEADLINE: root deadline exhausted".into());
234        }
235        Ok(root)
236    }
237    fn insert_bundle(
238        &mut self,
239        bundle: BTreeMap<String, WorkflowDefinition>,
240        owner: &str,
241    ) -> Result<Vec<WorkflowReference>, String> {
242        let version = digest(&(1u32, &bundle))?;
243        let refs = bundle
244            .keys()
245            .map(|member| WorkflowReference {
246                store: self.store.clone(),
247                version: version.clone(),
248                member: member.clone(),
249            })
250            .collect();
251        if !self.definitions.contains_key(&version) {
252            let bytes = serde_json::to_vec(&bundle)
253                .map_err(|e| e.to_string())?
254                .len();
255            let root_id = self.nodes[owner].root.clone();
256            let root = self
257                .roots
258                .get_mut(&root_id)
259                .ok_or("WORKFLOW_ROOT_MISSING")?;
260            if root.bytes.saturating_add(bytes) > root.limits.bytes {
261                return Err("WORKFLOW_BYTES: retained storage budget exhausted".into());
262            }
263            root.bytes += bytes;
264            self.definitions.insert(version, bundle);
265        }
266        Ok(refs)
267    }
268    fn validate_bindings(&self, value: &Value) -> Result<(), String> {
269        match value {
270            Value::Object(fields) if fields.contains_key("__workflow_ref") => {
271                self.member(&reference(value)?)?;
272            }
273            Value::Object(fields) => {
274                if fields.contains_key("__codemode_type") || fields.contains_key("__workflow_run") {
275                    return Err(
276                        "WORKFLOW_BINDINGS: only JSON data and workflow references are portable"
277                            .into(),
278                    );
279                }
280                for v in fields.values() {
281                    self.validate_bindings(v)?;
282                }
283            }
284            Value::Array(values) => {
285                for v in values {
286                    self.validate_bindings(v)?;
287                }
288            }
289            _ => {}
290        }
291        Ok(())
292    }
293}
294
295impl CodeModeRuntime {
296    async fn workflow_catalog(&self) -> Result<Catalog, String> {
297        let state = self.store.get_workflows().await?;
298        let mut c = match state {
299            None => Catalog {
300                store: self.store.workflow_identity().await?,
301                abi: 1,
302                ..Default::default()
303            },
304            Some(v) => {
305                let c: Catalog =
306                    serde_json::from_value(v).map_err(|e| format!("WORKFLOW_STORE: {e}"))?;
307                if c.abi != 1 {
308                    return Err("WORKFLOW_ABI: incompatible workflow metadata".into());
309                }
310                c
311            }
312        };
313        for snippet in self.store.list_snippets().await? {
314            if c.publications.contains_key(&snippet.name) || c.deleted.contains(&snippet.name) {
315                continue;
316            }
317            if c.store.is_empty() {
318                c.store = digest(&(&snippet.name, snippet.saved_at))?;
319                c.abi = 1;
320            }
321            let bundle = BTreeMap::from([(
322                "main".into(),
323                WorkflowDefinition {
324                    source: crate::normalize_code(&snippet.code),
325                    input: snippet.input_schema.clone().unwrap_or(Value::Bool(true)),
326                    output: Value::Bool(true),
327                    bindings: json!({}),
328                },
329            )]);
330            let version = digest(&(1u32, &bundle))?;
331            c.definitions.insert(version.clone(), bundle);
332            c.publications.insert(
333                snippet.name.clone(),
334                Publication {
335                    reference: WorkflowReference {
336                        store: c.store.clone(),
337                        version,
338                        member: "main".into(),
339                    },
340                    protected: false,
341                    at: snippet.saved_at,
342                    legacy: Some(snippet),
343                },
344            );
345        }
346        Ok(c)
347    }
348
349    async fn save_workflows(&self, c: &Catalog) -> Result<(), String> {
350        let v = serde_json::to_value(c).map_err(|e| e.to_string())?;
351        if serde_json::to_vec(&v).map_err(|e| e.to_string())?.len() > 32_000_000 {
352            return Err(
353                "WORKFLOW_STORE_FULL: prune retained executions before further admission".into(),
354            );
355        }
356        self.store.put_workflows(&v).await
357    }
358    fn workflow_init(
359        &self,
360        c: &mut Catalog,
361        state: &ExecutionState,
362        now: u64,
363    ) -> Result<(), String> {
364        if c.nodes.contains_key(&state.id) {
365            c.root(&state.id, now)?;
366            return Ok(());
367        }
368        self.workflow_limits.check()?;
369        if c.store.is_empty() {
370            c.store = digest(&(&state.id, now))?;
371            c.abi = 1;
372        }
373        c.roots.insert(
374            state.id.clone(),
375            Root {
376                limits: self.workflow_limits.clone(),
377                deadline: state
378                    .created_at
379                    .saturating_add(self.workflow_limits.lifetime_ms),
380                admissions: 0,
381                attempts: 0,
382                bytes: 0,
383            },
384        );
385        c.nodes.insert(
386            state.id.clone(),
387            Node {
388                root: state.id.clone(),
389                parent: None,
390                reference: None,
391                depth: 0,
392                bound: true,
393                scope: state.id.clone(),
394                released: BTreeSet::new(),
395                observed: false,
396                dependencies: BTreeSet::new(),
397                checkpoint_bytes: 0,
398                execution_bytes: 0,
399            },
400        );
401        Ok(())
402    }
403    /// Registers host-owned, protected workflow definitions without executing them.
404    pub async fn install_workflows(
405        &self,
406        definitions: BTreeMap<String, WorkflowDefinition>,
407        now: u64,
408    ) -> Result<(), String> {
409        let _guard = self.workflow_gate.lock().await;
410        let mut c = match self.workflow_catalog().await {
411            Ok(catalog) => catalog,
412            Err(error) if definitions.is_empty() && error.contains("WORKFLOW_UNSUPPORTED") => {
413                return Ok(());
414            }
415            Err(error) => return Err(error),
416        };
417        if c.store.is_empty() {
418            c.store = digest(&(now, definitions.keys().collect::<Vec<_>>()))?;
419            c.abi = 1;
420        }
421        let removed: Vec<String> = c
422            .publications
423            .iter()
424            .filter(|(name, p)| p.protected && !definitions.contains_key(*name))
425            .map(|(name, _)| name.clone())
426            .collect();
427        for name in removed {
428            let p = c
429                .publications
430                .remove(&name)
431                .ok_or("WORKFLOW_PUBLICATION_MISSING")?;
432            if let Some(snippet) = p.legacy {
433                let bundle = BTreeMap::from([(
434                    "main".into(),
435                    WorkflowDefinition {
436                        source: crate::normalize_code(&snippet.code),
437                        input: snippet.input_schema.clone().unwrap_or(Value::Bool(true)),
438                        output: Value::Bool(true),
439                        bindings: json!({}),
440                    },
441                )]);
442                let version = digest(&(1u32, &bundle))?;
443                c.definitions.insert(version.clone(), bundle);
444                c.publications.insert(
445                    name,
446                    Publication {
447                        reference: WorkflowReference {
448                            store: c.store.clone(),
449                            version,
450                            member: "main".into(),
451                        },
452                        protected: false,
453                        at: snippet.saved_at,
454                        legacy: Some(snippet),
455                    },
456                );
457            }
458        }
459        for (name, definition) in definitions {
460            validate_definition(&definition, &[], false)?;
461            let bundle = BTreeMap::from([("main".into(), definition)]);
462            let version = digest(&(1u32, &bundle))?;
463            c.definitions.insert(version.clone(), bundle);
464            c.deleted.remove(&name);
465            let legacy = c.publications.get(&name).and_then(|p| p.legacy.clone());
466            c.publications.insert(
467                name,
468                Publication {
469                    reference: WorkflowReference {
470                        store: c.store.clone(),
471                        version,
472                        member: "main".into(),
473                    },
474                    protected: true,
475                    at: now,
476                    legacy,
477                },
478            );
479        }
480        self.save_workflows(&c).await
481    }
482    pub(crate) async fn workflow_publish_snippet(&self, snippet: &Snippet) -> Result<bool, String> {
483        let _guard = self.workflow_gate.lock().await;
484        let mut c = match self.workflow_catalog().await {
485            Ok(c) => c,
486            Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(false),
487            Err(e) => return Err(e),
488        };
489        validate_name(&snippet.name)?;
490        check_publication(&c, &snippet.name, None)?;
491        if c.store.is_empty() {
492            c.store = digest(&(&snippet.name, snippet.saved_at))?;
493            c.abi = 1;
494        }
495        let d = WorkflowDefinition {
496            source: crate::normalize_code(&snippet.code),
497            input: snippet.input_schema.clone().unwrap_or(Value::Bool(true)),
498            output: Value::Bool(true),
499            bindings: json!({}),
500        };
501        validate_definition(&d, &snippet.connectors, false)?;
502        let bundle = BTreeMap::from([("main".into(), d)]);
503        let version = digest(&(1u32, &bundle))?;
504        c.definitions.insert(version.clone(), bundle);
505        c.deleted.remove(&snippet.name);
506        c.publications.insert(
507            snippet.name.clone(),
508            Publication {
509                reference: WorkflowReference {
510                    store: c.store.clone(),
511                    version,
512                    member: "main".into(),
513                },
514                protected: false,
515                at: snippet.saved_at,
516                legacy: Some(snippet.clone()),
517            },
518        );
519        self.sweep_catalog(&mut c).await?;
520        self.save_workflows(&c).await?;
521        Ok(true)
522    }
523    pub(crate) async fn workflow_snippets(&self) -> Result<Vec<Snippet>, String> {
524        let _guard = self.workflow_gate.lock().await;
525        let c = match self.workflow_catalog().await {
526            Ok(c) => c,
527            Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(Vec::new()),
528            Err(e) => return Err(e),
529        };
530        c.publications
531            .iter()
532            .filter(|(_, p)| !p.protected || p.legacy.is_some())
533            .map(|(name, p)| {
534                if let Some(s) = &p.legacy {
535                    return Ok(s.clone());
536                }
537                let d = c.member(&p.reference)?;
538                Ok(Snippet {
539                    name: name.clone(),
540                    description: "Published callable workflow".into(),
541                    code: format!(
542                        "async input => await codemode.workflows.hydrate({})(input)",
543                        wire(&p.reference)
544                    ),
545                    saved_at: p.at,
546                    input_schema: Some(d.input.clone()),
547                    connectors: Vec::new(),
548                })
549            })
550            .collect()
551    }
552    pub(crate) async fn workflow_delete_snippet(&self, name: &str) -> Result<bool, String> {
553        let _guard = self.workflow_gate.lock().await;
554        let mut c = match self.workflow_catalog().await {
555            Ok(c) => c,
556            Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(false),
557            Err(e) => return Err(e),
558        };
559        check_publication(&c, name, None)?;
560        let removed = c.publications.remove(name).is_some();
561        c.deleted.insert(name.into());
562        if removed {
563            self.sweep_catalog(&mut c).await?;
564            self.save_workflows(&c).await?;
565        }
566        Ok(removed)
567    }
568    pub(crate) async fn workflow_call(
569        &self,
570        id: &str,
571        seq: u64,
572        method: &str,
573        args: Value,
574        now: u64,
575    ) -> Result<DispatchResponse, String> {
576        let _guard = self.workflow_gate.lock().await;
577        let state = self
578            .store
579            .get_execution(id)
580            .await?
581            .ok_or("WORKFLOW_EXECUTION_MISSING")?;
582        if state.status != ExecutionStatus::Running {
583            return Ok(pause());
584        }
585        let mut c = self.workflow_catalog().await?;
586        self.workflow_init(&mut c, &state, now)?;
587        let key = format!("{id}:{seq}");
588        if let Some(receipt) = c.receipts.get(&key) {
589            if receipt.method != method || receipt.arguments != args {
590                return Err("WORKFLOW_DIVERGENCE: operation receipt differs".into());
591            }
592            return Ok(result(receipt.result.clone()));
593        }
594        let value = match method {
595            "define" | "bundle" => {
596                let bundle: BTreeMap<String, WorkflowDefinition> = if method == "define" {
597                    BTreeMap::from([(
598                        "main".into(),
599                        serde_json::from_value(args["definition"].clone())
600                            .map_err(|e| format!("WORKFLOW_DEFINITION: {e}"))?,
601                    )])
602                } else {
603                    serde_json::from_value(args["definitions"].clone())
604                        .map_err(|e| format!("WORKFLOW_DEFINITION: {e}"))?
605                };
606                if bundle.is_empty() {
607                    return Err("WORKFLOW_DEFINITION: empty bundle".into());
608                }
609                for definition in bundle.values() {
610                    validate_definition(definition, &state.connectors, true)?;
611                    c.validate_bindings(&definition.bindings)?;
612                }
613                let refs = c.insert_bundle(bundle, id)?;
614                if method == "define" {
615                    wire(&refs[0])
616                } else {
617                    Value::Object(refs.iter().map(|r| (r.member.clone(), wire(r))).collect())
618                }
619            }
620            "resolve" => {
621                let name = text(&args, "name")?;
622                if c.deleted.contains(name) {
623                    return Err(format!("WORKFLOW_NOT_FOUND: {name}"));
624                }
625                let r = if let Some(p) = c.publications.get(name) {
626                    p.reference.clone()
627                } else {
628                    let s = self
629                        .store
630                        .get_snippet(name)
631                        .await?
632                        .ok_or_else(|| format!("WORKFLOW_NOT_FOUND: {name}"))?;
633                    let d = WorkflowDefinition {
634                        source: crate::normalize_code(&s.code),
635                        input: s.input_schema.unwrap_or(Value::Bool(true)),
636                        output: Value::Bool(true),
637                        bindings: json!({}),
638                    };
639                    // Existing saved programs retain their syntax and admission behavior.
640                    c.insert_bundle(BTreeMap::from([("main".into(), d)]), id)?
641                        .remove(0)
642                };
643                if let Some(version) = args.get("version").and_then(Value::as_str)
644                    && r.version != version
645                {
646                    return Err("WORKFLOW_VERSION: publication version differs".into());
647                }
648                wire(&r)
649            }
650            "inspect" => {
651                let r = reference(&args["handle"])?;
652                let d = c.member(&r)?;
653                json!({"reference":wire(&r),"input":d.input,"output":d.output,"types":format!("WorkflowHandle<{}, {}>",crate::json_schema_to_type(&d.input),crate::json_schema_to_type(&d.output))})
654            }
655            "bind" => {
656                let r = reference(&args["handle"])?;
657                let d = c.member(&r)?.clone();
658                let values = args["values"]
659                    .as_object()
660                    .ok_or("WORKFLOW_BIND: bound values must be an object")?;
661                c.validate_bindings(&args["values"])?;
662                let mut input = d.input.clone();
663                if let Some(required) = input.get_mut("required").and_then(Value::as_array_mut) {
664                    required.retain(|v| !values.contains_key(v.as_str().unwrap_or("")));
665                }
666                if let Some(properties) = d.input.get("properties").and_then(Value::as_object) {
667                    for (key, value) in values {
668                        if let Some(schema) = properties.get(key) {
669                            crate::workflow_schema::validate(schema, value)
670                                .map_err(|e| format!("WORKFLOW_BIND: {}", e.join("; ")))?;
671                        }
672                    }
673                }
674                let bound=WorkflowDefinition {source:"async (input, bindings) => { for (const key of Object.keys(bindings.values)) { if (Object.prototype.hasOwnProperty.call(input, key)) throw new Error('WORKFLOW_BIND_OVERRIDE: bound input cannot be overridden'); } return await bindings.target({...input,...bindings.values}); }".into(),input,output:d.output,bindings:json!({"target":wire(&r),"values":values})};
675                wire(&c.insert_bundle(BTreeMap::from([("main".into(), bound)]), id)?[0])
676            }
677            "pipe" => {
678                let handles = args["handles"]
679                    .as_array()
680                    .ok_or("WORKFLOW_PIPE: expected handles")?;
681                if handles.is_empty() {
682                    return Err("WORKFLOW_PIPE: expected at least one handle".into());
683                }
684                let refs = handles
685                    .iter()
686                    .map(reference)
687                    .collect::<Result<Vec<_>, _>>()?;
688                let definitions = refs
689                    .iter()
690                    .map(|r| c.member(r).cloned())
691                    .collect::<Result<Vec<_>, _>>()?;
692                for pair in definitions.windows(2) {
693                    if schema_disjoint(&pair[0].output, &pair[1].input) {
694                        return Err("WORKFLOW_SCHEMA_INCOMPATIBLE: pipe output and input have disjoint types".into());
695                    }
696                }
697                let d=WorkflowDefinition {source:"async (input, bindings) => { let value=input; for (const handle of bindings.handles) value=await handle(value); return value; }".into(),input:definitions[0].input.clone(),output:definitions.last().unwrap().output.clone(),bindings:json!({"handles":refs.iter().map(wire).collect::<Vec<_>>()})};
698                let compatibility: Vec<_> = definitions
699                    .windows(2)
700                    .map(|pair| {
701                        if pair[1].input == Value::Bool(true)
702                            || pair[0].output == Value::Bool(false)
703                            || pair[0].output == pair[1].input
704                        {
705                            "compatible"
706                        } else {
707                            "unknown"
708                        }
709                    })
710                    .collect();
711                let mut value =
712                    wire(&c.insert_bundle(BTreeMap::from([("main".into(), d)]), id)?[0]);
713                value["__workflow_compatibility"] = json!(compatibility);
714                value
715            }
716            "start" => {
717                let r = reference(&args["handle"])?;
718                let d = c.member(&r)?.clone();
719                let scope = args.get("scope").and_then(Value::as_str).unwrap_or(id);
720                check_scope(&c, id, scope)?;
721                if c.nodes[id].released.contains(&r.version) {
722                    return Err("WORKFLOW_REFERENCE: handle released by this execution".into());
723                }
724                c.validate_bindings(&args["input"])?;
725                crate::workflow_schema::validate(&d.input, &args["input"])
726                    .map_err(|e| format!("WORKFLOW_INPUT: {}", e.join("; ")))?;
727                let child_id = format!("child_{}", digest(&(id, seq))?);
728                if !c.nodes.contains_key(&child_id) {
729                    let parent = c.nodes[id].clone();
730                    let root = c
731                        .roots
732                        .get_mut(&parent.root)
733                        .ok_or("WORKFLOW_ROOT_MISSING")?;
734                    if parent.depth >= root.limits.depth {
735                        return Err("WORKFLOW_DEPTH: recursive depth exhausted".into());
736                    }
737                    if root.admissions >= root.limits.admissions {
738                        return Err("WORKFLOW_ADMISSIONS: root child budget exhausted".into());
739                    }
740                    let bytes = serde_json::to_vec(&args).map_err(|e| e.to_string())?.len();
741                    if root.bytes.saturating_add(bytes) > root.limits.bytes {
742                        return Err("WORKFLOW_BYTES: retained storage budget exhausted".into());
743                    }
744                    root.admissions += 1;
745                    root.bytes += bytes;
746                    c.nodes.insert(
747                        child_id.clone(),
748                        Node {
749                            root: parent.root,
750                            parent: Some(id.into()),
751                            reference: Some(r.clone()),
752                            depth: parent.depth + 1,
753                            bound: false,
754                            scope: scope.into(),
755                            released: BTreeSet::new(),
756                            observed: false,
757                            dependencies: BTreeSet::new(),
758                            checkpoint_bytes: 0,
759                            execution_bytes: 0,
760                        },
761                    );
762                    self.save_workflows(&c).await?; // Reservation precedes preparation and effects.
763                }
764                let mut dependencies = BTreeSet::new();
765                collect_references(&args["input"], &mut dependencies);
766                for version in &dependencies {
767                    if !c.definitions.contains_key(version) {
768                        return Err("WORKFLOW_REFERENCE: unknown input definition".into());
769                    }
770                }
771                c.nodes
772                    .get_mut(&child_id)
773                    .ok_or("WORKFLOW_CHILD_MISSING")?
774                    .dependencies = dependencies;
775                let code = definition_program(&c, &r, &args["input"])?;
776                match self.store.get_execution(&child_id).await? {
777                    None if c.nodes[&child_id].bound => {
778                        return Err("WORKFLOW_BOUND_CHILD_MISSING: reconciliation required".into());
779                    }
780                    None => {
781                        self.begin_retained(
782                            &code,
783                            CapabilitySnapshot::new(
784                                state
785                                    .capabilities
786                                    .as_ref()
787                                    .map(|s| s.connectors.clone())
788                                    .unwrap_or_default(),
789                            )?,
790                            now,
791                            Some(
792                                c.roots[&c.nodes[id].root]
793                                    .deadline
794                                    .saturating_add(86_400_000),
795                            ),
796                            Some(child_id.clone()),
797                        )
798                        .await
799                        .map_err(|e| e.to_string())?;
800                    }
801                    Some(child) if child.code != code => {
802                        return Err("WORKFLOW_BOUND_CHILD_MISMATCH".into());
803                    }
804                    Some(_) => {}
805                }
806                c.nodes
807                    .get_mut(&child_id)
808                    .ok_or("WORKFLOW_CHILD_MISSING")?
809                    .bound = true;
810                run_wire(&c.store, &child_id)
811            }
812            "join" => {
813                let runs = args["runs"]
814                    .as_array()
815                    .ok_or("WORKFLOW_ARGUMENT: runs must be an array")?;
816                let mut ids = Vec::new();
817                for run in runs {
818                    let child = run_id(run, &c.store)?.to_string();
819                    let node = c
820                        .nodes
821                        .get(&child)
822                        .ok_or("WORKFLOW_REFERENCE: unknown run")?;
823                    if node.root != c.nodes[id].root {
824                        return Err("WORKFLOW_REFERENCE: run belongs to another root".into());
825                    }
826                    let mut ancestor = Some(id);
827                    while let Some(a) = ancestor {
828                        if a == child {
829                            return Err("WORKFLOW_WAIT_CYCLE: cannot await self or ancestor".into());
830                        }
831                        ancestor = c.nodes.get(a).and_then(|n| n.parent.as_deref());
832                    }
833                    let mut pending = vec![child.clone()];
834                    let mut visited = BTreeSet::new();
835                    while let Some(next) = pending.pop() {
836                        if next == id {
837                            return Err(
838                                "WORKFLOW_WAIT_CYCLE: wait graph would contain a cycle".into()
839                            );
840                        }
841                        if visited.insert(next.clone())
842                            && let Some(wait) = self
843                                .store
844                                .get_execution(&next)
845                                .await?
846                                .and_then(|s| s.workflow_wait)
847                        {
848                            pending.extend(wait.children);
849                        }
850                    }
851                    ids.push(child);
852                }
853                let settle = args["settle"].as_bool().unwrap_or(false);
854                let mut values = Vec::new();
855                let mut unfinished = false;
856                let mut failure = None;
857                for child in &ids {
858                    let s = self
859                        .store
860                        .get_execution(child)
861                        .await?
862                        .ok_or("WORKFLOW_BOUND_CHILD_MISSING")?;
863                    match s.status {
864                        ExecutionStatus::Completed => values.push(if settle {
865                            json!({"status":"fulfilled","value":s.result})
866                        } else {
867                            s.result.unwrap_or(Value::Null)
868                        }),
869                        ExecutionStatus::Running | ExecutionStatus::Paused => {
870                            unfinished = true;
871                        }
872                        _ => {
873                            let e = s
874                                .error
875                                .unwrap_or_else(|| format!("Child {child} {:?}", s.status));
876                            if settle {
877                                values.push(json!({"status":"rejected","reason":e}));
878                            } else {
879                                failure = Some(e);
880                            }
881                        }
882                    }
883                }
884                if unfinished && (failure.is_none() || settle) {
885                    self.save_workflows(&c).await?;
886                    self.workflow_suspend(
887                        id,
888                        WorkflowWait {
889                            children: ids,
890                            settle,
891                        },
892                        now,
893                    )
894                    .await?;
895                    return Ok(pause());
896                }
897                if failure.is_some() && !settle {
898                    for child in &ids {
899                        if !owned_descendant(&c, id, child) {
900                            continue;
901                        }
902                        let s = self
903                            .store
904                            .get_execution(child)
905                            .await?
906                            .ok_or("WORKFLOW_BOUND_CHILD_MISSING")?;
907                        if matches!(s.status, ExecutionStatus::Running | ExecutionStatus::Paused) {
908                            self.cancel(child, now).await.map_err(|e| e.to_string())?;
909                        }
910                    }
911                }
912                for child in ids {
913                    if let Some(n) = c.nodes.get_mut(&child) {
914                        n.observed = true;
915                    }
916                }
917                if let Some(e) = failure {
918                    json!({"__workflow_error":e})
919                } else {
920                    Value::Array(values)
921                }
922            }
923            "publish" => {
924                if !c.root(id, now)?.limits.allow_publication {
925                    return Err("WORKFLOW_PERMISSION: publication disabled by host".into());
926                }
927                let name = text(&args, "name")?.to_string();
928                validate_name(&name)?;
929                let r = reference(&args["handle"])?;
930                c.member(&r)?;
931                check_publication(&c, &name, args.get("expectedVersion"))?;
932                c.deleted.remove(&name);
933                c.publications.insert(
934                    name.clone(),
935                    Publication {
936                        reference: r.clone(),
937                        protected: false,
938                        at: now,
939                        legacy: None,
940                    },
941                );
942                json!({"name":name,"version":r.version,"handle":wire(&r)})
943            }
944            "delete" => {
945                if !c.root(id, now)?.limits.allow_publication {
946                    return Err("WORKFLOW_PERMISSION: deletion disabled by host".into());
947                }
948                let name = text(&args, "name")?;
949                if args
950                    .get("expectedVersion")
951                    .and_then(Value::as_str)
952                    .is_none()
953                {
954                    return Err("WORKFLOW_VERSION: deletion requires expectedVersion".into());
955                }
956                check_publication(&c, name, args.get("expectedVersion"))?;
957                let removed = c.publications.remove(name).is_some();
958                c.deleted.insert(name.into());
959                json!(removed)
960            }
961            "release" => {
962                let r = reference(&args["handle"])?;
963                c.member(&r)?;
964                c.nodes
965                    .get_mut(id)
966                    .ok_or("WORKFLOW_ROOT_MISSING")?
967                    .released
968                    .insert(r.version.clone());
969                for (owner, versions) in &mut c.owners {
970                    if owner == id || c.scopes.get(owner).is_some_and(|s| s.owner == id) {
971                        versions.remove(&r.version);
972                    }
973                }
974                Value::Null
975            }
976            "scope_open" => {
977                let scope = format!("scope_{}", digest(&(id, seq))?);
978                c.scopes.insert(
979                    scope.clone(),
980                    Scope {
981                        owner: id.into(),
982                        closed: false,
983                    },
984                );
985                json!(scope)
986            }
987            "scope_close" => {
988                let scope = text(&args, "scope")?;
989                check_scope(&c, id, scope)?;
990                let children: Vec<String> = c
991                    .nodes
992                    .iter()
993                    .filter(|(_, n)| n.parent.as_deref() == Some(id) && n.scope == scope && n.bound)
994                    .map(|(id, _)| id.clone())
995                    .collect();
996                let mut unfinished = false;
997                for child in &children {
998                    let s = self
999                        .store
1000                        .get_execution(child)
1001                        .await?
1002                        .ok_or("WORKFLOW_BOUND_CHILD_MISSING")?;
1003                    if matches!(s.status, ExecutionStatus::Running | ExecutionStatus::Paused) {
1004                        if args["failed"].as_bool().unwrap_or(false) {
1005                            self.cancel(child, now).await.map_err(|e| e.to_string())?;
1006                        } else {
1007                            unfinished = true;
1008                        }
1009                    }
1010                }
1011                if unfinished {
1012                    self.save_workflows(&c).await?;
1013                    self.workflow_suspend(
1014                        id,
1015                        WorkflowWait {
1016                            children,
1017                            settle: args["failed"].as_bool().unwrap_or(false),
1018                        },
1019                        now,
1020                    )
1021                    .await?;
1022                    return Ok(pause());
1023                }
1024                c.scopes
1025                    .get_mut(scope)
1026                    .ok_or("WORKFLOW_SCOPE_MISSING")?
1027                    .closed = true;
1028                c.owners.remove(scope);
1029                Value::Null
1030            }
1031            _ => return Err(format!("WORKFLOW_OPERATION: unsupported {method}")),
1032        };
1033        if matches!(method, "define" | "bundle" | "resolve" | "bind" | "pipe") {
1034            let scope = args.get("scope").and_then(Value::as_str).unwrap_or(id);
1035            check_scope(&c, id, scope)?;
1036            let mut refs = BTreeSet::new();
1037            collect_references(&value, &mut refs);
1038            for version in &refs {
1039                c.nodes
1040                    .get_mut(id)
1041                    .ok_or("WORKFLOW_ROOT_MISSING")?
1042                    .released
1043                    .remove(version);
1044            }
1045            c.owners.entry(scope.into()).or_default().extend(refs);
1046        }
1047        c.receipts.insert(
1048            key,
1049            Receipt {
1050                method: method.into(),
1051                arguments: args,
1052                result: value.clone(),
1053            },
1054        );
1055        self.sweep_catalog(&mut c).await?;
1056        let root_id = c.nodes[id].root.clone();
1057        let bytes = root_bytes(&c, &root_id)?;
1058        let root = c.roots.get_mut(&root_id).ok_or("WORKFLOW_ROOT_MISSING")?;
1059        if bytes > root.limits.bytes {
1060            return Err("WORKFLOW_BYTES: retained storage budget exhausted".into());
1061        }
1062        root.bytes = bytes;
1063        self.save_workflows(&c).await?;
1064        Ok(result(value))
1065    }
1066    pub(crate) async fn workflow_sweep(&self) -> Result<(), String> {
1067        let _guard = self.workflow_gate.lock().await;
1068        let mut c = match self.workflow_catalog().await {
1069            Ok(c) => c,
1070            Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(()),
1071            Err(e) => return Err(e),
1072        };
1073        if c.abi == 0 {
1074            return Ok(());
1075        }
1076        self.sweep_catalog(&mut c).await?;
1077        self.save_workflows(&c).await
1078    }
1079    async fn sweep_catalog(&self, c: &mut Catalog) -> Result<(), String> {
1080        let mut missing = BTreeSet::new();
1081        let mut terminal = BTreeSet::new();
1082        for id in c.nodes.keys() {
1083            match self.store.get_execution(id).await? {
1084                None => {
1085                    missing.insert(id.clone());
1086                }
1087                Some(s)
1088                    if !matches!(s.status, ExecutionStatus::Running | ExecutionStatus::Paused) =>
1089                {
1090                    terminal.insert(id.clone());
1091                }
1092                _ => {}
1093            }
1094        }
1095        for id in &missing {
1096            let node = &c.nodes[id];
1097            if node.bound
1098                && node
1099                    .parent
1100                    .as_ref()
1101                    .is_some_and(|parent| !missing.contains(parent) && !terminal.contains(parent))
1102            {
1103                return Err("WORKFLOW_BOUND_CHILD_MISSING: reconciliation required".into());
1104            }
1105        }
1106        // Retained child diagnostics keep their root budget and ancestry available.
1107        let retained_roots: BTreeSet<String> = c
1108            .nodes
1109            .iter()
1110            .filter(|(id, _)| !missing.contains(*id))
1111            .map(|(_, node)| node.root.clone())
1112            .collect();
1113        missing.retain(|id| !retained_roots.contains(id));
1114        for id in &missing {
1115            c.nodes.remove(id);
1116            c.owners.remove(id);
1117            c.roots.remove(id);
1118        }
1119        for id in &terminal {
1120            c.owners.remove(id);
1121        }
1122        for (scope, owner) in &c.scopes {
1123            if owner.closed || missing.contains(&owner.owner) || terminal.contains(&owner.owner) {
1124                c.owners.remove(scope);
1125            }
1126        }
1127        let mut retained: BTreeSet<String> = c
1128            .publications
1129            .values()
1130            .map(|p| p.reference.version.clone())
1131            .collect();
1132        for versions in c.owners.values() {
1133            retained.extend(versions.iter().cloned());
1134        }
1135        for node in c.nodes.values() {
1136            if let Some(r) = &node.reference {
1137                retained.insert(r.version.clone());
1138            }
1139            retained.extend(node.dependencies.iter().cloned());
1140        }
1141        loop {
1142            let before = retained.len();
1143            for version in retained.clone() {
1144                if let Some(bundle) = c.definitions.get(&version) {
1145                    for d in bundle.values() {
1146                        collect_references(&d.bindings, &mut retained);
1147                    }
1148                }
1149            }
1150            if retained.len() == before {
1151                break;
1152            }
1153        }
1154        c.definitions
1155            .retain(|version, _| retained.contains(version));
1156        c.receipts
1157            .retain(|key, _| !missing.iter().any(|id| key.starts_with(&format!("{id}:"))));
1158        c.scopes.retain(|_, s| !missing.contains(&s.owner));
1159        Ok(())
1160    }
1161    pub(crate) async fn workflow_lineage(
1162        &self,
1163        id: &str,
1164    ) -> Result<Option<(String, Option<String>, Option<WorkflowReference>)>, String> {
1165        let _guard = self.workflow_gate.lock().await;
1166        let c = match self.workflow_catalog().await {
1167            Ok(c) => c,
1168            Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(None),
1169            Err(e) => return Err(e),
1170        };
1171        Ok(c.nodes.get(id).map(|node| {
1172            (
1173                node.root.clone(),
1174                node.parent.clone(),
1175                node.reference.clone(),
1176            )
1177        }))
1178    }
1179    pub(crate) async fn workflow_children(&self, id: &str) -> Result<Vec<WorkflowChild>, String> {
1180        let _guard = self.workflow_gate.lock().await;
1181        let c = match self.workflow_catalog().await {
1182            Ok(c) => c,
1183            Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(Vec::new()),
1184            Err(e) => return Err(e),
1185        };
1186        let mut children = Vec::new();
1187        for (child, node) in &c.nodes {
1188            if owned_descendant(&c, id, child) && node.bound {
1189                let state = self
1190                    .store
1191                    .get_execution(child)
1192                    .await?
1193                    .ok_or("WORKFLOW_BOUND_CHILD_MISSING")?;
1194                children.push(WorkflowChild {
1195                    id: child.clone(),
1196                    parent: node.parent.clone().unwrap_or_default(),
1197                    reference: node.reference.clone(),
1198                    status: state.status,
1199                    pending: state
1200                        .log
1201                        .iter()
1202                        .filter(|e| e.state == crate::LogEntryState::Pending)
1203                        .map(|e| e.seq)
1204                        .collect(),
1205                    error: state.error,
1206                });
1207            }
1208        }
1209        Ok(children)
1210    }
1211    pub(crate) async fn workflow_admit_root(
1212        &self,
1213        id: &str,
1214        now: u64,
1215    ) -> Result<Option<u64>, String> {
1216        let _guard = self.workflow_gate.lock().await;
1217        let mut c = match self.workflow_catalog().await {
1218            Ok(c) => c,
1219            Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(None),
1220            Err(e) => return Err(e),
1221        };
1222        let state = self
1223            .store
1224            .get_execution(id)
1225            .await?
1226            .ok_or("WORKFLOW_EXECUTION_MISSING")?;
1227        if !c.nodes.contains_key(id) {
1228            self.workflow_init(&mut c, &state, now)?;
1229            self.save_workflows(&c).await?;
1230        }
1231        Ok(Some(c.roots[&c.nodes[id].root].deadline))
1232    }
1233    pub(crate) async fn workflow_deadline(&self, id: &str, now: u64) -> Result<(), String> {
1234        let _guard = self.workflow_gate.lock().await;
1235        let c = match self.workflow_catalog().await {
1236            Ok(c) => c,
1237            Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(()),
1238            Err(e) => return Err(e),
1239        };
1240        if c.nodes.contains_key(id) {
1241            c.root(id, now)?;
1242        }
1243        Ok(())
1244    }
1245    pub(crate) async fn workflow_finish(&self, id: &str, now: u64) -> Result<bool, String> {
1246        let _guard = self.workflow_gate.lock().await;
1247        let c = match self.workflow_catalog().await {
1248            Ok(c) => c,
1249            Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(false),
1250            Err(e) => return Err(e),
1251        };
1252        let children: Vec<String> = c
1253            .nodes
1254            .iter()
1255            .filter(|(_, n)| n.parent.as_deref() == Some(id) && n.bound)
1256            .map(|(id, _)| id.clone())
1257            .collect();
1258        let mut unfinished = false;
1259        for child in &children {
1260            let s = self
1261                .store
1262                .get_execution(child)
1263                .await?
1264                .ok_or("WORKFLOW_BOUND_CHILD_MISSING")?;
1265            if matches!(s.status, ExecutionStatus::Running | ExecutionStatus::Paused) {
1266                unfinished = true;
1267            } else if s.status != ExecutionStatus::Completed && !c.nodes[child].observed {
1268                return Err(format!(
1269                    "WORKFLOW_CHILD_FAILED: {child}: {}",
1270                    s.error.unwrap_or_default()
1271                ));
1272            }
1273        }
1274        if unfinished {
1275            self.workflow_suspend(
1276                id,
1277                WorkflowWait {
1278                    children,
1279                    settle: false,
1280                },
1281                now,
1282            )
1283            .await?;
1284        }
1285        Ok(unfinished)
1286    }
1287    async fn workflow_suspend(&self, id: &str, wait: WorkflowWait, now: u64) -> Result<(), String> {
1288        let _guard = self.gate.lock().await;
1289        let mut s = self
1290            .store
1291            .get_execution(id)
1292            .await?
1293            .ok_or("WORKFLOW_EXECUTION_MISSING")?;
1294        if s.status == ExecutionStatus::Running {
1295            s.status = ExecutionStatus::Paused;
1296            s.workflow_wait = Some(wait);
1297            s.updated_at = now;
1298            self.store.put_execution(&s).await?;
1299        }
1300        Ok(())
1301    }
1302    pub(crate) async fn workflow_wake(&self, id: &str, now: u64) -> Result<(), String> {
1303        let _guard = self.gate.lock().await;
1304        let mut s = self
1305            .store
1306            .get_execution(id)
1307            .await?
1308            .ok_or("WORKFLOW_EXECUTION_MISSING")?;
1309        if s.workflow_wait.take().is_some() && s.status == ExecutionStatus::Paused {
1310            s.status = ExecutionStatus::Running;
1311            s.updated_at = now;
1312            self.store.put_execution(&s).await?;
1313        }
1314        Ok(())
1315    }
1316    pub(crate) async fn workflow_nodes(
1317        &self,
1318        id: &str,
1319    ) -> Result<Option<(String, usize, Vec<(String, Option<String>)>)>, String> {
1320        let _guard = self.workflow_gate.lock().await;
1321        // Stores without composition support still execute ordinary Code Mode.
1322        let c = match self.workflow_catalog().await {
1323            Ok(c) => c,
1324            Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(None),
1325            Err(e) => return Err(e),
1326        };
1327        let Some(n) = c.nodes.get(id) else {
1328            return Ok(None);
1329        };
1330        Ok(Some((
1331            n.root.clone(),
1332            c.roots[&n.root].limits.concurrency,
1333            c.nodes
1334                .iter()
1335                .filter(|(_, v)| v.root == n.root && v.bound)
1336                .map(|(id, n)| (id.clone(), n.parent.clone()))
1337                .collect(),
1338        )))
1339    }
1340    pub(crate) async fn workflow_checkpoint_bytes(
1341        &self,
1342        id: &str,
1343        checkpoint: &crate::ExecutionCheckpoint,
1344    ) -> Result<(), String> {
1345        let _guard = self.workflow_gate.lock().await;
1346        let mut c = match self.workflow_catalog().await {
1347            Ok(c) => c,
1348            Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(()),
1349            Err(e) => return Err(e),
1350        };
1351        let Some(node) = c.nodes.get_mut(id) else {
1352            return Ok(());
1353        };
1354        node.checkpoint_bytes = serde_json::to_vec(checkpoint)
1355            .map_err(|e| e.to_string())?
1356            .len();
1357        node.execution_bytes = match self.store.get_execution(id).await? {
1358            Some(state) => serde_json::to_vec(&state).map_err(|e| e.to_string())?.len(),
1359            None => return Err("WORKFLOW_EXECUTION_MISSING".into()),
1360        };
1361        let root = node.root.clone();
1362        check_retained_bytes(&mut c, &root)?;
1363        self.save_workflows(&c).await
1364    }
1365    pub(crate) async fn workflow_output(&self, id: &str, value: &Value) -> Result<(), String> {
1366        let _guard = self.workflow_gate.lock().await;
1367        let mut c = match self.workflow_catalog().await {
1368            Ok(c) => c,
1369            Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(()),
1370            Err(e) => return Err(e),
1371        };
1372        if let Some(r) = c.nodes.get(id).and_then(|n| n.reference.as_ref()) {
1373            crate::workflow_schema::validate(&c.member(r)?.output, value)
1374                .map_err(|e| format!("WORKFLOW_OUTPUT: {}", e.join("; ")))?;
1375        }
1376        if let Some(node) = c.nodes.get_mut(id) {
1377            let state = self
1378                .store
1379                .get_execution(id)
1380                .await?
1381                .ok_or("WORKFLOW_EXECUTION_MISSING")?;
1382            node.execution_bytes = serde_json::to_vec(&state)
1383                .map_err(|e| e.to_string())?
1384                .len()
1385                .saturating_add(serde_json::to_vec(value).map_err(|e| e.to_string())?.len());
1386            let root = node.root.clone();
1387            check_retained_bytes(&mut c, &root)?;
1388            self.save_workflows(&c).await?;
1389        }
1390        Ok(())
1391    }
1392    pub(crate) async fn workflow_charge(&self, id: &str, now: u64) -> Result<(), String> {
1393        let _guard = self.workflow_gate.lock().await;
1394        let mut c = match self.workflow_catalog().await {
1395            Ok(c) => c,
1396            Err(e) if e == "WORKFLOW_UNSUPPORTED" => return Ok(()),
1397            Err(e) => return Err(e),
1398        };
1399        if let Some(node) = c.nodes.get(id) {
1400            c.root(id, now)?;
1401            let root = c.roots.get_mut(&node.root).ok_or("WORKFLOW_ROOT_MISSING")?;
1402            if root.attempts >= root.limits.attempts {
1403                return Err("WORKFLOW_ATTEMPTS: root tool budget exhausted".into());
1404            }
1405            root.attempts += 1;
1406            self.save_workflows(&c).await?;
1407        }
1408        Ok(())
1409    }
1410}
1411fn check_scope(c: &Catalog, id: &str, scope: &str) -> Result<(), String> {
1412    if scope == id {
1413        return Ok(());
1414    }
1415    match c.scopes.get(scope) {
1416        Some(s) if s.owner == id && !s.closed => Ok(()),
1417        _ => Err("WORKFLOW_SCOPE: closed or foreign scope".into()),
1418    }
1419}
1420fn validate_name(name: &str) -> Result<(), String> {
1421    if name.is_empty()
1422        || name.len() > 128
1423        || !name
1424            .chars()
1425            .all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c))
1426    {
1427        Err("WORKFLOW_NAME: use 1-128 ASCII letters, digits, -, _, or .".into())
1428    } else {
1429        Ok(())
1430    }
1431}
1432fn check_publication(c: &Catalog, name: &str, expected: Option<&Value>) -> Result<(), String> {
1433    if c.publications.get(name).is_some_and(|p| p.protected) {
1434        return Err("WORKFLOW_PROTECTED: shipped publication".into());
1435    }
1436    if let Some(expected) = expected {
1437        let actual = c
1438            .publications
1439            .get(name)
1440            .map(|p| p.reference.version.as_str());
1441        if (expected.is_null() && actual.is_some())
1442            || (!expected.is_null() && expected.as_str() != actual)
1443        {
1444            return Err("WORKFLOW_VERSION: publication changed".into());
1445        }
1446    }
1447    Ok(())
1448}
1449fn definition_program(c: &Catalog, r: &WorkflowReference, input: &Value) -> Result<String, String> {
1450    let d = c.member(r)?;
1451    let peers: Value = Value::Object(
1452        c.definitions[&r.version]
1453            .keys()
1454            .map(|member| {
1455                (
1456                    member.clone(),
1457                    wire(&WorkflowReference {
1458                        member: member.clone(),
1459                        ..r.clone()
1460                    }),
1461                )
1462            })
1463            .collect(),
1464    );
1465    Ok(format!(
1466        "async () => {{ const w = codemode.workflows; return await ({})(w.hydrate({}), w.hydrate({}), w.hydrate({}), w.hydrate({})); }}",
1467        d.source,
1468        input,
1469        d.bindings,
1470        wire(r),
1471        peers
1472    ))
1473}
1474fn validate_definition(
1475    d: &WorkflowDefinition,
1476    connectors: &[String],
1477    lexical: bool,
1478) -> Result<(), String> {
1479    crate::workflow_schema::check_supported(&d.input)
1480        .map_err(|e| format!("WORKFLOW_SCHEMA: {}", e.join("; ")))?;
1481    crate::workflow_schema::check_supported(&d.output)
1482        .map_err(|e| format!("WORKFLOW_SCHEMA: {}", e.join("; ")))?;
1483    if !lexical {
1484        return Ok(());
1485    }
1486    let source = format!("({});", d.source);
1487    let allocator = oxc_allocator::Allocator::default();
1488    let parsed = oxc_parser::Parser::new(&allocator, &source, oxc_span::SourceType::mjs()).parse();
1489    if !parsed.errors.is_empty() {
1490        return Err(format!("WORKFLOW_SYNTAX: {}", parsed.errors[0]));
1491    }
1492    if !matches!(parsed.program.body.first(),Some(oxc_ast::ast::Statement::ExpressionStatement(statement)) if statement.expression.get_inner_expression().is_function())
1493    {
1494        return Err("WORKFLOW_DEFINITION: source must be a function expression".into());
1495    }
1496    let semantics = oxc_semantic::SemanticBuilder::new()
1497        .with_check_syntax_error(true)
1498        .build(&parsed.program);
1499    if !semantics.errors.is_empty() {
1500        return Err(format!("WORKFLOW_SYNTAX: {}", semantics.errors[0]));
1501    }
1502    const GLOBALS: &[&str] = &[
1503        "codemode",
1504        "console",
1505        "Promise",
1506        "Error",
1507        "TypeError",
1508        "RangeError",
1509        "JSON",
1510        "Object",
1511        "Array",
1512        "String",
1513        "Number",
1514        "Boolean",
1515        "BigInt",
1516        "Uint8Array",
1517        "Math",
1518        "Symbol",
1519        "Map",
1520        "Set",
1521        "Date",
1522        "RegExp",
1523        "undefined",
1524        "NaN",
1525        "Infinity",
1526        "parseInt",
1527        "parseFloat",
1528        "isNaN",
1529        "isFinite",
1530    ];
1531    for (name, _) in semantics.semantic.scoping().root_unresolved_references() {
1532        if !GLOBALS.contains(name) && !connectors.iter().any(|c| c == name) {
1533            return Err(format!(
1534                "WORKFLOW_CAPTURE: unresolved identifier {name}; pass explicit bindings"
1535            ));
1536        }
1537    }
1538    Ok(())
1539}
1540
1541fn schema_disjoint(output: &Value, input: &Value) -> bool {
1542    fn types(value: &Value) -> Option<BTreeSet<String>> {
1543        match value.get("type")? {
1544            Value::String(t) => Some(BTreeSet::from([t.clone()])),
1545            Value::Array(a) => Some(
1546                a.iter()
1547                    .filter_map(Value::as_str)
1548                    .map(str::to_string)
1549                    .collect(),
1550            ),
1551            _ => None,
1552        }
1553    }
1554    match (types(output), types(input)) {
1555        (Some(a), Some(b)) => !a.iter().any(|x| {
1556            b.iter().any(|y| {
1557                x == y || (x == "integer" && y == "number") || (x == "number" && y == "integer")
1558            })
1559        }),
1560        _ => false,
1561    }
1562}
1563
1564fn collect_references(value: &Value, refs: &mut BTreeSet<String>) {
1565    match value {
1566        Value::Object(fields) => {
1567            if let Some(version) = fields
1568                .get("__workflow_ref")
1569                .and_then(|r| r.get("version"))
1570                .and_then(Value::as_str)
1571            {
1572                refs.insert(version.into());
1573            }
1574            for child in fields.values() {
1575                collect_references(child, refs);
1576            }
1577        }
1578        Value::Array(values) => {
1579            for child in values {
1580                collect_references(child, refs);
1581            }
1582        }
1583        _ => {}
1584    }
1585}
1586
1587fn owned_descendant(c: &Catalog, owner: &str, child: &str) -> bool {
1588    let mut at = c.nodes.get(child).and_then(|node| node.parent.as_deref());
1589    while let Some(id) = at {
1590        if id == owner {
1591            return true;
1592        }
1593        at = c.nodes.get(id).and_then(|node| node.parent.as_deref());
1594    }
1595    false
1596}
1597
1598fn root_bytes(c: &Catalog, root: &str) -> Result<usize, String> {
1599    let nodes: BTreeMap<_, _> = c.nodes.iter().filter(|(_, n)| n.root == root).collect();
1600    let receipts: BTreeMap<_, _> = c
1601        .receipts
1602        .iter()
1603        .filter(|(key, _)| nodes.keys().any(|id| key.starts_with(&format!("{id}:"))))
1604        .collect();
1605    let scopes: BTreeMap<_, _> = c
1606        .scopes
1607        .iter()
1608        .filter(|(_, s)| nodes.contains_key(&s.owner))
1609        .collect();
1610    let owners: BTreeMap<_, _> = c
1611        .owners
1612        .iter()
1613        .filter(|(id, _)| nodes.contains_key(id) || scopes.contains_key(id))
1614        .collect();
1615    let mut versions = BTreeSet::new();
1616    for n in nodes.values() {
1617        if let Some(r) = &n.reference {
1618            versions.insert(r.version.clone());
1619        }
1620        versions.extend(n.dependencies.iter().cloned());
1621    }
1622    for refs in owners.values() {
1623        versions.extend(refs.iter().cloned());
1624    }
1625    loop {
1626        let before = versions.len();
1627        for version in versions.clone() {
1628            if let Some(bundle) = c.definitions.get(&version) {
1629                for d in bundle.values() {
1630                    collect_references(&d.bindings, &mut versions);
1631                }
1632            }
1633        }
1634        if before == versions.len() {
1635            break;
1636        }
1637    }
1638    let definitions: BTreeMap<_, _> = c
1639        .definitions
1640        .iter()
1641        .filter(|(version, _)| versions.contains(*version))
1642        .collect();
1643    let retained = nodes.values().fold(0usize, |bytes, node| {
1644        bytes
1645            .saturating_add(node.checkpoint_bytes)
1646            .saturating_add(node.execution_bytes)
1647    });
1648    serde_json::to_vec(&(nodes, receipts, scopes, owners, definitions))
1649        .map(|bytes| bytes.len().saturating_add(retained))
1650        .map_err(|e| e.to_string())
1651}
1652
1653fn check_retained_bytes(c: &mut Catalog, root: &str) -> Result<(), String> {
1654    let bytes = root_bytes(c, root)?;
1655    let budget = c.roots.get_mut(root).ok_or("WORKFLOW_ROOT_MISSING")?;
1656    if bytes > budget.limits.bytes {
1657        return Err("WORKFLOW_BYTES: retained storage budget exhausted".into());
1658    }
1659    budget.bytes = bytes;
1660    Ok(())
1661}
1662
1663#[cfg(test)]
1664mod tests {
1665    use super::*;
1666    use crate::MemoryStore;
1667    use std::sync::Arc;
1668
1669    #[tokio::test]
1670    async fn ancestor_and_sibling_wait_cycles_are_rejected() {
1671        let store = Arc::new(MemoryStore::default());
1672        let runtime = CodeModeRuntime::new(store);
1673        let root = runtime.begin("return 1;", vec![], 100).await.unwrap();
1674        let definition=runtime.workflow_call(&root,0,"define",json!({"definition":{"source":"async n=>n","input":true,"output":true,"bindings":{}}}),101).await.unwrap().result.unwrap();
1675        let first = runtime
1676            .workflow_call(
1677                &root,
1678                1,
1679                "start",
1680                json!({"handle":definition,"input":1}),
1681                102,
1682            )
1683            .await
1684            .unwrap()
1685            .result
1686            .unwrap();
1687        let second = runtime
1688            .workflow_call(
1689                &root,
1690                2,
1691                "start",
1692                json!({"handle":definition,"input":2}),
1693                103,
1694            )
1695            .await
1696            .unwrap()
1697            .result
1698            .unwrap();
1699        let c = runtime.workflow_catalog().await.unwrap();
1700        let a = run_id(&first, &c.store).unwrap();
1701        let b = run_id(&second, &c.store).unwrap();
1702        let ancestor = runtime
1703            .workflow_call(
1704                a,
1705                0,
1706                "join",
1707                json!({"runs":[run_wire(&c.store,&root)]}),
1708                104,
1709            )
1710            .await
1711            .unwrap_err();
1712        assert!(ancestor.contains("WORKFLOW_WAIT_CYCLE"), "{ancestor}");
1713        let wait = runtime
1714            .workflow_call(a, 1, "join", json!({"runs":[second]}), 105)
1715            .await
1716            .unwrap();
1717        assert_eq!(wait.control.as_deref(), Some("pause"));
1718        let sibling = runtime
1719            .workflow_call(b, 0, "join", json!({"runs":[first]}), 106)
1720            .await
1721            .unwrap_err();
1722        assert!(sibling.contains("WORKFLOW_WAIT_CYCLE"), "{sibling}");
1723    }
1724}