Skip to main content

lash_lashlang_runtime/
lib.rs

1use std::sync::{Arc, Mutex};
2
3use sha2::{Digest, Sha256};
4
5#[cfg(feature = "testing")]
6pub mod testing;
7
8pub use lash_trace::{
9    TraceLashlangChildExecution, TraceLashlangEdgeSelection, TraceLashlangExecutionEvent,
10    TraceLashlangExecutionIdentity, TraceLashlangGraph, TraceLashlangGraphChildLink,
11    TraceLashlangGraphEdge, TraceLashlangGraphNode, TraceLashlangGraphStore, TraceLashlangMap,
12    TraceLashlangMapEdge, TraceLashlangMapNode, TraceLashlangNodeStatus, TraceLashlangStatus,
13};
14pub use lashlang::{
15    CompiledProcessCache, InMemoryLashlangArtifactStore, LASH_TYPE_KEY, LashlangAbilities,
16    LashlangArtifactStore, LashlangHostCatalog, LashlangHostEnvironment, LashlangLanguageFeatures,
17};
18
19/// Map the lashlang language crate's durability tier onto the runtime's
20/// [`lash_core::DurabilityTier`]. The two enums are parallel; this is the single
21/// bridge point between them (the parallel `LashlangDurabilityTier` alias is
22/// gone — process engines self-describe their tier via `lash_core::DurabilityTier`).
23pub fn lashlang_durability_tier(tier: lashlang::DurabilityTier) -> lash_core::DurabilityTier {
24    match tier {
25        lashlang::DurabilityTier::Inline => lash_core::DurabilityTier::Inline,
26        lashlang::DurabilityTier::Durable => lash_core::DurabilityTier::Durable,
27    }
28}
29
30pub const LASHLANG_ENGINE_KIND: &str = "lashlang";
31pub const LASHLANG_TOOL_BINDING_KEY: &str = "lashlang.tool";
32pub const LASHLANG_SURFACE_EXTENSION_ID: &str = "lashlang.surface";
33
34#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
35#[serde(default)]
36pub struct LashlangSurfaceContribution {
37    pub abilities: LashlangAbilities,
38    pub language_features: LashlangLanguageFeatures,
39    pub resources: LashlangHostCatalog,
40}
41
42impl LashlangSurfaceContribution {
43    pub fn new(
44        abilities: LashlangAbilities,
45        language_features: LashlangLanguageFeatures,
46        resources: LashlangHostCatalog,
47    ) -> Self {
48        Self {
49            abilities,
50            language_features,
51            resources,
52        }
53    }
54
55    pub fn from_surface(surface: LashlangSurface) -> Self {
56        Self {
57            abilities: surface.abilities,
58            language_features: surface.language_features,
59            resources: surface.resources,
60        }
61    }
62}
63
64#[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
65pub struct LashlangToolBinding {
66    #[serde(default, skip_serializing_if = "Vec::is_empty")]
67    pub module_path: Vec<String>,
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub operation: Option<String>,
70    #[serde(default, skip_serializing_if = "Option::is_none")]
71    pub authority_type: Option<String>,
72    #[serde(default, skip_serializing_if = "Vec::is_empty")]
73    pub aliases: Vec<String>,
74}
75
76impl LashlangToolBinding {
77    pub fn new(
78        module_path: impl IntoIterator<Item = impl Into<String>>,
79        operation: impl Into<String>,
80    ) -> Self {
81        Self {
82            module_path: module_path.into_iter().map(Into::into).collect(),
83            operation: Some(operation.into()),
84            authority_type: None,
85            aliases: Vec::new(),
86        }
87    }
88
89    pub fn with_authority_type(mut self, authority_type: impl Into<String>) -> Self {
90        self.authority_type = Some(authority_type.into());
91        self
92    }
93
94    pub fn with_aliases(mut self, aliases: impl IntoIterator<Item = impl Into<String>>) -> Self {
95        self.aliases = aliases.into_iter().map(Into::into).collect();
96        self
97    }
98
99    pub fn executable_for(&self, tool_name: &str) -> Result<ResolvedLashlangToolBinding, String> {
100        if self.module_path.is_empty() {
101            return Err(format!(
102                "tool `{tool_name}` is missing an explicit Lashlang module path"
103            ));
104        }
105        for segment in &self.module_path {
106            validate_lashlang_identifier(tool_name, "module path segment", segment)?;
107        }
108        let operation = self
109            .operation
110            .as_deref()
111            .filter(|operation| !operation.trim().is_empty())
112            .ok_or_else(|| {
113                format!("tool `{tool_name}` is missing an explicit Lashlang operation name")
114            })?;
115        validate_lashlang_identifier(tool_name, "operation name", operation)?;
116        let authority_type = self
117            .authority_type
118            .as_deref()
119            .filter(|authority_type| !authority_type.trim().is_empty())
120            .map(ToOwned::to_owned)
121            .unwrap_or_else(|| default_authority_type(&self.module_path));
122        Ok(ResolvedLashlangToolBinding {
123            module_path: self.module_path.clone(),
124            operation: operation.to_string(),
125            authority_type,
126            aliases: self.aliases.clone(),
127        })
128    }
129
130    pub fn required_for_remote(
131        manifest: &lash_core::ToolManifest,
132    ) -> Result<ResolvedLashlangToolBinding, String> {
133        required_tool_lashlang_executable(manifest)
134    }
135
136    pub fn required_executable_for_remote(
137        &self,
138        tool_name: &str,
139    ) -> Result<ResolvedLashlangToolBinding, String> {
140        self.executable_for(tool_name)
141    }
142}
143
144#[derive(Clone, Debug, PartialEq, Eq)]
145pub struct ResolvedLashlangToolBinding {
146    pub module_path: Vec<String>,
147    pub operation: String,
148    pub authority_type: String,
149    pub aliases: Vec<String>,
150}
151
152impl ResolvedLashlangToolBinding {
153    pub fn module_path_string(&self) -> String {
154        self.module_path.join(".")
155    }
156
157    pub fn call_path(&self) -> String {
158        format!("{}.{}", self.module_path_string(), self.operation)
159    }
160}
161
162fn default_authority_type(module_path: &[String]) -> String {
163    module_path
164        .last()
165        .map(|segment| {
166            let mut chars = segment.chars();
167            match chars.next() {
168                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
169                None => "Tool".to_string(),
170            }
171        })
172        .unwrap_or_else(|| "Tool".to_string())
173}
174
175fn validate_lashlang_identifier(tool_name: &str, label: &str, value: &str) -> Result<(), String> {
176    let value = value.trim();
177    let mut chars = value.chars();
178    let Some(first) = chars.next() else {
179        return Err(format!("tool `{tool_name}` has an empty Lashlang {label}"));
180    };
181    if !(first == '_' || first.is_ascii_alphabetic()) {
182        return Err(format!(
183            "tool `{tool_name}` has invalid Lashlang {label} `{value}`"
184        ));
185    }
186    if !chars.all(|ch| ch == '_' || ch.is_ascii_alphanumeric()) {
187        return Err(format!(
188            "tool `{tool_name}` has invalid Lashlang {label} `{value}`"
189        ));
190    }
191    Ok(())
192}
193
194pub fn tool_lashlang_binding(
195    manifest: &lash_core::ToolManifest,
196) -> Result<Option<LashlangToolBinding>, String> {
197    manifest
198        .bindings
199        .get(LASHLANG_TOOL_BINDING_KEY)
200        .cloned()
201        .map(serde_json::from_value)
202        .transpose()
203        .map_err(|err| {
204            format!(
205                "tool `{}` has invalid `{LASHLANG_TOOL_BINDING_KEY}` binding: {err}",
206                manifest.name
207            )
208        })
209}
210
211pub fn required_tool_lashlang_binding(
212    manifest: &lash_core::ToolManifest,
213) -> Result<LashlangToolBinding, String> {
214    tool_lashlang_binding(manifest)?.ok_or_else(|| {
215        format!(
216            "tool `{}` is missing an explicit `{LASHLANG_TOOL_BINDING_KEY}` binding",
217            manifest.name
218        )
219    })
220}
221
222pub fn required_tool_lashlang_executable(
223    manifest: &lash_core::ToolManifest,
224) -> Result<ResolvedLashlangToolBinding, String> {
225    required_tool_lashlang_binding(manifest)?.executable_for(&manifest.name)
226}
227
228pub trait ToolManifestLashlangExt {
229    fn lashlang_binding(&self) -> Result<Option<LashlangToolBinding>, serde_json::Error>;
230}
231
232impl ToolManifestLashlangExt for lash_core::ToolManifest {
233    fn lashlang_binding(&self) -> Result<Option<LashlangToolBinding>, serde_json::Error> {
234        self.bindings
235            .get(LASHLANG_TOOL_BINDING_KEY)
236            .cloned()
237            .map(serde_json::from_value)
238            .transpose()
239    }
240}
241
242pub trait ToolDefinitionLashlangExt {
243    fn with_lashlang_binding(self, lashlang_binding: LashlangToolBinding) -> Self;
244}
245
246impl ToolDefinitionLashlangExt for lash_core::ToolDefinition {
247    fn with_lashlang_binding(mut self, lashlang_binding: LashlangToolBinding) -> Self {
248        let value = serde_json::to_value(lashlang_binding)
249            .expect("lashlang tool binding must serialize to JSON");
250        self.manifest
251            .bindings
252            .insert(LASHLANG_TOOL_BINDING_KEY.to_string(), value);
253        self
254    }
255}
256
257pub trait RemoteToolGrantLashlangExt {
258    fn with_lashlang_binding(self, lashlang_binding: LashlangToolBinding) -> Self;
259    fn lashlang_binding(&self) -> Result<Option<LashlangToolBinding>, serde_json::Error>;
260}
261
262impl RemoteToolGrantLashlangExt for lash_remote_protocol::RemoteToolGrant {
263    fn with_lashlang_binding(mut self, lashlang_binding: LashlangToolBinding) -> Self {
264        let value = serde_json::to_value(lashlang_binding)
265            .expect("lashlang tool binding must serialize to JSON");
266        self.bindings
267            .insert(LASHLANG_TOOL_BINDING_KEY.to_string(), value);
268        self
269    }
270
271    fn lashlang_binding(&self) -> Result<Option<LashlangToolBinding>, serde_json::Error> {
272        self.bindings
273            .get(LASHLANG_TOOL_BINDING_KEY)
274            .cloned()
275            .map(serde_json::from_value)
276            .transpose()
277    }
278}
279
280#[derive(Clone, Debug)]
281pub struct LashlangSurface {
282    pub abilities: LashlangAbilities,
283    pub language_features: LashlangLanguageFeatures,
284    pub resources: LashlangHostCatalog,
285}
286
287impl Default for LashlangSurface {
288    fn default() -> Self {
289        Self {
290            abilities: LashlangAbilities::default().with_sleep(),
291            language_features: LashlangLanguageFeatures::default(),
292            resources: LashlangHostCatalog::new(),
293        }
294    }
295}
296
297impl LashlangSurface {
298    pub fn new(
299        abilities: LashlangAbilities,
300        language_features: LashlangLanguageFeatures,
301        resources: LashlangHostCatalog,
302    ) -> Self {
303        Self {
304            abilities,
305            language_features,
306            resources,
307        }
308    }
309
310    pub fn for_process_registry(mut self, process_registry_available: bool) -> Self {
311        self.abilities = self.abilities.with_sleep();
312        if process_registry_available {
313            self.abilities = self.abilities.with_processes().with_process_signals();
314        } else {
315            self.abilities.processes = false;
316            self.abilities.process_signals = false;
317        }
318        self
319    }
320
321    pub fn with_resources(mut self, resources: LashlangHostCatalog) -> Self {
322        self.resources.extend(resources);
323        self
324    }
325
326    pub fn with_plugin_extensions(
327        mut self,
328        extensions: &lash_core::PluginExtensions,
329    ) -> Result<Self, String> {
330        for payload in extensions.payloads(LASHLANG_SURFACE_EXTENSION_ID) {
331            let contribution: LashlangSurfaceContribution = serde_json::from_value(payload.clone())
332                .map_err(|err| {
333                    format!("invalid `{LASHLANG_SURFACE_EXTENSION_ID}` extension payload: {err}")
334                })?;
335            self.abilities = self.abilities.union(contribution.abilities);
336            self.language_features = self.language_features.union(contribution.language_features);
337            self.resources.extend(contribution.resources);
338        }
339        Ok(self)
340    }
341
342    pub fn host_environment(
343        &self,
344        catalog: &lash_core::ToolCatalog,
345    ) -> Result<LashlangHostEnvironment, String> {
346        lashlang_host_environment_from_tool_catalog(
347            catalog,
348            self.abilities,
349            self.language_features,
350            self.resources.clone(),
351        )
352    }
353}
354
355pub fn lashlang_host_environment_from_tool_catalog(
356    catalog: &lash_core::ToolCatalog,
357    abilities: LashlangAbilities,
358    language_features: LashlangLanguageFeatures,
359    host_resources: LashlangHostCatalog,
360) -> Result<LashlangHostEnvironment, String> {
361    let mut resources = lashlang_resources_from_tool_catalog(catalog)?;
362    resources.extend(host_resources);
363    if abilities.triggers {
364        lashlang::add_trigger_resource_operations(&mut resources);
365    }
366    Ok(
367        LashlangHostEnvironment::new(resources, abilities)
368            .with_language_features(language_features),
369    )
370}
371
372pub fn lashlang_resources_from_tool_catalog(
373    catalog: &lash_core::ToolCatalog,
374) -> Result<LashlangHostCatalog, String> {
375    let mut host_catalog = LashlangHostCatalog::new();
376    // Every catalog member is callable; membership is the execution gate.
377    for entry in catalog.tools.iter() {
378        let lashlang_binding = required_tool_lashlang_executable(&entry.manifest)?;
379        let operation_binding = catalog
380            .resolve_contract(&entry.manifest.name)
381            .as_deref()
382            .map(lashlang_tool_contract_types)
383            .unwrap_or(lashlang::ResourceOperationBinding {
384                input_ty: lashlang::TypeExpr::Any,
385                output_ty: lashlang::TypeExpr::Any,
386                output_from_input: None,
387            });
388        host_catalog.add_module_operation_binding(
389            lashlang_binding.module_path.iter().map(String::as_str),
390            lashlang_binding.authority_type.clone(),
391            lashlang_binding.operation.clone(),
392            entry.manifest.id.to_string(),
393            operation_binding,
394        );
395    }
396    Ok(host_catalog)
397}
398
399fn lashlang_tool_contract_types(
400    contract: &lash_core::ToolContract,
401) -> lashlang::ResourceOperationBinding {
402    let input_ty = lashlang::json_schema_to_type_expr(contract.input_schema.canonical());
403    let (output_ty, output_from_input) = match &contract.output_contract {
404        lash_core::ToolOutputContract::Static => (
405            lashlang::json_schema_to_type_expr(contract.output_schema.canonical()),
406            None,
407        ),
408        lash_core::ToolOutputContract::FromInputSchema {
409            input_field,
410            default_schema,
411        } => (
412            lashlang::TypeExpr::Any,
413            Some(lashlang::OutputFromInputBinding {
414                input_field: input_field.clone(),
415                default_schema: default_schema
416                    .as_ref()
417                    .map(lashlang::json_schema_to_type_expr),
418            }),
419        ),
420    };
421    lashlang::ResourceOperationBinding {
422        input_ty,
423        output_ty,
424        output_from_input,
425    }
426}
427
428pub fn lashlang_host_environment_satisfies_requirements(
429    required: &lashlang::HostRequirements,
430    current: &LashlangHostEnvironment,
431) -> Result<(), String> {
432    let abilities = required.abilities;
433    let current_abilities = current.abilities;
434    if abilities.processes && !current_abilities.processes {
435        return Err("processes are not available".to_string());
436    }
437    if abilities.sleep && !current_abilities.sleep {
438        return Err("sleep is not available".to_string());
439    }
440    if abilities.process_signals && !current_abilities.process_signals {
441        return Err("process signals are not available".to_string());
442    }
443    if abilities.triggers && !current_abilities.triggers {
444        return Err("triggers are not available".to_string());
445    }
446    if required.language_features.label_annotations && !current.language_features.label_annotations
447    {
448        return Err("label annotations are not available".to_string());
449    }
450
451    for (_, module) in required.resources.module_instances() {
452        let current_module = current
453            .resources
454            .resolve_module_path(&module.path)
455            .ok_or_else(|| format!("module `{}` is not available", module.alias))?;
456        if current_module.resource_type != module.resource_type {
457            return Err(format!(
458                "module `{}` has type `{}`, expected `{}`",
459                module.alias, current_module.resource_type, module.resource_type
460            ));
461        }
462        for (operation, required_binding) in &module.operations {
463            match current.resources.resolve_module_operation(
464                &module.resource_type,
465                &module.alias,
466                operation,
467            ) {
468                Some(current_binding) if current_binding == required_binding => {}
469                Some(current_binding) => {
470                    return Err(format!(
471                        "module `{}` operation `{operation}` resolves to `{}`, expected `{}`",
472                        module.alias,
473                        current_binding.host_operation,
474                        required_binding.host_operation
475                    ));
476                }
477                None => {
478                    return Err(format!(
479                        "module `{}` does not expose operation `{operation}`",
480                        module.alias
481                    ));
482                }
483            }
484        }
485    }
486
487    for (resource_type, required_type) in required.resources.resource_types() {
488        if !current.resources.has_resource_type(resource_type) {
489            return Err(format!("resource type `{resource_type}` is not available"));
490        }
491        for (operation, required_binding) in &required_type.operations {
492            let current_binding = current
493                .resources
494                .resolve_operation(resource_type, operation)
495                .ok_or_else(|| {
496                    format!(
497                        "resource type `{resource_type}` does not expose operation `{operation}`"
498                    )
499                })?;
500            if current_binding.input_ty != required_binding.input_ty {
501                return Err(format!(
502                    "resource type `{resource_type}` operation `{operation}` has incompatible input type"
503                ));
504            }
505            if current_binding.output_ty != required_binding.output_ty {
506                return Err(format!(
507                    "resource type `{resource_type}` operation `{operation}` has incompatible output type"
508                ));
509            }
510        }
511    }
512    for (name, required_data_type) in required.resources.named_data_types() {
513        let current_data_type = current
514            .resources
515            .resolve_named_data_type(name)
516            .ok_or_else(|| format!("host data type `{name}` is not available"))?;
517        if current_data_type != required_data_type {
518            return Err(format!(
519                "host data type `{name}` has incompatible structure"
520            ));
521        }
522    }
523    for (path, required_binding) in required.resources.value_constructors() {
524        let current_binding = current
525            .resources
526            .resolve_value_constructor(&path.split('.').collect::<Vec<_>>())
527            .ok_or_else(|| format!("value constructor `{path}` is not available"))?;
528        if current_binding.input_ty != required_binding.input_ty {
529            return Err(format!(
530                "value constructor `{path}` has incompatible input type"
531            ));
532        }
533        if current_binding.output_ty != required_binding.output_ty {
534            return Err(format!(
535                "value constructor `{path}` has incompatible output type"
536            ));
537        }
538    }
539    for (source_ty, required_binding) in required.resources.trigger_sources() {
540        let current_binding = current
541            .resources
542            .resolve_trigger_source(source_ty)
543            .ok_or_else(|| format!("trigger source type `{source_ty}` is not available"))?;
544        if current_binding != required_binding {
545            return Err(format!(
546                "trigger source type `{source_ty}` has incompatible event type"
547            ));
548        }
549    }
550
551    Ok(())
552}
553
554#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
555pub struct LashlangProcessInput {
556    pub module_ref: lashlang::ModuleRef,
557    pub process_ref: lashlang::ProcessRef,
558    pub host_requirements_ref: lashlang::HostRequirementsRef,
559    pub process_name: String,
560    #[serde(default)]
561    pub args: serde_json::Map<String, serde_json::Value>,
562}
563
564impl LashlangProcessInput {
565    pub fn process_identity(&self) -> lash_core::ProcessIdentity {
566        lashlang_process_identity(self)
567    }
568
569    pub fn remote_identity(&self) -> lash_remote_protocol::RemoteProcessIdentity {
570        lash_remote_protocol::RemoteProcessIdentity {
571            kind: LASHLANG_ENGINE_KIND.to_string(),
572            label: Some(self.process_name.clone()),
573            definition: Some(lash_remote_protocol::RemoteProcessDefinitionIdentity {
574                value: self.definition(),
575            }),
576        }
577    }
578
579    pub fn to_process_input(&self) -> Result<lash_core::ProcessInput, serde_json::Error> {
580        Ok(lash_core::ProcessInput::Engine {
581            kind: LASHLANG_ENGINE_KIND.to_string(),
582            payload: serde_json::to_value(self)?,
583        })
584    }
585
586    pub fn into_process_input(self) -> Result<lash_core::ProcessInput, serde_json::Error> {
587        self.to_process_input()
588    }
589
590    pub fn remote_trigger_subscription_draft(
591        &self,
592        subscription_key: impl Into<String>,
593        env_ref: lash_remote_protocol::RemoteProcessExecutionEnvRef,
594        source_type: impl Into<String>,
595        source_key: impl Into<String>,
596    ) -> Result<lash_remote_protocol::RemoteTriggerSubscriptionDraft, serde_json::Error> {
597        Ok(
598            lash_remote_protocol::RemoteTriggerSubscriptionDraft::for_process(
599                subscription_key,
600                env_ref,
601                source_type,
602                source_key,
603                self.clone().try_into()?,
604                self.remote_identity(),
605            ),
606        )
607    }
608
609    pub fn from_payload(payload: serde_json::Value) -> Result<Self, serde_json::Error> {
610        serde_json::from_value(payload)
611    }
612
613    pub fn definition(&self) -> serde_json::Value {
614        serde_json::json!({
615            "module_ref": self.module_ref,
616            "process_ref": self.process_ref,
617            "host_requirements_ref": self.host_requirements_ref,
618            "process_name": self.process_name,
619        })
620    }
621}
622
623impl TryFrom<LashlangProcessInput> for lash_remote_protocol::RemoteProcessInput {
624    type Error = serde_json::Error;
625
626    fn try_from(value: LashlangProcessInput) -> Result<Self, Self::Error> {
627        Ok(Self::Engine {
628            kind: LASHLANG_ENGINE_KIND.to_string(),
629            payload: serde_json::to_value(value)?,
630        })
631    }
632}
633
634#[derive(Clone, Debug)]
635pub struct PreparedLashlangProcessStart {
636    pub registration: lash_core::ProcessRegistration,
637    pub label: Option<String>,
638}
639
640pub async fn prepare_lashlang_process_start(
641    artifact_store: Arc<dyn LashlangArtifactStore>,
642    parent_start_seed: &str,
643    start: lashlang::ProcessStart,
644) -> Result<PreparedLashlangProcessStart, String> {
645    let display_name = Some(start.process_name.clone());
646    let artifact = artifact_store
647        .get_module_artifact(&start.module_ref)
648        .await
649        .map_err(|err| format!("failed to load lashlang module artifact: {err}"))?
650        .ok_or_else(|| {
651            format!(
652                "missing lashlang module artifact `{}` for process `{}`",
653                start.module_ref, start.process_name
654            )
655        })?;
656    if artifact.host_requirements_ref != start.host_requirements_ref {
657        return Err(format!(
658            "lashlang module artifact `{}` host requirements mismatch: process requested {}, artifact has {}",
659            start.module_ref, start.host_requirements_ref, artifact.host_requirements_ref
660        ));
661    }
662    if artifact.process_ref(&start.process_name) != Some(&start.process_ref) {
663        return Err(format!(
664            "lashlang module artifact `{}` does not export process `{}` as requested ref {:?}",
665            start.module_ref, start.process_name, start.process_ref
666        ));
667    }
668    let args = match serde_json::to_value(lashlang::Value::Record(Arc::new(start.args)))
669        .map_err(|err| format!("failed to serialize process args: {err}"))?
670    {
671        serde_json::Value::Object(map) => map,
672        _ => return Err("process args must serialize as a record".to_string()),
673    };
674    let signal_event_types = artifact
675        .canonical_ir
676        .process(&start.process_name)
677        .map(lashlang_process_signal_event_types)
678        .unwrap_or_default();
679    let process_input = LashlangProcessInput {
680        module_ref: start.module_ref,
681        process_ref: start.process_ref,
682        host_requirements_ref: start.host_requirements_ref,
683        process_name: start.process_name,
684        args,
685    };
686    let identity = lashlang_process_identity(&process_input);
687    let process_id =
688        deterministic_lashlang_process_id(parent_start_seed, &start.start_site, &process_input)
689            .map_err(|err| format!("failed to derive deterministic process id: {err}"))?;
690    let process_input = process_input
691        .into_process_input()
692        .map_err(|err| format!("failed to encode process input: {err}"))?;
693    let registration = lash_core::ProcessRegistration::new(
694        process_id,
695        process_input,
696        // Lashlang engine rows are journaled and idempotent by process id, so
697        // recovery may re-execute them (ADR 0019).
698        lash_core::RecoveryDisposition::Rerunnable,
699        lash_core::ProcessProvenance::host(),
700    )
701    .with_identity(identity)
702    .with_extra_event_types(
703        lashlang_process_event_types()
704            .into_iter()
705            .chain(signal_event_types),
706    );
707    Ok(PreparedLashlangProcessStart {
708        registration,
709        label: display_name,
710    })
711}
712
713pub fn deterministic_lashlang_process_id(
714    parent_start_seed: &str,
715    start_site: &lashlang::LashlangExecutionCallSite,
716    input: &LashlangProcessInput,
717) -> Result<String, serde_json::Error> {
718    let args = serde_json::to_string(&input.args)?;
719    let occurrence = start_site.occurrence.to_string();
720    let process_ref = lashlang::process_ref_key(&input.process_ref);
721    let mut hasher = Sha256::new();
722    for part in [
723        "lashlang-process-start:v1",
724        parent_start_seed,
725        start_site.site.node_id.as_str(),
726        occurrence.as_str(),
727        input.module_ref.as_str(),
728        process_ref.as_str(),
729        input.host_requirements_ref.as_str(),
730        input.process_name.as_str(),
731        args.as_str(),
732    ] {
733        hasher.update(part.as_bytes());
734        hasher.update([0]);
735    }
736    let hash = format!("{:x}", hasher.finalize());
737    Ok(format!("process:lashlang:sha256:{hash}"))
738}
739
740pub fn resolve_lashlang_module_operation(
741    host_environment: &lashlang::LashlangHostEnvironment,
742    receiver: &lashlang::ResourceHandle,
743    operation: &str,
744) -> Result<String, lashlang::ExecutionHostError> {
745    host_environment
746        .resources
747        .resolve_module_operation(&receiver.resource_type, &receiver.alias, operation)
748        .map(|binding| binding.host_operation.clone())
749        .ok_or_else(|| {
750            lashlang::ExecutionHostError::new(format!(
751                "module `{}` of type `{}` does not expose operation `{operation}`",
752                receiver.alias, receiver.resource_type
753            ))
754        })
755}
756
757fn lashlang_process_identity(input: &LashlangProcessInput) -> lash_core::ProcessIdentity {
758    lash_core::ProcessIdentity::new(LASHLANG_ENGINE_KIND)
759        .with_label(Some(input.process_name.clone()))
760        .with_definition(Some(input.definition()))
761}
762
763#[derive(Clone)]
764pub struct LashlangProcessEngine {
765    artifact_store: Arc<dyn LashlangArtifactStore>,
766    process_cache: Arc<Mutex<CompiledProcessCache>>,
767    surface: LashlangSurface,
768    execution_sink: Option<Arc<dyn lash_trace::TraceSink>>,
769    trace_context: lash_trace::TraceContext,
770}
771
772impl LashlangProcessEngine {
773    pub fn new(artifact_store: Arc<dyn LashlangArtifactStore>, surface: LashlangSurface) -> Self {
774        Self {
775            artifact_store,
776            process_cache: Arc::new(Mutex::new(CompiledProcessCache::new())),
777            surface,
778            execution_sink: None,
779            trace_context: lash_trace::TraceContext::default(),
780        }
781    }
782
783    pub fn in_memory(surface: LashlangSurface) -> Self {
784        Self::new(
785            lashlang::global_in_memory_lashlang_artifact_store(),
786            surface,
787        )
788    }
789
790    pub fn with_execution_trace(
791        mut self,
792        sink: Option<Arc<dyn lash_trace::TraceSink>>,
793        trace_context: lash_trace::TraceContext,
794    ) -> Self {
795        self.execution_sink = sink;
796        self.trace_context = trace_context;
797        self
798    }
799
800    pub fn artifact_store(&self) -> Arc<dyn LashlangArtifactStore> {
801        Arc::clone(&self.artifact_store)
802    }
803}
804
805#[async_trait::async_trait]
806impl lash_core::ProcessEngine for LashlangProcessEngine {
807    fn kind(&self) -> &'static str {
808        LASHLANG_ENGINE_KIND
809    }
810
811    async fn validate_start(
812        &self,
813        context: lash_core::ProcessEngineValidationContext<'_>,
814        payload: &serde_json::Value,
815        _env_spec: Option<&lash_core::ProcessExecutionEnvSpec>,
816    ) -> Result<(), lash_core::PluginError> {
817        let input: LashlangProcessInput =
818            serde_json::from_value(payload.clone()).map_err(|err| {
819                lash_core::PluginError::Session(format!("invalid lashlang process payload: {err}"))
820            })?;
821        let artifact = self
822            .artifact_store
823            .get_module_artifact(&input.module_ref)
824            .await
825            .map_err(|err| lash_core::PluginError::Session(format!("load module artifact: {err}")))?
826            .ok_or_else(|| {
827                lash_core::PluginError::Session(format!(
828                    "missing lashlang module artifact `{}`",
829                    input.module_ref
830                ))
831            })?;
832        if artifact.host_requirements_ref != input.host_requirements_ref {
833            return Err(lash_core::PluginError::Session(format!(
834                "lashlang process `{}` requested surface {}, artifact has {}",
835                input.process_name, input.host_requirements_ref, artifact.host_requirements_ref
836            )));
837        }
838        if artifact.process_ref(&input.process_name) != Some(&input.process_ref) {
839            return Err(lash_core::PluginError::Session(format!(
840                "lashlang module `{}` does not export process `{}` as requested ref {:?}",
841                input.module_ref, input.process_name, input.process_ref
842            )));
843        }
844        let surface = self
845            .surface
846            .clone()
847            .for_process_registry(context.process_registry_available());
848        let host_environment = surface
849            .host_environment(context.tool_catalog())
850            .map_err(lash_core::PluginError::Session)?;
851        if let Err(err) = lashlang_host_environment_satisfies_requirements(
852            &artifact.host_requirements,
853            &host_environment,
854        ) {
855            return Err(lash_core::PluginError::Session(format!(
856                "lashlang process `{}` is incompatible with this host surface: {err}",
857                input.process_name
858            )));
859        }
860        Ok(())
861    }
862
863    async fn run(
864        &self,
865        context: lash_core::ProcessEngineRunContext<'_>,
866        payload: serde_json::Value,
867    ) -> lash_core::ProcessRunOutcome {
868        process::run_lashlang_process(self.clone(), context, payload).await
869    }
870
871    fn identity(&self, payload: &serde_json::Value) -> lash_core::ProcessIdentity {
872        match LashlangProcessInput::from_payload(payload.clone()) {
873            Ok(input) => lashlang_process_identity(&input),
874            Err(_) => lash_core::ProcessIdentity::new(LASHLANG_ENGINE_KIND),
875        }
876    }
877
878    fn durability_tier(&self) -> lash_core::DurabilityTier {
879        lashlang_durability_tier(self.artifact_store.durability_tier())
880    }
881}
882
883mod bridge;
884mod catalogue_preview;
885mod deferred;
886mod process;
887mod typed_output;
888
889pub use bridge::{
890    lashlang_value_to_json, process_event_payload, protocol_tool_output_to_lashlang_value,
891    protocol_tool_reply_to_lashlang_value, sleep_duration_ms,
892};
893pub use catalogue_preview::{
894    CataloguePreviewEntry, CataloguePreviewOptions, DEFAULT_CATALOGUE_PREVIEW_CALL_NAME_LIMIT,
895    DEFAULT_CATALOGUE_PREVIEW_MODULE_LIMIT, catalogue_preview_contribution,
896    catalogue_preview_contribution_for_entries,
897    catalogue_preview_contribution_for_entries_with_options,
898    catalogue_preview_contribution_for_manifests, catalogue_preview_contribution_with_options,
899    catalogue_preview_entries_from_catalog_records, catalogue_preview_entries_from_manifests,
900    catalogue_preview_entry_from_catalog_record, catalogue_preview_entry_from_manifest,
901};
902pub use deferred::{
903    DeferredResolutionLinkKey, DeferredResolutionRecord, DeferredToolResolver, Resolution,
904    SharedDeferredToolResolver, ToolGrant, link_with_deferred_resolution,
905    resolve_and_fold_deferred,
906};
907pub use process::{
908    lashlang_process_event_types, lashlang_process_signal_event_types, lashlang_type_expr_schema,
909    trace_lashlang_main_map,
910};
911pub use typed_output::parse_output_schema;
912
913#[cfg(test)]
914mod tests {
915    use super::*;
916
917    struct EveryNEffectsController(usize);
918
919    #[async_trait::async_trait]
920    impl lash_core::AwaitEventResolver for EveryNEffectsController {}
921
922    #[async_trait::async_trait]
923    impl lash_core::RuntimeEffectController for EveryNEffectsController {
924        fn wants_segment_boundary(
925            &self,
926            progress: &lash_core::SegmentProgress,
927        ) -> Option<lash_core::BoundaryReason> {
928            progress
929                .effects_executed
930                .is_multiple_of(self.0 as u64)
931                .then_some(lash_core::BoundaryReason::JournalBudget)
932        }
933
934        async fn execute_effect(
935            &self,
936            _envelope: lash_core::RuntimeEffectEnvelope,
937            _local_executor: lash_core::RuntimeEffectLocalExecutor<'_>,
938        ) -> Result<lash_core::RuntimeEffectOutcome, lash_core::RuntimeEffectControllerError>
939        {
940            unreachable!("predicate test does not execute effects")
941        }
942    }
943
944    #[test]
945    fn every_n_controller_requests_boundaries_and_inline_default_does_not() {
946        let progress = lash_core::SegmentProgress {
947            effects_executed: 2,
948            journaled_bytes_estimate: None,
949        };
950        assert_eq!(
951            lash_core::RuntimeEffectController::wants_segment_boundary(
952                &EveryNEffectsController(2),
953                &progress,
954            ),
955            Some(lash_core::BoundaryReason::JournalBudget)
956        );
957        let inline = lash_core::InlineRuntimeEffectController::default();
958        assert_eq!(
959            lash_core::RuntimeEffectController::wants_segment_boundary(&inline, &progress,),
960            None
961        );
962    }
963
964    #[tokio::test(flavor = "current_thread")]
965    async fn foreground_trace_skeleton_is_derived_from_the_workflow_graph() {
966        let source = r#"
967            @label(title: "Seed value")
968            value = 1
969            if true {
970              @label(title: "Selected print")
971              print value
972            } else {
973              @label(title: "Skipped print")
974              print 0
975            }
976            count = 0
977            while count < 1 {
978              @label(title: "Loop print")
979              print count
980              count = count + 1
981            }
982            @label(title: "Finish value")
983            finish value
984        "#;
985        let environment = LashlangHostEnvironment::new(
986            lashlang::LashlangHostCatalog::new(),
987            LashlangAbilities::all(),
988        )
989        .with_language_features(
990            lashlang::LashlangLanguageFeatures::default().with_label_annotations(),
991        );
992        let output = lashlang::compile_module(lashlang::ModuleCompileRequest {
993            source,
994            environment: &environment,
995            artifact_store: None,
996        })
997        .await
998        .expect("labeled workflow compiles");
999        let graph = lashlang::workflow_graph_from_source(source).expect("workflow graph projects");
1000        let trace_map = trace_lashlang_main_map(&output.artifact);
1001
1002        let expected_nodes = graph
1003            .nodes()
1004            .flat_map(|node| &node.execution_sites)
1005            .map(|site| {
1006                lashlang::runtime_execution_site_for_workflow_site(&output.artifact, site)
1007                    .expect("workflow execution site should exist in the compiled artifact")
1008                    .node_id
1009            })
1010            .collect::<std::collections::BTreeSet<_>>();
1011        let actual_nodes = trace_map
1012            .nodes
1013            .iter()
1014            .map(|node| node.id.clone())
1015            .collect::<std::collections::BTreeSet<_>>();
1016
1017        assert!(!expected_nodes.is_empty());
1018        assert_eq!(actual_nodes, expected_nodes);
1019        assert!(
1020            trace_map
1021                .nodes
1022                .iter()
1023                .any(|node| node.label == "Selected print")
1024        );
1025        assert!(
1026            trace_map
1027                .nodes
1028                .iter()
1029                .any(|node| node.label == "Loop print")
1030        );
1031    }
1032
1033    #[test]
1034    fn process_input_serializes_as_generic_engine_payload() {
1035        let hash = lashlang::ContentHash::new("abc123");
1036        let input = LashlangProcessInput {
1037            module_ref: lashlang::ModuleRef::new(&hash),
1038            process_ref: lashlang::ProcessRef::new(hash.clone(), 7),
1039            host_requirements_ref: lashlang::HostRequirementsRef::new(&hash),
1040            process_name: "main".to_string(),
1041            args: serde_json::Map::from_iter([("prompt".to_string(), serde_json::json!("go"))]),
1042        };
1043
1044        let process_input = input
1045            .clone()
1046            .into_process_input()
1047            .expect("lashlang process input serializes");
1048
1049        let lash_core::ProcessInput::Engine { kind, payload } = process_input else {
1050            panic!("lashlang runtime must use the generic engine process input");
1051        };
1052        assert_eq!(kind, LASHLANG_ENGINE_KIND);
1053        assert_eq!(
1054            LashlangProcessInput::from_payload(payload)
1055                .expect("engine payload decodes")
1056                .process_name,
1057            input.process_name
1058        );
1059    }
1060
1061    #[test]
1062    fn process_input_remote_helpers_use_generic_engine_and_identity() {
1063        let hash = lashlang::ContentHash::new("abc123");
1064        let input = LashlangProcessInput {
1065            module_ref: lashlang::ModuleRef::new(&hash),
1066            process_ref: lashlang::ProcessRef::new(hash.clone(), 7),
1067            host_requirements_ref: lashlang::HostRequirementsRef::new(&hash),
1068            process_name: "main".to_string(),
1069            args: serde_json::Map::from_iter([("prompt".to_string(), serde_json::json!("go"))]),
1070        };
1071
1072        let remote_input: lash_remote_protocol::RemoteProcessInput = input
1073            .clone()
1074            .try_into()
1075            .expect("lashlang process input serializes remotely");
1076        let lash_remote_protocol::RemoteProcessInput::Engine { kind, payload } = remote_input
1077        else {
1078            panic!("lashlang runtime must use the generic remote engine process input");
1079        };
1080        assert_eq!(kind, LASHLANG_ENGINE_KIND);
1081        assert_eq!(
1082            LashlangProcessInput::from_payload(payload)
1083                .expect("remote payload decodes")
1084                .process_name,
1085            "main"
1086        );
1087
1088        let identity = input.process_identity();
1089        assert_eq!(identity.kind, LASHLANG_ENGINE_KIND);
1090        assert_eq!(identity.label.as_deref(), Some("main"));
1091        assert_eq!(input.remote_identity().label.as_deref(), Some("main"));
1092
1093        let draft = input
1094            .remote_trigger_subscription_draft(
1095                "button-main",
1096                "process-env:sha256:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
1097                    .parse()
1098                    .expect("canonical env ref"),
1099                "ui.button.pressed",
1100                "source-key",
1101            )
1102            .expect("remote trigger draft");
1103        draft.validate().expect("draft validates");
1104        assert_eq!(draft.target_label.as_deref(), Some("main"));
1105        assert_eq!(draft.target_identity.label.as_deref(), Some("main"));
1106    }
1107
1108    #[test]
1109    fn missing_tool_binding_is_not_fabricated() {
1110        let tool = lash_core::ToolDefinition::raw(
1111            "tool:test/read_file",
1112            "read_file",
1113            "read a file",
1114            lash_core::ToolDefinition::default_input_schema(),
1115            serde_json::Value::Null,
1116        );
1117
1118        let err = required_tool_lashlang_executable(&tool.manifest)
1119            .expect_err("missing explicit binding should fail");
1120
1121        assert!(err.contains("missing an explicit `lashlang.tool` binding"));
1122    }
1123
1124    #[test]
1125    fn explicit_tool_binding_attaches_lashlang_metadata() {
1126        let tool = lash_core::ToolDefinition::raw(
1127            "tool:test/read_file",
1128            "read_file",
1129            "read a file",
1130            lash_core::ToolDefinition::default_input_schema(),
1131            serde_json::Value::Null,
1132        )
1133        .with_lashlang_binding(
1134            LashlangToolBinding::new(["fs"], "read")
1135                .with_authority_type("Filesystem")
1136                .with_aliases(["cat"]),
1137        );
1138
1139        let binding =
1140            required_tool_lashlang_executable(&tool.manifest).expect("explicit binding resolves");
1141
1142        assert_eq!(binding.module_path, vec!["fs"]);
1143        assert_eq!(binding.operation, "read");
1144        assert_eq!(binding.authority_type, "Filesystem");
1145        assert_eq!(binding.aliases, vec!["cat"]);
1146    }
1147
1148    #[test]
1149    fn tool_catalog_imports_declared_static_schema_types() {
1150        let tool = lash_core::ToolDefinition::raw(
1151            "tool:test/read_file",
1152            "read_file",
1153            "read a file",
1154            serde_json::json!({
1155                "type": "object",
1156                "properties": {
1157                    "path": { "type": "string" },
1158                    "retries": { "type": "integer" }
1159                },
1160                "required": ["path"],
1161                "additionalProperties": false
1162            }),
1163            serde_json::json!({
1164                "type": "array",
1165                "items": { "type": ["string", "null"] }
1166            }),
1167        )
1168        .with_lashlang_binding(
1169            LashlangToolBinding::new(["fs"], "read").with_authority_type("Filesystem"),
1170        );
1171        let catalog = lash_core::ToolCatalog::from_tool_definitions(vec![tool]);
1172
1173        let resources =
1174            lashlang_resources_from_tool_catalog(&catalog).expect("tool schemas import");
1175        let operation = resources
1176            .resolve_operation("Filesystem", "read")
1177            .expect("operation is registered");
1178
1179        assert_eq!(
1180            operation.input_ty,
1181            lashlang::TypeExpr::Object(vec![
1182                lashlang::TypeField {
1183                    name: "path".into(),
1184                    ty: lashlang::TypeExpr::Str,
1185                    optional: false,
1186                },
1187                lashlang::TypeField {
1188                    name: "retries".into(),
1189                    ty: lashlang::TypeExpr::Int,
1190                    optional: true,
1191                },
1192            ])
1193        );
1194        assert_eq!(
1195            operation.output_ty,
1196            lashlang::TypeExpr::List(Box::new(lashlang::TypeExpr::Union(vec![
1197                lashlang::TypeExpr::Str,
1198                lashlang::TypeExpr::Null,
1199            ])))
1200        );
1201    }
1202
1203    #[test]
1204    fn from_input_schema_tool_imports_contract_marker_and_default() {
1205        let tool = lash_core::ToolDefinition::raw(
1206            "tool:test/generate",
1207            "generate",
1208            "generate typed output",
1209            serde_json::json!({
1210                "type": "object",
1211                "properties": { "schema": {} },
1212                "required": ["schema"],
1213                "additionalProperties": false
1214            }),
1215            serde_json::json!({ "type": "string" }),
1216        )
1217        .with_output_from_input_schema("schema", Some(serde_json::json!({ "type": "string" })))
1218        .with_lashlang_binding(
1219            LashlangToolBinding::new(["generate"], "run").with_authority_type("Generator"),
1220        );
1221        let catalog = lash_core::ToolCatalog::from_tool_definitions(vec![tool]);
1222
1223        let resources =
1224            lashlang_resources_from_tool_catalog(&catalog).expect("tool schemas import");
1225        let operation = resources
1226            .resolve_operation("Generator", "run")
1227            .expect("operation is registered");
1228
1229        assert_eq!(
1230            operation.input_ty,
1231            lashlang::TypeExpr::Object(vec![lashlang::TypeField {
1232                name: "schema".into(),
1233                ty: lashlang::TypeExpr::Any,
1234                optional: false,
1235            }])
1236        );
1237        assert_eq!(operation.output_ty, lashlang::TypeExpr::Any);
1238        assert_eq!(
1239            operation.output_from_input,
1240            Some(lashlang::OutputFromInputBinding {
1241                input_field: "schema".to_string(),
1242                default_schema: Some(lashlang::TypeExpr::Str),
1243            })
1244        );
1245    }
1246
1247    #[test]
1248    fn representable_type_schema_subset_round_trips() {
1249        let types = [
1250            lashlang::TypeExpr::Any,
1251            lashlang::TypeExpr::Str,
1252            lashlang::TypeExpr::Int,
1253            lashlang::TypeExpr::Float,
1254            lashlang::TypeExpr::Bool,
1255            lashlang::TypeExpr::Null,
1256            lashlang::TypeExpr::Enum(vec!["fast".into(), "safe".into()]),
1257            lashlang::TypeExpr::List(Box::new(lashlang::TypeExpr::Str)),
1258            lashlang::TypeExpr::Union(vec![lashlang::TypeExpr::Str, lashlang::TypeExpr::Null]),
1259        ];
1260
1261        for expected in types {
1262            let schema = lashlang_type_expr_schema(&expected);
1263            assert_eq!(lashlang::json_schema_to_type_expr(&schema), expected);
1264        }
1265    }
1266
1267    #[test]
1268    fn dotted_operation_names_are_rejected() {
1269        let tool = lash_core::ToolDefinition::raw(
1270            "tool:test/update_plan",
1271            "update_plan",
1272            "update a plan",
1273            lash_core::ToolDefinition::default_input_schema(),
1274            serde_json::Value::Null,
1275        )
1276        .with_lashlang_binding(LashlangToolBinding::new(["tools"], "update.plan"));
1277
1278        let err = required_tool_lashlang_executable(&tool.manifest)
1279            .expect_err("dotted operation cannot compile as one Lashlang operation");
1280
1281        assert!(err.contains("invalid Lashlang operation name `update.plan`"));
1282    }
1283
1284    #[test]
1285    fn manifest_lashlang_binding_accessor_reports_absent_valid_and_malformed() {
1286        let mut manifest = lash_core::ToolDefinition::raw(
1287            "tool:test/read_file",
1288            "read_file",
1289            "read a file",
1290            lash_core::ToolDefinition::default_input_schema(),
1291            serde_json::Value::Null,
1292        )
1293        .manifest;
1294        assert_eq!(manifest.lashlang_binding().expect("absent binding"), None);
1295
1296        manifest.bindings.insert(
1297            LASHLANG_TOOL_BINDING_KEY.to_string(),
1298            serde_json::json!({
1299                "module_path": ["fs"],
1300                "operation": "read"
1301            }),
1302        );
1303        let binding = manifest
1304            .lashlang_binding()
1305            .expect("valid binding")
1306            .expect("present binding");
1307        assert_eq!(binding.module_path, vec!["fs"]);
1308        assert_eq!(binding.operation.as_deref(), Some("read"));
1309
1310        manifest.bindings.insert(
1311            LASHLANG_TOOL_BINDING_KEY.to_string(),
1312            serde_json::json!({ "module_path": "fs" }),
1313        );
1314        assert!(manifest.lashlang_binding().is_err());
1315    }
1316
1317    #[test]
1318    fn remote_grant_lashlang_binding_accessor_reports_absent_valid_and_malformed() {
1319        let grant = remote_tool_grant("read_file");
1320        assert_eq!(grant.lashlang_binding().expect("absent binding"), None);
1321
1322        let grant = grant.with_lashlang_binding(LashlangToolBinding::new(["fs"], "read"));
1323        let binding = grant
1324            .lashlang_binding()
1325            .expect("valid binding")
1326            .expect("present binding");
1327        assert_eq!(binding.module_path, vec!["fs"]);
1328        assert_eq!(binding.operation.as_deref(), Some("read"));
1329
1330        let mut malformed = grant;
1331        malformed.bindings.insert(
1332            LASHLANG_TOOL_BINDING_KEY.to_string(),
1333            serde_json::json!({ "module_path": "fs" }),
1334        );
1335        assert!(malformed.lashlang_binding().is_err());
1336    }
1337
1338    #[test]
1339    fn deterministic_process_id_reuses_replayed_start_site_and_args() {
1340        let input = test_process_input(serde_json::json!({ "root": "." }));
1341        let site = test_start_site("child_process:scan", 1);
1342
1343        let first = deterministic_lashlang_process_id("parent:root", &site, &input)
1344            .expect("process id derives");
1345        let second = deterministic_lashlang_process_id("parent:root", &site, &input)
1346            .expect("process id derives");
1347
1348        assert_eq!(first, second);
1349        assert!(first.starts_with("process:lashlang:sha256:"));
1350    }
1351
1352    #[test]
1353    fn deterministic_process_id_separates_parallel_sites_ordinals_and_parents() {
1354        let input = test_process_input(serde_json::json!({ "root": "." }));
1355        let left = deterministic_lashlang_process_id(
1356            "parent:root",
1357            &test_start_site("child_process:left", 1),
1358            &input,
1359        )
1360        .expect("left id derives");
1361        let right = deterministic_lashlang_process_id(
1362            "parent:root",
1363            &test_start_site("child_process:right", 1),
1364            &input,
1365        )
1366        .expect("right id derives");
1367        let second_ordinal = deterministic_lashlang_process_id(
1368            "parent:root",
1369            &test_start_site("child_process:left", 2),
1370            &input,
1371        )
1372        .expect("second ordinal id derives");
1373        let nested_parent = deterministic_lashlang_process_id(
1374            "parent:nested",
1375            &test_start_site("child_process:left", 1),
1376            &input,
1377        )
1378        .expect("nested parent id derives");
1379
1380        assert_ne!(left, right);
1381        assert_ne!(left, second_ordinal);
1382        assert_ne!(left, nested_parent);
1383    }
1384
1385    #[tokio::test(flavor = "current_thread")]
1386    async fn prepared_start_replays_same_registration_id_without_duplicate_child_identity() {
1387        let store = Arc::new(InMemoryLashlangArtifactStore::new());
1388        let environment = LashlangHostEnvironment::new(
1389            lashlang::LashlangHostCatalog::new(),
1390            LashlangAbilities::default().with_processes(),
1391        );
1392        let output = lashlang::compile_module(lashlang::ModuleCompileRequest {
1393            source: r#"process scan(root: str) -> str { finish root }"#,
1394            environment: &environment,
1395            artifact_store: Some(store.as_ref()),
1396        })
1397        .await
1398        .expect("module compiles and persists");
1399        let artifact_store: Arc<dyn LashlangArtifactStore> = store;
1400        let site = test_start_site("child_process:scan", 1);
1401
1402        let first = prepare_lashlang_process_start(
1403            Arc::clone(&artifact_store),
1404            "parent:root",
1405            test_process_start(&output, site.clone(), "."),
1406        )
1407        .await
1408        .expect("first start prepares");
1409        let replayed = prepare_lashlang_process_start(
1410            Arc::clone(&artifact_store),
1411            "parent:root",
1412            test_process_start(&output, site.clone(), "."),
1413        )
1414        .await
1415        .expect("replayed start prepares");
1416        let sibling = prepare_lashlang_process_start(
1417            Arc::clone(&artifact_store),
1418            "parent:root",
1419            test_process_start(&output, test_start_site("child_process:scan", 2), "."),
1420        )
1421        .await
1422        .expect("sibling start prepares");
1423
1424        assert_eq!(first.registration.id, replayed.registration.id);
1425        assert_eq!(first.registration.identity, replayed.registration.identity);
1426        assert_ne!(first.registration.id, sibling.registration.id);
1427    }
1428
1429    #[test]
1430    fn surface_merges_plugin_extensions() {
1431        let contribution = LashlangSurfaceContribution::new(
1432            LashlangAbilities::default().with_processes(),
1433            LashlangLanguageFeatures::default().with_label_annotations(),
1434            LashlangHostCatalog::tool_default(["lookup"]),
1435        );
1436        let extensions = lash_core::PluginExtensions::from_contributions([
1437            lash_core::PluginExtensionContribution::new(
1438                LASHLANG_SURFACE_EXTENSION_ID,
1439                contribution,
1440            )
1441            .expect("extension payload serializes"),
1442        ]);
1443
1444        let surface = LashlangSurface::default()
1445            .with_plugin_extensions(&extensions)
1446            .expect("lashlang surface extension merges");
1447        let environment = surface
1448            .host_environment(&lash_core::ToolCatalog::default())
1449            .expect("empty tool catalog has no Lashlang bindings to validate");
1450
1451        assert!(environment.abilities.sleep);
1452        assert!(environment.abilities.processes);
1453        assert!(environment.language_features.label_annotations);
1454        assert!(
1455            environment
1456                .resources
1457                .resolve_module_operation("Tools", "tools", "lookup")
1458                .is_some()
1459        );
1460    }
1461
1462    fn remote_tool_grant(name: &str) -> lash_remote_protocol::RemoteToolGrant {
1463        lash_remote_protocol::RemoteToolGrant {
1464            protocol_version: lash_remote_protocol::REMOTE_PROTOCOL_VERSION,
1465            id: format!("remote-tool:{name}"),
1466            name: name.to_string(),
1467            description: String::new(),
1468            input_schema: lash_remote_protocol::RemoteSchemaContract {
1469                canonical: lash_core::ToolDefinition::default_input_schema(),
1470                projection: lash_remote_protocol::RemoteSchemaProjectionPolicy::default(),
1471            },
1472            output_schema: lash_remote_protocol::RemoteSchemaContract::default(),
1473            output_contract: lash_remote_protocol::RemoteToolOutputContract::Static,
1474            examples: Vec::new(),
1475            activation: None,
1476            argument_projection: None,
1477            retry_policy: None,
1478            bindings: Default::default(),
1479        }
1480    }
1481
1482    fn test_process_input(args: serde_json::Value) -> LashlangProcessInput {
1483        let hash = lashlang::ContentHash::new("abc123");
1484        let args = args
1485            .as_object()
1486            .expect("test args must be an object")
1487            .clone();
1488        LashlangProcessInput {
1489            module_ref: lashlang::ModuleRef::new(&hash),
1490            process_ref: lashlang::ProcessRef::new(hash.clone(), 7),
1491            host_requirements_ref: lashlang::HostRequirementsRef::new(&hash),
1492            process_name: "scan".to_string(),
1493            args,
1494        }
1495    }
1496
1497    fn test_start_site(node_id: &str, occurrence: u64) -> lashlang::LashlangExecutionCallSite {
1498        lashlang::LashlangExecutionCallSite {
1499            site: lashlang::LashlangExecutionSite {
1500                node_id: node_id.to_string(),
1501                node_kind: "child_process".to_string(),
1502                label: "start scan".to_string(),
1503                branch: None,
1504                workflow_site: lashlang::WorkflowExecutionSite::new(
1505                    "process:scan",
1506                    [],
1507                    "child_process",
1508                    "start scan",
1509                ),
1510            },
1511            occurrence,
1512        }
1513    }
1514
1515    fn test_process_start(
1516        output: &lashlang::ModuleCompileOutput,
1517        start_site: lashlang::LashlangExecutionCallSite,
1518        root: &str,
1519    ) -> lashlang::ProcessStart {
1520        let mut args = lashlang::Record::new();
1521        args.insert("root".to_string(), lashlang::Value::String(root.into()));
1522        lashlang::ProcessStart {
1523            module_ref: output.module_ref.clone(),
1524            process_ref: output
1525                .artifact
1526                .process_ref("scan")
1527                .expect("scan process export")
1528                .clone(),
1529            host_requirements_ref: output.host_requirements_ref.clone(),
1530            start_site,
1531            process_name: "scan".to_string(),
1532            args,
1533        }
1534    }
1535}