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