Skip to main content

greentic_runner_host/runner/
engine.rs

1use std::collections::HashMap;
2use std::error::Error as StdError;
3use std::str::FromStr;
4use std::sync::Arc;
5use std::time::Duration;
6
7use crate::component_api::node::{ExecCtx as ComponentExecCtx, TenantCtx as ComponentTenantCtx};
8use anyhow::{Context, Result, anyhow, bail};
9use chrono::{DateTime, SecondsFormat, Utc};
10use indexmap::IndexMap;
11use parking_lot::RwLock;
12use serde::{Deserialize, Serialize};
13use serde_json::{Map as JsonMap, Value, json};
14use tokio::task;
15
16use super::mocks::MockLayer;
17use super::templating::{TemplateOptions, render_template_value};
18use crate::config::{FlowRetryConfig, HostConfig};
19use crate::pack::{FlowDescriptor, PackRuntime};
20use crate::runner::approval_token;
21use crate::runner::invocation::{InvocationMeta, build_invocation_envelope_as};
22use crate::telemetry::{
23    FlowSpanAttributes, RolloutIds, annotate_span, backoff_delay_ms, set_flow_context,
24};
25#[cfg(feature = "fault-injection")]
26use crate::testing::fault_injection::{FaultContext, FaultPoint, maybe_fail};
27use crate::validate::{
28    ValidationConfig, ValidationIssue, ValidationMode, validate_component_envelope,
29    validate_tool_envelope,
30};
31use greentic_flow::SLOT_SCHEMA_METADATA_KEY;
32use greentic_types::{Flow, Node, NodeId, Routing};
33
34/// Component ID of the slot-extractor WASM component. Used to detect
35/// slot-extractor nodes and inject flow-level `slot_schema` as
36/// `slot_definitions` into the invocation payload (Phase D).
37const SLOT_EXTRACTOR_COMPONENT_ID: &str = "ai.greentic.component-slot-extractor";
38
39/// Callback trait for resolving cross-pack provider invocations.
40///
41/// When a `provider.invoke` node references a provider that is not in the
42/// current pack, the flow engine calls this resolver as a fallback.
43/// Implementations typically delegate to a capability registry that knows
44/// about all packs in the bundle.
45pub trait CrossPackResolver: Send + Sync {
46    fn invoke(
47        &self,
48        provider_id: &str,
49        provider_type: Option<&str>,
50        op: &str,
51        input: &[u8],
52        tenant: &str,
53        team: Option<&str>,
54    ) -> Result<Value>;
55}
56
57pub struct FlowEngine {
58    packs: Vec<Arc<PackRuntime>>,
59    flows: Vec<FlowDescriptor>,
60    flow_sources: HashMap<FlowKey, usize>,
61    /// Pack ids whose manifest declares a `messaging.*` provider. Such a pack's
62    /// flows are that provider's own ingress plumbing, not the application
63    /// entrypoint, so they are excluded from type-only entry-flow resolution.
64    /// Without this, a multi-provider bundle (app pack + `messaging-*` provider
65    /// packs) registers several entry `messaging` flows and
66    /// `entry_flow_by_type("messaging")` bails "ambiguous; pack_id is required".
67    messaging_provider_pack_ids: std::collections::HashSet<String>,
68    flow_cache: RwLock<HashMap<FlowKey, HostFlow>>,
69    default_env: String,
70    validation: ValidationConfig,
71    cross_pack_resolver: Option<Arc<dyn CrossPackResolver>>,
72    /// Rollout identifiers of the revision-keyed runtime this engine belongs to,
73    /// stamped onto every per-invocation `TenantCtx` for telemetry attribution
74    /// (C5.4). Empty for tenant-only (legacy) runtimes; the Phase-D revision
75    /// dispatcher supplies real IDs via [`with_rollout_ids`](Self::with_rollout_ids).
76    rollout_ids: RolloutIds,
77    /// Bridges `sorla.call` flow nodes into a separate runtime over pub/sub.
78    /// Not feature-gated: `sorla.call` is a core runtime-dispatch node.
79    remote_dispatch_handler: Option<Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>>,
80    /// The handler an `approval.call` dispatch goes through BEFORE
81    /// `remote_dispatch_handler`: the HTTP approval inbox
82    /// (`runner::approval_http`) on lanes with no broker. Read ONLY for the
83    /// approval runtime. It is a separate slot on purpose:
84    /// [`Self::remote_dispatch_configured`] reads `remote_dispatch_handler`
85    /// alone, so installing the inbox never turns a missing SoR route document
86    /// into a `sorla` remote dispatch — `sorla.call` keeps failing with
87    /// `sorla_route_missing`.
88    approval_dispatch_handler:
89        Option<Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>>,
90    /// Bridges `operala.call` flow nodes into an in-process deep-worker
91    /// runtime (see `runner::operala_node`). Not feature-gated (like
92    /// `remote_dispatch_handler`): `operala.call` is a core runtime-dispatch
93    /// node and the trait itself has no feature-gated dependencies — only the
94    /// concrete production impl (built under `operala-in-process` in
95    /// `runtime.rs`) does. `None` falls back to the existing NATS
96    /// `RemoteDispatchHandler` path (`execute_remote_dispatch`).
97    operala_node_handler: Option<Arc<dyn crate::runner::operala_node::OperalaNodeHandler>>,
98    /// Controls whether `dw.agent` nodes run in-process (default) or are
99    /// rerouted over the durable agentic NATS path (`GREENTIC_AW_DISPATCH=nats`).
100    #[cfg(feature = "agentic-worker")]
101    dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch,
102    #[cfg(feature = "agentic-worker")]
103    agent_node_handler: Option<Arc<dyn crate::runner::agent_node::AgentNodeHandler>>,
104    #[cfg(feature = "agentic-worker")]
105    graph_node_handler: Option<Arc<dyn crate::runner::graph_node::GraphNodeHandler>>,
106    /// Per-tenant MCP tool source for `component == "mcp"` flow nodes
107    /// (role `flow_editor`). Built once from env so the TTL catalog cache is
108    /// shared across nodes/flows. `None` when MCP is unconfigured/opted-out,
109    /// in which case MCP nodes fail gracefully with a clear node error.
110    #[cfg(feature = "agentic-worker")]
111    mcp_tool_source: Option<Arc<greentic_aw_runtime::McpToolSource>>,
112    /// The secrets manager the HOST injected, used to resolve an `mcp` node's
113    /// credential. `None` for a standalone runner, which then falls back to the
114    /// env-derived manager exactly as before.
115    ///
116    /// Separate from the engine's other state because it is not the engine's
117    /// own: `TenantRuntime` owns it and hands it over, the same way it hands
118    /// over `mcp_tool_source`.
119    #[cfg(feature = "agentic-worker")]
120    mcp_secrets: Option<crate::secrets::DynSecretsManager>,
121    /// Per-`(tenant, pack)` A2A tool source for `component == "a2a"` flow
122    /// nodes, built lazily from that pack's own `assets/a2a-routes.json`.
123    ///
124    /// Unlike MCP there is no env-derived source to build at construction: a
125    /// pack IS the only A2A source, and the source captures the tenant and the
126    /// deployed unit its credentials resolve under. It is cached because the
127    /// source owns the agent-card cache — rebuilding per node would refetch
128    /// every card on every turn.
129    ///
130    /// Only successes are cached. A pack that declares no agents is cheap to
131    /// re-decide (`PackRuntime::a2a_routes` is itself memoised) and caching
132    /// that answer would freeze the `GREENTIC_AW_A2A` opt-out for the life of
133    /// the process.
134    #[cfg(feature = "agentic-worker")]
135    a2a_sources: RwLock<HashMap<(String, String), Arc<greentic_aw_runtime::A2aToolSource>>>,
136    /// The port `media.create` stores its file through: the SAME port the agent
137    /// runtime hands extensions as `host.artifact.put`. `None` makes the node
138    /// answer an `artifact_unavailable` value.
139    #[cfg(feature = "agentic-worker")]
140    ext_artifact_port: Option<crate::host::ExtArtifactPort>,
141}
142
143#[derive(Clone, Debug, PartialEq, Eq, Hash)]
144struct FlowKey {
145    pack_id: String,
146    flow_id: String,
147}
148
149#[derive(Clone, Debug, Serialize, Deserialize)]
150pub struct FlowSnapshot {
151    pub pack_id: String,
152    pub flow_id: String,
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub next_flow: Option<String>,
155    pub next_node: String,
156    /// True only when this snapshot was taken because conditional routing fell
157    /// through and the node parked at ITSELF awaiting the next submit — the
158    /// card case. False for `session.wait`, whose `next_node` is the SUCCESSOR,
159    /// not the node that was waiting; attaching a person's answers there would
160    /// name a node that had not run yet. Defaulted so snapshots written before
161    /// this field behave exactly as they did.
162    #[serde(default)]
163    pub awaiting_submit: bool,
164    pub state: ExecutionState,
165}
166
167#[derive(Clone, Debug)]
168pub struct FlowWait {
169    pub reason: Option<String>,
170    pub snapshot: FlowSnapshot,
171}
172
173#[derive(Clone, Debug)]
174pub enum FlowStatus {
175    Completed,
176    Waiting(Box<FlowWait>),
177}
178
179#[derive(Clone, Debug)]
180pub struct FlowExecution {
181    pub output: Value,
182    pub status: FlowStatus,
183    /// Per-node outputs for this turn (`node_id → node_output_view(payload)`),
184    /// captured from the flow's `ExecutionState` before it is finalised.
185    /// Observability only — never affects `output`/egress.
186    pub node_outputs: JsonMap<String, Value>,
187}
188
189#[derive(Clone, Debug)]
190struct HostFlow {
191    id: String,
192    start: Option<NodeId>,
193    nodes: IndexMap<NodeId, HostNode>,
194    vars_init: JsonMap<String, Value>,
195    /// Names of `vars_init` declarations whose decl has `"required": true`.
196    /// Parsed from `metadata.extra.vars_init`; order follows the map iteration.
197    /// Not yet read by production dispatch code — this is Task 1 of the
198    /// "required flow-var fail-fast" plan; a later task consumes it to reject
199    /// flow execution when a required var has no value at start. Exercised by
200    /// `from_flow_collects_required_vars` in the meantime.
201    #[allow(dead_code)]
202    required_vars: Vec<String>,
203    /// Flow-level slot definitions extracted from `metadata.extra["greentic.slot_schema"]`.
204    /// Injected into slot-extractor component invocations at dispatch time (Phase D).
205    slot_schema: Option<Value>,
206}
207
208#[derive(Clone, Debug)]
209pub struct HostNode {
210    kind: NodeKind,
211    /// Backwards-compatible component label for observers/transcript.
212    pub component: String,
213    component_id: String,
214    operation_name: Option<String>,
215    operation_in_mapping: Option<String>,
216    payload_expr: Value,
217    routing: Routing,
218    /// Per-node implicit output bindings: after this node runs, each entry
219    /// `{ varName: template }` is rendered against a context where `prev` is
220    /// the node's own output payload, and the result is written to
221    /// `ExecutionState.vars[varName]`.
222    vars_out: Option<JsonMap<String, Value>>,
223    /// The node's `response_timeout_secs` (a positive integer), read from the
224    /// ROOT of its compiled `input.mapping` and stripped from the payload so a
225    /// component never sees it. Only the run audit reads it: the deadline an
226    /// `in_progress` event reports when the flow parks at this node.
227    response_timeout_secs: Option<u64>,
228}
229
230impl HostNode {
231    pub fn component_id(&self) -> &str {
232        &self.component_id
233    }
234
235    pub fn operation_name(&self) -> Option<&str> {
236        self.operation_name.as_deref()
237    }
238
239    pub fn operation_in_mapping(&self) -> Option<&str> {
240        self.operation_in_mapping.as_deref()
241    }
242
243    /// Whether this node is an `approval.call` gate.
244    pub(crate) fn is_approval(&self) -> bool {
245        matches!(self.kind, NodeKind::ApprovalCall { .. })
246    }
247
248    /// The canonical id of the worker an agentic node runs (`agent_id` of a
249    /// `dw.agent`, `graph_id` of a `dw.agent_graph`, the dispatch target of an
250    /// `operala.call` / `agentic.call`). `None` for every other node.
251    pub(crate) fn agent_ref(&self) -> Option<&str> {
252        match &self.kind {
253            NodeKind::DwAgent { agent_id, .. } => Some(agent_id.as_str()),
254            NodeKind::DwAgentGraph { graph_id } => Some(graph_id.as_str()),
255            NodeKind::OperalaCall { target } | NodeKind::AgenticCall { target } => {
256                Some(target.as_str())
257            }
258            _ => None,
259        }
260        .map(str::trim)
261        .filter(|id| !id.is_empty())
262    }
263
264    /// See [`HostNode::response_timeout_secs`] (the field).
265    pub(crate) fn response_timeout_secs(&self) -> Option<u64> {
266        self.response_timeout_secs
267    }
268
269    /// Whether this node runs an agentic worker: `dw.agent`, `dw.agent_graph`,
270    /// an `operala.call` deep worker, or an out-of-process `agentic.call`.
271    /// The run audit (`crate::run_outcome`) reports such a run as agentic.
272    pub(crate) fn is_agentic(&self) -> bool {
273        matches!(
274            self.kind,
275            NodeKind::DwAgent { .. }
276                | NodeKind::DwAgentGraph { .. }
277                | NodeKind::OperalaCall { .. }
278                | NodeKind::AgenticCall { .. }
279        )
280    }
281}
282
283#[cfg(test)]
284impl HostNode {
285    /// Test-only constructor. `HostNode`'s fields (and `NodeKind`/`Routing`
286    /// literals) are private to this module, so sibling-module unit tests
287    /// (e.g. `trace::recorder`) that need to build a `NodeEvent` for the
288    /// `ExecutionObserver` trait cannot construct one via struct literal.
289    /// This is additive test scaffolding only — no production behavior change.
290    pub(crate) fn for_test(component_id: &str, operation_name: Option<&str>) -> Self {
291        HostNode {
292            kind: NodeKind::Exec {
293                target_component: component_id.to_string(),
294            },
295            component: component_id.to_string(),
296            component_id: component_id.to_string(),
297            operation_name: operation_name.map(str::to_string),
298            operation_in_mapping: None,
299            payload_expr: Value::Null,
300            routing: Routing::End,
301            vars_out: None,
302            response_timeout_secs: None,
303        }
304    }
305
306    /// An `approval.call` node, for tests that only need the node's kind.
307    pub(crate) fn for_test_approval(target: &str) -> Self {
308        HostNode {
309            kind: NodeKind::ApprovalCall {
310                target: target.to_string(),
311            },
312            ..Self::for_test("approval.call", Some(target))
313        }
314    }
315
316    /// Set the node's `response_timeout_secs`.
317    pub(crate) fn with_response_timeout(mut self, secs: u64) -> Self {
318        self.response_timeout_secs = Some(secs);
319        self
320    }
321
322    /// A `dw.agent` node, for tests that only need the node's kind.
323    pub(crate) fn for_test_dw_agent(agent_id: &str) -> Self {
324        HostNode {
325            kind: NodeKind::DwAgent {
326                agent_id: agent_id.to_string(),
327                conversational: false,
328            },
329            ..Self::for_test("dw.agent", Some(agent_id))
330        }
331    }
332}
333
334#[derive(Clone, Debug)]
335enum NodeKind {
336    Exec {
337        target_component: String,
338    },
339    PackComponent {
340        component_ref: String,
341    },
342    ProviderInvoke,
343    FlowCall,
344    /// Hand the turn over to another flow and do NOT come back.
345    ///
346    /// [`FlowCall`] is a subroutine: it awaits the callee and turns a
347    /// `FlowStatus::Waiting` into a hard error, so a target that asks the user
348    /// anything can never be called. `FlowGoto` is the transfer instead — it
349    /// resolves to [`NodeControl::Jump`], which switches the walk to the target
350    /// flow rather than nesting an execution, so the target's status BECOMES
351    /// the turn's status. A target that parks parks the turn, and the snapshot
352    /// records `next_flow`, so the next inbound activity resumes inside the
353    /// target rather than back here.
354    ///
355    /// That is what a menu whose options open a conversation needs, and what
356    /// `flow.call` structurally cannot do.
357    FlowGoto,
358    BuiltinEmit {
359        kind: EmitKind,
360    },
361    BuiltinStateGet,
362    BuiltinStateSet,
363    /// Session-scoped variable write: renders `value` against the current
364    /// template context and inserts into `ExecutionState.vars[name]`.
365    /// Config shape: `{ name: String, value: any }`.
366    VarSet {
367        name: String,
368        value: Value,
369    },
370    Wait,
371    DwAgent {
372        agent_id: String,
373        /// SP2: opt into multi-turn conversation-segment park-loop behaviour.
374        /// SP3 will populate this from the flow doc; the loader defaults it false.
375        conversational: bool,
376    },
377    DwAgentGraph {
378        graph_id: String,
379    },
380    /// Native runtime-dispatch node: publishes work to a separate runtime
381    /// (e.g. sorx) via the injected [`RemoteDispatchHandler`]. `target` is the
382    /// node operation (the logical runtime target).
383    SorlaCall {
384        target: String,
385    },
386    /// Native runtime-dispatch node for the Operala runtime. Mirrors
387    /// [`SorlaCall`] but routes to the `"operala"` runtime name.
388    OperalaCall {
389        target: String,
390    },
391    /// Native runtime-dispatch node for an out-of-process agentic runtime.
392    /// Mirrors [`SorlaCall`] but routes to the `"agentic"` runtime name.
393    /// This is an ADDITIONAL path: the in-process `dw.agent` node is
394    /// completely separate and untouched.
395    AgenticCall {
396        target: String,
397    },
398    /// Native runtime-dispatch node for the Telco-X runtime. Mirrors
399    /// [`SorlaCall`] but routes to the `"telco-x"` runtime name. Wire-ready: the
400    /// runtime side (a telco-x NATS dispatch service) is not built yet, so an
401    /// `await: true` node pauses until that runtime exists.
402    TelcoXCall {
403        target: String,
404    },
405    /// Native runtime-dispatch node for the Human-in-the-Loop approval runtime.
406    /// Mirrors [`SorlaCall`] but routes to the `"approval"` runtime name and
407    /// applies an autonomy gate (auto-approve below the configured risk /
408    /// above the configured confidence) before dispatching.
409    ApprovalCall {
410        target: String,
411    },
412    /// Flow-execution MCP node (LOCKED ENCODING v2): `component == "mcp"` with
413    /// `server`/`tool` carried in the node payload/config. Invokes the named
414    /// MCP tool through the tenant's `flow_editor` MCP catalog (reusing
415    /// `greentic-aw-runtime`'s `McpToolSource`). Completely separate from the
416    /// agent-loop MCP path (role `agentic_worker`).
417    ///
418    /// `server_id`/`tool` here are the values resolved at flow-load time;
419    /// `execute_mcp` re-reads them from the rendered payload (source of truth)
420    /// and only uses these as a fallback for the legacy `operation` encoding.
421    Mcp {
422        server_id: String,
423        tool: String,
424    },
425    /// Flow-execution A2A node (LOCKED ENCODING v1): `component == "a2a"` with
426    /// `agent`/`message` carried in the node payload/config. Asks one external
427    /// A2A agent one question through the SAME
428    /// `greentic_aw_runtime::a2a_source` machinery an agentic worker's
429    /// `a2a:<agent_id>` TOOL uses — including its outcome classification, so a
430    /// flow and a worker cannot disagree about what a remote task's state
431    /// means. See [`crate::runner::a2a_node`].
432    ///
433    /// `agent_id` here is the value resolved at flow-load time; `execute_a2a`
434    /// re-reads it from the rendered payload (the source of truth) and only
435    /// uses this as the fallback for the `operation` / `a2a:<id>` ref forms.
436    A2a {
437        agent_id: String,
438    },
439    /// Flow-execution media node (LOCKED ENCODING v1): `component ==
440    /// "media.create"` with `format`/`name`/`text`/`rows`/`output` in the node
441    /// payload. Renders a `txt`/`md`/`csv`/`pdf` file and stores it through the
442    /// engine's artifact port. See [`crate::runner::media_node`].
443    MediaCreate,
444}
445
446impl NodeKind {
447    /// Whether a SUCCESSFUL run of this node may already have changed something
448    /// outside the turn (a dispatched request, a tool call, an uploaded file, a
449    /// nested flow's own effects), so re-running the turn from the start would
450    /// repeat it.
451    ///
452    /// Deliberately NOT included:
453    /// - `emit.*`: it only appends to the turn's egress, which is dropped when
454    ///   the turn fails, so a re-run re-appends into a fresh state;
455    /// - `var.set`, `state.get`, `session.wait`, `flow.goto`: no external write
456    ///   or idempotent;
457    /// - `state.set`: a plain overwrite is idempotent (a read-modify-write
458    ///   counter is not; that gap is documented in CLAUDE.md);
459    /// - generic component nodes (`Exec` / `PackComponent`): opaque to the host,
460    ///   so the host cannot tell a pure formatter from an HTTP writer. Treating
461    ///   them all as effectful would turn the whole-turn retry into a no-op for
462    ///   almost every flow. Known limitation, documented in CLAUDE.md.
463    ///
464    /// Over-conservative cases, accepted: a `flow.call` to a pure sub-flow and a
465    /// read-only `dw.agent` count as effectful on SUCCESS, because the host
466    /// cannot cheaply tell (the nested run's own flag is not surfaced, and an
467    /// agent's tools are chosen by the model at run time). The cost is that a
468    /// later transient failure in that turn is not re-run.
469    fn performs_external_effect(&self) -> bool {
470        matches!(
471            self,
472            NodeKind::ProviderInvoke
473                | NodeKind::FlowCall
474                | NodeKind::DwAgent { .. }
475                | NodeKind::DwAgentGraph { .. }
476                | NodeKind::SorlaCall { .. }
477                | NodeKind::OperalaCall { .. }
478                | NodeKind::AgenticCall { .. }
479                | NodeKind::TelcoXCall { .. }
480                | NodeKind::ApprovalCall { .. }
481                | NodeKind::Mcp { .. }
482                | NodeKind::A2a { .. }
483                | NodeKind::MediaCreate
484        )
485    }
486
487    /// Whether a FAILED run of this node may already have changed something
488    /// outside the turn. Same set as [`Self::performs_external_effect`] except
489    /// `flow.call`, whose nested `drive_flow` classifies its own failure.
490    ///
491    /// This is only the default: a failure marked [`pre_effect`] (proven to
492    /// precede every effect of the node) does not count, see the failure site in
493    /// `drive_flow_tracked`.
494    fn may_have_partial_effect_on_failure(&self) -> bool {
495        !matches!(self, NodeKind::FlowCall) && self.performs_external_effect()
496    }
497}
498
499/// Make a failure terminal when an earlier node of the turn already performed
500/// an external effect: re-running the turn would repeat it (a second SoR write,
501/// a second approval request, a second upload). Failures before any effect keep
502/// their classification, so a transient failure there still retries.
503///
504/// The rebuilt error's `Display` is only the OUTERMOST message
505/// (`err.to_string()`), the same text the error had before, because that string
506/// reaches the user-facing failure envelope (`metadata.error_message`) and a
507/// cause chain can name a host or URL. The original causes are kept as its
508/// `source()`, so `{err:#}` and `anyhow_chain_text` (operator log, redacted run
509/// error) still see the root cause.
510fn terminal_after_effects(err: anyhow::Error, effects_performed: bool) -> anyhow::Error {
511    if !effects_performed || is_after_effects_failure(&err) {
512        return err;
513    }
514    tracing::warn!(
515        error = %format!("{err:#}"),
516        "flow failed after an earlier node performed an external effect; the turn is not re-run"
517    );
518    // An error that is ALREADY terminal (a step budget, an unknown node) is
519    // rebuilt too: it still has to carry the "effects ran" marker, which a
520    // resume reads to decide whether the park may be cleared.
521    terminal_flow_error_from_after_effects(err)
522}
523
524#[derive(Clone, Debug)]
525enum EmitKind {
526    Log,
527    Response,
528    Other(String),
529}
530
531struct ComponentOverrides<'a> {
532    component: Option<&'a str>,
533    operation: Option<&'a str>,
534}
535
536struct ComponentCall {
537    component_ref: String,
538    operation: String,
539    input: Value,
540    config: Value,
541    /// Whether the originating node has an `on_error`-family route, so a
542    /// component failure is surfaced as a node_io `{errors}` output and routed
543    /// to that branch instead of aborting the flow (see `node_has_error_route`).
544    has_error_route: bool,
545}
546
547/// A flow run that failed, with what the nodes that DID run produced.
548///
549/// The terminal failure is surfaced to a session as a metadata-only `Ok`
550/// envelope (see `execute_with_retries`). That envelope used to carry no node
551/// outputs at all, so a caller reading per-node traces (the designer's Run
552/// Demo developer mode) saw nothing for a turn whose earlier steps had really
553/// run. Every `?` inside a flow run still converts from `anyhow::Error` with no
554/// outputs; only the site that has the state in hand fills them in.
555struct FlowFailure {
556    error: anyhow::Error,
557    node_outputs: JsonMap<String, Value>,
558}
559
560impl From<anyhow::Error> for FlowFailure {
561    fn from(error: anyhow::Error) -> Self {
562        Self {
563            error,
564            node_outputs: JsonMap::new(),
565        }
566    }
567}
568
569impl FlowExecution {
570    fn completed(output: Value, node_outputs: JsonMap<String, Value>) -> Self {
571        Self {
572            output,
573            status: FlowStatus::Completed,
574            node_outputs,
575        }
576    }
577
578    fn waiting(output: Value, wait: FlowWait, node_outputs: JsonMap<String, Value>) -> Self {
579        Self {
580            output,
581            status: FlowStatus::Waiting(Box::new(wait)),
582            node_outputs,
583        }
584    }
585}
586
587/// i18n key for what a chat user is told when a flow fails terminally.
588/// Resolved by [`user_facing_flow_failure_text`].
589///
590/// Deliberately generic. The engine's own error text stays in
591/// `metadata.error_message` for logs, the conformance harness and richer
592/// clients — putting it in `text` is what the surrounding code exists to
593/// prevent ("instead of leaking raw engine text to the chat").
594///
595/// It is NOT optional, and that is the point. A terminal failure on a session
596/// flow used to be reported as an `Ok` whose payload carried metadata ONLY, and
597/// every messaging provider refuses a payload with no `text`/card:
598/// `messaging-provider-telegram` returns `"text required"`, slack/teams/whatsapp
599/// /email/webex behave the same, and even `messaging-provider-webchat` — the one
600/// provider with an `extract_error_envelope` error-card path — rejects it at its
601/// `"text, adaptive_card, attachments, or extensions required"` guard BEFORE
602/// that path is reached. So a failing flow was silent on every channel: no
603/// reply, no error, nothing. The worst case is an `approval.call` gate with
604/// `mode: always`, which must reach a human and instead failed invisibly.
605///
606/// webchat still renders its styled card rather than this string: it checks the
607/// envelope first and only falls back to `text`. This message is what the other
608/// twelve providers send.
609///
610/// Localized at the **deployment** level, not per conversation. See
611/// [`user_facing_flow_failure_text`] for what that does and does not buy.
612const USER_FACING_FLOW_FAILURE_KEY: &str = "runner.flow.execution_failed";
613
614/// Runtime name `approval.call` dispatches under. The only runtime whose
615/// correlation id carries a per-dispatch `::n=` nonce — see
616/// `FlowEngine::execute_remote_dispatch`.
617pub(crate) const APPROVAL_RUNTIME: &str = "approval";
618
619/// Resolve the failure text for an explicitly supplied locale.
620///
621/// Split out from [`user_facing_flow_failure_text`] so tests can exercise every
622/// entry in the table without mutating the process environment (which is
623/// `unsafe` in Rust 2024) — the same shape as
624/// `HostConfig::oauth_broker_config_with_env`.
625///
626/// Unknown, empty and untranslated locales resolve to the English wording, and
627/// the result is **never empty**: a blank `text` is the silent-on-every-channel
628/// bug this whole path exists to prevent, so a blank table entry is corrected
629/// here rather than shipped to a user.
630fn user_facing_flow_failure_text_for(locale: &str) -> String {
631    let text = crate::runner::i18n::resolve_message(
632        USER_FACING_FLOW_FAILURE_KEY,
633        crate::runner::i18n::FLOW_EXECUTION_FAILED_EN,
634        locale,
635    );
636    if text.trim().is_empty() {
637        return crate::runner::i18n::FLOW_EXECUTION_FAILED_EN.to_string();
638    }
639    text
640}
641
642/// What a chat user is told when a flow fails terminally, in their language
643/// where we know it.
644///
645/// Two sources, in order:
646///
647/// 1. **The conversation**, via [`activity_locale`] on the inbound activity
648///    payload — the same `metadata.locale` the card path already honours. This
649///    is what makes one process able to answer two users in two languages.
650/// 2. **The deployment**, via `i18n::select_locale(None)`: `--locale`, then
651///    `GREENTIC_LOCALE`, then the system `LANG`/`LC_ALL`/`LC_MESSAGES`. The
652///    existing operator knob, and the same resolver `runner::operator` uses, so
653///    an operator serving one language sets it once for every channel.
654///
655/// Then English, for an unknown or untranslated locale.
656///
657/// **What is honestly still missing.** Source 1 depends on the *producer*
658/// stamping `metadata.locale` into the payload: `FlowContext` has no locale
659/// field, `IngressEnvelope` has no typed one (and `host.rs` sends its
660/// free-form `metadata` as `None`), and although `greentic_types::TenantCtx`
661/// carries an `i18n_id` slot meant for exactly this, every construction site on
662/// the flow path sets it `None` — only `greentic_x_provider` populates it, from
663/// a greentic-x `input_locale`. So a channel that stamps nothing falls to the
664/// deployment locale, and a deployment serving mixed languages answers them all
665/// in one. Closing that needs a typed locale on the envelope threaded onto
666/// `FlowContext`; it is not something this function can do from here.
667fn user_facing_flow_failure_text(entry: &Value) -> String {
668    let locale = activity_locale(entry)
669        .map(str::to_owned)
670        .unwrap_or_else(|| crate::runner::i18n::select_locale(None));
671    user_facing_flow_failure_text_for(&locale)
672}
673
674/// The metadata-only envelope a session flow's terminal failure is rendered as
675/// (see `USER_FACING_FLOW_FAILURE_KEY`), shared by a fresh run and by a resumed
676/// run that failed after an effect so both answer the user identically.
677fn surfaced_failure_execution(
678    input: &Value,
679    flow_id: &str,
680    err: &anyhow::Error,
681    node_outputs: JsonMap<String, Value>,
682) -> FlowExecution {
683    FlowExecution::completed(
684        json!({
685            "text": user_facing_flow_failure_text(input),
686            // Generic, user-safe, and REQUIRED for the failure to reach
687            // anyone. See `USER_FACING_FLOW_FAILURE_KEY`.
688            "metadata": {
689                "error_kind": "flow_execution_failed",
690                "error_message": err.to_string(),
691                "flow_id": flow_id,
692            }
693        }),
694        node_outputs,
695    )
696}
697
698impl FlowEngine {
699    pub async fn new(packs: Vec<Arc<PackRuntime>>, config: Arc<HostConfig>) -> Result<Self> {
700        let mut flow_sources: HashMap<FlowKey, usize> = HashMap::new();
701        let mut messaging_provider_pack_ids: std::collections::HashSet<String> =
702            std::collections::HashSet::new();
703        let mut descriptors = Vec::new();
704        let mut bindings = HashMap::new();
705        for pack in &config.pack_bindings {
706            bindings.insert(pack.pack_id.clone(), pack.flows.clone());
707        }
708        let enforce_bindings = !bindings.is_empty();
709        for (idx, pack) in packs.iter().enumerate() {
710            let pack_id = pack.metadata().pack_id.clone();
711            if enforce_bindings && !bindings.contains_key(&pack_id) {
712                bail!("no gtbind entries found for pack {}", pack_id);
713            }
714            // Mark packs that declare a `messaging.*` provider so their ingress
715            // flows are excluded from type-only entry-flow routing (see
716            // `messaging_provider_pack_ids`). Derived once here, off the hot path.
717            let declares_messaging_provider = pack
718                .provider_registry_optional()
719                .ok()
720                .flatten()
721                .map(|registry| {
722                    registry
723                        .operator_metadata()
724                        .iter()
725                        .any(|meta| meta.provider_type.starts_with("messaging."))
726                })
727                .unwrap_or(false);
728            if declares_messaging_provider {
729                messaging_provider_pack_ids.insert(pack_id.clone());
730            }
731            let flows = pack.list_flows().await?;
732            let allowed = bindings.get(&pack_id).map(|flows| {
733                flows
734                    .iter()
735                    .cloned()
736                    .collect::<std::collections::HashSet<_>>()
737            });
738            let mut seen = std::collections::HashSet::new();
739            for flow in flows {
740                if let Some(ref allow) = allowed
741                    && !allow.contains(&flow.id)
742                {
743                    continue;
744                }
745                seen.insert(flow.id.clone());
746                tracing::info!(
747                    flow_id = %flow.id,
748                    flow_type = %flow.flow_type,
749                    pack_id = %flow.pack_id,
750                    pack_index = idx,
751                    "registered flow"
752                );
753                if let Ok(flow_ir) = pack.load_flow(&flow.id) {
754                    for node in flow_ir.nodes.values() {
755                        config
756                            .secrets_policy
757                            .register_flow_secret_refs(&node.input.mapping);
758                        config
759                            .secrets_policy
760                            .register_flow_secret_refs(&node.output.mapping);
761                    }
762                }
763                flow_sources.insert(
764                    FlowKey {
765                        pack_id: flow.pack_id.clone(),
766                        flow_id: flow.id.clone(),
767                    },
768                    idx,
769                );
770                descriptors.retain(|existing: &FlowDescriptor| {
771                    !(existing.id == flow.id && existing.pack_id == flow.pack_id)
772                });
773                descriptors.push(flow);
774            }
775            if let Some(allow) = allowed {
776                let missing = allow.difference(&seen).cloned().collect::<Vec<_>>();
777                if !missing.is_empty() {
778                    bail!(
779                        "gtbind flow ids missing in pack {}: {}",
780                        pack_id,
781                        missing.join(", ")
782                    );
783                }
784            }
785        }
786
787        let mut flow_map = HashMap::new();
788        for flow in &descriptors {
789            let pack_id = flow.pack_id.clone();
790            if let Some(&pack_idx) = flow_sources.get(&FlowKey {
791                pack_id: pack_id.clone(),
792                flow_id: flow.id.clone(),
793            }) {
794                let pack_clone = Arc::clone(&packs[pack_idx]);
795                let flow_id = flow.id.clone();
796                let task_flow_id = flow_id.clone();
797                match task::spawn_blocking(move || pack_clone.load_flow(&task_flow_id)).await {
798                    Ok(Ok(loaded_flow)) => {
799                        flow_map.insert(
800                            FlowKey {
801                                pack_id: pack_id.clone(),
802                                flow_id,
803                            },
804                            HostFlow::from(loaded_flow),
805                        );
806                    }
807                    Ok(Err(err)) => {
808                        tracing::warn!(flow_id = %flow.id, error = %err, "failed to load flow metadata");
809                    }
810                    Err(err) => {
811                        tracing::warn!(flow_id = %flow.id, error = %err, "join error loading flow metadata");
812                    }
813                }
814            }
815        }
816
817        Ok(Self {
818            packs,
819            flows: descriptors,
820            flow_sources,
821            messaging_provider_pack_ids,
822            flow_cache: RwLock::new(flow_map),
823            default_env: crate::config::greentic_env_or_local(),
824            validation: config.validation.clone(),
825            cross_pack_resolver: None,
826            approval_dispatch_handler: None,
827            remote_dispatch_handler: None,
828            rollout_ids: RolloutIds::default(),
829            operala_node_handler: None,
830            #[cfg(feature = "agentic-worker")]
831            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
832            #[cfg(feature = "agentic-worker")]
833            agent_node_handler: None,
834            #[cfg(feature = "agentic-worker")]
835            graph_node_handler: None,
836            #[cfg(feature = "agentic-worker")]
837            mcp_tool_source: crate::runner::mcp_node::source_from_env(),
838            #[cfg(feature = "agentic-worker")]
839            mcp_secrets: None,
840            #[cfg(feature = "agentic-worker")]
841            a2a_sources: RwLock::new(HashMap::new()),
842            #[cfg(feature = "agentic-worker")]
843            ext_artifact_port: None,
844        })
845    }
846
847    /// Bind the rollout identifiers of the revision-keyed runtime this engine
848    /// serves, so every invocation's telemetry carries deployment/bundle/
849    /// revision attribution (C5.4). Called by the Phase-D revision dispatcher
850    /// when it constructs a revision runtime; tenant-only runtimes leave the
851    /// default (empty) IDs.
852    pub fn with_rollout_ids(mut self, rollout_ids: RolloutIds) -> Self {
853        self.rollout_ids = rollout_ids;
854        self
855    }
856
857    /// The rollout identifiers bound to this engine (read counterpart to
858    /// [`with_rollout_ids`](Self::with_rollout_ids)). Empty by default for the
859    /// legacy tenant-only path.
860    pub fn rollout_ids(&self) -> &RolloutIds {
861        &self.rollout_ids
862    }
863
864    /// The deployed unit a remote-tool credential is scoped to: this engine's
865    /// revision `bundle_id`. Read by the `mcp` node AND by the `a2a` node —
866    /// the unit is a property of the ENGINE's revision, not of the credential
867    /// category, so both must read the one value rather than each deriving its
868    /// own. The name is historical; it predates the `a2a` node.
869    ///
870    /// Read from the engine, not from `GREENTIC_BUNDLE_ID`: one greentic-start
871    /// process serves every revision of an environment, each through its own
872    /// `TenantRuntime` -> `FlowEngine` built by `TenantRuntime::load_revision`,
873    /// so the per-engine rollout identity is the only value that differs per
874    /// unit in every lane. `None` on the legacy tenant-only runtime, which then
875    /// resolves the team / `_` scopes exactly as before.
876    #[cfg(feature = "agentic-worker")]
877    pub(crate) fn mcp_credential_unit(&self) -> Option<&str> {
878        self.rollout_ids.bundle_id.as_deref()
879    }
880
881    /// Use an MCP tool source the embedding host built, in place of the one
882    /// [`FlowEngine::new`] derives from the process-global `GREENTIC_AW_*`
883    /// environment.
884    ///
885    /// Env can only ever name ONE tenant, so a host that serves many tenants
886    /// from one process cannot express its per-tenant catalog that way. Such a
887    /// host builds a source per tenant (see
888    /// `greentic_aw_runtime::McpCallerIdentity`) and injects it here.
889    ///
890    /// `None` LEAVES THE ENV-DERIVED SOURCE IN PLACE rather than clearing it —
891    /// callers thread this straight through from a host that may not have one,
892    /// and the standalone runner must keep working off its environment. Use
893    /// `GREENTIC_AW_MCP=0` to disable MCP outright.
894    #[cfg(feature = "agentic-worker")]
895    pub fn with_mcp_source(
896        mut self,
897        source: Option<Arc<greentic_aw_runtime::McpToolSource>>,
898    ) -> Self {
899        if let Some(source) = source {
900            self.mcp_tool_source = Some(source);
901        }
902        self
903    }
904
905    /// Bind the host's secrets manager for MCP credential resolution.
906    ///
907    /// Same shape and same reason as [`with_mcp_source`](Self::with_mcp_source):
908    /// `None` leaves the env-derived behaviour alone, so a standalone runner is
909    /// unaffected.
910    #[cfg(feature = "agentic-worker")]
911    pub fn with_mcp_secrets(mut self, secrets: Option<crate::secrets::DynSecretsManager>) -> Self {
912        if let Some(secrets) = secrets {
913            self.mcp_secrets = Some(secrets);
914        }
915        self
916    }
917
918    /// The manager an `mcp` node dispatches with, per
919    /// [`crate::runner::mcp_node::aw::choose_mcp_secrets`] — an explicit
920    /// `SECRETS_BACKEND` first, then the host-injected manager, then the
921    /// env-derived default.
922    #[cfg(feature = "agentic-worker")]
923    fn mcp_secrets_for_dispatch(&self) -> Option<crate::secrets::DynSecretsManager> {
924        let requested = std::env::var("SECRETS_BACKEND").ok();
925        crate::runner::mcp_node::aw::choose_mcp_secrets(
926            requested.as_deref(),
927            crate::runner::mcp_node::aw::secrets_from_env(),
928            self.mcp_secrets.as_ref(),
929        )
930    }
931
932    /// Set an optional cross-pack resolver for `provider.invoke` nodes that
933    /// reference providers in other packs (resolved via capability registry).
934    pub fn set_cross_pack_resolver(&mut self, resolver: Arc<dyn CrossPackResolver>) {
935        self.cross_pack_resolver = Some(resolver);
936    }
937
938    /// Set the handler that bridges `sorla.call` flow nodes into a separate
939    /// runtime over pub/sub. Constructed by the runner binary when a transport
940    /// (e.g. NATS) is configured.
941    pub fn set_remote_dispatch_handler(
942        &mut self,
943        handler: Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>,
944    ) {
945        self.remote_dispatch_handler = Some(handler);
946    }
947
948    /// Set the handler `approval.call` dispatches through in preference to
949    /// the shared remote-dispatch handler: the HTTP approval inbox
950    /// (`runner::approval_http`). Never consulted for any other runtime, and
951    /// never counted by [`Self::remote_dispatch_configured`].
952    pub fn set_approval_dispatch_handler(
953        &mut self,
954        handler: Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>,
955    ) {
956        self.approval_dispatch_handler = Some(handler);
957    }
958
959    /// The handler a dispatch to `runtime` goes through: the approval slot
960    /// first for the approval runtime, the shared slot otherwise.
961    fn dispatch_handler_for(
962        &self,
963        runtime: &str,
964    ) -> Option<&Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>> {
965        if runtime == APPROVAL_RUNTIME {
966            self.approval_dispatch_handler
967                .as_ref()
968                .or(self.remote_dispatch_handler.as_ref())
969        } else {
970            self.remote_dispatch_handler.as_ref()
971        }
972    }
973
974    /// Whether a [`RemoteDispatchHandler`] (e.g. NATS) is configured on this
975    /// engine. `execute_sorla_call` reads this to decide, once a route
976    /// document has failed to resolve, whether to fall back to remote
977    /// dispatch or fail outright with `sorla_route_missing`.
978    ///
979    /// [`RemoteDispatchHandler`]: crate::runner::remote_dispatch::RemoteDispatchHandler
980    #[cfg(feature = "agentic-worker")]
981    fn remote_dispatch_configured(&self) -> bool {
982        self.remote_dispatch_handler.is_some()
983    }
984
985    /// Set the handler that bridges `operala.call` flow nodes into an
986    /// in-process deep-worker runtime. Constructed by the runner binary
987    /// (`runtime.rs`, `operala-in-process` feature, unless
988    /// `GREENTIC_OPERALA_DISPATCH=nats`) so `operala.call` nodes run with no
989    /// NATS in that build. Mirrors [`set_agent_node_handler`].
990    ///
991    /// [`set_agent_node_handler`]: FlowEngine::set_agent_node_handler
992    pub fn set_operala_node_handler(
993        &mut self,
994        handler: Arc<dyn crate::runner::operala_node::OperalaNodeHandler>,
995    ) {
996        self.operala_node_handler = Some(handler);
997    }
998
999    /// Set the handler that bridges `DwAgent` flow nodes into the agentic-worker
1000    /// runtime. Constructed by the runner binary (Task 4.3).
1001    #[cfg(feature = "agentic-worker")]
1002    pub fn set_agent_node_handler(
1003        &mut self,
1004        handler: Arc<dyn crate::runner::agent_node::AgentNodeHandler>,
1005    ) {
1006        self.agent_node_handler = Some(handler);
1007    }
1008
1009    /// Set the artifact port `media.create` nodes store their file through.
1010    /// Pass the same port the agent runtime receives, so a flow's file and a
1011    /// worker's file land in the same store.
1012    #[cfg(feature = "agentic-worker")]
1013    pub fn set_ext_artifact_port(&mut self, port: Option<crate::host::ExtArtifactPort>) {
1014        self.ext_artifact_port = port;
1015    }
1016
1017    /// Set the handler that bridges `DwAgentGraph` flow nodes into the durable
1018    /// graph executor. Constructed by the pack loader (Task 8). Mirrors
1019    /// [`set_agent_node_handler`].
1020    ///
1021    /// [`set_agent_node_handler`]: FlowEngine::set_agent_node_handler
1022    #[cfg(feature = "agentic-worker")]
1023    pub fn set_graph_node_handler(
1024        &mut self,
1025        handler: Arc<dyn crate::runner::graph_node::GraphNodeHandler>,
1026    ) {
1027        self.graph_node_handler = Some(handler);
1028    }
1029
1030    /// Set the dispatch mode for `dw.agent` nodes.
1031    ///
1032    /// - [`DwAgentDispatch::InProcess`] (default): runs the agent in-process via
1033    ///   [`AgentNodeHandler`]. Zero configuration overhead; today's behaviour.
1034    /// - [`DwAgentDispatch::Nats`]: reroutes the node over the durable agentic
1035    ///   NATS path (`greentic.agentic.request.v1`), identical to an `agentic.call`
1036    ///   node. Requires [`set_remote_dispatch_handler`] to also be set.
1037    ///
1038    /// Called by `runtime.rs` when `GREENTIC_AW_DISPATCH=nats`.
1039    ///
1040    /// [`AgentNodeHandler`]: crate::runner::agent_node::AgentNodeHandler
1041    /// [`set_remote_dispatch_handler`]: FlowEngine::set_remote_dispatch_handler
1042    #[cfg(feature = "agentic-worker")]
1043    pub fn set_dw_agent_dispatch(&mut self, mode: crate::runner::agent_node::DwAgentDispatch) {
1044        self.dw_agent_dispatch = mode;
1045    }
1046
1047    async fn get_or_load_flow(&self, pack_id: &str, flow_id: &str) -> Result<HostFlow> {
1048        let key = FlowKey {
1049            pack_id: pack_id.to_string(),
1050            flow_id: flow_id.to_string(),
1051        };
1052        if let Some(flow) = self.flow_cache.read().get(&key).cloned() {
1053            return Ok(flow);
1054        }
1055
1056        let pack_idx = *self
1057            .flow_sources
1058            .get(&key)
1059            // Deterministic: re-running cannot register the flow. (A
1060            // `load_flow` I/O failure below stays retryable.)
1061            .ok_or_else(|| {
1062                terminal_flow_error(format!("flow {pack_id}:{flow_id} not registered"))
1063            })?;
1064        let pack = Arc::clone(&self.packs[pack_idx]);
1065        let flow_id_owned = flow_id.to_string();
1066        let task_flow_id = flow_id_owned.clone();
1067        let flow = task::spawn_blocking(move || pack.load_flow(&task_flow_id))
1068            .await
1069            .context("failed to join flow metadata task")??;
1070        let host_flow = HostFlow::from(flow);
1071        self.flow_cache.write().insert(
1072            FlowKey {
1073                pack_id: pack_id.to_string(),
1074                flow_id: flow_id_owned.clone(),
1075            },
1076            host_flow.clone(),
1077        );
1078        Ok(host_flow)
1079    }
1080
1081    /// Create the `flow.execute` span and install per-invocation telemetry:
1082    /// declared span fields, the task-local tenant context, and the **exported**
1083    /// `gt.*` attribution — the live `pack_id` plus any rollout identifiers from
1084    /// the owning revision runtime (C5.4). Returned for the caller to
1085    /// `.instrument()`. Both `execute` and `resume` route through here so every
1086    /// per-invocation entry point carries the same attribution.
1087    fn flow_execute_span(&self, ctx: &FlowContext<'_>) -> tracing::Span {
1088        let span = tracing::info_span!(
1089            "flow.execute",
1090            tenant = tracing::field::Empty,
1091            flow_id = tracing::field::Empty,
1092            node_id = tracing::field::Empty,
1093            tool = tracing::field::Empty,
1094            action = tracing::field::Empty
1095        );
1096        annotate_span(
1097            &span,
1098            &FlowSpanAttributes {
1099                tenant: ctx.tenant,
1100                flow_id: ctx.flow_id,
1101                node_id: ctx.node_id,
1102                tool: ctx.tool,
1103                action: ctx.action,
1104            },
1105        );
1106        set_flow_context(
1107            &span,
1108            &self.default_env,
1109            ctx.tenant,
1110            ctx.flow_id,
1111            ctx.node_id,
1112            ctx.provider_id,
1113            ctx.session_id,
1114            ctx.pack_id,
1115            &self.rollout_ids,
1116        );
1117        span
1118    }
1119
1120    pub async fn execute(&self, ctx: FlowContext<'_>, input: Value) -> Result<FlowExecution> {
1121        self.execute_with_entry(ctx, input, None).await
1122    }
1123
1124    /// [`Self::execute`] without the user-facing failure envelope: a terminal
1125    /// error is returned as `Err` even for a session flow. Used by nested
1126    /// executions (`flow.call`) whose caller must SEE the failure rather than
1127    /// receive a "something went wrong" card as if the sub-flow had succeeded.
1128    async fn execute_propagating_failure(
1129        &self,
1130        ctx: FlowContext<'_>,
1131        input: Value,
1132    ) -> Result<FlowExecution> {
1133        self.execute_with_options(ctx, input, None, false).await
1134    }
1135
1136    /// Execute a flow whose cursor starts at `entry_node` instead of the flow's
1137    /// declared entrypoint.
1138    ///
1139    /// Card-driven messaging packs carry the id of the next node to run on the
1140    /// inbound activity (the designer emits it as `nextCardId`). A host that can
1141    /// only call [`FlowEngine::execute`] restarts such a flow at its entrypoint
1142    /// on every turn, so the capture nodes chained between two cards never run.
1143    ///
1144    /// Unlike [`FlowEngine::resume`] this needs no persisted `FlowSnapshot`:
1145    /// state starts fresh from `input`. That is what makes it usable for packs
1146    /// whose pause points are rendered cards rather than `session.wait` nodes —
1147    /// those never park, so they never leave a snapshot behind.
1148    ///
1149    /// An `entry_node` that is not a node of the flow is a hard error. Falling
1150    /// back to the entrypoint would re-introduce the silent restart this exists
1151    /// to remove.
1152    pub async fn execute_from(
1153        &self,
1154        ctx: FlowContext<'_>,
1155        input: Value,
1156        entry_node: &str,
1157    ) -> Result<FlowExecution> {
1158        self.execute_with_entry(ctx, input, Some(entry_node.to_string()))
1159            .await
1160    }
1161
1162    async fn execute_with_entry(
1163        &self,
1164        ctx: FlowContext<'_>,
1165        input: Value,
1166        entry_node: Option<String>,
1167    ) -> Result<FlowExecution> {
1168        self.execute_with_options(ctx, input, entry_node, true)
1169            .await
1170    }
1171
1172    /// `surface_failures`: convert a terminal error of a session flow into a
1173    /// metadata-only completed envelope (top-level behaviour) instead of
1174    /// returning it.
1175    async fn execute_with_options(
1176        &self,
1177        ctx: FlowContext<'_>,
1178        input: Value,
1179        entry_node: Option<String>,
1180        surface_failures: bool,
1181    ) -> Result<FlowExecution> {
1182        // Validate the caller's entry node BEFORE the retry loop below, whose
1183        // session-flow arm converts a terminal error into an Ok envelope. A
1184        // node id the flow does not have is a caller/pack defect, not a
1185        // transient failure, and must surface as an error rather than as a
1186        // rendered "something went wrong" card.
1187        if let Some(node) = entry_node.as_deref() {
1188            let flow_ir = self.get_or_load_flow(ctx.pack_id, ctx.flow_id).await?;
1189            let node_id = NodeId::from_str(node)
1190                .with_context(|| format!("invalid entry node id `{node}`"))?;
1191            if !flow_ir.nodes.contains_key(&node_id) {
1192                return Err(terminal_flow_error(format!(
1193                    "flow {} has no node `{}`",
1194                    ctx.flow_id, node
1195                )));
1196            }
1197        }
1198        let span = self.flow_execute_span(&ctx);
1199        let retry_config = ctx.retry_config;
1200        let original_input = input;
1201        let mut ctx = ctx;
1202        let metric_tenant = ctx.tenant.to_string();
1203        let metric_flow_id = ctx.flow_id.to_string();
1204        let started = std::time::Instant::now();
1205        let observer = ctx.observer;
1206        // Set when a session flow's terminal failure was rendered as a
1207        // completed envelope: metrics must still report it as a failure.
1208        let mut surfaced_failure = false;
1209        let surfaced_ref = &mut surfaced_failure;
1210        let result = async move {
1211            let mut attempt = 0u32;
1212            loop {
1213                attempt += 1;
1214                ctx.attempt = attempt;
1215                if let Some(observer) = ctx.observer {
1216                    observer.on_flow_attempt(ctx.flow_id, attempt);
1217                }
1218                #[cfg(feature = "fault-injection")]
1219                {
1220                    let fault_ctx = FaultContext {
1221                        pack_id: ctx.pack_id,
1222                        flow_id: ctx.flow_id,
1223                        node_id: ctx.node_id,
1224                        attempt: ctx.attempt,
1225                    };
1226                    maybe_fail(FaultPoint::Timeout, fault_ctx).map_err(injected_error)?;
1227                }
1228                match self
1229                    .execute_once(&ctx, original_input.clone(), entry_node.clone())
1230                    .await
1231                {
1232                    Ok(value) => return Ok(value),
1233                    Err(FlowFailure {
1234                        error: err,
1235                        node_outputs,
1236                    }) => {
1237                        if attempt >= retry_config.max_attempts || !should_retry(&err) {
1238                            // User-facing session flows surface the terminal
1239                            // error as a metadata-only Ok envelope so the
1240                            // messaging provider renders it instead of leaking
1241                            // raw engine text to the chat.
1242                            if surface_failures && ctx.session_id.is_some() {
1243                                *surfaced_ref = true;
1244                                return Ok(surfaced_failure_execution(
1245                                    &original_input,
1246                                    ctx.flow_id,
1247                                    &err,
1248                                    node_outputs,
1249                                ));
1250                            }
1251                            return Err(err);
1252                        }
1253                        let delay = backoff_delay_ms(retry_config.base_delay_ms, attempt - 1);
1254                        tracing::warn!(
1255                            tenant = ctx.tenant,
1256                            flow_id = ctx.flow_id,
1257                            attempt,
1258                            max_attempts = retry_config.max_attempts,
1259                            delay_ms = delay,
1260                            error = %err,
1261                            "transient flow execution failure, backing off"
1262                        );
1263                        tokio::time::sleep(Duration::from_millis(delay)).await;
1264                    }
1265                }
1266            }
1267        }
1268        .instrument(span)
1269        .await;
1270        if let Some(observer) = observer {
1271            observer.on_flow_exit(&metric_flow_id);
1272        }
1273        let status = if result.is_ok() && !surfaced_failure {
1274            "ok"
1275        } else {
1276            "err"
1277        };
1278        let duration_ms = started.elapsed().as_secs_f64() * 1000.0;
1279        crate::metrics::record_flow_execution(&metric_tenant, &metric_flow_id, status, duration_ms);
1280        result
1281    }
1282
1283    pub async fn resume(
1284        &self,
1285        ctx: FlowContext<'_>,
1286        snapshot: FlowSnapshot,
1287        input: Value,
1288    ) -> Result<FlowExecution> {
1289        self.resume_with_options(ctx, snapshot, input, false).await
1290    }
1291
1292    /// [`Self::resume`] for the top-level turn path. A resumed run whose failure
1293    /// FOLLOWED an external effect of that same run (`is_after_effects_failure`)
1294    /// is rendered as the same metadata-only envelope a fresh run gets, as an
1295    /// `Ok` completed execution, so the caller clears the park exactly as it
1296    /// does for any completed turn; returning `Err` would leave the snapshot in
1297    /// place and the next message would resume it and repeat the effect. Every
1298    /// other failure (deterministic pre-effect, transient pre-effect) is still
1299    /// an `Err` and the park is kept, so a transient one can be retried.
1300    pub async fn resume_surfacing_failures(
1301        &self,
1302        ctx: FlowContext<'_>,
1303        snapshot: FlowSnapshot,
1304        input: Value,
1305    ) -> Result<FlowExecution> {
1306        self.resume_with_options(ctx, snapshot, input, true).await
1307    }
1308
1309    async fn resume_with_options(
1310        &self,
1311        ctx: FlowContext<'_>,
1312        snapshot: FlowSnapshot,
1313        input: Value,
1314        surface_after_effects: bool,
1315    ) -> Result<FlowExecution> {
1316        if snapshot.pack_id != ctx.pack_id {
1317            return Err(terminal_flow_error(format!(
1318                "snapshot pack {} does not match requested {}",
1319                snapshot.pack_id, ctx.pack_id
1320            )));
1321        }
1322        let resume_flow = snapshot
1323            .next_flow
1324            .clone()
1325            .unwrap_or_else(|| snapshot.flow_id.clone());
1326        let flow_ir = self.get_or_load_flow(ctx.pack_id, &resume_flow).await?;
1327        // Computed before `snapshot.state` is moved out below, since it borrows
1328        // `snapshot` (specifically `next_node` and `awaiting_submit`).
1329        let pending_card_answers = pending_from_snapshot(&snapshot, &input);
1330        let resumed_at = resumed_card_node(&snapshot);
1331        let mut state = snapshot.state;
1332        state.resumed_at = resumed_at;
1333        // `redirect_limit` guards a loop inside ONE inbound turn. A new inbound
1334        // message is a new turn, so gotos from earlier parked turns must not
1335        // count against it (the 4th goto across turns used to fail).
1336        state.reset_redirect_count();
1337        // Replace BOTH `input` AND `entry` with the new activity. The
1338        // routing context (built by `build_routing_context`) reads
1339        // `entry.input.metadata.*` for the synthesised `response.*` fields
1340        // that conditional routes test against — keeping the snapshot's
1341        // stale entry would make `response.action` perpetually empty and
1342        // every condition fail, looping the user back to the wait point
1343        // forever. `replace_input` only touches `state.input`, so we have
1344        // to refresh `entry` ourselves; `ensure_entry` is a no-op once
1345        // entry is non-null.
1346        state.replace_input(input.clone());
1347        let surfaced_input = surface_after_effects.then(|| input.clone());
1348        // Park the submitted fields for the node that was awaiting them. Only a
1349        // snapshot flagged `awaiting_submit` names the waiting node in
1350        // `next_node`; `session.wait` names its SUCCESSOR, which has not run.
1351        state.pending_card_answers = pending_card_answers;
1352        state.entry = input;
1353        let span = self.flow_execute_span(&ctx);
1354        let result = self
1355            .drive_flow(&ctx, flow_ir, state, Some(snapshot.next_node), resume_flow)
1356            .instrument(span)
1357            .await;
1358        match result {
1359            Ok(execution) => Ok(execution),
1360            Err(failure) => match surfaced_input {
1361                Some(input)
1362                    if ctx.session_id.is_some() && is_after_effects_failure(&failure.error) =>
1363                {
1364                    tracing::warn!(
1365                        error = %format!("{:#}", failure.error),
1366                        flow_id = ctx.flow_id,
1367                        "resumed flow failed after an effect; surfacing the failure and clearing the park"
1368                    );
1369                    Ok(surfaced_failure_execution(
1370                        &input,
1371                        ctx.flow_id,
1372                        &failure.error,
1373                        failure.node_outputs,
1374                    ))
1375                }
1376                _ => Err(failure.error),
1377            },
1378        }
1379    }
1380
1381    async fn execute_once(
1382        &self,
1383        ctx: &FlowContext<'_>,
1384        input: Value,
1385        entry_node: Option<String>,
1386    ) -> Result<FlowExecution, FlowFailure> {
1387        let flow_ir = self.get_or_load_flow(ctx.pack_id, ctx.flow_id).await?;
1388        let mut state = ExecutionState::new(input);
1389        let missing = seed_vars_and_collect_missing_required(
1390            &flow_ir.vars_init,
1391            &flow_ir.required_vars,
1392            &mut state.vars,
1393        );
1394        if !missing.is_empty() {
1395            // Non-retryable by design: the message avoids should_retry's trigger
1396            // words (transient/unavailable/internal/timeout).
1397            let label = crate::runner::i18n::resolve_message(
1398                "runner.flow.required_var_missing",
1399                "required flow variable not provided",
1400                "en",
1401            );
1402            return Err(terminal_flow_error(format!("{label}: {}", missing.join(", "))).into());
1403        }
1404        self.drive_flow(ctx, flow_ir, state, entry_node, ctx.flow_id.to_string())
1405            .await
1406    }
1407
1408    /// Drive the flow, making any failure terminal once a node of THIS run has
1409    /// performed an external effect (see [`terminal_after_effects`]). Both retry
1410    /// layers (the engine's own and the state machine's whole-turn retry) read
1411    /// that classification, so neither re-runs the effects.
1412    async fn drive_flow(
1413        &self,
1414        ctx: &FlowContext<'_>,
1415        flow_ir: HostFlow,
1416        state: ExecutionState,
1417        resume_from: Option<String>,
1418        current_flow_id: String,
1419    ) -> Result<FlowExecution, FlowFailure> {
1420        let mut effects_performed = false;
1421        self.drive_flow_tracked(
1422            ctx,
1423            flow_ir,
1424            state,
1425            resume_from,
1426            current_flow_id,
1427            &mut effects_performed,
1428        )
1429        .await
1430        .map_err(|failure| FlowFailure {
1431            error: terminal_after_effects(failure.error, effects_performed),
1432            node_outputs: failure.node_outputs,
1433        })
1434    }
1435
1436    async fn drive_flow_tracked(
1437        &self,
1438        ctx: &FlowContext<'_>,
1439        mut flow_ir: HostFlow,
1440        mut state: ExecutionState,
1441        resume_from: Option<String>,
1442        mut current_flow_id: String,
1443        effects_performed: &mut bool,
1444    ) -> Result<FlowExecution, FlowFailure> {
1445        let mut current = match resume_from {
1446            Some(node) => NodeId::from_str(&node)
1447                .with_context(|| format!("invalid resume node id `{node}`"))?,
1448            None => flow_ir
1449                .start
1450                .clone()
1451                .or_else(|| flow_ir.nodes.keys().next().cloned())
1452                .ok_or_else(|| {
1453                    terminal_flow_error(format!("flow {} has no start node", flow_ir.id))
1454                })?,
1455        };
1456
1457        let mut steps_run: usize = 0;
1458        loop {
1459            steps_run += 1;
1460            check_step_budget(steps_run, flow_ir.id.as_str())?;
1461            let step_ctx = FlowContext {
1462                tenant: ctx.tenant,
1463                pack_id: ctx.pack_id,
1464                flow_id: current_flow_id.as_str(),
1465                node_id: ctx.node_id,
1466                tool: ctx.tool,
1467                action: ctx.action,
1468                session_id: ctx.session_id,
1469                provider_id: ctx.provider_id,
1470                reply_scope: ctx.reply_scope,
1471                retry_config: ctx.retry_config,
1472                attempt: ctx.attempt,
1473                observer: ctx.observer,
1474                mocks: ctx.mocks,
1475                // Propagated, never re-established: only the run entry may
1476                // read a caller (see `crate::caller_identity`).
1477                caller: ctx.caller,
1478            };
1479            let node = flow_ir
1480                .nodes
1481                .get(&current)
1482                .with_context(|| format!("node {} not found", current.as_str()))?;
1483
1484            let payload_template = node.payload_expr.clone();
1485            let prev = state
1486                .last_output
1487                .as_ref()
1488                .cloned()
1489                .unwrap_or_else(|| Value::Object(JsonMap::new()));
1490            let ctx_value = template_context(&state, prev);
1491            #[cfg(feature = "fault-injection")]
1492            {
1493                let fault_ctx = FaultContext {
1494                    pack_id: ctx.pack_id,
1495                    flow_id: ctx.flow_id,
1496                    node_id: Some(current.as_str()),
1497                    attempt: ctx.attempt,
1498                };
1499                maybe_fail(FaultPoint::TemplateRender, fault_ctx).map_err(injected_error)?;
1500            }
1501            let mut payload =
1502                render_template_value(&payload_template, &ctx_value, TemplateOptions::default())
1503                    .context("failed to render node input template")?;
1504            let node_id = current.clone();
1505
1506            // Phase D: inject flow-level slot_schema as slot_definitions into
1507            // the slot-extractor's input when the author omitted inline
1508            // definitions. Explicit inline `slot_definitions` win
1509            // (back-compat with M2.4 NDA demo).
1510            if let NodeKind::Exec { target_component } = &node.kind
1511                && target_component == SLOT_EXTRACTOR_COMPONENT_ID
1512                && let Some(schema) = flow_ir.slot_schema.as_ref()
1513                && let Some(map) = payload.as_object_mut()
1514            {
1515                let input = map.entry("input").or_insert(Value::Null);
1516                inject_slot_definitions(input, schema, step_ctx.flow_id, node_id.as_str());
1517            }
1518
1519            let observed_payload = payload.clone();
1520            let event = NodeEvent {
1521                context: &step_ctx,
1522                node_id: node_id.as_str(),
1523                node,
1524                payload: &observed_payload,
1525            };
1526            if let Some(observer) = step_ctx.observer {
1527                observer.on_node_start(&event);
1528            }
1529            let dispatch = self
1530                .dispatch_node(
1531                    &step_ctx,
1532                    node_id.as_str(),
1533                    node,
1534                    &mut state,
1535                    payload,
1536                    &event,
1537                )
1538                .await;
1539            let DispatchOutcome {
1540                mut output,
1541                control,
1542            } = match dispatch {
1543                Ok(outcome) => outcome,
1544                Err(err) => {
1545                    if let Some(observer) = step_ctx.observer {
1546                        observer.on_node_error(&event, err.as_ref());
1547                    }
1548                    // Propagate so `execute()`'s retry loop can retry transient
1549                    // failures, then convert to a metadata-only Ok envelope at
1550                    // the top level once retries are exhausted (session flows).
1551                    // The envelope keeps what the earlier nodes produced.
1552                    //
1553                    // An effectful node that fails may already have done part
1554                    // of its work (a published request, a tool call that ran
1555                    // before the next one failed), so a TRANSIENT failure here
1556                    // must not re-run the turn either. `FlowCall` is exempt: the
1557                    // nested `drive_flow` tracks its own effects and has already
1558                    // made the failure terminal when it had any. Errors that are
1559                    // not retryable anyway (validation, config) are unaffected.
1560                    //
1561                    // A failure PROVEN to precede every effect (marked with
1562                    // `pre_effect`: no handler configured, a payload that did not
1563                    // validate, a request that was never published) leaves the
1564                    // flag alone, so a transient one of those still retries. The
1565                    // default stays conservative: an unmarked error sets it.
1566                    if node.kind.may_have_partial_effect_on_failure() && !is_pre_effect_error(&err)
1567                    {
1568                        *effects_performed = true;
1569                    }
1570                    return Err(FlowFailure {
1571                        error: err,
1572                        node_outputs: state.outputs_map(),
1573                    });
1574                }
1575            };
1576
1577            if node.kind.performs_external_effect() {
1578                *effects_performed = true;
1579            }
1580            let owned_the_submit =
1581                attach_pending_card_answers(&mut state, node_id.as_str(), node, &mut output);
1582            state.note_created_artifacts(std::mem::take(&mut output.created));
1583            state.record_node_output(node_id.clone().into(), output.clone());
1584            state.last_output = Some(output.payload.clone());
1585            // Apply per-node vars_out bindings: render each template against a
1586            // context where `prev` is this node's own output payload (already
1587            // stored in state.last_output above), then write into state.vars.
1588            if let Some(bindings) = node.vars_out.as_ref() {
1589                let ctx = template_context(&state, output.payload.clone());
1590                for (var_name, template) in bindings.iter() {
1591                    let rendered = render_template_value(
1592                        template,
1593                        &ctx,
1594                        TemplateOptions {
1595                            allow_pointer: true,
1596                        },
1597                    )
1598                    .with_context(|| format!("failed to render vars_out binding `{var_name}`"))?;
1599                    state.vars.insert(var_name.clone(), rendered);
1600                }
1601            }
1602            if let Some(observer) = step_ctx.observer {
1603                observer.on_node_end(&event, &output.payload);
1604            }
1605
1606            match control {
1607                NodeControl::Continue => {
1608                    enum NextDecision {
1609                        Next(NodeId),
1610                        End,
1611                        Wait,
1612                    }
1613                    let decision = match &node.routing {
1614                        Routing::Next { node_id } => NextDecision::Next(node_id.clone()),
1615                        Routing::End | Routing::Reply => NextDecision::End,
1616                        Routing::Branch { on_status, default } => {
1617                            match branch_target(on_status, default.as_ref(), &output) {
1618                                Some(target) => NextDecision::Next(target),
1619                                None => NextDecision::End,
1620                            }
1621                        }
1622                        Routing::Custom(raw) => {
1623                            match evaluate_custom_routing(raw, &output, &state, &flow_ir, &node_id)
1624                            {
1625                                CustomRoutingDecision::Next(nid) => NextDecision::Next(nid),
1626                                CustomRoutingDecision::End => NextDecision::End,
1627                                CustomRoutingDecision::Wait => NextDecision::Wait,
1628                            }
1629                        }
1630                    };
1631
1632                    // This node has now routed on the submit that was delivered
1633                    // to it, so the action is spent. `response.*` is synthesised
1634                    // from the run's entry envelope and is therefore run-scoped:
1635                    // left in place it matches again at the NEXT card and the
1636                    // run walks straight past it, advancing the journey by two
1637                    // pages per submit. Clearing it here means every later node
1638                    // sees a freshly rendered card with no pending action, falls
1639                    // through its conditional routing, and parks for the user.
1640                    if owned_the_submit {
1641                        consume_routing_action(&mut state.entry);
1642                    }
1643                    // Routed (or parked): the resume it carried is spent.
1644                    state.resumed_at = None;
1645
1646                    match decision {
1647                        NextDecision::Next(n) => current = n,
1648                        NextDecision::End => {
1649                            let node_outputs = state.outputs_map();
1650                            let failure = state.first_unhandled_failure(&flow_ir);
1651                            let final_output = state.finalize_with(Some(output.payload.clone()));
1652                            return Ok(FlowExecution::completed(
1653                                lift_node_error(final_output, failure.as_ref()),
1654                                node_outputs,
1655                            ));
1656                        }
1657                        NextDecision::Wait => {
1658                            // Conditional routing fell through. Pause at the
1659                            // current node so the next inbound activity
1660                            // resumes here and re-evaluates this node's
1661                            // routing with the user's new submit payload.
1662                            let mut snapshot_state = state.clone();
1663                            snapshot_state.clear_egress();
1664                            let snapshot = FlowSnapshot {
1665                                pack_id: step_ctx.pack_id.to_string(),
1666                                flow_id: step_ctx.flow_id.to_string(),
1667                                next_flow: (current_flow_id != step_ctx.flow_id)
1668                                    .then_some(current_flow_id.clone()),
1669                                next_node: node_id.as_str().to_string(),
1670                                awaiting_submit: true,
1671                                state: snapshot_state,
1672                            };
1673                            let node_outputs = state.outputs_map();
1674                            let output_value = state.finalize_with(Some(output.payload.clone()));
1675                            return Ok(FlowExecution::waiting(
1676                                output_value,
1677                                FlowWait {
1678                                    reason: Some(format!(
1679                                        "awaiting user submit at node `{}`",
1680                                        node_id.as_str()
1681                                    )),
1682                                    snapshot,
1683                                },
1684                                node_outputs,
1685                            ));
1686                        }
1687                    }
1688                }
1689                NodeControl::Wait { reason } => {
1690                    let next: Option<NodeId> = match &node.routing {
1691                        Routing::Next { node_id } => Some(node_id.clone()),
1692                        Routing::End | Routing::Reply => None,
1693                        Routing::Branch { on_status, default } => {
1694                            branch_target(on_status, default.as_ref(), &output)
1695                        }
1696                        Routing::Custom(raw) => {
1697                            match evaluate_custom_routing(raw, &output, &state, &flow_ir, &node_id)
1698                            {
1699                                CustomRoutingDecision::Next(nid) => Some(nid),
1700                                // session.wait operator must have an
1701                                // explicit forward target — both End and
1702                                // Wait decisions collapse to "no next" and
1703                                // surface the same error below.
1704                                CustomRoutingDecision::End | CustomRoutingDecision::Wait => None,
1705                            }
1706                        }
1707                    };
1708                    let resume_target = next.ok_or_else(|| {
1709                        anyhow!(
1710                            "session.wait node {} requires a non-empty route",
1711                            current.as_str()
1712                        )
1713                    })?;
1714                    let mut snapshot_state = state.clone();
1715                    snapshot_state.clear_egress();
1716                    let snapshot = FlowSnapshot {
1717                        pack_id: step_ctx.pack_id.to_string(),
1718                        flow_id: step_ctx.flow_id.to_string(),
1719                        next_flow: (current_flow_id != step_ctx.flow_id)
1720                            .then_some(current_flow_id.clone()),
1721                        next_node: resume_target.as_str().to_string(),
1722                        awaiting_submit: false,
1723                        state: snapshot_state,
1724                    };
1725                    let node_outputs = state.outputs_map();
1726                    let output_value = state.clone().finalize_with(None);
1727                    return Ok(FlowExecution::waiting(
1728                        output_value,
1729                        FlowWait { reason, snapshot },
1730                        node_outputs,
1731                    ));
1732                }
1733                NodeControl::LoopHere { reason } => {
1734                    // Conversational dw.agent: park and re-enter THIS node so the
1735                    // next user message drives the next turn. Render the reply
1736                    // (finalize_with Some) — unlike NodeControl::Wait, which
1737                    // resumes at the successor and finalizes with None.
1738                    let mut snapshot_state = state.clone();
1739                    snapshot_state.clear_egress();
1740                    let snapshot = FlowSnapshot {
1741                        pack_id: step_ctx.pack_id.to_string(),
1742                        flow_id: step_ctx.flow_id.to_string(),
1743                        next_flow: (current_flow_id != step_ctx.flow_id)
1744                            .then_some(current_flow_id.clone()),
1745                        next_node: node_id.as_str().to_string(),
1746                        awaiting_submit: false,
1747                        state: snapshot_state,
1748                    };
1749                    let node_outputs = state.outputs_map();
1750                    // A `dw.agent` parked on a `flow:` tool renders that flow's
1751                    // card, not its own envelope: the card is what the user
1752                    // must answer, and channels render the turn output as they
1753                    // would a card node's. The full envelope (carrying the
1754                    // card as `pending_presentation`) stays the node output.
1755                    let rendered = rendered_park(&output.payload);
1756                    let output_value = state.finalize_with(Some(rendered));
1757                    return Ok(FlowExecution::waiting(
1758                        output_value,
1759                        FlowWait { reason, snapshot },
1760                        node_outputs,
1761                    ));
1762                }
1763                NodeControl::AwaitHere {
1764                    reason,
1765                    correlation_id: _,
1766                } => {
1767                    // Await the async agent response, but resume at THIS node so
1768                    // the conversational branch evaluates `terminated_by`. Mirror the
1769                    // remote-await Wait snapshot construction EXCEPT next_node = self.
1770                    //
1771                    // Keying note: the resume snapshot is stored under the SAME
1772                    // `(session_hint, scope_hash)` store key as every other wait kind
1773                    // (`build_store_ctx` strips the correlation from the key). The
1774                    // correlation id is NOT part of the key — it only drives how the
1775                    // NATS response reconstructs the hint/scope (RuntimeSessionResumer)
1776                    // so it recomputes that same key. So an AwaitHere park and a later
1777                    // LoopHere park for the same conversation occupy the same single
1778                    // slot; they never coexist because each park overwrites it. Safety
1779                    // rests on sequential single-slot resume, not key separation — an
1780                    // inbound arriving mid-await resolves to this slot (a known
1781                    // interleaving limitation, tracked as a follow-up).
1782                    let mut snapshot_state = state.clone();
1783                    snapshot_state.clear_egress();
1784                    let snapshot = FlowSnapshot {
1785                        pack_id: step_ctx.pack_id.to_string(),
1786                        flow_id: step_ctx.flow_id.to_string(),
1787                        next_flow: (current_flow_id != step_ctx.flow_id)
1788                            .then_some(current_flow_id.clone()),
1789                        next_node: node_id.as_str().to_string(), // SELF, not successor
1790                        awaiting_submit: false,
1791                        state: snapshot_state,
1792                    };
1793                    let node_outputs = state.outputs_map();
1794                    // Finalize with None (render nothing here — the reply, if any,
1795                    // was already surfaced before the dispatch): match the
1796                    // remote-await Wait finalize semantics confirmed in Task 1.
1797                    let output_value = state.clone().finalize_with(None);
1798                    return Ok(FlowExecution::waiting(
1799                        output_value,
1800                        FlowWait { reason, snapshot },
1801                        node_outputs,
1802                    ));
1803                }
1804                NodeControl::Jump(jump) => {
1805                    let jump_target = self.apply_jump(&step_ctx, &mut state, jump).await?;
1806                    flow_ir = jump_target.flow;
1807                    current_flow_id = jump_target.flow_id;
1808                    current = jump_target.node_id;
1809                }
1810                NodeControl::Respond {
1811                    text,
1812                    card_cbor,
1813                    needs_user,
1814                } => {
1815                    let response = json!({
1816                        "text": text,
1817                        "card_cbor": card_cbor,
1818                        "needs_user": needs_user,
1819                    });
1820                    state.push_egress(response);
1821                    let node_outputs = state.outputs_map();
1822                    let failure = state.first_unhandled_failure(&flow_ir);
1823                    let final_output = state.finalize_with(None);
1824                    return Ok(FlowExecution::completed(
1825                        lift_node_error(final_output, failure.as_ref()),
1826                        node_outputs,
1827                    ));
1828                }
1829            }
1830        }
1831    }
1832
1833    async fn dispatch_node(
1834        &self,
1835        ctx: &FlowContext<'_>,
1836        node_id: &str,
1837        node: &HostNode,
1838        state: &mut ExecutionState,
1839        mut payload: Value,
1840        event: &NodeEvent<'_>,
1841    ) -> Result<DispatchOutcome> {
1842        inject_card_locale(&mut payload, &state.entry);
1843        inject_card_route(&mut payload, &state.entry, node);
1844        match &node.kind {
1845            NodeKind::Exec { target_component } => self
1846                .execute_component_exec(
1847                    ctx,
1848                    node_id,
1849                    node,
1850                    payload,
1851                    event,
1852                    ComponentOverrides {
1853                        component: Some(target_component.as_str()),
1854                        operation: node.operation_name.as_deref(),
1855                    },
1856                )
1857                .await
1858                .and_then(component_dispatch_outcome),
1859            NodeKind::PackComponent { component_ref } => self
1860                .execute_component_call(ctx, node_id, node, payload, component_ref.as_str(), event)
1861                .await
1862                .and_then(component_dispatch_outcome),
1863            NodeKind::FlowCall => self
1864                .execute_flow_call(ctx, payload)
1865                .await
1866                .map(DispatchOutcome::complete),
1867            NodeKind::FlowGoto => execute_flow_goto(payload),
1868            NodeKind::ProviderInvoke => self
1869                .execute_provider_invoke(ctx, node_id, state, payload, event)
1870                .await
1871                .map(DispatchOutcome::complete),
1872            NodeKind::BuiltinEmit { kind } => {
1873                match kind {
1874                    EmitKind::Log | EmitKind::Response => {}
1875                    EmitKind::Other(component) => {
1876                        tracing::debug!(%component, "handling emit.* as builtin");
1877                    }
1878                }
1879                state.push_egress(payload.clone());
1880                Ok(DispatchOutcome::complete(NodeOutput::new(payload)))
1881            }
1882            NodeKind::BuiltinStateGet => self
1883                .execute_state_get(ctx, payload)
1884                .await
1885                .map(DispatchOutcome::complete),
1886            NodeKind::BuiltinStateSet => self
1887                .execute_state_set(ctx, payload)
1888                .await
1889                .map(DispatchOutcome::complete),
1890            NodeKind::VarSet { name, value } => {
1891                if name.trim().is_empty() {
1892                    tracing::warn!(
1893                        node_id = %node_id,
1894                        "var_set node has an empty variable name; skipping write"
1895                    );
1896                    return Ok(DispatchOutcome::complete(NodeOutput::new(
1897                        serde_json::json!({ "ok": true }),
1898                    )));
1899                }
1900                let prev = state.last_output.clone().unwrap_or(Value::Null);
1901                let ctx_val = template_context(state, prev);
1902                let rendered = render_template_value(
1903                    value,
1904                    &ctx_val,
1905                    TemplateOptions {
1906                        allow_pointer: true,
1907                    },
1908                )
1909                .context("failed to render var_set value")?;
1910                state.vars.insert(name.clone(), rendered);
1911                Ok(DispatchOutcome::complete(NodeOutput::new(
1912                    serde_json::json!({ "ok": true }),
1913                )))
1914            }
1915            NodeKind::Wait => {
1916                let reason = extract_wait_reason(&payload);
1917                Ok(DispatchOutcome::wait(NodeOutput::new(payload), reason))
1918            }
1919            NodeKind::DwAgent {
1920                agent_id,
1921                conversational,
1922            } => {
1923                #[cfg(feature = "agentic-worker")]
1924                match self.dw_agent_dispatch {
1925                    crate::runner::agent_node::DwAgentDispatch::Nats => {
1926                        if *conversational {
1927                            // Interleave guard (#1): the pending-await marker alone
1928                            // does not prove this resume carries the agent's NATS
1929                            // response — a user message can arrive before it (e.g.
1930                            // the user types again while the agent is still
1931                            // thinking) and land in `state.entry` too. The NATS
1932                            // response envelope is always `{ok, output, events,
1933                            // error}`; a user-message resume has no `"ok"` key. Only
1934                            // treat this as the response path when BOTH the marker
1935                            // is set AND `state.entry` looks like that envelope.
1936                            // `&&` short-circuits, so `take_agent_await` (which
1937                            // clears the marker) is not called when the shape check
1938                            // fails — the marker survives for the real response,
1939                            // and the stray user message falls through to the
1940                            // fresh-dispatch branch below (re-dispatches as a new
1941                            // turn instead of being misread as a null agent reply).
1942                            let is_agent_response = state.entry.get("ok").is_some();
1943                            if is_agent_response && state.take_agent_await(node_id) {
1944                                // Resuming with the agent's NATS response. SPIKE §Q2:
1945                                // the response is NOT in the `payload` argument (that
1946                                // is a freshly re-rendered request-mapping template) —
1947                                // it landed in `state.entry` as the envelope
1948                                // `{ok, output, events, error}`, so the agent output is
1949                                // `state.entry.output` (= `{reply, trail, terminated_by}`)
1950                                // and `terminated_by` is nested one level under `.output`.
1951                                // `state.entry` is readable here (same module; precedent
1952                                // `inject_card_locale(&mut payload, &state.entry)` above).
1953                                let ok = state
1954                                    .entry
1955                                    .get("ok")
1956                                    .and_then(Value::as_bool)
1957                                    .unwrap_or(false);
1958                                if !ok {
1959                                    // Error envelope (Fix B): a transport/agent error
1960                                    // must not be silently swallowed as a null reply,
1961                                    // and must NOT bump the park-loop cap — a flapping
1962                                    // backend should not burn the segment's turn budget
1963                                    // or force-advance past it. Surface the error
1964                                    // message as the reply and re-park (fail-safe:
1965                                    // await the next user message). There is currently
1966                                    // no self-inflicted await deadline (see the
1967                                    // fresh-dispatch branch below), but this also
1968                                    // handles a `{ok:false}` envelope from any other
1969                                    // source (e.g. a flow-authored deadline) the same way.
1970                                    let (_reply, payload) =
1971                                        agent_error_envelope_reply(&state.entry);
1972                                    // Log the MACHINE error (code + message), not the
1973                                    // localized user-safe reply, so operators keep
1974                                    // their diagnostics.
1975                                    let (error_code, error_message) =
1976                                        agent_error_log_fields(&state.entry);
1977                                    tracing::warn!(
1978                                        agent_id = %agent_id,
1979                                        error_code = %error_code,
1980                                        error = %error_message,
1981                                        "conversational dw.agent (nats) response was an error/timeout envelope; surfacing and re-parking without bumping the park-loop cap"
1982                                    );
1983                                    let output = NodeOutput::new(payload);
1984                                    Ok(DispatchOutcome::with_control(
1985                                        output,
1986                                        NodeControl::LoopHere {
1987                                            reason: Some(format!(
1988                                                "conversational dw.agent `{agent_id}` (nats) awaiting next user message after error response"
1989                                            )),
1990                                        },
1991                                    ))
1992                                } else {
1993                                    let agent_out =
1994                                        state.entry.get("output").cloned().unwrap_or(Value::Null);
1995                                    let output = NodeOutput::new(agent_out.clone());
1996                                    let ended = agent_out
1997                                        .get("terminated_by")
1998                                        .and_then(serde_json::Value::as_str)
1999                                        == Some("conversation_ended");
2000                                    if ended {
2001                                        state.reset_park_turns(node_id);
2002                                        Ok(DispatchOutcome::complete(output))
2003                                    } else {
2004                                        let turns = state.bump_park_turns(node_id);
2005                                        if turns >= MAX_PARK_TURNS {
2006                                            tracing::warn!(
2007                                                agent_id = %agent_id,
2008                                                turns,
2009                                                "conversational dw.agent (nats) hit park-loop cap ({MAX_PARK_TURNS}); force-advancing to successor"
2010                                            );
2011                                            // Reset on force-advance too, so a graph that
2012                                            // re-enters this node later starts with a fresh
2013                                            // budget (mirrors the `conversation_ended` path —
2014                                            // the counter is cleared on every exit past the node).
2015                                            state.reset_park_turns(node_id);
2016                                            Ok(DispatchOutcome::complete(output))
2017                                        } else {
2018                                            Ok(DispatchOutcome::with_control(
2019                                                output,
2020                                                NodeControl::LoopHere {
2021                                                    reason: Some(format!(
2022                                                        "conversational dw.agent `{agent_id}` (nats) awaiting next user message"
2023                                                    )),
2024                                                },
2025                                            ))
2026                                        }
2027                                    }
2028                                }
2029                            } else {
2030                                // Fresh user turn: dispatch to NATS, park awaiting the
2031                                // response and re-enter THIS node on resume (not the
2032                                // routing successor) so the conversational decision
2033                                // above can evaluate the agent's response. No await
2034                                // deadline: a bounded wait needs a per-dispatch
2035                                // correlation nonce + watchdog cancellation (the
2036                                // correlation id is deterministic per-conversation and
2037                                // the resume-store slot is overwritten every turn, so a
2038                                // naive deadline's fire-and-forget watchdog can inject a
2039                                // spurious timeout into a later, healthy turn) — tracked
2040                                // as a follow-up.
2041                                state.mark_agent_await(node_id);
2042                                let remote_payload =
2043                                    serde_json::json!({ "await": true, "input": payload });
2044                                self.execute_remote_dispatch(
2045                                    ctx,
2046                                    "agentic",
2047                                    agent_id,
2048                                    remote_payload,
2049                                    true,
2050                                )
2051                                .await
2052                            }
2053                        } else {
2054                            // Non-conversational: unchanged single await → resumes at
2055                            // the routing successor, exactly as before.
2056                            let remote_payload =
2057                                serde_json::json!({ "await": true, "input": payload });
2058                            self.execute_remote_dispatch(
2059                                ctx,
2060                                "agentic",
2061                                agent_id,
2062                                remote_payload,
2063                                false,
2064                            )
2065                            .await
2066                        }
2067                    }
2068                    crate::runner::agent_node::DwAgentDispatch::InProcess => {
2069                        // Re-entry from an `awaiting_tool_input` park: the
2070                        // inbound activity is the answer to the agent's parked
2071                        // `flow:` tool — when it is a card submit. A typed
2072                        // message instead reaches the agent as a message, and
2073                        // the agent cancels the parked tool.
2074                        let resume_payload = (state.take_tool_await(node_id)
2075                            && is_card_submit(&state.entry))
2076                        .then(|| state.entry.clone());
2077                        let output = self
2078                            .execute_dw_agent(
2079                                ctx,
2080                                agent_id,
2081                                payload,
2082                                *conversational,
2083                                resume_payload.as_ref(),
2084                            )
2085                            .await?;
2086                        if awaiting_tool_input(&output.payload) {
2087                            // A `flow:` tool parked on the user. Park HERE,
2088                            // whatever `conversational` says: the next inbound
2089                            // re-enters this node so the agent can resume the
2090                            // tool. Not a conversational turn, so the
2091                            // `MAX_PARK_TURNS` budget is left alone.
2092                            state.mark_tool_await(node_id);
2093                            Ok(DispatchOutcome::with_control(
2094                                output,
2095                                NodeControl::LoopHere {
2096                                    reason: Some(format!(
2097                                        "dw.agent `{agent_id}` awaiting the user on a flow tool"
2098                                    )),
2099                                },
2100                            ))
2101                        } else if *conversational {
2102                            let ended = output
2103                                .payload
2104                                .get("terminated_by")
2105                                .and_then(serde_json::Value::as_str)
2106                                == Some("conversation_ended");
2107                            if ended {
2108                                state.reset_park_turns(node_id);
2109                                Ok(DispatchOutcome::complete(output))
2110                            } else {
2111                                let turns = state.bump_park_turns(node_id);
2112                                if turns >= MAX_PARK_TURNS {
2113                                    tracing::warn!(
2114                                        agent_id = %agent_id,
2115                                        turns,
2116                                        "conversational dw.agent hit park-loop cap ({MAX_PARK_TURNS}); force-advancing to successor"
2117                                    );
2118                                    // Reset on force-advance too, so a graph that
2119                                    // re-enters this node later starts with a fresh
2120                                    // budget (mirrors the `conversation_ended` path —
2121                                    // the counter is cleared on every exit past the node).
2122                                    state.reset_park_turns(node_id);
2123                                    Ok(DispatchOutcome::complete(output))
2124                                } else {
2125                                    Ok(DispatchOutcome::with_control(
2126                                        output,
2127                                        NodeControl::LoopHere {
2128                                            reason: Some(format!(
2129                                                "conversational dw.agent `{agent_id}` awaiting next user message"
2130                                            )),
2131                                        },
2132                                    ))
2133                                }
2134                            }
2135                        } else {
2136                            Ok(DispatchOutcome::complete(output))
2137                        }
2138                    }
2139                }
2140                #[cfg(not(feature = "agentic-worker"))]
2141                {
2142                    self.execute_dw_agent(ctx, agent_id, payload, *conversational, None)
2143                        .await
2144                        .map(DispatchOutcome::complete)
2145                }
2146            }
2147            NodeKind::DwAgentGraph { graph_id } => self
2148                .execute_dw_agent_graph(ctx, graph_id, payload)
2149                .await
2150                .map(DispatchOutcome::complete),
2151            NodeKind::SorlaCall { target } => {
2152                self.execute_sorla_call(
2153                    ctx,
2154                    node_id,
2155                    target,
2156                    payload,
2157                    node_has_error_route(&node.routing),
2158                )
2159                .await
2160            }
2161            NodeKind::OperalaCall { target } => {
2162                self.execute_operala_call(ctx, target, payload).await
2163            }
2164            NodeKind::AgenticCall { target } => {
2165                self.execute_agentic_call(ctx, target, payload).await
2166            }
2167            NodeKind::TelcoXCall { target } => {
2168                self.execute_telco_x_call(ctx, target, payload).await
2169            }
2170            NodeKind::ApprovalCall { target } => {
2171                self.execute_approval_call(ctx, node_id, target, payload, state)
2172                    .await
2173            }
2174            NodeKind::Mcp { server_id, tool } => self
2175                .execute_mcp(
2176                    ctx,
2177                    server_id,
2178                    tool,
2179                    payload,
2180                    node_has_error_route(&node.routing),
2181                )
2182                .await
2183                .map(DispatchOutcome::complete),
2184            NodeKind::A2a { agent_id } => self
2185                .execute_a2a(ctx, agent_id, payload, node_has_error_route(&node.routing))
2186                .await
2187                .map(DispatchOutcome::complete),
2188            NodeKind::MediaCreate => self
2189                .execute_media_create(ctx, payload, node_has_error_route(&node.routing))
2190                .await
2191                .map(DispatchOutcome::complete),
2192        }
2193    }
2194
2195    /// Execute a `component == "media.create"` flow node (LOCKED ENCODING v1).
2196    ///
2197    /// `payload` is the already-rendered node input mapping, shaped
2198    /// `{ format, name?, text?, rows?, output? }`. A failure is a C5 value
2199    /// (`{ok:false, error:{code,message}}`), never an aborted run; the node is
2200    /// marked failed only when it has an `on_error` edge, like `a2a`.
2201    #[cfg(feature = "agentic-worker")]
2202    async fn execute_media_create(
2203        &self,
2204        ctx: &FlowContext<'_>,
2205        payload: Value,
2206        has_error_route: bool,
2207    ) -> Result<NodeOutput> {
2208        let result = crate::runner::media_node::create(
2209            &payload,
2210            ctx.tenant,
2211            self.ext_artifact_port.as_ref(),
2212        )
2213        .await;
2214        Ok(media_node_output(
2215            bind_node_result(&payload, result.clone()),
2216            &result,
2217            has_error_route,
2218        ))
2219    }
2220
2221    /// Compile-time stub when the agentic-worker feature (which carries the
2222    /// artifact port) is disabled: the node degrades to an error value.
2223    #[cfg(not(feature = "agentic-worker"))]
2224    async fn execute_media_create(
2225        &self,
2226        _ctx: &FlowContext<'_>,
2227        _payload: Value,
2228        _has_error_route: bool,
2229    ) -> Result<NodeOutput> {
2230        Ok(NodeOutput::new(json!({
2231            "ok": false,
2232            "error": {
2233                "code": "artifact_unavailable",
2234                "message": "media.create requires the agentic-worker feature"
2235            }
2236        })))
2237    }
2238
2239    #[cfg(feature = "agentic-worker")]
2240    async fn execute_dw_agent(
2241        &self,
2242        ctx: &FlowContext<'_>,
2243        agent_id: &str,
2244        payload: Value,
2245        conversational: bool,
2246        resume_payload: Option<&Value>,
2247    ) -> Result<NodeOutput> {
2248        let handler = self
2249            .agent_node_handler
2250            .as_ref()
2251            .context("DwAgent node dispatched but no AgentNodeHandler configured on FlowEngine")
2252            .map_err(pre_effect)?;
2253        // Inside a `flow:` tool the flow context has no session; the nested
2254        // agent then runs under the session the tool call derived
2255        // (`nested_flow`), never `""` (one conversation shared by every user
2256        // of the tenant) and never the caller's (whose lock it holds).
2257        let session_owned = crate::runner::nested_flow::agent_session_for(ctx.session_id)
2258            .map_err(anyhow::Error::msg)
2259            .map_err(pre_effect)?;
2260        let session_id = session_owned.as_str();
2261        let started = std::time::Instant::now();
2262        let mut result = handler
2263            .execute_with_resume(
2264                ctx.tenant,
2265                &self.default_env,
2266                agent_id,
2267                session_id,
2268                &payload,
2269                conversational,
2270                // From the context, NOT from `payload`: the node's payload is
2271                // whatever the flow mapped, and a flow's mapping is authorable.
2272                ctx.caller,
2273                resume_payload,
2274            )
2275            .await?;
2276        // Per-node timing: record this agent step's own execution time on its
2277        // output (`duration_ms`), so a trace can show per-node — not just
2278        // per-turn — latency. Injected only when the output is a JSON object.
2279        if let Value::Object(map) = &mut result {
2280            map.insert(
2281                "duration_ms".into(),
2282                Value::from(started.elapsed().as_millis() as u64),
2283            );
2284        }
2285        Ok(NodeOutput::new(result))
2286    }
2287
2288    #[cfg(not(feature = "agentic-worker"))]
2289    async fn execute_dw_agent(
2290        &self,
2291        _ctx: &FlowContext<'_>,
2292        agent_id: &str,
2293        _payload: Value,
2294        _conversational: bool,
2295        _resume_payload: Option<&Value>,
2296    ) -> Result<NodeOutput> {
2297        anyhow::bail!(
2298            "DwAgent node '{agent_id}' cannot run: this build was compiled without the \
2299             `agentic-worker` feature. Rebuild with --features agentic-worker."
2300        )
2301    }
2302
2303    /// Dispatch a `sorla.call` flow node.
2304    ///
2305    /// Amendment A1: **a route document always wins over NATS.** If a route
2306    /// document resolves for `target`
2307    /// ([`crate::runner::sorla_node::execute_sorla_http`]), the call runs
2308    /// SYNCHRONOUSLY over HTTP and the node completes (or fails) in this same
2309    /// step — no publish, no wait, no [`RemoteDispatchHandler`] involved.
2310    ///
2311    /// Only when no route document exists does the node fall back to the
2312    /// historical publish-to-a-separate-runtime path, and only when a
2313    /// [`RemoteDispatchHandler`] is actually configured
2314    /// ([`Self::remote_dispatch_configured`]); with neither, the node fails
2315    /// with `sorla_route_missing`.
2316    ///
2317    /// The NATS fallback keeps its original input payload contract (JSON):
2318    /// `{ "await": bool (default true), "operation": str, "deadline_ms": u64?,
2319    ///    "input": any }`, and the same correlation-id/session-hint behaviour
2320    /// documented on [`Self::execute_remote_dispatch`].
2321    ///
2322    /// [`RemoteDispatchHandler`]: crate::runner::remote_dispatch::RemoteDispatchHandler
2323    #[cfg(feature = "agentic-worker")]
2324    async fn execute_sorla_call(
2325        &self,
2326        ctx: &FlowContext<'_>,
2327        node_id: &str,
2328        target: &str,
2329        payload: Value,
2330        has_error_route: bool,
2331    ) -> Result<DispatchOutcome> {
2332        // Caller identity for a route-document call (never sent over NATS):
2333        // `flow:<flow id>/<node id>`, mirroring the shape SP1's fixed
2334        // `dw-agent` caller id uses for the agent-tool path.
2335        let caller = format!("flow:{}/{node_id}", ctx.flow_id);
2336        let http_result = match self.mcp_secrets_for_dispatch() {
2337            Some(secrets) => {
2338                crate::runner::sorla_node::execute_sorla_http(
2339                    &*secrets,
2340                    ctx.tenant,
2341                    self.mcp_credential_unit(),
2342                    target,
2343                    &payload,
2344                    &caller,
2345                )
2346                .await
2347            }
2348            // No secrets manager configured at all: a route document can
2349            // never resolve, which is exactly the "no route document" case.
2350            None => Ok(None),
2351        };
2352        match http_result {
2353            Ok(Some(result)) => {
2354                let bound = match payload.get("output").and_then(Value::as_str) {
2355                    Some(key) if !key.is_empty() => json!({ key: result.clone() }),
2356                    _ => result.clone(),
2357                };
2358                Ok(DispatchOutcome::complete(mcp_node_output(
2359                    bound,
2360                    &result,
2361                    has_error_route,
2362                )))
2363            }
2364            Ok(None) if self.remote_dispatch_configured() => {
2365                self.execute_remote_dispatch(ctx, "sorla", target, payload, false)
2366                    .await
2367            }
2368            Ok(None) => sorla_failure(
2369                format!(
2370                    "sorla_route_missing: no route document for SoR `{target}` and no NATS configured"
2371                ),
2372                has_error_route,
2373            ),
2374            Err(e) => sorla_failure(e, has_error_route),
2375        }
2376    }
2377
2378    /// Compile-time fallback for `sorla.call` when the `agentic-worker`
2379    /// feature (which carries `sorla_route`/`sorx_invoker`, and therefore all
2380    /// HTTP route resolution) is disabled. Dispatches through the
2381    /// [`RemoteDispatchHandler`] exactly as `sorla.call` always did before
2382    /// this task.
2383    ///
2384    /// [`RemoteDispatchHandler`]: crate::runner::remote_dispatch::RemoteDispatchHandler
2385    #[cfg(not(feature = "agentic-worker"))]
2386    async fn execute_sorla_call(
2387        &self,
2388        ctx: &FlowContext<'_>,
2389        _node_id: &str,
2390        target: &str,
2391        payload: Value,
2392        _has_error_route: bool,
2393    ) -> Result<DispatchOutcome> {
2394        self.execute_remote_dispatch(ctx, "sorla", target, payload, false)
2395            .await
2396    }
2397
2398    /// Dispatch an `operala.call` flow node.
2399    ///
2400    /// When an in-process [`OperalaNodeHandler`] is wired (`operala-in-process`),
2401    /// the node runs the deep-worker runtime directly — no NATS, no
2402    /// `RemoteDispatchHandler` — and completes inline. Otherwise falls back to
2403    /// the shared remote-dispatch seam, identical to [`execute_sorla_call`]
2404    /// except the runtime name is `"operala"`.
2405    ///
2406    /// [`OperalaNodeHandler`]: crate::runner::operala_node::OperalaNodeHandler
2407    async fn execute_operala_call(
2408        &self,
2409        ctx: &FlowContext<'_>,
2410        target: &str,
2411        payload: Value,
2412    ) -> Result<DispatchOutcome> {
2413        if let Some(handler) = self.operala_node_handler.as_ref() {
2414            // `greentic-dw-authoring` stamps `operation: "invoke"` on the
2415            // `operala.call` node, but the deep-worker invoker's contract
2416            // accepts only `"" | "run"`. Normalize so an authored `deep_worker`
2417            // actually runs in-process instead of failing operation validation.
2418            let raw_operation = payload
2419                .get("operation")
2420                .and_then(Value::as_str)
2421                .unwrap_or_default();
2422            let operation = if raw_operation.eq_ignore_ascii_case("invoke") {
2423                "run"
2424            } else {
2425                raw_operation
2426            };
2427            let inner_input = payload.get("input").cloned().unwrap_or(Value::Null);
2428            let session_id = ctx.session_id.unwrap_or("");
2429            let result = handler
2430                .execute(
2431                    ctx.tenant,
2432                    &self.default_env,
2433                    target,
2434                    operation,
2435                    session_id,
2436                    &inner_input,
2437                )
2438                .await?;
2439            return Ok(DispatchOutcome::complete(NodeOutput::new(result)));
2440        }
2441        self.execute_remote_dispatch(ctx, "operala", target, payload, false)
2442            .await
2443    }
2444
2445    /// Dispatch an `agentic.call` flow node via the shared remote-dispatch seam.
2446    /// Identical to [`execute_sorla_call`] except the runtime name is `"agentic"`.
2447    /// This is the out-of-process agentic path; the in-process `dw.agent` node
2448    /// is completely separate and untouched.
2449    async fn execute_agentic_call(
2450        &self,
2451        ctx: &FlowContext<'_>,
2452        target: &str,
2453        payload: Value,
2454    ) -> Result<DispatchOutcome> {
2455        self.execute_remote_dispatch(ctx, "agentic", target, payload, false)
2456            .await
2457    }
2458
2459    /// Dispatch a `telco-x.call` flow node via the shared remote-dispatch seam.
2460    /// Mirrors [`execute_operala_call`] with runtime name `"telco-x"`. Wire-ready:
2461    /// no telco-x runtime is deployed yet, so an awaiting node pauses until one is.
2462    async fn execute_telco_x_call(
2463        &self,
2464        ctx: &FlowContext<'_>,
2465        target: &str,
2466        payload: Value,
2467    ) -> Result<DispatchOutcome> {
2468        self.execute_remote_dispatch(ctx, "telco-x", target, payload, false)
2469            .await
2470    }
2471
2472    /// Human-in-the-loop approval gate.
2473    ///
2474    /// Sets `meta["outcome"]` to `approved` / `denied` / `timeout` on every path,
2475    /// so routing conditions (`event == "approved"`) work identically whether a
2476    /// human decided or the gate auto-approved. `ok` cannot serve as the
2477    /// discriminator: greentic-admin publishes `ok: true` for approve AND deny.
2478    ///
2479    /// Uses `resume_at_self = true` so the response re-enters THIS node and its
2480    /// own routing sees the decision. `pending_approval_await` distinguishes the
2481    /// first entry from the resume, and stops a stray inbound (which lands in the
2482    /// same wait slot — see the keying note on `NodeControl::AwaitHere`) from
2483    /// re-dispatching a duplicate approval request.
2484    async fn execute_approval_call(
2485        &self,
2486        ctx: &FlowContext<'_>,
2487        node_id: &str,
2488        target: &str,
2489        payload: Value,
2490        state: &mut ExecutionState,
2491    ) -> Result<DispatchOutcome> {
2492        if let Some(parked) = state.take_approval_await(node_id) {
2493            if entry_is_approval_response(&state.entry) {
2494                if response_authenticates(&state.entry, &parked) {
2495                    // Taking the mark above spent the token: a replay of this
2496                    // same response finds nothing parked to match.
2497                    let mut response = state.entry.clone();
2498                    approval_token::strip_from_response(&mut response);
2499                    let outcome = approval_outcome_from_entry(&response);
2500                    let output =
2501                        NodeOutput::with_meta(response, serde_json::json!({ "outcome": outcome }));
2502                    return Ok(DispatchOutcome::complete(output));
2503                }
2504                // The resumer already drops such a response; this is the
2505                // authoritative check, because anything else that lands an
2506                // `ok`-carrying entry on this node (a response routed without
2507                // the resumer's check, or an inbound shaped like one) must
2508                // not decide the gate either.
2509                tracing::warn!(
2510                    node_id,
2511                    "refusing approval response: its decision_token is missing or does not match the one this gate was issued; the gate stays parked"
2512                );
2513            }
2514            // A user activity (or a refused response) arrived while we were
2515            // parked. Re-park without re-dispatching. The AwaitHere handler
2516            // discards the correlation id, but the gate must keep the ORIGINAL
2517            // dispatch's id and token fingerprint: the decision that
2518            // eventually arrives carries both, and is matched against them.
2519            state.mark_approval_await(node_id, parked);
2520            return Ok(DispatchOutcome::await_here(
2521                NodeOutput::new(serde_json::json!({ "pending": true })),
2522                Some("awaiting approval decision".to_string()),
2523                String::new(),
2524            ));
2525        }
2526
2527        let input = payload.get("input").cloned().unwrap_or(Value::Null);
2528        if !approval_requires_human(&input) {
2529            let output = NodeOutput::with_meta(
2530                serde_json::json!({
2531                    "ok": true,
2532                    "output": { "decision": "approved", "auto": true },
2533                    "error": serde_json::Value::Null,
2534                }),
2535                serde_json::json!({ "outcome": "approved" }),
2536            );
2537            return Ok(DispatchOutcome::complete(output));
2538        }
2539
2540        // Mark only once the dispatch actually parked. A fire-and-forget
2541        // (`await: false`) dispatch completes without parking, and an early `?`
2542        // error never parks either — marking before the call would leave the
2543        // node believing it is awaiting a decision it never requested, and every
2544        // later inbound would re-park forever.
2545        //
2546        // A fresh single-use `decision_token` per dispatch (greentic-runner
2547        // #794): the request carries it, the park stores only its fingerprint,
2548        // and the decision resumes the gate only when it carries it back.
2549        let issued = approval_token::issue();
2550        let outcome = self
2551            .execute_remote_dispatch_with_token(
2552                ctx,
2553                APPROVAL_RUNTIME,
2554                target,
2555                payload,
2556                true,
2557                Some(issued.token),
2558            )
2559            .await?;
2560        if let NodeControl::AwaitHere { correlation_id, .. } = &outcome.control {
2561            state.mark_approval_await(
2562                node_id,
2563                ParkedApproval {
2564                    correlation_id: Some(correlation_id.clone()).filter(|id| !id.is_empty()),
2565                    token_fingerprint: Some(issued.fingerprint),
2566                },
2567            );
2568        }
2569        Ok(outcome)
2570    }
2571
2572    /// Execute a `component == "mcp"` flow node (LOCKED ENCODING v2).
2573    ///
2574    /// `payload` is the already-rendered node input mapping (the engine
2575    /// templates `{{ }}` against flow state before dispatch), shaped
2576    /// `{ "server": <id>, "tool": <name>, "arguments": <object>,
2577    ///    "output": <optional string state key> }`.
2578    ///
2579    /// `server`/`tool` are sourced from this payload (the source of truth);
2580    /// the `server_id`/`tool` parsed at flow-load time are passed in only as a
2581    /// fallback for the legacy `operation = "<server>/<tool>"` encoding. The MCP
2582    /// tool is invoked through the tenant's `flow_editor` catalog (reusing
2583    /// `greentic-aw-runtime`'s `McpToolSource`); the result value is bound under
2584    /// `output` when present, else returned as the node payload.
2585    ///
2586    /// Graceful by contract: MCP being unconfigured or the tool being
2587    /// unreachable yields a structured `{"error": ...}` value — never a panic,
2588    /// never an aborted runtime.
2589    #[cfg(feature = "agentic-worker")]
2590    async fn execute_mcp(
2591        &self,
2592        ctx: &FlowContext<'_>,
2593        server_id: &str,
2594        tool: &str,
2595        payload: Value,
2596        has_error_route: bool,
2597    ) -> Result<NodeOutput> {
2598        // Payload is the source of truth: prefer the rendered `server`/`tool`
2599        // from config, falling back to the values resolved at flow-load time
2600        // (legacy `operation`/`mcp:` encoding).
2601        let payload_server = crate::runner::mcp_node::str_field(&payload, "server");
2602        let payload_tool = crate::runner::mcp_node::str_field(&payload, "tool");
2603        let server_id = payload_server.as_deref().unwrap_or(server_id);
2604        let tool = payload_tool.as_deref().unwrap_or(tool);
2605
2606        // `arguments` defaults to `{}` so a no-arg tool needs no config.
2607        let arguments = payload
2608            .get("arguments")
2609            .cloned()
2610            .unwrap_or_else(|| Value::Object(JsonMap::new()));
2611
2612        // Route material the running pack carries. Preferred over the admin
2613        // catalog, so a deployed runner with no admin credentials can dispatch
2614        // at all; `None` (a pack predating the sidecar) falls back to the
2615        // catalog exactly as before.
2616        let pack_routes = self
2617            .packs
2618            .iter()
2619            .find(|pack| pack.metadata().pack_id == ctx.pack_id)
2620            .and_then(|pack| pack.mcp_routes());
2621
2622        // The team the AUTHORING session resolved this server's token under, as
2623        // recorded in the sidecar. `FlowContext` carries no team and a deployed
2624        // workload has no principled source for one, so this is the only place
2625        // the value can come from. Absent (a pack predating the field) yields
2626        // `None`, and the credential read then tries the tenant-default `_`
2627        // scope exactly as it did before.
2628        let auth_team = pack_routes
2629            .and_then(|routes| routes.get(server_id))
2630            .and_then(|route| route.auth_team.as_deref());
2631
2632        // The manager the HOST injected, not one built from `SECRETS_BACKEND`:
2633        // no Cloud Run or Kubernetes deployment sets that variable, so the
2634        // env-derived fallback resolved a `secrets://` URI as a literal
2635        // variable name and every credential lookup missed.
2636        let secrets = self.mcp_secrets_for_dispatch();
2637        let result = crate::runner::mcp_node::aw::invoke_with_secrets(
2638            self.mcp_tool_source.as_ref(),
2639            pack_routes,
2640            secrets.as_ref(),
2641            ctx.tenant,
2642            &self.default_env,
2643            auth_team,
2644            self.mcp_credential_unit(),
2645            server_id,
2646            tool,
2647            &arguments,
2648        )
2649        .await;
2650
2651        Ok(mcp_node_output(
2652            bind_node_result(&payload, result.clone()),
2653            &result,
2654            has_error_route,
2655        ))
2656    }
2657
2658    /// Compile-time stub for the MCP flow node when the agentic-worker feature
2659    /// (which carries the MCP runtime deps) is disabled. The node degrades to a
2660    /// clear error value rather than failing the build or the run.
2661    #[cfg(not(feature = "agentic-worker"))]
2662    async fn execute_mcp(
2663        &self,
2664        _ctx: &FlowContext<'_>,
2665        server_id: &str,
2666        tool: &str,
2667        _payload: Value,
2668        _has_error_route: bool,
2669    ) -> Result<NodeOutput> {
2670        Ok(NodeOutput::new(json!({
2671            "error": format!(
2672                "mcp node '{server_id}/{tool}' requires the agentic-worker feature (MCP runtime not compiled in)"
2673            )
2674        })))
2675    }
2676
2677    /// The A2A agents this flow's pack declares, built once per
2678    /// `(tenant, pack)` and cached for its agent-card cache.
2679    #[cfg(feature = "agentic-worker")]
2680    fn a2a_source_for(
2681        &self,
2682        tenant: &str,
2683        pack: &Arc<PackRuntime>,
2684    ) -> Option<Arc<greentic_aw_runtime::A2aToolSource>> {
2685        let key = (tenant.to_string(), pack.metadata().pack_id.to_string());
2686        if let Some(cached) = self.a2a_sources.read().get(&key) {
2687            return Some(Arc::clone(cached));
2688        }
2689        // The same manager the `mcp` node dispatches with. It is not
2690        // category-specific: which category a credential is read under is a
2691        // segment of the URI, chosen by `a2a_source`'s own `A2A_CATEGORY`.
2692        let secrets = self.mcp_secrets_for_dispatch();
2693        let source = crate::runner::a2a_node::aw::source_for_pack(
2694            pack,
2695            tenant,
2696            secrets,
2697            self.mcp_credential_unit(),
2698        )?;
2699        // A concurrent build wins rather than being replaced: two sources are
2700        // equivalent, and keeping the installed one keeps its warm card cache.
2701        let mut sources = self.a2a_sources.write();
2702        let entry = sources.entry(key).or_insert(source);
2703        Some(Arc::clone(entry))
2704    }
2705
2706    /// Execute a `component == "a2a"` flow node (LOCKED ENCODING v1).
2707    ///
2708    /// `payload` is the already-rendered node input mapping (the engine
2709    /// templates `{{ }}` against flow state before dispatch), shaped
2710    /// `{ "agent": <id>, "message": <text>, "output": <optional state key> }`.
2711    ///
2712    /// `agent` is sourced from this payload (the source of truth); the
2713    /// `agent_id` parsed at flow-load time is passed in only as the fallback
2714    /// for the `operation = "<agent_id>"` / `a2a:<agent_id>` ref encodings.
2715    ///
2716    /// ONE turn: the node sends one message and completes. It never parks.
2717    /// A remote task that is not `completed` is reported in the node's value
2718    /// as its own `status`, for the flow to route on — see
2719    /// [`crate::runner::a2a_node`] for why, and for the continuation rule that
2720    /// makes an `input_required` round trip answerable.
2721    ///
2722    /// Graceful by contract, exactly as the `mcp` node is: a pack that
2723    /// declares no agents, an agent it does not declare, a credential that
2724    /// cannot be read, and an unreachable agent all yield a structured
2725    /// `status: "error"` value — never a panic, never an aborted runtime, and
2726    /// never an unauthenticated call.
2727    #[cfg(feature = "agentic-worker")]
2728    async fn execute_a2a(
2729        &self,
2730        ctx: &FlowContext<'_>,
2731        agent_id: &str,
2732        payload: Value,
2733        has_error_route: bool,
2734    ) -> Result<NodeOutput> {
2735        let payload_agent = crate::runner::a2a_node::agent_from_payload(&payload);
2736        let agent_id = payload_agent.as_deref().unwrap_or(agent_id);
2737
2738        let pack = self.pack_for_flow(ctx).map_err(pre_effect)?;
2739        let pack_id = pack.metadata().pack_id.to_string();
2740
2741        // `message` must be configured. Refused as a value rather than as a
2742        // node abort, so a flow with an error route handles it like every
2743        // other a2a failure and one without still completes.
2744        let answer = crate::runner::a2a_node::answer_from_payload(&payload);
2745        // A card submit carries fields and no sentence, so `message` may be
2746        // blank when there is an answer to forward.
2747        let blank_message = Value::String(String::new());
2748        let message = payload
2749            .get("message")
2750            .filter(|value| !is_blank(value))
2751            .or_else(|| answer.as_ref().map(|_| &blank_message));
2752        let Some(message) = message else {
2753            let result = greentic_aw_runtime::a2a_source::call_error_value(
2754                agent_id,
2755                "a2a node has no `message` to send (expected a non-empty `message` field \
2756                 in the node's config)",
2757            );
2758            tracing::warn!(agent = agent_id, "a2a node has no message configured");
2759            return Ok(a2a_node_output(
2760                bind_node_result(&payload, result.clone()),
2761                &result,
2762                has_error_route,
2763            ));
2764        };
2765
2766        let card_submit_to = crate::runner::a2a_node::card_submit_target(&payload);
2767        let source = self.a2a_source_for(ctx.tenant, pack);
2768        let store = pack.state_store_handle();
2769        // A scope we cannot build only costs the continuation, so it degrades
2770        // rather than failing a call the remote would have answered.
2771        let state_ctx = self.state_tenant_ctx(ctx).ok();
2772
2773        let result = crate::runner::a2a_node::aw::invoke(
2774            crate::runner::a2a_node::aw::A2aCall {
2775                source: source.as_ref(),
2776                store: store.as_ref(),
2777                state_ctx: state_ctx.as_ref(),
2778                // From the CONTEXT, so the flow that owns the node owns the
2779                // remote context. `pack_for_flow` above has already resolved
2780                // this id against the loaded flows, which is what makes it a
2781                // safe key segment (see `a2a_node::aw::continuation_key`).
2782                flow_id: ctx.flow_id,
2783                session_id: ctx.session_id.filter(|hint| !hint.is_empty()),
2784                tenant: ctx.tenant,
2785                env: &self.default_env,
2786                pack_id: &pack_id,
2787                want_card: crate::runner::a2a_node::wants_card(&payload),
2788                answer,
2789                card_submit_to: card_submit_to.as_deref(),
2790            },
2791            agent_id,
2792            message,
2793        )
2794        .await;
2795
2796        Ok(a2a_node_output(
2797            bind_node_result(&payload, result.clone()),
2798            &result,
2799            has_error_route,
2800        ))
2801    }
2802
2803    /// Compile-time stub for the A2A flow node when the agentic-worker feature
2804    /// (which carries the A2A client) is disabled. Mirrors the `mcp` stub: the
2805    /// node degrades to a clear error value rather than failing the build or
2806    /// the run.
2807    #[cfg(not(feature = "agentic-worker"))]
2808    async fn execute_a2a(
2809        &self,
2810        _ctx: &FlowContext<'_>,
2811        agent_id: &str,
2812        _payload: Value,
2813        _has_error_route: bool,
2814    ) -> Result<NodeOutput> {
2815        Ok(NodeOutput::new(json!({
2816            "status": "error",
2817            "agent": agent_id,
2818            "error": format!(
2819                "a2a node '{agent_id}' requires the agentic-worker feature (the A2A client is \
2820                 not compiled in)"
2821            )
2822        })))
2823    }
2824
2825    /// Shared body for all native remote-dispatch flow nodes (`sorla.call`,
2826    /// `operala.call`, `agentic.call`). Routes through the injected
2827    /// [`RemoteDispatchHandler`] with the given `runtime` name.
2828    ///
2829    /// Input payload contract (JSON):
2830    /// `{ "await": bool (default true), "operation": str, "deadline_ms": u64?,
2831    ///    "input": any }`.
2832    ///
2833    /// The correlation id is the canonical session hint (`ctx.session_id`)
2834    /// suffixed with `::pack=<pack_id>::flow=<flow_id>` markers so the resume
2835    /// path (`RuntimeSessionResumer`) can route the response back. For the
2836    /// `approval` runtime ONLY, a per-dispatch `::n=<nonce>` segment is
2837    /// appended LAST — see the comment where the id is built.
2838    ///
2839    /// - `await=true`  -> publish + PAUSE the flow ([`DispatchOutcome::wait`]).
2840    /// - `await=false` -> publish + complete immediately with
2841    ///   `{ "dispatched": true, "correlation_id": <marked hint> }`.
2842    ///
2843    /// `resume_at_self`: when the runtime enters `AwaitingResponse`, controls
2844    /// whether the flow resumes at the routing successor
2845    /// ([`DispatchOutcome::wait`], `resume_at_self = false` — the behavior for
2846    /// every non-conversational caller) or re-enters THIS node
2847    /// ([`DispatchOutcome::await_here`], `resume_at_self = true` — the
2848    /// conversational out-of-process `dw.agent` caller) once the async
2849    /// response arrives. Only affects the `AwaitingResponse` branch; the
2850    /// `Dispatched` (fire-and-forget) branch is unaffected either way.
2851    ///
2852    /// [`RemoteDispatchHandler`]: crate::runner::remote_dispatch::RemoteDispatchHandler
2853    async fn execute_remote_dispatch(
2854        &self,
2855        ctx: &FlowContext<'_>,
2856        runtime: &str,
2857        target: &str,
2858        payload: Value,
2859        resume_at_self: bool,
2860    ) -> Result<DispatchOutcome> {
2861        self.execute_remote_dispatch_with_token(ctx, runtime, target, payload, resume_at_self, None)
2862            .await
2863    }
2864
2865    /// [`Self::execute_remote_dispatch`] for a dispatch that is issued a
2866    /// `decision_token` (only `approval.call`); see
2867    /// [`crate::runner::remote_dispatch::RemoteDispatch::decision_token`].
2868    async fn execute_remote_dispatch_with_token(
2869        &self,
2870        ctx: &FlowContext<'_>,
2871        runtime: &str,
2872        target: &str,
2873        payload: Value,
2874        resume_at_self: bool,
2875        decision_token: Option<String>,
2876    ) -> Result<DispatchOutcome> {
2877        let handler = self
2878            .dispatch_handler_for(runtime)
2879            .with_context(|| {
2880                format!("{runtime}.call node dispatched but no RemoteDispatchHandler configured")
2881            })
2882            .map_err(pre_effect)?;
2883
2884        let await_mode = payload
2885            .get("await")
2886            .and_then(Value::as_bool)
2887            .unwrap_or(true);
2888        let operation = payload
2889            .get("operation")
2890            .and_then(Value::as_str)
2891            .unwrap_or_default()
2892            .to_string();
2893        let deadline_ms = payload.get("deadline_ms").and_then(Value::as_u64);
2894        let inner_input = payload.get("input").cloned().unwrap_or(Value::Null);
2895
2896        // The resume path (`RuntimeSessionResumer`) recovers `pack_id` and
2897        // `flow_id` from `::pack=`/`::flow=` markers on the correlation id to
2898        // route the synthesized resume envelope, then strips them to recover the
2899        // bare canonical hint used as the store key. So the published
2900        // correlation id MUST carry those markers and preserve the bare hint.
2901        //
2902        // Bare canonical hint = everything before the first `::` marker. This is
2903        // robust whether `ctx.session_id` is already bare (the production case)
2904        // or has accreted a marker.
2905        let raw_hint = ctx.session_id.unwrap_or_default();
2906        // Strip only the trailing dispatch markers: the hint itself may contain
2907        // `::` (e.g. the `ep=<eid>::` endpoint prefix) and must survive intact.
2908        let bare_hint =
2909            crate::runner::runtime_session_resumer::parse_correlation(raw_hint).bare_hint;
2910        // The store key (`FlowResumeStore::save`) hashes the inbound reply
2911        // scope's `conversation`/`thread`/`reply_to`. The bare canonical hint
2912        // only encodes `conversation`, so a wait saved against a non-empty
2913        // `thread`/`reply_to` would be un-keyable on resume. Append OPAQUE
2914        // `::thread=`/`::reply=` markers so `RuntimeSessionResumer` can rebuild
2915        // the EXACT reply scope and recompute the same `scope_hash`. The remote
2916        // bridge echoes the correlation verbatim, so this needs no bridge change.
2917        // Markers are omitted when their value is empty (back-compat with the
2918        // no-thread case).
2919        let mut correlation_id =
2920            format!("{}::pack={}::flow={}", bare_hint, ctx.pack_id, ctx.flow_id);
2921        if let Some(scope) = ctx.reply_scope {
2922            crate::runner::runtime_session_resumer::push_scope_markers(&mut correlation_id, scope);
2923        }
2924        // An approval's correlation id is its responder's idempotency key:
2925        // greentic-designer-admin UNIQUE-indexes it and upserts only while the
2926        // row is still pending. Without a per-dispatch component a SECOND
2927        // approval in one conversation reuses the first's id, lands on the
2928        // already-resolved row, creates nothing, and the flow parks forever.
2929        //
2930        // Appended LAST so every existing segment keeps its position; the
2931        // resumer strips it first (`split_dispatch_nonce`). Scoped to the
2932        // approval runtime on purpose: the agentic/telco bridges reuse the
2933        // correlation id as the downstream SESSION id when the input names
2934        // none, so a nonce there would give every agent turn a fresh memory.
2935        if runtime == APPROVAL_RUNTIME {
2936            correlation_id.push_str(crate::runner::runtime_session_resumer::NONCE_HINT_MARKER);
2937            correlation_id.push_str(&crate::runner::runtime_session_resumer::new_dispatch_nonce());
2938        }
2939        let mode = if await_mode {
2940            greentic_types::DispatchMode::Await
2941        } else {
2942            greentic_types::DispatchMode::FireAndForget
2943        };
2944
2945        let action = handler
2946            .dispatch(crate::runner::remote_dispatch::RemoteDispatch {
2947                tenant: ctx.tenant.to_string(),
2948                env: self.default_env.clone(),
2949                runtime: runtime.to_string(),
2950                target: target.to_string(),
2951                operation,
2952                mode,
2953                correlation_id: correlation_id.clone(),
2954                input: inner_input,
2955                deadline_ms,
2956                decision_token,
2957            })
2958            .await?;
2959
2960        match action {
2961            crate::runner::remote_dispatch::RemoteDispatchAction::AwaitingResponse {
2962                correlation_id,
2963            } => {
2964                let reason = format!("await-runtime:{correlation_id}");
2965                let output = NodeOutput::new(serde_json::json!({
2966                    "pending": true,
2967                    "correlation_id": correlation_id.clone(),
2968                }));
2969                if resume_at_self {
2970                    Ok(DispatchOutcome::await_here(
2971                        output,
2972                        Some(reason),
2973                        correlation_id,
2974                    ))
2975                } else {
2976                    Ok(DispatchOutcome::wait(output, Some(reason)))
2977                }
2978            }
2979            crate::runner::remote_dispatch::RemoteDispatchAction::Dispatched => {
2980                let output = NodeOutput::new(serde_json::json!({
2981                    "dispatched": true,
2982                    "correlation_id": correlation_id,
2983                }));
2984                Ok(DispatchOutcome::complete(output))
2985            }
2986        }
2987    }
2988
2989    /// Dispatch a `DwAgentGraph` flow node to the configured
2990    /// [`GraphNodeHandler`]. Mirrors [`execute_dw_agent`]: same tenant/env/
2991    /// session-id derivation, same envelope, same "handler not configured"
2992    /// error path.
2993    ///
2994    /// [`execute_dw_agent`]: FlowEngine::execute_dw_agent
2995    #[cfg(feature = "agentic-worker")]
2996    async fn execute_dw_agent_graph(
2997        &self,
2998        ctx: &FlowContext<'_>,
2999        graph_id: &str,
3000        payload: Value,
3001    ) -> Result<NodeOutput> {
3002        let handler = self
3003            .graph_node_handler
3004            .as_ref()
3005            .context(
3006                "DwAgentGraph node dispatched but no GraphNodeHandler configured on FlowEngine",
3007            )
3008            .map_err(pre_effect)?;
3009        let session_id = ctx.session_id.unwrap_or("");
3010        let result = handler
3011            .execute(
3012                ctx.tenant,
3013                &self.default_env,
3014                graph_id,
3015                session_id,
3016                &payload,
3017            )
3018            .await?;
3019        Ok(NodeOutput::new(result))
3020    }
3021
3022    #[cfg(not(feature = "agentic-worker"))]
3023    async fn execute_dw_agent_graph(
3024        &self,
3025        _ctx: &FlowContext<'_>,
3026        graph_id: &str,
3027        _payload: Value,
3028    ) -> Result<NodeOutput> {
3029        anyhow::bail!(
3030            "DwAgentGraph node '{graph_id}' cannot run: this build was compiled without the \
3031             `agentic-worker` feature. Rebuild with --features agentic-worker."
3032        )
3033    }
3034
3035    async fn execute_state_get(&self, ctx: &FlowContext<'_>, payload: Value) -> Result<NodeOutput> {
3036        let key = Self::extract_state_key_helper(&payload)?;
3037        let pack = self.pack_for_flow(ctx)?;
3038        let store = pack
3039            .state_store_handle()
3040            .context("state store is not configured for this runtime")?;
3041        let tenant_ctx = self.state_tenant_ctx(ctx)?;
3042        let state_key = greentic_state::StateKey::new(&key);
3043        let value = store
3044            .get_json(
3045                &tenant_ctx,
3046                crate::storage::state::STATE_PREFIX,
3047                &state_key,
3048                None,
3049            )
3050            .with_context(|| format!("state.get failed for key `{key}`"))?;
3051        let payload = serde_json::json!({
3052            "key": key,
3053            "value": value,
3054            "found": value.is_some(),
3055        });
3056        Ok(NodeOutput::new(payload))
3057    }
3058
3059    async fn execute_state_set(&self, ctx: &FlowContext<'_>, payload: Value) -> Result<NodeOutput> {
3060        let key = Self::extract_state_key_helper(&payload)?;
3061        let value = payload.get("value").cloned().unwrap_or(Value::Null);
3062        let pack = self.pack_for_flow(ctx)?;
3063        let store = pack
3064            .state_store_handle()
3065            .context("state store is not configured for this runtime")?;
3066        let tenant_ctx = self.state_tenant_ctx(ctx)?;
3067        let state_key = greentic_state::StateKey::new(&key);
3068        store
3069            .set_json(
3070                &tenant_ctx,
3071                crate::storage::state::STATE_PREFIX,
3072                &state_key,
3073                None,
3074                &value,
3075                None,
3076            )
3077            .with_context(|| format!("state.set failed for key `{key}`"))?;
3078        let payload = serde_json::json!({ "key": key, "value": value });
3079        Ok(NodeOutput::new(payload))
3080    }
3081
3082    fn pack_for_flow(&self, ctx: &FlowContext<'_>) -> Result<&Arc<PackRuntime>> {
3083        let key = FlowKey {
3084            pack_id: ctx.pack_id.to_string(),
3085            flow_id: ctx.flow_id.to_string(),
3086        };
3087        let idx = self.flow_sources.get(&key).with_context(|| {
3088            format!("flow {} (pack {}) not registered", ctx.flow_id, ctx.pack_id)
3089        })?;
3090        Ok(&self.packs[*idx])
3091    }
3092
3093    fn extract_state_key_helper(payload: &Value) -> Result<String> {
3094        payload
3095            .get("key")
3096            .and_then(Value::as_str)
3097            .map(String::from)
3098            .filter(|k| !k.is_empty())
3099            .context("state node payload missing required `key` (non-empty string)")
3100    }
3101
3102    fn state_tenant_ctx(&self, ctx: &FlowContext<'_>) -> Result<greentic_types::TenantCtx> {
3103        let env = greentic_types::EnvId::from_str(&self.default_env)
3104            .with_context(|| format!("invalid env id `{}`", self.default_env))?;
3105        let tenant = greentic_types::TenantId::from_str(ctx.tenant)
3106            .with_context(|| format!("invalid tenant id `{}`", ctx.tenant))?;
3107        Ok(greentic_types::TenantCtx::new(env, tenant))
3108    }
3109
3110    async fn apply_jump(
3111        &self,
3112        ctx: &FlowContext<'_>,
3113        state: &mut ExecutionState,
3114        jump: JumpControl,
3115    ) -> Result<JumpTarget> {
3116        let target_flow = jump.flow.trim();
3117        if target_flow.is_empty() {
3118            return Err(terminal_flow_error("missing_flow"));
3119        }
3120
3121        let flow = self
3122            .get_or_load_flow(ctx.pack_id, target_flow)
3123            .await
3124            .with_context(|| format!("unknown_flow:{target_flow}"))?;
3125
3126        let target_node = if let Some(node) = jump.node.as_deref() {
3127            let parsed = NodeId::from_str(node)
3128                .map_err(|err| terminal_flow_error(format!("unknown_node:{node}: {err}")))?;
3129            if !flow.nodes.contains_key(&parsed) {
3130                return Err(terminal_flow_error(format!("unknown_node:{node}")));
3131            }
3132            parsed
3133        } else {
3134            flow.start
3135                .clone()
3136                .or_else(|| flow.nodes.keys().next().cloned())
3137                .ok_or_else(|| {
3138                    terminal_flow_error(format!(
3139                        "jump_failed: flow {target_flow} has no start node"
3140                    ))
3141                })?
3142        };
3143
3144        let max_redirects = jump.max_redirects.unwrap_or(3);
3145        if state.redirect_count() >= max_redirects {
3146            return Err(terminal_flow_error("redirect_limit"));
3147        }
3148        state.increment_redirect_count();
3149        state.replace_input(jump.payload.clone());
3150        state.last_output = Some(jump.payload);
3151        tracing::info!(
3152            flow_id = %ctx.flow_id,
3153            target_flow = %target_flow,
3154            target_node = %target_node.as_str(),
3155            reason = ?jump.reason,
3156            redirects = state.redirect_count(),
3157            "flow.jump.applied"
3158        );
3159
3160        Ok(JumpTarget {
3161            flow_id: target_flow.to_string(),
3162            flow,
3163            node_id: target_node,
3164        })
3165    }
3166
3167    async fn execute_flow_call(&self, ctx: &FlowContext<'_>, payload: Value) -> Result<NodeOutput> {
3168        #[derive(Deserialize)]
3169        struct FlowCallPayload {
3170            #[serde(alias = "flow")]
3171            flow_id: String,
3172            #[serde(default)]
3173            input: Value,
3174        }
3175
3176        let call: FlowCallPayload =
3177            serde_json::from_value(payload).context("invalid payload for flow.call node")?;
3178        if call.flow_id.trim().is_empty() {
3179            return Err(terminal_flow_error(
3180                "flow.call requires a non-empty flow_id",
3181            ));
3182        }
3183
3184        let sub_input = if call.input.is_null() {
3185            Value::Null
3186        } else {
3187            call.input
3188        };
3189
3190        let flow_id_owned = call.flow_id;
3191        let action = "flow.call";
3192        let sub_ctx = FlowContext {
3193            tenant: ctx.tenant,
3194            pack_id: ctx.pack_id,
3195            flow_id: flow_id_owned.as_str(),
3196            node_id: None,
3197            tool: ctx.tool,
3198            action: Some(action),
3199            session_id: ctx.session_id,
3200            provider_id: ctx.provider_id,
3201            reply_scope: ctx.reply_scope,
3202            retry_config: ctx.retry_config,
3203            attempt: ctx.attempt,
3204            observer: ctx.observer,
3205            mocks: ctx.mocks,
3206            // A called sub-flow runs on behalf of the same caller. Dropping
3207            // it here would silently anonymise every `flow.call`.
3208            caller: ctx.caller,
3209        };
3210
3211        let depth = FLOW_CALL_DEPTH.try_with(|depth| *depth).unwrap_or(0);
3212        if depth >= MAX_FLOW_CALL_DEPTH {
3213            return Err(terminal_flow_error(format!(
3214                "flow.call nesting exceeds {MAX_FLOW_CALL_DEPTH} levels (calling {})",
3215                flow_id_owned
3216            )));
3217        }
3218        // The caller's own retry loop owns retries; a nested loop would multiply
3219        // attempts. The failure is propagated, never rendered as an envelope.
3220        let sub_ctx = FlowContext {
3221            retry_config: RetryConfig {
3222                max_attempts: 1,
3223                ..sub_ctx.retry_config
3224            },
3225            ..sub_ctx
3226        };
3227        let execution = FLOW_CALL_DEPTH
3228            .scope(
3229                depth + 1,
3230                Box::pin(self.execute_propagating_failure(sub_ctx, sub_input)),
3231            )
3232            .await
3233            .with_context(|| format!("flow.call failed for {}", flow_id_owned))?;
3234        match execution.status {
3235            FlowStatus::Completed => Ok(NodeOutput::new(execution.output)),
3236            // The nested flow's effects already ran: never re-run the turn.
3237            FlowStatus::Waiting(wait) => Err(terminal_flow_error(format!(
3238                "flow.call cannot pause (flow {} waiting {:?})",
3239                flow_id_owned, wait.reason
3240            ))),
3241        }
3242    }
3243}
3244
3245/// Resolve a `Routing::Branch`: the node's reported `status` selects an
3246/// `on_status` entry, otherwise the `default` target applies.
3247///
3248/// The status is read from the node output payload's `status` field (string,
3249/// number or bool), falling back to `meta.status`.
3250fn branch_target(
3251    on_status: &std::collections::BTreeMap<String, NodeId>,
3252    default: Option<&NodeId>,
3253    output: &NodeOutput,
3254) -> Option<NodeId> {
3255    let status_of = |value: &Value| match value {
3256        Value::String(text) => Some(text.clone()),
3257        Value::Number(number) => Some(number.to_string()),
3258        Value::Bool(flag) => Some(flag.to_string()),
3259        _ => None,
3260    };
3261    let status = output
3262        .payload
3263        .get("status")
3264        .and_then(status_of)
3265        .or_else(|| output.meta.get("status").and_then(status_of));
3266    status
3267        .and_then(|status| on_status.get(&status).cloned())
3268        .or_else(|| default.cloned())
3269}
3270
3271#[cfg(feature = "agentic-worker")]
3272use crate::runner::media_node::MAX_CREATED_PER_TURN;
3273
3274/// Mirrors `media_node::MAX_CREATED_PER_TURN`; no node creates files without
3275/// the `agentic-worker` feature, so the list stays empty there.
3276#[cfg(not(feature = "agentic-worker"))]
3277const MAX_CREATED_PER_TURN: usize = 20;
3278
3279#[cfg(feature = "agentic-worker")]
3280fn attach_created_files(reply: Value, created: Vec<Value>) -> Value {
3281    crate::runner::media_node::attach_created(reply, created)
3282}
3283
3284/// Without `media.create` nothing is ever created; the reply is unchanged.
3285#[cfg(not(feature = "agentic-worker"))]
3286fn attach_created_files(reply: Value, _created: Vec<Value>) -> Value {
3287    reply
3288}
3289
3290/// Deepest `flow.call` nesting allowed before the call is refused.
3291const MAX_FLOW_CALL_DEPTH: u32 = 16;
3292
3293tokio::task_local! {
3294    /// How many `flow.call` frames enclose the node currently executing.
3295    static FLOW_CALL_DEPTH: u32;
3296}
3297
3298/// Build the jump that hands this turn over to another flow.
3299///
3300/// Payload shape mirrors `flow.call`'s, so a flow document reads the same
3301/// either way:
3302///
3303/// ```yaml
3304/// <node_id>:
3305///   flow.goto:
3306///     flow_id: support        # required; `flow` accepted as an alias
3307///     node: ask_order         # optional entry node, else the flow's start
3308///     input: { order: "..." } # optional; becomes the target's input
3309/// ```
3310///
3311/// Returns a `NodeControl::Jump`, which `apply_jump` then applies to the SAME
3312/// walk — that is what makes the target's `Waiting` become the turn's, instead
3313/// of the hard error `flow.call` raises. Loop protection is inherited: every
3314/// jump increments the execution's redirect count and `redirect_limit` trips at
3315/// `max_redirects` (default 3).
3316fn execute_flow_goto(payload: Value) -> Result<DispatchOutcome> {
3317    #[derive(Deserialize)]
3318    struct FlowGotoPayload {
3319        #[serde(alias = "flow")]
3320        flow_id: String,
3321        #[serde(default)]
3322        node: Option<String>,
3323        #[serde(default)]
3324        input: Value,
3325        #[serde(default)]
3326        max_redirects: Option<u32>,
3327        #[serde(default)]
3328        reason: Option<String>,
3329    }
3330
3331    let goto: FlowGotoPayload =
3332        serde_json::from_value(payload).context("invalid payload for flow.goto node")?;
3333    let flow = goto.flow_id.trim().to_string();
3334    if flow.is_empty() {
3335        return Err(terminal_flow_error(
3336            "flow.goto requires a non-empty flow_id",
3337        ));
3338    }
3339    let node = goto
3340        .node
3341        .map(|n| n.trim().to_string())
3342        .filter(|n| !n.is_empty());
3343
3344    let jump = JumpControl {
3345        flow,
3346        node,
3347        payload: goto.input,
3348        // `hints` carries component-supplied routing metadata; a declarative
3349        // goto has none to add, and passing anything here would put a value in
3350        // the target's meta that the flow author never wrote.
3351        hints: Value::Null,
3352        max_redirects: goto.max_redirects,
3353        reason: goto.reason.or_else(|| Some("flow.goto node".to_string())),
3354    };
3355    let output = NodeOutput::with_meta(jump.payload.clone(), jump.hints.clone());
3356    Ok(DispatchOutcome::with_control(
3357        output,
3358        NodeControl::Jump(jump),
3359    ))
3360}
3361
3362impl FlowEngine {
3363    async fn execute_component_exec(
3364        &self,
3365        ctx: &FlowContext<'_>,
3366        node_id: &str,
3367        node: &HostNode,
3368        payload: Value,
3369        event: &NodeEvent<'_>,
3370        overrides: ComponentOverrides<'_>,
3371    ) -> Result<NodeOutput> {
3372        #[derive(Deserialize)]
3373        struct ComponentPayload {
3374            #[serde(default, alias = "component_ref", alias = "component")]
3375            component: Option<String>,
3376            #[serde(alias = "op")]
3377            operation: Option<String>,
3378            #[serde(default)]
3379            input: Value,
3380            #[serde(default)]
3381            config: Value,
3382        }
3383
3384        let payload: ComponentPayload =
3385            serde_json::from_value(payload).context("invalid payload for component.exec")?;
3386        let component_ref = overrides
3387            .component
3388            .map(str::to_string)
3389            .or_else(|| payload.component.filter(|v| !v.trim().is_empty()))
3390            .with_context(|| "component.exec requires a component_ref")?;
3391        let operation = resolve_component_operation(
3392            node_id,
3393            node.component_id.as_str(),
3394            payload.operation,
3395            overrides.operation,
3396            node.operation_in_mapping.as_deref(),
3397        )?;
3398
3399        let call = ComponentCall {
3400            component_ref,
3401            operation,
3402            input: payload.input,
3403            config: payload.config,
3404            has_error_route: node_has_error_route(&node.routing),
3405        };
3406
3407        self.invoke_component_call(ctx, node_id, call, event).await
3408    }
3409
3410    async fn execute_component_call(
3411        &self,
3412        ctx: &FlowContext<'_>,
3413        node_id: &str,
3414        node: &HostNode,
3415        payload: Value,
3416        component_ref: &str,
3417        event: &NodeEvent<'_>,
3418    ) -> Result<NodeOutput> {
3419        let payload_operation = extract_operation_from_mapping(&payload);
3420        let (input, config) = split_operation_payload(payload);
3421        let operation = resolve_component_operation(
3422            node_id,
3423            node.component_id.as_str(),
3424            payload_operation,
3425            node.operation_name.as_deref(),
3426            node.operation_in_mapping.as_deref(),
3427        )?;
3428        let call = ComponentCall {
3429            component_ref: component_ref.to_string(),
3430            operation,
3431            input,
3432            config,
3433            has_error_route: node_has_error_route(&node.routing),
3434        };
3435        self.invoke_component_call(ctx, node_id, call, event).await
3436    }
3437
3438    async fn invoke_component_call(
3439        &self,
3440        ctx: &FlowContext<'_>,
3441        node_id: &str,
3442        mut call: ComponentCall,
3443        event: &NodeEvent<'_>,
3444    ) -> Result<NodeOutput> {
3445        self.validate_component(ctx, event, &call)?;
3446        let key = FlowKey {
3447            pack_id: ctx.pack_id.to_string(),
3448            flow_id: ctx.flow_id.to_string(),
3449        };
3450        let pack_idx = *self.flow_sources.get(&key).with_context(|| {
3451            format!("flow {} (pack {}) not registered", ctx.flow_id, ctx.pack_id)
3452        })?;
3453        let pack = Arc::clone(&self.packs[pack_idx]);
3454
3455        // Promote adaptive-card defaults from node config (default_card_asset /
3456        // default_card_inline / default_source) into the invocation, so the
3457        // component receives a valid `card_spec` field even when the user input
3458        // is empty (e.g. webchat ConversationStart with no text). Without this,
3459        // schema validation in the component reports AC_INVOCATION_MISSING_FIELD
3460        // and the renderer falls back to a generic "Welcome" placeholder.
3461        promote_card_config_to_invocation(&mut call.input, &call.config);
3462
3463        // Pre-resolve card asset paths: read JSON files from the pack's assets
3464        // directory and inject as inline_json so the component doesn't need
3465        // WASI filesystem access.
3466        resolve_card_assets(&mut call.input, &pack);
3467
3468        // When the input is a card-like invocation (has card_source/card_spec),
3469        // pass it directly to the component instead of wrapping in an
3470        // InvocationEnvelope.  The envelope serialises the payload field as a
3471        // byte array which the component cannot decode back, and the
3472        // InvocationPayload::parse heuristic strips domain fields when a
3473        // `payload` key is present (e.g.  the card's Handlebars template
3474        // context `payload: {}`).
3475        let is_card = is_card_invocation(&call.input);
3476
3477        let exec_ctx = component_exec_ctx(ctx, node_id);
3478        let caller = component_caller(ctx);
3479        let input_json = if is_card {
3480            serde_json::to_string(&call.input)?
3481        } else {
3482            // Runtime owns ctx; flows must not embed ctx, even if they provide envelopes.
3483            let meta = InvocationMeta {
3484                env: &self.default_env,
3485                tenant: ctx.tenant,
3486                flow_id: ctx.flow_id,
3487                node_id: Some(node_id),
3488                provider_id: ctx.provider_id,
3489                session_id: ctx.session_id,
3490                attempt: ctx.attempt,
3491            };
3492            let invocation_envelope = build_invocation_envelope_as(
3493                meta,
3494                caller.as_ref(),
3495                call.operation.as_str(),
3496                call.input,
3497            )
3498            .context("build invocation envelope for component call")?;
3499            serde_json::to_string(&invocation_envelope)?
3500        };
3501        let config_json = if call.config.is_null() {
3502            None
3503        } else {
3504            Some(serde_json::to_string(&call.config)?)
3505        };
3506
3507        #[cfg(feature = "fault-injection")]
3508        {
3509            let fault_ctx = FaultContext {
3510                pack_id: ctx.pack_id,
3511                flow_id: ctx.flow_id,
3512                node_id: Some(node_id),
3513                attempt: ctx.attempt,
3514            };
3515            maybe_fail(FaultPoint::BeforeComponentCall, fault_ctx).map_err(injected_error)?;
3516        }
3517        let value = pack
3518            .invoke_component_for(
3519                call.component_ref.as_str(),
3520                exec_ctx,
3521                caller,
3522                ctx.provider_id,
3523                call.operation.as_str(),
3524                config_json,
3525                input_json,
3526            )
3527            .await?;
3528        #[cfg(feature = "fault-injection")]
3529        {
3530            let fault_ctx = FaultContext {
3531                pack_id: ctx.pack_id,
3532                flow_id: ctx.flow_id,
3533                node_id: Some(node_id),
3534                attempt: ctx.attempt,
3535            };
3536            maybe_fail(FaultPoint::AfterComponentCall, fault_ctx).map_err(injected_error)?;
3537        }
3538
3539        if let Some((code, message)) = component_error(&value) {
3540            // node_io error routing: a node with an `on_error`-family route
3541            // surfaces the failure as an `{errors}` output and lets its error
3542            // branch handle it. Nodes without such a route keep the historical
3543            // hard-fail, so this is purely additive.
3544            if call.has_error_route {
3545                return Ok(NodeOutput::errored(value));
3546            }
3547            bail!(
3548                "component {} failed: {}: {}",
3549                call.component_ref,
3550                code,
3551                message
3552            );
3553        }
3554        // MCP-shaped tool errors (greentic-mcp-generator's tool_error_with_status)
3555        // come back as a top-level `{ "error": { "code", "message", "status" } }`
3556        // value with the WIT envelope still ok=true (because the wasm guest
3557        // returned normally). Treat them the same as a component_error so the
3558        // engine error-envelope lift path surfaces the failure to the user.
3559        //
3560        // This mirrors the `component_error` branch above: the asymmetry (this
3561        // branch bailing unconditionally while `component_error` checked
3562        // `has_error_route` first) was chronological, not deliberate — the
3563        // unconditional bail predates `has_error_route`/`NodeOutput::errored`
3564        // entirely, and nothing about the MCP wire shape makes it exempt from
3565        // node_io error routing.
3566        if let Some((code, message)) = mcp_tool_error(&value) {
3567            if call.has_error_route {
3568                // Normalize into the same `{ok:false, error:{code,message}}` shape
3569                // `component_error` recognises, rather than teaching `to_node_output`
3570                // a second "what does a failed node's error look like" branch. This
3571                // makes `to_node_output` (the `{errors}` envelope) and `meta.error`
3572                // (read by `lift_first_node_error_from_nodes`) agree with each other
3573                // AND with the `bail!` message below on the code/message pair —
3574                // there is exactly one place, `mcp_tool_error`, that decides what
3575                // an MCP tool error's code/message are.
3576                return Ok(NodeOutput::errored(normalize_mcp_tool_error(
3577                    &value, &code, &message,
3578                )));
3579            }
3580            bail!(
3581                "component {} returned tool error: {}: {}",
3582                call.component_ref,
3583                code,
3584                message
3585            );
3586        }
3587        let meta = outcome_meta(&value);
3588        Ok(NodeOutput::with_meta(value, meta))
3589    }
3590
3591    async fn execute_provider_invoke(
3592        &self,
3593        ctx: &FlowContext<'_>,
3594        node_id: &str,
3595        state: &ExecutionState,
3596        payload: Value,
3597        event: &NodeEvent<'_>,
3598    ) -> Result<NodeOutput> {
3599        #[derive(Deserialize)]
3600        struct ProviderPayload {
3601            #[serde(default)]
3602            provider_id: Option<String>,
3603            #[serde(default)]
3604            provider_type: Option<String>,
3605            #[serde(default, alias = "operation")]
3606            op: Option<String>,
3607            #[serde(default)]
3608            input: Value,
3609            #[serde(default)]
3610            in_map: Value,
3611            #[serde(default)]
3612            out_map: Value,
3613        }
3614
3615        // Every `?` below up to `invoke_provider` precedes the provider call, so
3616        // each failure is marked `pre_effect`: nothing has left the host yet.
3617        let payload: ProviderPayload = serde_json::from_value(payload)
3618            .context("invalid payload for provider.invoke")
3619            .map_err(pre_effect)?;
3620        let op = payload
3621            .op
3622            .as_deref()
3623            .filter(|v| !v.trim().is_empty())
3624            .with_context(|| "provider.invoke requires an op")
3625            .map_err(pre_effect)?
3626            .to_string();
3627
3628        let prev = state
3629            .last_output
3630            .as_ref()
3631            .cloned()
3632            .unwrap_or_else(|| Value::Object(JsonMap::new()));
3633        let base_ctx = template_context(state, prev);
3634
3635        let input_value = if !payload.in_map.is_null() {
3636            let mut ctx_value = base_ctx.clone();
3637            if let Value::Object(ref mut map) = ctx_value {
3638                map.insert("input".into(), payload.input.clone());
3639                map.insert("result".into(), payload.input.clone());
3640            }
3641            render_template_value(
3642                &payload.in_map,
3643                &ctx_value,
3644                TemplateOptions {
3645                    allow_pointer: true,
3646                },
3647            )
3648            .context("failed to render provider.invoke in_map")
3649            .map_err(pre_effect)?
3650        } else if !payload.input.is_null() {
3651            payload.input
3652        } else {
3653            Value::Null
3654        };
3655        let input_json = serde_json::to_vec(&input_value).map_err(pre_effect)?;
3656
3657        self.validate_tool(
3658            ctx,
3659            event,
3660            payload.provider_id.as_deref(),
3661            payload.provider_type.as_deref(),
3662            &op,
3663            &input_value,
3664        )
3665        .map_err(pre_effect)?;
3666
3667        let key = FlowKey {
3668            pack_id: ctx.pack_id.to_string(),
3669            flow_id: ctx.flow_id.to_string(),
3670        };
3671        let pack_idx = *self
3672            .flow_sources
3673            .get(&key)
3674            .with_context(|| format!("flow {} (pack {}) not registered", ctx.flow_id, ctx.pack_id))
3675            .map_err(pre_effect)?;
3676        let pack = Arc::clone(&self.packs[pack_idx]);
3677        let binding = pack.resolve_provider(
3678            payload.provider_id.as_deref(),
3679            payload.provider_type.as_deref(),
3680        );
3681
3682        // If pack-local resolution fails, try the cross-pack resolver (capability registry).
3683        if binding.is_err()
3684            && let Some(output) = self.try_invoke_cross_pack_resolver(
3685                payload.provider_id.as_deref(),
3686                payload.provider_type.as_deref(),
3687                &op,
3688                &input_json,
3689                ctx.tenant,
3690            )?
3691        {
3692            return Ok(output);
3693        }
3694
3695        let binding = binding.map_err(pre_effect)?;
3696        let exec_ctx = component_exec_ctx(ctx, node_id);
3697        #[cfg(feature = "fault-injection")]
3698        {
3699            let fault_ctx = FaultContext {
3700                pack_id: ctx.pack_id,
3701                flow_id: ctx.flow_id,
3702                node_id: Some(node_id),
3703                attempt: ctx.attempt,
3704            };
3705            maybe_fail(FaultPoint::BeforeToolCall, fault_ctx)
3706                .map_err(injected_error)
3707                .map_err(pre_effect)?;
3708        }
3709        let provider_metric_id = payload
3710            .provider_id
3711            .as_deref()
3712            .or(payload.provider_type.as_deref())
3713            .unwrap_or("unknown");
3714        let invoke_started = std::time::Instant::now();
3715        let invoke_result = pack
3716            .invoke_provider(&binding, exec_ctx, &op, input_json)
3717            .await;
3718        let invoke_duration_ms = invoke_started.elapsed().as_secs_f64() * 1000.0;
3719        crate::metrics::record_provider_invocation(
3720            ctx.tenant,
3721            provider_metric_id,
3722            &op,
3723            if invoke_result.is_ok() { "ok" } else { "err" },
3724            invoke_duration_ms,
3725        );
3726        let result = invoke_result?;
3727        #[cfg(feature = "fault-injection")]
3728        {
3729            let fault_ctx = FaultContext {
3730                pack_id: ctx.pack_id,
3731                flow_id: ctx.flow_id,
3732                node_id: Some(node_id),
3733                attempt: ctx.attempt,
3734            };
3735            maybe_fail(FaultPoint::AfterToolCall, fault_ctx).map_err(injected_error)?;
3736        }
3737
3738        let output = if payload.out_map.is_null() {
3739            result
3740        } else {
3741            let mut ctx_value = base_ctx;
3742            if let Value::Object(ref mut map) = ctx_value {
3743                map.insert("input".into(), result.clone());
3744                map.insert("result".into(), result.clone());
3745            }
3746            render_template_value(
3747                &payload.out_map,
3748                &ctx_value,
3749                TemplateOptions {
3750                    allow_pointer: true,
3751                },
3752            )
3753            .context("failed to render provider.invoke out_map")?
3754        };
3755        Ok(NodeOutput::new(output))
3756    }
3757
3758    fn try_invoke_cross_pack_resolver(
3759        &self,
3760        provider_id: Option<&str>,
3761        provider_type: Option<&str>,
3762        op: &str,
3763        input_json: &[u8],
3764        tenant: &str,
3765    ) -> Result<Option<NodeOutput>> {
3766        tracing::debug!(
3767            has_resolver = self.cross_pack_resolver.is_some(),
3768            "provider.invoke: pack-local failed"
3769        );
3770        let Some(resolver) = self.cross_pack_resolver.as_ref() else {
3771            return Ok(None);
3772        };
3773        let provider_id = provider_id.unwrap_or("unknown");
3774        tracing::info!(
3775            provider_id,
3776            op = %op,
3777            "provider.invoke: pack-local resolution failed, trying cross-pack resolver"
3778        );
3779        let result_value =
3780            resolver.invoke(provider_id, provider_type, op, input_json, tenant, None)?;
3781        Ok(Some(NodeOutput::new(result_value)))
3782    }
3783
3784    fn validate_component(
3785        &self,
3786        ctx: &FlowContext<'_>,
3787        event: &NodeEvent<'_>,
3788        call: &ComponentCall,
3789    ) -> Result<()> {
3790        if self.validation.mode == ValidationMode::Off {
3791            return Ok(());
3792        }
3793        let mut metadata = JsonMap::new();
3794        metadata.insert("tenant_id".to_string(), json!(ctx.tenant));
3795        if let Some(id) = ctx.session_id {
3796            metadata.insert("session".to_string(), json!({ "id": id }));
3797        }
3798        let envelope = json!({
3799            "component_id": call.component_ref,
3800            "operation": call.operation,
3801            "input": call.input,
3802            "config": call.config,
3803            "metadata": Value::Object(metadata),
3804        });
3805        let issues = validate_component_envelope(&envelope);
3806        self.report_validation(ctx, event, "component", issues)
3807    }
3808
3809    fn validate_tool(
3810        &self,
3811        ctx: &FlowContext<'_>,
3812        event: &NodeEvent<'_>,
3813        provider_id: Option<&str>,
3814        provider_type: Option<&str>,
3815        operation: &str,
3816        input: &Value,
3817    ) -> Result<()> {
3818        if self.validation.mode == ValidationMode::Off {
3819            return Ok(());
3820        }
3821        let tool_id = provider_id.or(provider_type).unwrap_or("provider.invoke");
3822        let mut metadata = JsonMap::new();
3823        metadata.insert("tenant_id".to_string(), json!(ctx.tenant));
3824        if let Some(id) = ctx.session_id {
3825            metadata.insert("session".to_string(), json!({ "id": id }));
3826        }
3827        let envelope = json!({
3828            "tool_id": tool_id,
3829            "operation": operation,
3830            "input": input,
3831            "metadata": Value::Object(metadata),
3832        });
3833        let issues = validate_tool_envelope(&envelope);
3834        self.report_validation(ctx, event, "tool", issues)
3835    }
3836
3837    fn report_validation(
3838        &self,
3839        ctx: &FlowContext<'_>,
3840        event: &NodeEvent<'_>,
3841        kind: &str,
3842        issues: Vec<ValidationIssue>,
3843    ) -> Result<()> {
3844        if issues.is_empty() {
3845            return Ok(());
3846        }
3847        if let Some(observer) = ctx.observer {
3848            observer.on_validation(event, &issues);
3849        }
3850        match self.validation.mode {
3851            ValidationMode::Warn => {
3852                tracing::warn!(
3853                    tenant = ctx.tenant,
3854                    flow_id = ctx.flow_id,
3855                    node_id = event.node_id,
3856                    kind,
3857                    issues = ?issues,
3858                    "invocation envelope validation issues"
3859                );
3860                Ok(())
3861            }
3862            ValidationMode::Error => {
3863                tracing::error!(
3864                    tenant = ctx.tenant,
3865                    flow_id = ctx.flow_id,
3866                    node_id = event.node_id,
3867                    kind,
3868                    issues = ?issues,
3869                    "invocation envelope validation failed"
3870                );
3871                bail!("invocation_validation_failed");
3872            }
3873            ValidationMode::Off => Ok(()),
3874        }
3875    }
3876
3877    pub fn flows(&self) -> &[FlowDescriptor] {
3878        &self.flows
3879    }
3880
3881    /// Node ids declared by a flow, for callers that must tell a flow node
3882    /// apart from something else that shares the id space — a card asset, in
3883    /// the case of [`crate::runner::card_nav`].
3884    ///
3885    /// Loads the flow if it is not cached yet; an unloadable flow yields an
3886    /// empty list rather than an error, because the caller's question ("is
3887    /// this a node?") has a sound negative answer either way.
3888    pub async fn flow_node_ids(&self, pack_id: &str, flow_id: &str) -> Vec<String> {
3889        match self.get_or_load_flow(pack_id, flow_id).await {
3890            Ok(flow) => flow
3891                .nodes
3892                .keys()
3893                .map(|id| id.as_str().to_string())
3894                .collect(),
3895            Err(error) => {
3896                tracing::debug!(
3897                    pack_id,
3898                    flow_id,
3899                    error = %error,
3900                    "flow not loadable while listing node ids; treating as no nodes"
3901                );
3902                Vec::new()
3903            }
3904        }
3905    }
3906
3907    pub fn flow_by_key(&self, pack_id: &str, flow_id: &str) -> Option<&FlowDescriptor> {
3908        self.flows
3909            .iter()
3910            .find(|descriptor| descriptor.pack_id == pack_id && descriptor.id == flow_id)
3911    }
3912
3913    pub fn flow_by_type(&self, flow_type: &str) -> Option<&FlowDescriptor> {
3914        let mut matches = self
3915            .flows
3916            .iter()
3917            .filter(|descriptor| descriptor.flow_type == flow_type);
3918        let first = matches.next()?;
3919        if matches.next().is_some() {
3920            return None;
3921        }
3922        Some(first)
3923    }
3924
3925    /// Resolve a flow by type, considering only application entrypoint flows.
3926    ///
3927    /// Used to disambiguate an inbound provider event (routed by flow type,
3928    /// with no explicit `pack_id`/`flow_id`) when a pack registers one public
3929    /// entrypoint plus internal helper flows of the same type — the common
3930    /// "dispatcher + sub-flows" shape. Internal flows are only reachable via
3931    /// `flow.call`, so they must never win a type-only route.
3932    ///
3933    /// Flows owned by a messaging **provider** pack (its manifest declares a
3934    /// `messaging.*` provider) are also excluded: a provider ships its own
3935    /// ingress `main`/`default` flow that is plumbing for *that provider*, not
3936    /// the application. In a multi-provider bundle that flow would otherwise
3937    /// compete with the app's real entrypoint and make the route ambiguous.
3938    ///
3939    /// Returns `None` when zero or more than one *application* entry flow of the
3940    /// type exists (genuinely ambiguous — the caller must then require a
3941    /// `pack_id`).
3942    pub fn entry_flow_by_type(&self, flow_type: &str) -> Option<&FlowDescriptor> {
3943        let mut matches = self.flows.iter().filter(|descriptor| {
3944            descriptor.flow_type == flow_type
3945                && descriptor.entry
3946                && !self
3947                    .messaging_provider_pack_ids
3948                    .contains(&descriptor.pack_id)
3949        });
3950        let first = matches.next()?;
3951        if matches.next().is_some() {
3952            return None;
3953        }
3954        Some(first)
3955    }
3956
3957    /// `(pack_id, manifest name, version)` of a loaded pack, for the run
3958    /// audit's worker identity.
3959    pub(crate) fn pack_identity(&self, pack_id: &str) -> Option<(String, Option<String>, String)> {
3960        self.packs
3961            .iter()
3962            .find(|pack| pack.metadata().pack_id == pack_id)
3963            .map(|pack| {
3964                let meta = pack.metadata();
3965                (
3966                    meta.pack_id.clone(),
3967                    pack.manifest_name().map(str::to_string),
3968                    meta.version.clone(),
3969                )
3970            })
3971    }
3972
3973    pub fn flow_by_id(&self, flow_id: &str) -> Option<&FlowDescriptor> {
3974        let mut matches = self
3975            .flows
3976            .iter()
3977            .filter(|descriptor| descriptor.id == flow_id);
3978        let first = matches.next()?;
3979        if matches.next().is_some() {
3980            return None;
3981        }
3982        Some(first)
3983    }
3984}
3985
3986pub trait ExecutionObserver: Send + Sync {
3987    fn on_node_start(&self, event: &NodeEvent<'_>);
3988    fn on_node_end(&self, event: &NodeEvent<'_>, output: &Value);
3989    fn on_node_error(&self, event: &NodeEvent<'_>, error: &dyn StdError);
3990    fn on_validation(&self, _event: &NodeEvent<'_>, _issues: &[ValidationIssue]) {}
3991    /// A flow walk entered through `execute` / `execute_from` (a turn's
3992    /// top-level run, or a `flow.call` callee) starts attempt `attempt`
3993    /// (1-based). Attempt > 1 is an engine retry that re-runs the walk from
3994    /// its entry node. Calls nest: a callee's attempts arrive between its
3995    /// caller's attempt and the caller's [`Self::on_flow_exit`].
3996    fn on_flow_attempt(&self, _flow_id: &str, _attempt: u32) {}
3997    /// The walk whose attempts [`Self::on_flow_attempt`] reported has returned
3998    /// (success or final failure). Exactly one per walk that reported
3999    /// attempt 1. `FlowEngine::resume` reports neither.
4000    fn on_flow_exit(&self, _flow_id: &str) {}
4001}
4002
4003pub struct NodeEvent<'a> {
4004    pub context: &'a FlowContext<'a>,
4005    pub node_id: &'a str,
4006    pub node: &'a HostNode,
4007    pub payload: &'a Value,
4008}
4009
4010/// Safety backstop for a CONVERSATIONAL `dw.agent` node's park-and-loop cycle.
4011///
4012/// This is NOT a UX limit — it exists purely so that a stuck or misbehaving
4013/// conversational agent (one that never emits `conversation_ended`) cannot
4014/// trap a flow at the same node forever. After this many parked turns at a
4015/// single conversational `dw.agent` node without a `conversation_ended`
4016/// termination, the flow force-advances to the node's successor using the
4017/// agent's last output. Deliberately a plain constant: no env var, no
4018/// per-agent config knob.
4019///
4020/// Only referenced from the conversational `DwAgent` branch of
4021/// `dispatch_node` and from the (already `#[cfg(feature = "agentic-worker")]`
4022/// -gated) park-loop-cap unit tests below; cfg-gate it the same way so it
4023/// isn't flagged dead when that feature is off (e.g. a lean
4024/// `--no-default-features --features verify` build). Unlike
4025/// `bump_park_turns`/etc. below, no plain (ungated) test references this
4026/// constant directly, so no `test` alternative is needed here.
4027#[cfg(feature = "agentic-worker")]
4028const MAX_PARK_TURNS: u32 = 100;
4029
4030/// Submitted fields waiting to be attached to the output of the node that
4031/// parked for them.
4032///
4033/// It cannot be attached at resume time: `drive_flow` re-dispatches
4034/// `snapshot.next_node` and `state.nodes.insert` REPLACES that node's stored
4035/// output, so anything written before the dispatch is destroyed.
4036#[derive(Clone, Debug, Serialize, Deserialize)]
4037struct PendingCardAnswers {
4038    node_id: String,
4039    answers: JsonMap<String, Value>,
4040}
4041
4042#[derive(Clone, Debug, Serialize, Deserialize)]
4043pub struct ExecutionState {
4044    #[serde(default)]
4045    entry: Value,
4046    #[serde(default)]
4047    input: Value,
4048    #[serde(default)]
4049    nodes: HashMap<String, NodeOutput>,
4050    /// Node ids in the order their (latest) output was recorded. `nodes` is a
4051    /// `HashMap`, so without this "the first failed node" was whichever the
4052    /// hasher happened to yield.
4053    #[serde(default, skip_serializing_if = "Vec::is_empty")]
4054    node_order: Vec<String>,
4055    #[serde(default)]
4056    egress: Vec<Value>,
4057    #[serde(default, skip_serializing_if = "Option::is_none")]
4058    last_output: Option<Value>,
4059    #[serde(default)]
4060    redirect_count: u32,
4061    #[serde(default)]
4062    vars: JsonMap<String, Value>,
4063    /// Per-node park-loop turn counter for conversational `dw.agent` nodes,
4064    /// keyed by node id. Mirrors `redirect_count`'s per-execution safety-cap
4065    /// pattern, but tracked per node since a flow may hold more than one
4066    /// conversational agent.
4067    #[serde(default)]
4068    park_turns: HashMap<String, u32>,
4069    /// Marks a node as awaiting an async `dw.agent` NATS dispatch response.
4070    /// Set on dispatch, checked-and-cleared on resume; mirrors `park_turns`'
4071    /// per-node, serde-defaulted, persisted-in-snapshot pattern.
4072    #[serde(default)]
4073    pending_agent_await: HashMap<String, ()>,
4074    /// Files created for the end user during THIS turn (`media.create`),
4075    /// folded into the turn's final reply by `finalize_with`
4076    /// (see [`crate::runner::media_node::CREATED_ARTIFACTS_KEY`]). Never
4077    /// serialised and cleared on every snapshot, so a parked run cannot
4078    /// deliver a file again on its next turn.
4079    #[serde(skip)]
4080    created_artifacts: Vec<Value>,
4081    /// Nodes that dispatched an approval request and are parked awaiting the
4082    /// decision. Set on dispatch, cleared when the response re-enters the node.
4083    /// Without it a stray inbound arriving mid-await would look like a first
4084    /// entry and re-dispatch — a duplicate approval request to the operator.
4085    ///
4086    /// The value is the correlation id the request was published under —
4087    /// per-dispatch since it carries a `::n=` nonce — so the resume path can
4088    /// refuse a response meant for a DIFFERENT approval (an earlier gate in the
4089    /// same conversation, or its watchdog's late `timeout`). The park itself is
4090    /// keyed per conversation, so without this any approval response in the
4091    /// conversation would resume whichever gate happens to be parked. `None`
4092    /// is a snapshot written before the id was recorded (the old `()` value
4093    /// serialised as `null`), which decodes cleanly and is not verified.
4094    #[serde(default)]
4095    pending_approval_await: HashMap<String, Option<String>>,
4096    /// `sha256(decision_token)`, hex, for each approval in
4097    /// [`Self::pending_approval_await`] that was issued one (greentic-runner
4098    /// #794). Never the token itself. Kept as a SEPARATE map rather than
4099    /// widening the value above so a snapshot written before tokens existed
4100    /// decodes unchanged — a gate with no entry here is a legacy park and is
4101    /// resumed without a token, exactly as before.
4102    #[serde(default)]
4103    pending_approval_token: HashMap<String, String>,
4104    /// In-process `dw.agent` nodes parked because one of the agent's `flow:`
4105    /// tools is waiting on the user (a card). Set when the agent answers
4106    /// `terminated_by == "awaiting_tool_input"`, taken on the re-entry that
4107    /// resumes it — which is what tells that re-entry to hand the inbound
4108    /// submit to the agent as the tool's answer rather than as a new message.
4109    #[serde(default)]
4110    pending_tool_await: HashMap<String, ()>,
4111    /// Submitted fields awaiting attachment to their node's output. In practice
4112    /// never survives a snapshot — it is consumed by the first dispatch after a
4113    /// resume — but is serde-defaulted like its neighbours.
4114    #[serde(default, skip_serializing_if = "Option::is_none")]
4115    pending_card_answers: Option<PendingCardAnswers>,
4116    /// The node this turn RESUMED at, when it resumed a card parked on
4117    /// `awaiting_submit`. It is what lets a route marked `on_message` tell "the
4118    /// card was just rendered" (park) from "the person answered the card by
4119    /// typing" (take the route). Cleared as soon as that node has routed, so
4120    /// it never survives into a later node or a snapshot.
4121    #[serde(default, skip_serializing_if = "Option::is_none")]
4122    resumed_at: Option<String>,
4123}
4124
4125impl ExecutionState {
4126    fn new(input: Value) -> Self {
4127        Self {
4128            entry: input.clone(),
4129            input,
4130            nodes: HashMap::new(),
4131            node_order: Vec::new(),
4132            egress: Vec::new(),
4133            last_output: None,
4134            redirect_count: 0,
4135            vars: JsonMap::new(),
4136            park_turns: HashMap::new(),
4137            pending_agent_await: HashMap::new(),
4138            created_artifacts: Vec::new(),
4139            pending_approval_await: HashMap::new(),
4140            pending_approval_token: HashMap::new(),
4141            pending_tool_await: HashMap::new(),
4142            pending_card_answers: None,
4143            resumed_at: None,
4144        }
4145    }
4146
4147    /// Refresh `entry` from `input` if the snapshot was loaded without an
4148    /// entry value. Kept for backwards compatibility with snapshots
4149    /// persisted before the entry-refresh fix in `FlowEngine::resume`.
4150    #[allow(dead_code)]
4151    fn ensure_entry(&mut self) {
4152        if self.entry.is_null() {
4153            self.entry = self.input.clone();
4154        }
4155    }
4156
4157    fn context(&self) -> Value {
4158        let mut nodes = JsonMap::new();
4159        for (id, output) in &self.nodes {
4160            nodes.insert(
4161                id.clone(),
4162                json!({
4163                    "ok": output.ok,
4164                    "payload": output.payload.clone(),
4165                    "meta": output.meta.clone(),
4166                }),
4167            );
4168        }
4169        json!({
4170            "entry": self.entry.clone(),
4171            "input": self.input.clone(),
4172            "nodes": nodes,
4173            "redirect_count": self.redirect_count,
4174            "park_turns": self.park_turns.clone(),
4175            "pending_agent_await": self.pending_agent_await.keys().cloned().collect::<Vec<_>>(),
4176        })
4177    }
4178
4179    /// Record `output` as the latest result of `node_id`, tracking execution order.
4180    fn record_node_output(&mut self, node_id: String, output: NodeOutput) {
4181        self.node_order.retain(|id| id != &node_id);
4182        self.node_order.push(node_id.clone());
4183        self.nodes.insert(node_id, output);
4184    }
4185
4186    /// The first node, in execution order, that finished `ok == false` and is
4187    /// NOT handled by an error edge (a handled failure was routed, not
4188    /// unhandled, and must not be lifted into the reply as if it escaped).
4189    fn first_unhandled_failure(&self, flow: &HostFlow) -> Option<(String, NodeOutput)> {
4190        let handled = |id: &str| {
4191            NodeId::from_str(id)
4192                .ok()
4193                .and_then(|node_id| flow.nodes.get(&node_id))
4194                .is_some_and(|node| node_has_error_route(&node.routing))
4195        };
4196        let ordered = self
4197            .node_order
4198            .iter()
4199            .filter_map(|id| self.nodes.get(id).map(|out| (id, out)));
4200        // Nodes restored from a snapshot written before `node_order` existed
4201        // have no recorded order: fall back to sorted ids so the pick is at
4202        // least deterministic.
4203        let mut unordered: Vec<(&String, &NodeOutput)> = self
4204            .nodes
4205            .iter()
4206            .filter(|(id, _)| !self.node_order.contains(id))
4207            .collect();
4208        unordered.sort_by(|a, b| a.0.cmp(b.0));
4209        unordered
4210            .into_iter()
4211            .chain(ordered)
4212            .find(|(id, out)| !out.ok && !handled(id))
4213            .map(|(id, out)| (id.clone(), out.clone()))
4214    }
4215
4216    fn outputs_map(&self) -> JsonMap<String, Value> {
4217        let mut outputs = JsonMap::new();
4218        for (id, output) in &self.nodes {
4219            outputs.insert(id.clone(), node_output_view(&output.payload));
4220        }
4221        outputs
4222    }
4223    fn push_egress(&mut self, payload: Value) {
4224        self.egress.push(payload);
4225    }
4226
4227    fn replace_input(&mut self, input: Value) {
4228        self.input = input;
4229    }
4230
4231    /// Drop everything a snapshot must not carry into the next turn: the
4232    /// emitted payloads and the files created this turn (both belong to the
4233    /// reply being finalised now, not to the parked run).
4234    fn clear_egress(&mut self) {
4235        self.egress.clear();
4236        self.created_artifacts.clear();
4237    }
4238
4239    /// Record files a node created for the user this turn. Deduplicated by id
4240    /// and bounded, so a looping flow cannot grow the list without limit.
4241    fn note_created_artifacts(&mut self, created: Vec<Value>) {
4242        let mut dropped = 0usize;
4243        for file in created {
4244            if self.created_artifacts.len() >= MAX_CREATED_PER_TURN {
4245                // The file exists in the artifact store but will NOT be listed
4246                // in the turn's reply, so the user never receives it.
4247                dropped += 1;
4248                continue;
4249            }
4250            let id = file.get("id").and_then(Value::as_str);
4251            let known = self
4252                .created_artifacts
4253                .iter()
4254                .any(|seen| seen.get("id").and_then(Value::as_str) == id);
4255            if id.is_some() && !known {
4256                self.created_artifacts.push(file);
4257            }
4258        }
4259        if dropped > 0 {
4260            tracing::warn!(
4261                dropped,
4262                cap = MAX_CREATED_PER_TURN,
4263                "a turn created more files than the per-turn delivery cap; the extra files are stored but not listed in the reply"
4264            );
4265        }
4266    }
4267
4268    fn redirect_count(&self) -> u32 {
4269        self.redirect_count
4270    }
4271
4272    fn reset_redirect_count(&mut self) {
4273        self.redirect_count = 0;
4274    }
4275
4276    fn increment_redirect_count(&mut self) {
4277        self.redirect_count = self.redirect_count.saturating_add(1);
4278    }
4279
4280    /// Bump the park-loop turn counter for `node_id` and return the NEW count.
4281    ///
4282    /// Like `MAX_PARK_TURNS`, only called from the conversational `DwAgent`
4283    /// branch of `dispatch_node` (`agentic-worker`-gated) plus the unit tests
4284    /// below.
4285    #[cfg(any(feature = "agentic-worker", test))]
4286    fn bump_park_turns(&mut self, node_id: &str) -> u32 {
4287        let entry = self.park_turns.entry(node_id.to_string()).or_insert(0);
4288        *entry = entry.saturating_add(1);
4289        *entry
4290    }
4291
4292    /// Clear the park-loop turn counter for `node_id` (e.g. once the
4293    /// conversational segment ends), so a later re-entry starts fresh.
4294    #[cfg(any(feature = "agentic-worker", test))]
4295    fn reset_park_turns(&mut self, node_id: &str) {
4296        self.park_turns.remove(node_id);
4297    }
4298
4299    /// Mark `node_id` as awaiting an async `dw.agent` NATS dispatch response.
4300    /// Called from the conversational `DwAgentDispatch::Nats` branch in
4301    /// `dispatch_node` before dispatching a fresh user turn.
4302    #[cfg(any(feature = "agentic-worker", test))]
4303    fn mark_agent_await(&mut self, node_id: &str) {
4304        self.pending_agent_await.insert(node_id.to_string(), ());
4305    }
4306
4307    /// Check-and-clear: returns whether `node_id` was awaiting an agent response.
4308    /// Called from the conversational `DwAgentDispatch::Nats` branch in
4309    /// `dispatch_node` on resume, to distinguish "resuming with the agent's
4310    /// response" from "a fresh user turn".
4311    #[cfg(any(feature = "agentic-worker", test))]
4312    fn take_agent_await(&mut self, node_id: &str) -> bool {
4313        self.pending_agent_await.remove(node_id).is_some()
4314    }
4315
4316    /// Mark `node_id` as parked on an agent's suspended `flow:` tool.
4317    #[cfg(any(feature = "agentic-worker", test))]
4318    fn mark_tool_await(&mut self, node_id: &str) {
4319        self.pending_tool_await.insert(node_id.to_string(), ());
4320    }
4321
4322    /// Check-and-clear: whether `node_id` parked on a suspended `flow:` tool.
4323    #[cfg(any(feature = "agentic-worker", test))]
4324    fn take_tool_await(&mut self, node_id: &str) -> bool {
4325        self.pending_tool_await.remove(node_id).is_some()
4326    }
4327
4328    /// Mark `node_id` as parked awaiting an approval decision (see
4329    /// [`Self::pending_approval_await`] and [`Self::pending_approval_token`]).
4330    fn mark_approval_await(&mut self, node_id: &str, parked: ParkedApproval) {
4331        self.pending_approval_await
4332            .insert(node_id.to_string(), parked.correlation_id);
4333        match parked.token_fingerprint {
4334            Some(fingerprint) => {
4335                self.pending_approval_token
4336                    .insert(node_id.to_string(), fingerprint);
4337            }
4338            None => {
4339                self.pending_approval_token.remove(node_id);
4340            }
4341        }
4342    }
4343
4344    /// Check-and-clear: `Some` when `node_id` dispatched an approval and is
4345    /// awaiting the decision, `None` otherwise. Clearing the token fingerprint
4346    /// here is what makes the token single-use.
4347    fn take_approval_await(&mut self, node_id: &str) -> Option<ParkedApproval> {
4348        let correlation_id = self.pending_approval_await.remove(node_id)?;
4349        Some(ParkedApproval {
4350            correlation_id,
4351            token_fingerprint: self.pending_approval_token.remove(node_id),
4352        })
4353    }
4354
4355    /// Every approval this state is parked on. Read by the dispatch resume
4356    /// path to match a response to its own gate before resuming anything.
4357    pub(crate) fn pending_approvals(&self) -> Vec<ParkedApproval> {
4358        self.pending_approval_await
4359            .iter()
4360            .map(|(node_id, correlation_id)| ParkedApproval {
4361                correlation_id: correlation_id.clone(),
4362                token_fingerprint: self.pending_approval_token.get(node_id).cloned(),
4363            })
4364            .collect()
4365    }
4366
4367    fn finalize_with(mut self, final_payload: Option<Value>) -> Value {
4368        let created = std::mem::take(&mut self.created_artifacts);
4369        let reply = self.finalize_reply(final_payload);
4370        attach_created_files(reply, created)
4371    }
4372
4373    fn finalize_reply(mut self, final_payload: Option<Value>) -> Value {
4374        if self.egress.is_empty() {
4375            return final_payload.unwrap_or(Value::Null);
4376        }
4377        let mut emitted = std::mem::take(&mut self.egress);
4378        if let Some(value) = final_payload {
4379            match value {
4380                Value::Null => {}
4381                Value::Array(items) => emitted.extend(items),
4382                // A terminal `emit.response` node BOTH pushes its payload to
4383                // egress (see `push_egress` in `dispatch_node`) AND returns that
4384                // same payload as its node output, which the `End` path passes
4385                // here as `final_payload`. Appending it unconditionally would
4386                // emit the response twice (the webchat "double card"). Skip the
4387                // re-append when it merely repeats the last emitted response;
4388                // a genuinely distinct terminal output is still appended.
4389                other if emitted.last() == Some(&other) => {}
4390                other => emitted.push(other),
4391            }
4392        }
4393        Value::Array(emitted)
4394    }
4395}
4396
4397#[derive(Clone, Debug, Serialize, Deserialize)]
4398struct NodeOutput {
4399    ok: bool,
4400    payload: Value,
4401    meta: Value,
4402    /// Files this node created for the end user of the CURRENT turn
4403    /// (`media.create` only). Never serialised: the run loop moves it into
4404    /// [`ExecutionState`]'s per-turn list right after dispatch, so it can
4405    /// neither reach a snapshot nor a later turn.
4406    #[serde(skip)]
4407    created: Vec<Value>,
4408}
4409
4410impl NodeOutput {
4411    fn new(payload: Value) -> Self {
4412        Self {
4413            ok: true,
4414            payload,
4415            meta: Value::Null,
4416            created: Vec::new(),
4417        }
4418    }
4419
4420    /// `ok=false` output stashing error context in `meta.error`. Currently
4421    /// only used by `lift_first_node_error_from_nodes` tests — kept around so
4422    /// drive_flow can resume populating it once we have a hook for it.
4423    #[allow(dead_code)]
4424    fn with_error(node_id: &str, err: &(dyn std::error::Error + 'static)) -> Self {
4425        Self {
4426            ok: false,
4427            payload: Value::Null,
4428            meta: json!({
4429                "error": {
4430                    "kind": "flow_node_failed",
4431                    "message": err.to_string(),
4432                    "node_id": node_id,
4433                }
4434            }),
4435            created: Vec::new(),
4436        }
4437    }
4438}
4439
4440struct DispatchOutcome {
4441    output: NodeOutput,
4442    control: NodeControl,
4443}
4444
4445impl DispatchOutcome {
4446    fn complete(output: NodeOutput) -> Self {
4447        Self {
4448            output,
4449            control: NodeControl::Continue,
4450        }
4451    }
4452
4453    fn wait(output: NodeOutput, reason: Option<String>) -> Self {
4454        Self {
4455            output,
4456            control: NodeControl::Wait { reason },
4457        }
4458    }
4459
4460    fn await_here(output: NodeOutput, reason: Option<String>, correlation_id: String) -> Self {
4461        Self {
4462            output,
4463            control: NodeControl::AwaitHere {
4464                reason,
4465                correlation_id,
4466            },
4467        }
4468    }
4469
4470    fn with_control(output: NodeOutput, control: NodeControl) -> Self {
4471        Self { output, control }
4472    }
4473}
4474
4475#[derive(Clone, Debug)]
4476enum NodeControl {
4477    Continue,
4478    Wait {
4479        reason: Option<String>,
4480    },
4481    /// Park the flow and RE-ENTER this same node on the next inbound activity
4482    /// (conversational `dw.agent` loop), rendering the node output first.
4483    /// Unlike `Wait` (which resumes at the routing successor and renders
4484    /// nothing), `LoopHere` sets the resume target to the current node and
4485    /// renders the reply.
4486    ///
4487    /// Only constructed from the conversational `DwAgent` branch of
4488    /// `dispatch_node`, which is `#[cfg(feature = "agentic-worker")]` —
4489    /// `#[allow(dead_code)]` rather than cfg-gating the variant itself so the
4490    /// (unconditionally-compiled) match arm handling it in `run_flow`'s
4491    /// dispatch loop doesn't need a matching cfg attribute.
4492    #[allow(dead_code)]
4493    LoopHere {
4494        reason: Option<String>,
4495    },
4496    /// Park the flow and await a correlation-keyed async runtime response
4497    /// (out-of-process conversational `dw.agent`), but RE-ENTER this same
4498    /// node when the response arrives — like `LoopHere` it resumes at THIS
4499    /// node (not the routing successor) so the conversational decision can
4500    /// evaluate the response, unlike `Wait` which resumes at the routing
4501    /// successor. Resumed via the dispatch listener + `RuntimeSessionResumer`.
4502    AwaitHere {
4503        reason: Option<String>,
4504        // Audit-carried, not read: per the spike's keying model (§Q3), the
4505        // actual resume lookup is keyed by `(session_hint, ReplyScope.scope_hash)`
4506        // via `build_store_ctx`/`FlowResumeStore`, not by this field — the
4507        // `drive_flow` handler destructures it as `correlation_id: _`. Kept on
4508        // the variant for debugging/observability only.
4509        #[allow(dead_code)]
4510        correlation_id: String,
4511    },
4512    Jump(JumpControl),
4513    Respond {
4514        text: Option<String>,
4515        card_cbor: Option<Vec<u8>>,
4516        needs_user: Option<bool>,
4517    },
4518}
4519
4520#[derive(Clone, Debug)]
4521struct JumpControl {
4522    flow: String,
4523    node: Option<String>,
4524    payload: Value,
4525    hints: Value,
4526    max_redirects: Option<u32>,
4527    reason: Option<String>,
4528}
4529
4530#[derive(Clone, Debug)]
4531struct JumpTarget {
4532    flow_id: String,
4533    flow: HostFlow,
4534    node_id: NodeId,
4535}
4536
4537impl NodeOutput {
4538    fn with_meta(payload: Value, meta: Value) -> Self {
4539        Self {
4540            ok: true,
4541            payload,
4542            meta,
4543            created: Vec::new(),
4544        }
4545    }
4546
4547    /// A failure output (`ok == false`). `build_routing_context` derives the
4548    /// `error_event` from this, so a node with an `on_error`-family route lands
4549    /// on its failure branch; `node_output_view` exposes the `{errors}` envelope.
4550    ///
4551    /// `meta` is built by MERGING two things a failure payload can carry, not
4552    /// by replacing one with the other: `outcome` (read by
4553    /// `build_routing_context` so a component-distinguished failure like
4554    /// `on_timeout` routes to its own branch instead of the generic error
4555    /// branch — mirrors the success path's `outcome_meta`) and `error` (read
4556    /// by `lift_first_node_error_from_nodes`, the same carrier
4557    /// `NodeOutput::with_error` populates). A component can emit both at once
4558    /// (`{"ok":false,"outcome":"on_timeout","error":{...}}`), and neither must
4559    /// clobber the other.
4560    fn errored(payload: Value) -> Self {
4561        let mut meta = JsonMap::new();
4562        if let Some(outcome) = payload.get("outcome").and_then(Value::as_str) {
4563            meta.insert("outcome".to_string(), Value::String(outcome.to_string()));
4564        }
4565        if let Some(error) = payload.get("error") {
4566            meta.insert("error".to_string(), error.clone());
4567        }
4568        let meta = if meta.is_empty() {
4569            Value::Null
4570        } else {
4571            Value::Object(meta)
4572        };
4573        Self {
4574            ok: false,
4575            payload,
4576            meta,
4577            created: Vec::new(),
4578        }
4579    }
4580}
4581
4582/// The context a component invocation runs under.
4583///
4584/// `tenant` is the HOST's scope for the component's secrets and state, and is
4585/// unchanged by a caller: `team` stays `None` so tenant-wide secrets keep
4586/// resolving, and `user` stays the provider id so existing component state is
4587/// not re-keyed. That `user` is a storage key, NOT an identity: it is never
4588/// presented to the component as its user. The provider-verified caller
4589/// travels separately in `caller` (from `FlowContext::caller`, never from the
4590/// node payload) and is what the component is told its `user`/`team` are;
4591/// with no verified subject the component is told no user at all, and the
4592/// provider is presented in its own slot — see
4593/// `PackRuntime::invoke_component_for`,
4594/// [`crate::caller_identity::ComponentCaller`] and [`component_caller`].
4595fn component_exec_ctx(ctx: &FlowContext<'_>, node_id: &str) -> ComponentExecCtx {
4596    ComponentExecCtx {
4597        tenant: ComponentTenantCtx {
4598            tenant: ctx.tenant.to_string(),
4599            team: None,
4600            user: ctx.provider_id.map(str::to_string),
4601            trace_id: None,
4602            i18n_id: None,
4603            correlation_id: ctx.session_id.map(str::to_string),
4604            deadline_unix_ms: None,
4605            attempt: ctx.attempt,
4606            idempotency_key: ctx.session_id.map(str::to_string),
4607        },
4608        i18n_id: None,
4609        flow_id: ctx.flow_id.to_string(),
4610        node_id: Some(node_id.to_string()),
4611    }
4612}
4613
4614/// The provider-verified caller a component invocation is told about, from
4615/// `FlowContext::caller` (never from the node payload). Carried beside the
4616/// `ExecCtx` rather than inside it — see `PackRuntime::invoke_component_as`.
4617fn component_caller(ctx: &FlowContext<'_>) -> Option<crate::caller_identity::ComponentCaller> {
4618    ctx.caller
4619        .and_then(crate::caller_identity::ComponentCaller::from_block)
4620}
4621
4622/// Surface a component-emitted `outcome` (from its output envelope) as node
4623/// metadata, so the routing context can match `event == "<outcome>"`. A
4624/// component opts in by adding `"outcome": "<name>"` to its output envelope
4625/// (alongside `ok`); `<name>` must be one of its declared
4626/// `ComponentDescribe.outcomes`. Returns `Value::Null` when the component does
4627/// not emit one — the engine then falls back to the `ok`-derived default
4628/// (`on_success`/`on_error`) in `build_routing_context`.
4629/// Adapt a raw component/node result `Value` into the typed node_io [`NodeOutput`]
4630/// (`greentic_types::node_io`). Native `{data}` / `{errors}` envelopes parse straight
4631/// through; legacy `{ok, error}` results are shimmed (`ok:false` + `error` → `Errors`,
4632/// otherwise → `Data{data: <value>}`) so existing packs keep routing unchanged.
4633fn to_node_output(value: &Value) -> greentic_types::node_io::NodeOutput {
4634    use greentic_types::node_io::{ErrorKind, NodeError, NodeOutput as NioOutput};
4635
4636    if let Value::Object(map) = value {
4637        // Native node_io envelopes carry a sole `errors` or `data` key and no legacy
4638        // `ok` flag — deserialize them directly so `kind`/`retryable`/etc. round-trip.
4639        let native_errors = map.contains_key("errors") && !map.contains_key("ok");
4640        let native_data = map.contains_key("data") && !map.contains_key("ok") && map.len() == 1;
4641        if (native_errors || native_data)
4642            && let Ok(parsed) = serde_json::from_value::<NioOutput>(value.clone())
4643        {
4644            return parsed;
4645        }
4646        // Legacy failure envelope `{ok:false, error:{code,message}}` → Errors.
4647        if let Some((code, message)) = component_error(value) {
4648            return NioOutput::failed(vec![NodeError {
4649                code,
4650                message,
4651                kind: ErrorKind::Internal,
4652                retryable: false,
4653                source: None,
4654                details: Value::Null,
4655            }]);
4656        }
4657    }
4658    // Default: a bare result (or `{ok:true, ...}`) is success data.
4659    NioOutput::ok(value.clone())
4660}
4661
4662/// Build the per-node template view exposed under `{{node.<id>...}}`. Object payloads
4663/// keep their fields at the top level (legacy `{{node.<id>.<field>}}`) and additionally
4664/// gain canonical node_io surfaces `data` (`{{node.<id>.data.<field>}}`) and `errors`
4665/// (`{{node.<id>.errors}}`). Non-object payloads are exposed verbatim, as before.
4666fn node_output_view(payload: &Value) -> Value {
4667    let nio = to_node_output(payload);
4668    let data = nio.data().cloned().unwrap_or(Value::Null);
4669    let errors = serde_json::to_value(nio.errors()).unwrap_or_else(|_| Value::Array(Vec::new()));
4670    match payload {
4671        Value::Object(map) => {
4672            let mut view = map.clone();
4673            view.insert("data".to_string(), data);
4674            view.insert("errors".to_string(), errors);
4675            Value::Object(view)
4676        }
4677        other => other.clone(),
4678    }
4679}
4680
4681/// The result of reading `answer_fields` from a card node's raw input mapping.
4682///
4683/// `Absent` and `Malformed` both fall back to the permissive (unfiltered)
4684/// path in [`attach_pending_card_answers`] — the contract is "absent means
4685/// this pack predates the allow-list", so failing permissively rather than
4686/// closed is deliberate for both. They are kept as separate variants (rather
4687/// than collapsed into one `None`) purely so the caller can log the
4688/// `Malformed` case: an ordinary pre-upgrade pack has no `answer_fields` key
4689/// at all and must stay quiet, but a *present-and-broken* value is a
4690/// designer-side bug reproducing this feature's original leak, and must not
4691/// be silently indistinguishable from the ordinary case in the logs.
4692enum DeclaredAnswerFields {
4693    /// The `answer_fields` key is not present at all. The ordinary case for
4694    /// every pack built before this feature — must not be logged.
4695    Absent,
4696    /// The key is present but is not a valid array of strings (wrong type,
4697    /// or an array containing a non-string entry — e.g. an unresolved
4698    /// template). Distinct from `Absent` so it can be surfaced.
4699    Malformed,
4700    /// The key is present and a valid (possibly empty) array of strings.
4701    Declared(Vec<String>),
4702}
4703
4704/// The card's own declared allow-list for `answers`, read from its raw input
4705/// mapping (`HostNode::payload_expr`) BEFORE template rendering — greentic-designer
4706/// writes the card's declared `Input.*` ids under this key
4707/// (`answer_fields: ["field_a", "field_b", ...]`) at composer-save time.
4708///
4709/// Reading `payload_expr` here is safe from upstream interference: it is
4710/// built once, from the pack's `Node.input.mapping`, in `HostNode`'s
4711/// `From<Node>` impl, and `flow_ir.nodes` is never mutated for the lifetime of
4712/// a `drive_flow` call (only `.get()` — see `engine.rs` near `drive_flow`'s
4713/// dispatch loop). The dispatch loop's own template render
4714/// (`let payload_template = node.payload_expr.clone();`, a few lines above the
4715/// call site) clones it into a separate value before rendering, so the render
4716/// never touches `node.payload_expr` itself. By the time this function runs —
4717/// after that node has already been dispatched — `node.payload_expr` is
4718/// byte-identical to what was loaded from the pack.
4719///
4720/// `Absent` means the key is absent — a pack built before this change, or any
4721/// path that never runs the designer injector. That is deliberately treated as
4722/// "no allow-list", not "empty allow-list": those packs, and the fixtures for
4723/// paths that skip the injector, would otherwise silently lose every submitted
4724/// answer. A present-but-malformed value (not an array, or containing a
4725/// non-string entry) is likewise treated as permissive (see
4726/// [`DeclaredAnswerFields`]), so a malformed pack fails open instead of
4727/// collapsing to zero answers — but unlike `Absent`, it is observable.
4728///
4729/// `Declared(vec![])` — a present but EMPTY array — means the card genuinely
4730/// declares no inputs; the caller must produce `{}`, not the unfiltered set.
4731fn declared_answer_fields(payload_expr: &Value) -> DeclaredAnswerFields {
4732    let Some(raw) = payload_expr.get("answer_fields") else {
4733        return DeclaredAnswerFields::Absent;
4734    };
4735    let Some(arr) = raw.as_array() else {
4736        return DeclaredAnswerFields::Malformed;
4737    };
4738    match arr
4739        .iter()
4740        .map(|entry| entry.as_str().map(str::to_string))
4741        .collect::<Option<Vec<String>>>()
4742    {
4743        Some(list) => DeclaredAnswerFields::Declared(list),
4744        None => DeclaredAnswerFields::Malformed,
4745    }
4746}
4747
4748/// Remove the routing `action` from a run's entry envelope.
4749///
4750/// Mirrors the two shapes [`build_routing_context`] reads it from: the
4751/// greentic-start demo path wraps the activity (`entry.input.metadata`), the
4752/// direct runner path does not (`entry.metadata`).
4753fn consume_routing_action(entry: &mut Value) {
4754    for pointer in ["/input/metadata", "/metadata"] {
4755        if let Some(Value::Object(meta)) = entry.pointer_mut(pointer) {
4756            meta.remove("action");
4757        }
4758    }
4759}
4760
4761/// Returns true when the pending submit belonged to `node_id` and was consumed
4762/// here — the caller clears the routing action once this node has routed on it.
4763///
4764/// Merge the pending submitted fields into `output` when it belongs to the node
4765/// that parked for them, then CONSUME the pending entry.
4766///
4767/// Consuming rather than reading is what stops a loop back through the same node
4768/// (without a resume) re-attaching stale answers.
4769///
4770/// When `node`'s input mapping carries `answer_fields` (see
4771/// [`declared_answer_fields`]), `answers` is intersected down to exactly those
4772/// keys — `submitted_fields` unions the whole submit envelope, which on the
4773/// `greentic-start` path includes transport identity (`tenant`, `session_id`,
4774/// `from`, ...) and pack config (routing keys, secret references, ...) that a
4775/// person never typed. Without a declared allow-list, `answers` stays exactly
4776/// what `submitted_fields` produced (today's behaviour, unchanged).
4777///
4778/// Called immediately before `state.nodes.insert`, and that position is
4779/// load-bearing — see `submitted_answers_survive_the_resume_redispatch_and_reach_a_later_node`.
4780fn attach_pending_card_answers(
4781    state: &mut ExecutionState,
4782    node_id: &str,
4783    node: &HostNode,
4784    output: &mut NodeOutput,
4785) -> bool {
4786    let is_target = state
4787        .pending_card_answers
4788        .as_ref()
4789        .is_some_and(|pending| pending.node_id == node_id);
4790    if !is_target {
4791        return false;
4792    }
4793    let Some(pending) = state.pending_card_answers.take() else {
4794        return false;
4795    };
4796    // No `ok` check on purpose: the answers are real whether or not the
4797    // re-render succeeded, and dropping them would let a transient render error
4798    // silently destroy what someone typed.
4799    let Some(map) = output.payload.as_object_mut() else {
4800        tracing::warn!(
4801            node_id = %node_id,
4802            "node output payload is not an object; submitted answers not attached"
4803        );
4804        return true;
4805    };
4806    if map.contains_key("answers") {
4807        tracing::warn!(
4808            node_id = %node_id,
4809            "node output already carries `answers`; overwriting with the submitted fields"
4810        );
4811    }
4812    let answers = match declared_answer_fields(&node.payload_expr) {
4813        DeclaredAnswerFields::Declared(allow_list) => {
4814            let allowed: std::collections::HashSet<&str> =
4815                allow_list.iter().map(String::as_str).collect();
4816            pending
4817                .answers
4818                .into_iter()
4819                .filter(|(key, _)| allowed.contains(key.as_str()))
4820                .collect()
4821        }
4822        DeclaredAnswerFields::Malformed => {
4823            // Distinct from `Absent` on purpose: an ordinary pre-upgrade pack
4824            // has no `answer_fields` key and must stay quiet, but a
4825            // present-and-broken value reproduces this feature's original
4826            // leak (the full unfiltered envelope, including any secret
4827            // references, ships as `answers`) and must be observable.
4828            tracing::warn!(
4829                node_id = %node_id,
4830                "answer_fields present but malformed; falling back to unfiltered answers"
4831            );
4832            pending.answers
4833        }
4834        DeclaredAnswerFields::Absent => pending.answers,
4835    };
4836    map.insert("answers".to_string(), Value::Object(answers));
4837    true
4838}
4839
4840/// The card node a resume lands on, or `None` when the snapshot is not a card
4841/// awaiting its submit. A `session.wait` snapshot names its SUCCESSOR in
4842/// `next_node`, which has not run, so it must not be treated as a resumed card.
4843fn resumed_card_node(snapshot: &FlowSnapshot) -> Option<String> {
4844    snapshot.awaiting_submit.then(|| snapshot.next_node.clone())
4845}
4846
4847/// Decide what to park for the node awaiting a submit, from the snapshot being
4848/// resumed and the fresh input that carries the submission.
4849///
4850/// Only a snapshot flagged `awaiting_submit` names the waiting node in
4851/// `next_node`; a `session.wait` snapshot names its SUCCESSOR, which has not
4852/// run yet, so attaching answers there would name the wrong node. Returns
4853/// `None` in that case, so nothing gets parked.
4854/// Whether a `dw.agent` node output says the agent parked on a `flow:` tool.
4855fn awaiting_tool_input(payload: &Value) -> bool {
4856    payload.get("terminated_by").and_then(Value::as_str) == Some("awaiting_tool_input")
4857}
4858
4859/// The card a `dw.agent` parked on a `flow:` tool asks the user to answer —
4860/// `Some` only for such a park, and only when it carries one.
4861pub(crate) fn tool_presentation(payload: &Value) -> Option<&Value> {
4862    if !awaiting_tool_input(payload) {
4863        return None;
4864    }
4865    payload
4866        .get("pending_presentation")
4867        .filter(|value| !value.is_null())
4868}
4869
4870/// Envelope metadata key the webchat provider sets to `"true"` on a card submit
4871/// (an activity carrying Action.Submit `data`, even `{}`) and never on typed
4872/// text. Contract with `messaging-provider-webchat` (`SUBMIT_MARKER_KEY`). The
4873/// `greentic_` prefix is one the provider never copies from client data.
4874const SUBMIT_MARKER_KEY: &str = "greentic_submit";
4875
4876/// What a `dw.agent` parked on a `flow:` tool renders as the turn's output.
4877/// The card alone for a plain park. For a SIDE turn (a typed message answered
4878/// while the tool stays parked) the agent's reply followed by the card, as two
4879/// replies, so the user reads the answer and still sees the form to continue.
4880/// The result is always ONE flat list (see the card-as-list note below).
4881pub(crate) fn rendered_park(payload: &Value) -> Value {
4882    let Some(card) = tool_presentation(payload) else {
4883        return payload.clone();
4884    };
4885    let side_reply = payload
4886        .get("side_turn")
4887        .and_then(Value::as_bool)
4888        .unwrap_or(false)
4889        && payload
4890            .get("reply")
4891            .and_then(Value::as_str)
4892            .is_some_and(|reply| !reply.trim().is_empty());
4893    if !side_reply {
4894        return card.clone();
4895    }
4896    let mut reply = payload.clone();
4897    if let Some(map) = reply.as_object_mut() {
4898        map.remove("pending_presentation");
4899        map.remove("side_turn");
4900    }
4901    // One flat list: a card that is itself a list (`emit.response` renders its
4902    // messages as one) contributes its items, so each stays its own reply.
4903    let mut items = vec![reply];
4904    match card {
4905        Value::Array(cards) => items.extend(cards.iter().cloned()),
4906        single => items.push(single.clone()),
4907    }
4908    Value::Array(items)
4909}
4910
4911/// Keys of a `ChannelMessageEnvelope` that the TRANSPORT owns. On the
4912/// `greentic-start` path every inbound message carries them, typed or not, so
4913/// they say nothing about whether a person submitted a card.
4914///
4915/// `text` and `metadata` are excluded by [`submitted_fields`] already.
4916#[cfg(any(feature = "agentic-worker", test))]
4917const ENVELOPE_TRANSPORT_KEYS: &[&str] = &[
4918    "id",
4919    "tenant",
4920    "channel",
4921    "session_id",
4922    "reply_scope",
4923    "from",
4924    "to",
4925    "correlation_id",
4926    "attachments",
4927    "extensions",
4928];
4929
4930/// Channel context a provider may stamp on a message's `metadata` whether or
4931/// not a card was submitted. Context, not input, so it never makes a typed
4932/// message a submit.
4933///
4934/// The webchat provider (`messaging-provider-webchat` `ops/envelope.rs`,
4935/// `ops/ingest.rs`) MAY stamp these on a Direct Line activity: `universal`,
4936/// `env`, `locale`, `extensions`, `user_id`, `user_verified`, and `flow_hint`
4937/// when the `X-Greentic-Flow` header is present. `team` is kept from the
4938/// earlier allow-list. `route` and `tenant` are handled separately
4939/// ([`stamped_identity_matches`]).
4940///
4941/// NONE of these is trustworthy: Action.Submit `data` is copied into
4942/// `metadata` after the stamping, so a client can overwrite any of them (only
4943/// `user_*`/`greentic_*` are protected). Safe here only because a client that
4944/// can add keys can already send plain text or add `action`.
4945///
4946/// The failure direction matters: a card INPUT that shares one of these names
4947/// is invisible to the classifier, so a click carrying only that input reads
4948/// as typed text and the parked tool is cancelled (#811). The explicit submit
4949/// marker (spec PR-2) is the real fix.
4950#[cfg(any(feature = "agentic-worker", test))]
4951const CHANNEL_CONTEXT_METADATA_KEYS: &[&str] = &[
4952    "locale",
4953    "team",
4954    "env",
4955    "autoStart",
4956    "universal",
4957    "user_id",
4958    "user_verified",
4959    "flow_hint",
4960    "extensions",
4961];
4962
4963/// Provider passthroughs are flattened into `metadata` as `channel.<key>`.
4964#[cfg(any(feature = "agentic-worker", test))]
4965const CHANNEL_CONTEXT_METADATA_PREFIX: &str = "channel.";
4966
4967#[cfg(any(feature = "agentic-worker", test))]
4968fn is_channel_context_key(key: &str) -> bool {
4969    CHANNEL_CONTEXT_METADATA_KEYS.contains(&key) || key.starts_with(CHANNEL_CONTEXT_METADATA_PREFIX)
4970}
4971
4972/// `route` (= conversation id = `session_id`) and `tenant` (= `tenant.tenant`)
4973/// are context only when they carry the value the provider derives from the
4974/// envelope itself. A card input that merely shares the name overwrites them
4975/// with its own value and is therefore input, not context.
4976#[cfg(any(feature = "agentic-worker", test))]
4977fn stamped_identity_matches(key: &str, value: &Value, envelope: &Value) -> bool {
4978    let Some(value) = value.as_str() else {
4979        return false;
4980    };
4981    match key {
4982        "route" => envelope.get("session_id").and_then(Value::as_str) == Some(value),
4983        "tenant" => envelope.pointer("/tenant/tenant").and_then(Value::as_str) == Some(value),
4984        _ => false,
4985    }
4986}
4987
4988/// Whether `map` is a `ChannelMessageEnvelope`: the three keys no card input
4989/// has any reason to share are all there. Decided by SHAPE, not by where the
4990/// map sits, because both arrive — wrapped under `entry.input` and as the flat
4991/// entry itself — and a Run Demo entry's root keys are the card's own input
4992/// ids (an input named `channel` is still an input there, since it never
4993/// comes with a `session_id` and a `tenant`).
4994#[cfg(any(feature = "agentic-worker", test))]
4995fn is_channel_envelope(map: &JsonMap<String, Value>) -> bool {
4996    map.contains_key("session_id") && map.contains_key("channel") && map.contains_key("tenant")
4997}
4998
4999/// Whether an inbound activity is a card submit rather than a typed message:
5000/// it names a route (`metadata.action`) or carries INPUT values. Anything
5001/// with neither is an ordinary message, even with empty text.
5002///
5003/// Input values exclude what the envelope carries for transport and channel
5004/// context. Counting them (via [`submitted_fields`] alone) made every message
5005/// on the `greentic-start` path a "submit", because the whole
5006/// `ChannelMessageEnvelope` is the entry (or sits under `entry.input`) and
5007/// always has `id`, `tenant`, `channel` and `session_id` — so a person typing
5008/// while a `flow:` tool was parked had the text delivered AS the tool's
5009/// answer, and the tool's card was shown again, for any text at all.
5010#[cfg(any(feature = "agentic-worker", test))]
5011fn is_card_submit(entry: &Value) -> bool {
5012    let metadata = resolve_entry_metadata(entry).and_then(Value::as_object);
5013    let has_action = metadata
5014        .and_then(|meta| meta.get("action"))
5015        .and_then(Value::as_str)
5016        .is_some_and(|action| !action.trim().is_empty());
5017    if has_action {
5018        return true;
5019    }
5020    // An explicit marker from the provider settles it, including a submit with
5021    // no fields of its own that no key-shape heuristic can tell from typed text.
5022    let marked = metadata
5023        .and_then(|meta| meta.get(SUBMIT_MARKER_KEY))
5024        .is_some_and(|value| value.as_str() == Some("true") || value.as_bool() == Some(true));
5025    if marked {
5026        return true;
5027    }
5028    let envelope = entry
5029        .get("input")
5030        .filter(|v| v.is_object())
5031        .unwrap_or(entry);
5032    let root_input = envelope.as_object().is_some_and(|map| {
5033        let channel_envelope = is_channel_envelope(map);
5034        map.keys().any(|key| {
5035            key != "metadata"
5036                && key != "text"
5037                && !(channel_envelope && ENVELOPE_TRANSPORT_KEYS.contains(&key.as_str()))
5038        })
5039    });
5040    let metadata_input = metadata.is_some_and(|meta| {
5041        meta.iter().any(|(key, value)| {
5042            key != "action"
5043                && key != SUBMIT_MARKER_KEY
5044                && !is_channel_context_key(key)
5045                && !stamped_identity_matches(key, value, envelope)
5046        })
5047    });
5048    root_input || metadata_input
5049}
5050
5051fn pending_from_snapshot(snapshot: &FlowSnapshot, input: &Value) -> Option<PendingCardAnswers> {
5052    if !snapshot.awaiting_submit {
5053        return None;
5054    }
5055    Some(PendingCardAnswers {
5056        node_id: snapshot.next_node.clone(),
5057        answers: submitted_fields(input),
5058    })
5059}
5060
5061fn outcome_meta(output: &Value) -> Value {
5062    match output.get("outcome").and_then(Value::as_str) {
5063        Some(outcome) => json!({ "outcome": outcome }),
5064        None => Value::Null,
5065    }
5066}
5067
5068fn component_error(value: &Value) -> Option<(String, String)> {
5069    let obj = value.as_object()?;
5070    let ok = obj.get("ok").and_then(Value::as_bool)?;
5071    if ok {
5072        return None;
5073    }
5074    let err = obj.get("error")?.as_object()?;
5075    let code = err
5076        .get("code")
5077        .and_then(Value::as_str)
5078        .unwrap_or("component_error");
5079    let message = err
5080        .get("message")
5081        .and_then(Value::as_str)
5082        .unwrap_or("component reported error");
5083    Some((code.to_string(), message.to_string()))
5084}
5085
5086#[cfg(feature = "agentic-worker")]
5087/// `(code, message)` of an `{ok:false, error}` envelope for operator logs.
5088/// The error may be an object `{code, message}` or a bare string; anything
5089/// missing degrades to `unknown` / the empty string rather than failing.
5090fn agent_error_log_fields(entry: &Value) -> (String, String) {
5091    match entry.get("error") {
5092        Some(Value::Object(obj)) => (
5093            obj.get("code")
5094                .and_then(Value::as_str)
5095                .unwrap_or("unknown")
5096                .to_string(),
5097            obj.get("message")
5098                .and_then(Value::as_str)
5099                .unwrap_or_default()
5100                .to_string(),
5101        ),
5102        Some(Value::String(message)) => ("unknown".to_string(), message.clone()),
5103        _ => ("unknown".to_string(), String::new()),
5104    }
5105}
5106
5107/// Reply and node payload for an `{ok:false}` agent response envelope.
5108///
5109/// The agentic bridge reports a turn that ended without a final reply
5110/// (timeout, max iterations) as `ok:false` with `error.message` set to a
5111/// machine string while keeping the partial reply in `output.reply`. A
5112/// non-empty `output.reply` is what the user should see; the error (and the
5113/// trail, when present) stay on the payload for operators and routing. Without
5114/// one, the reply is the localized user-safe failure line
5115/// ([`user_facing_flow_failure_text`]), never the machine string; the error
5116/// (code and message) stays on the payload for operators either way.
5117#[cfg(feature = "agentic-worker")]
5118fn agent_error_envelope_reply(entry: &Value) -> (String, Value) {
5119    let error = entry.get("error").filter(|e| !e.is_null());
5120    let output = entry.get("output");
5121    let partial = output
5122        .and_then(|o| o.get("reply"))
5123        .and_then(Value::as_str)
5124        .filter(|reply| !reply.trim().is_empty());
5125    let message = partial
5126        .map(str::to_string)
5127        .unwrap_or_else(|| user_facing_flow_failure_text(entry));
5128    let mut payload = serde_json::Map::new();
5129    payload.insert("reply".to_string(), Value::String(message.clone()));
5130    if let Some(error) = error {
5131        payload.insert("error".to_string(), error.clone());
5132    }
5133    if partial.is_some()
5134        && let Some(trail) = output.and_then(|o| o.get("trail"))
5135    {
5136        payload.insert("trail".to_string(), trail.clone());
5137    }
5138    (message, Value::Object(payload))
5139}
5140
5141/// MCP tool-error wire shape from greentic-mcp-generator's `tool_error_with_status`:
5142/// `{ "error": { "code", "message", "status" } }`. The component returned ok=true at
5143/// the WIT level (the HTTP failure was caught and serialized), so the regular
5144/// component_error path doesn't catch it.
5145fn mcp_tool_error(value: &Value) -> Option<(String, String)> {
5146    let obj = value.as_object()?;
5147    // Must be the error shape: no `result` field, just `error`.
5148    if obj.contains_key("result") {
5149        return None;
5150    }
5151    let err = obj.get("error")?.as_object()?;
5152    let code = err
5153        .get("code")
5154        .and_then(Value::as_str)
5155        .unwrap_or("tool_error");
5156    let raw_message = err
5157        .get("message")
5158        .and_then(Value::as_str)
5159        .unwrap_or("tool returned an error");
5160    let status = err.get("status").and_then(Value::as_u64);
5161    let message = match status {
5162        Some(s) => format!("{raw_message} (status {s})"),
5163        None => raw_message.to_string(),
5164    };
5165    Some((code.to_string(), message))
5166}
5167
5168/// Reshape an MCP-shaped tool-error payload (`{ "error": { "code", "message",
5169/// "status" } }`, no `ok`/`result` key) into the `{ok:false, error:{code,message}}`
5170/// shape `component_error` already recognises. `code`/`message` are the pair
5171/// `mcp_tool_error` already computed (so `message` is the status-qualified string,
5172/// identical to what the `bail!` branch would have said) and simply replace the
5173/// raw `error.code`/`error.message` fields; any other field on `error` (e.g.
5174/// `status`) and any other top-level field on the payload survive untouched.
5175///
5176/// This is the single normalization point — for the `a2a` node as well, via
5177/// [`a2a_node_output`]: once a payload is in this shape,
5178/// `to_node_output` (the `{{node.<id>.errors}}` template envelope) and
5179/// `NodeOutput::errored`'s `meta.error` (read by
5180/// `lift_first_node_error_from_nodes`) both read it exactly as they already read
5181/// a genuine `component_error` failure — no second "what does a failed node's
5182/// error look like" branch needed anywhere downstream.
5183fn normalize_mcp_tool_error(value: &Value, code: &str, message: &str) -> Value {
5184    let mut obj = value.as_object().cloned().unwrap_or_default();
5185    obj.insert("ok".to_string(), Value::Bool(false));
5186    let mut error = obj
5187        .get("error")
5188        .and_then(Value::as_object)
5189        .cloned()
5190        .unwrap_or_default();
5191    error.insert("code".to_string(), Value::String(code.to_string()));
5192    error.insert("message".to_string(), Value::String(message.to_string()));
5193    obj.insert("error".to_string(), Value::Object(error));
5194    Value::Object(obj)
5195}
5196
5197/// Build an MCP node's output, marking it failed when the tool did not run —
5198/// but only for a node that has somewhere to route the failure.
5199///
5200/// `mcp_node::invoke_with_secrets` is infallible by contract: a runner
5201/// without MCP credentials, a tool missing from the tenant catalog, a dead
5202/// endpoint, and bad arguments all arrive as `{"error": "..."}` inside
5203/// `result`, with the WIT-level call itself having returned normally. Always
5204/// reporting `ok: true` left the flow with nothing to route on: a Digital
5205/// Worker run showed 33/33 green nodes and rendered its quote card with
5206/// every field blank.
5207///
5208/// **`has_error_route` gates the whole thing.** `Routing::Next` and a
5209/// `Routing::Custom` array with only success-family routes have nowhere to
5210/// send a failure: `evaluate_custom_routing`'s fall-through for a routing
5211/// array that has conditions but matched none of them is
5212/// `CustomRoutingDecision::Wait`, which PARKS the run — a worse outcome for
5213/// an operator who never wired up error handling than the pre-existing
5214/// silent wrong answer (a parked run needs manual intervention to ever
5215/// resolve; a silent wrong answer at least lets the flow finish). So a node
5216/// with no error route keeps reporting `ok: true`, byte-for-byte the pre-R3
5217/// behaviour — this mirrors the `has_error_route` gate
5218/// `execute_component_call` already uses for the same reason (there:
5219/// `bail!` vs `NodeOutput::errored`; here: `ok: true` vs `NodeOutput::errored`),
5220/// keeping the change purely additive.
5221///
5222/// When the node DOES have an error route, the failure is normalized into
5223/// the exact `{ok:false, error:{code,message}}` shape `component_error`
5224/// already recognises, via `normalize_mcp_tool_error` — reusing Phase 2's
5225/// single definition of what a failed node's `{errors}` output looks like,
5226/// rather than inventing a second one for this code path. `bound` (the tool
5227/// result, optionally wrapped under the node's `output:` binding key) is
5228/// passed as the base object, so any field already on it — most importantly
5229/// the `output:` binding key — survives alongside the new top-level
5230/// `ok`/`error` fields: `node.<id>.<binding-key>` keeps resolving exactly as
5231/// before, while `node.<id>.errors[0].message` now resolves too.
5232// Gated like its only caller, `execute_mcp` (agentic-worker).
5233#[cfg(feature = "agentic-worker")]
5234fn mcp_node_output(bound: Value, result: &Value, has_error_route: bool) -> NodeOutput {
5235    if !has_error_route {
5236        return NodeOutput::new(bound);
5237    }
5238    let Some(error) = result.get("error") else {
5239        return NodeOutput::new(bound);
5240    };
5241    // `error` is not always a plain string: greentic-mcp-generator's
5242    // `tool_error_with_status` shape (`{"error":{"code","message","status"}}`,
5243    // the same shape `mcp_tool_error` already parses for the component-error
5244    // path around `execute_component_call`) puts an object there. Try that
5245    // detector FIRST so this shape gets the real `tool_error` code and the
5246    // status-qualified message it already computes, instead of falling
5247    // through to the plain-string handling below — which would stuff the
5248    // whole serialized error object into `message` and hardcode a generic
5249    // `mcp_call_failed` code, discarding both.
5250    if let Some((code, message)) = mcp_tool_error(result) {
5251        return NodeOutput::errored(normalize_mcp_tool_error(&bound, &code, &message));
5252    }
5253    let message = error
5254        .as_str()
5255        .map(str::to_string)
5256        .unwrap_or_else(|| error.to_string());
5257    NodeOutput::errored(normalize_mcp_tool_error(
5258        &bound,
5259        "mcp_call_failed",
5260        &message,
5261    ))
5262}
5263
5264/// Bind a remote-tool node's result under its optional `output` state key.
5265///
5266/// When `output` is absent the raw result becomes the node payload (still
5267/// addressable through the standard `node.<id>.payload` mechanism). Shared by
5268/// the `mcp` and `a2a` nodes so the two cannot answer `output:` differently.
5269#[cfg(feature = "agentic-worker")]
5270fn bind_node_result(payload: &Value, result: Value) -> Value {
5271    match payload.get("output").and_then(Value::as_str) {
5272        Some(key) if !key.is_empty() => json!({ key: result }),
5273        _ => result,
5274    }
5275}
5276
5277/// Whether a rendered node field carries nothing to act on: absent, `null`, or
5278/// a string that is empty once trimmed (which is what an unresolved `{{ }}`
5279/// template renders to — `render_template_string` yields the empty string
5280/// rather than failing).
5281#[cfg(feature = "agentic-worker")]
5282fn is_blank(value: &Value) -> bool {
5283    match value {
5284        Value::Null => true,
5285        Value::String(text) => text.trim().is_empty(),
5286        _ => false,
5287    }
5288}
5289
5290/// Build an A2A node's output, marking it failed when there is no answer to
5291/// carry — but, exactly as [`mcp_node_output`] does, only for a node that has
5292/// somewhere to route the failure. See that function for why a node without an
5293/// error route keeps reporting `ok: true`: a routing array that matches
5294/// nothing PARKS the run, which is worse for an operator than the value they
5295/// can still read off `node.<id>.payload.status`.
5296///
5297/// Only the two `error`-carrying statuses mark the node failed. `completed`
5298/// is an answer, and `input_required` / `working` are NOT failures — the
5299/// remote agent is working correctly and the flow is expected to route on
5300/// them. Treating either as an error would send a perfectly healthy exchange
5301/// down an error branch, which is precisely the conflation
5302/// `a2a_source::outcome` exists to prevent.
5303///
5304/// The two failing statuses keep different codes because they send an
5305/// operator to different systems: `a2a_agent_failed` is the remote agent
5306/// deciding something (`failed`/`canceled`/`rejected`/`auth_required`), while
5307/// `a2a_call_failed` is us never reaching it at all. The envelope itself is
5308/// built by [`normalize_mcp_tool_error`], the single definition of what a
5309/// failed node's `{errors}` output looks like, so `node.<id>.errors[0].message`
5310/// reads the same here as for any other node — and every other field, the
5311/// `output:` binding key and `status` included, survives beside it.
5312#[cfg(feature = "agentic-worker")]
5313fn a2a_node_output(bound: Value, result: &Value, has_error_route: bool) -> NodeOutput {
5314    if !has_error_route {
5315        return NodeOutput::new(bound);
5316    }
5317    let Some(error) = result.get("error").and_then(Value::as_str) else {
5318        return NodeOutput::new(bound);
5319    };
5320    let code = match result.get("status").and_then(Value::as_str) {
5321        Some("failed") => "a2a_agent_failed",
5322        _ => "a2a_call_failed",
5323    };
5324    NodeOutput::errored(normalize_mcp_tool_error(&bound, code, error))
5325}
5326
5327/// Build a `media.create` node's output. A C5 failure is a value; only a node
5328/// with an `on_error` edge is marked failed (the same gate `a2a` uses, for the
5329/// same reason: a failed node without a route would park the run).
5330#[cfg(feature = "agentic-worker")]
5331fn media_node_output(bound: Value, result: &Value, has_error_route: bool) -> NodeOutput {
5332    if !crate::runner::media_node::is_failure(result) {
5333        let mut output = NodeOutput::new(bound);
5334        output.created = crate::runner::media_node::created_files(result);
5335        return output;
5336    }
5337    if !has_error_route {
5338        return NodeOutput::new(bound);
5339    }
5340    NodeOutput::errored(normalize_mcp_tool_error(
5341        &bound,
5342        &crate::runner::media_node::failure_code(result),
5343        &crate::runner::media_node::failure_message(result),
5344    ))
5345}
5346
5347/// Turn a `sorla.call` HTTP failure (a malformed route document, an unknown
5348/// action, or the SoR request itself failing) into a `DispatchOutcome`: a
5349/// structured `{"error": msg}` node output when the node has an error route
5350/// to send it down, else a hard `Err` that aborts the flow. Mirrors the
5351/// `has_error_route` gate `execute_mcp` (via [`mcp_node_output`]) already
5352/// uses for a component failure, for the same reason: a node with no error
5353/// route has nowhere to send a failure, so it keeps the pre-existing hard
5354/// fail rather than silently reporting `ok: true`.
5355// Gated like its only caller, `execute_sorla_call` (agentic-worker).
5356#[cfg(feature = "agentic-worker")]
5357fn sorla_failure(msg: impl Into<String>, has_error_route: bool) -> Result<DispatchOutcome> {
5358    let msg = msg.into();
5359    if has_error_route {
5360        Ok(DispatchOutcome::complete(NodeOutput::errored(json!({
5361            "error": msg
5362        }))))
5363    } else {
5364        Err(anyhow!(msg))
5365    }
5366}
5367
5368fn extract_wait_reason(payload: &Value) -> Option<String> {
5369    match payload {
5370        Value::String(s) => Some(s.clone()),
5371        Value::Object(map) => map
5372            .get("reason")
5373            .and_then(Value::as_str)
5374            .map(|value| value.to_string()),
5375        _ => None,
5376    }
5377}
5378
5379fn component_dispatch_outcome(output: NodeOutput) -> Result<DispatchOutcome> {
5380    if let Some(control) = parse_component_control(&output.payload)? {
5381        return Ok(match control {
5382            NodeControl::Jump(jump) => {
5383                let adjusted = NodeOutput::with_meta(jump.payload.clone(), jump.hints.clone());
5384                DispatchOutcome::with_control(adjusted, NodeControl::Jump(jump))
5385            }
5386            NodeControl::Respond {
5387                text,
5388                card_cbor,
5389                needs_user,
5390            } => DispatchOutcome::with_control(
5391                output,
5392                NodeControl::Respond {
5393                    text,
5394                    card_cbor,
5395                    needs_user,
5396                },
5397            ),
5398            other => DispatchOutcome::with_control(output, other),
5399        });
5400    }
5401    Ok(DispatchOutcome::complete(output))
5402}
5403
5404/// Parse a component's `greentic_control` block. A malformed block is a
5405/// deterministic output of the component, so the failure is terminal: re-running
5406/// the turn would produce the same block.
5407fn parse_component_control(payload: &Value) -> Result<Option<NodeControl>> {
5408    parse_component_control_inner(payload).map_err(|err| terminal_flow_error(format!("{err:#}")))
5409}
5410
5411fn parse_component_control_inner(payload: &Value) -> Result<Option<NodeControl>> {
5412    let Value::Object(map) = payload else {
5413        return Ok(None);
5414    };
5415    let Some(control_value) = map.get("greentic_control") else {
5416        return Ok(None);
5417    };
5418    let control = control_value
5419        .as_object()
5420        .ok_or_else(|| anyhow!("jump_failed: greentic_control must be an object"))?;
5421    let action = control
5422        .get("action")
5423        .and_then(Value::as_str)
5424        .ok_or_else(|| anyhow!("jump_failed: greentic_control.action is required"))?;
5425    let version = control
5426        .get("v")
5427        .and_then(Value::as_u64)
5428        .ok_or_else(|| anyhow!("jump_failed: greentic_control.v is required"))?;
5429    if version != 1 {
5430        bail!("jump_failed: unsupported greentic_control.v={version}");
5431    }
5432
5433    match action {
5434        "jump" => {
5435            let flow = control
5436                .get("flow")
5437                .and_then(Value::as_str)
5438                .map(str::trim)
5439                .filter(|value| !value.is_empty())
5440                .ok_or_else(|| anyhow!("jump_failed: jump flow is required"))?
5441                .to_string();
5442            let node = control
5443                .get("node")
5444                .and_then(Value::as_str)
5445                .map(str::trim)
5446                .filter(|value| !value.is_empty())
5447                .map(str::to_string);
5448            let payload = control.get("payload").cloned().unwrap_or(Value::Null);
5449            let hints = control.get("hints").cloned().unwrap_or(Value::Null);
5450            let max_redirects = control
5451                .get("max_redirects")
5452                .and_then(Value::as_u64)
5453                .and_then(|value| u32::try_from(value).ok());
5454            let reason = control
5455                .get("reason")
5456                .and_then(Value::as_str)
5457                .map(str::to_string);
5458            Ok(Some(NodeControl::Jump(JumpControl {
5459                flow,
5460                node,
5461                payload,
5462                hints,
5463                max_redirects,
5464                reason,
5465            })))
5466        }
5467        "respond" => {
5468            let text = control
5469                .get("text")
5470                .and_then(Value::as_str)
5471                .map(str::to_string);
5472            let card_cbor = control
5473                .get("card_cbor")
5474                .and_then(Value::as_array)
5475                .map(|bytes| {
5476                    bytes
5477                        .iter()
5478                        .filter_map(Value::as_u64)
5479                        .filter_map(|value| u8::try_from(value).ok())
5480                        .collect::<Vec<_>>()
5481                });
5482            let needs_user = control.get("needs_user").and_then(Value::as_bool);
5483            Ok(Some(NodeControl::Respond {
5484                text,
5485                card_cbor,
5486                needs_user,
5487            }))
5488        }
5489        _ => Ok(None),
5490    }
5491}
5492
5493/// Make `in.input.*` resolve even when the flow entry IS the message (the
5494/// env/revision path passes `envelope.payload` — the message — directly), not
5495/// the legacy `{ "input": <message> }` wrapper. Packs are compiled against the
5496/// legacy shape and read `in.input.metadata.*` (e.g. a card button's dispatch
5497/// `flow_{{in.input.metadata.operation}}`); on the direct path `in.input` was
5498/// null, so metadata-based routing fell through to the entry/welcome flow.
5499///
5500/// When the entry is an object without an `input` key, alias `input` to the
5501/// entry itself so both `in.input.X` and `in.X` resolve. Entries that already
5502/// carry an explicit `input` (the legacy wrapper) are left untouched.
5503fn alias_input_to_entry(mut entry: Value) -> Value {
5504    if let Value::Object(map) = &mut entry
5505        && !map.contains_key("input")
5506    {
5507        let base = Value::Object(map.clone());
5508        map.insert("input".into(), base);
5509    }
5510    entry
5511}
5512
5513/// Merge the submitted form fields into the entry object's own ROOT, so a node
5514/// parameter can read `{{entry.<field>}}` on either delivery path.
5515///
5516/// One submit is normalised in three independent places, and until this merge
5517/// existed `template_context` was the only one of them doing none of it:
5518///
5519/// * [`attach_pending_card_answers`] calls [`submitted_fields`] and exposes the
5520///   flat view as `node.<card>.answers.<field>`;
5521/// * [`build_routing_context`] does **not** call it — `response.*` is built
5522///   straight from [`resolve_entry_metadata`] (the metadata object, plus the
5523///   envelope `text`), which is exactly why `response.action` survives there;
5524/// * node parameters received the envelope verbatim. So `{{entry.<field>}}`
5525///   rendered the empty string on the wrapped `greentic-start` path while the
5526///   same card resolved under Run Demo, whose inputs already sit at the entry
5527///   root — one card, correct in the editor preview and blank in production.
5528///
5529/// Additive only, and **a key already present at the entry root wins**: `input`,
5530/// `tenant`, `team`, `correlation_id` and every other envelope key keep their
5531/// exact meaning, so no digest-pinned pack reading `entry.input.metadata.*` or
5532/// `in.input.metadata.*` can observe a change.
5533///
5534/// The keys [`submitted_fields`] drops stay dropped, and for node config the
5535/// reason is its own rather than inherited from the answers map: **each one is
5536/// still reachable by its raw path, so dropping it costs nothing.** `metadata`
5537/// and `text` are the envelope's bookkeeping and its message body, still at
5538/// `entry.metadata` / `entry.input.metadata` and `entry.text` /
5539/// `entry.input.text`. `action` is dropped only from INSIDE the metadata, where
5540/// it is the route discriminator — `entry.input.metadata.action` still resolves
5541/// and `response.action` is untouched — while a key named `action` at the
5542/// envelope ROOT is a real keystroke on the demo path and merges like any other
5543/// field.
5544fn merge_submitted_fields_into_entry(mut entry: Value, fields: JsonMap<String, Value>) -> Value {
5545    if let Value::Object(map) = &mut entry {
5546        for (key, value) in fields {
5547            map.entry(key).or_insert(value);
5548        }
5549    }
5550    entry
5551}
5552
5553/// The wall-clock namespace flow templates read as `{{now.*}}`.
5554///
5555/// Until this existed a flow had no way to name the current time at all. The
5556/// template context is exactly `entry`/`in`/`prev`/`node`/`state`/`vars`, and
5557/// the handlebars registry is built with **no helpers registered**, so
5558/// `{{now}}` rendered as the empty string — silently, because strict mode is
5559/// off. Any step needing a timestamp it had not been handed as input was
5560/// therefore unauthorable: HubSpot's notes and tasks both require
5561/// `hs_timestamp` and the component supplies no default, so the step failed
5562/// with a message naming a field the author had no way to fill.
5563///
5564/// A helper would not have worked. `render_template_string` intercepts an
5565/// exact `{{…}}` expression and resolves it as a PATH before handlebars is
5566/// consulted, so a bare `{{now}}` would resolve against the context, miss, and
5567/// return the empty string without the helper ever running. The value has to
5568/// be in the context.
5569///
5570/// Three fields rather than one string, because callers want different shapes
5571/// and this grammar cannot derive one from another — no helpers, no arithmetic,
5572/// no formatting:
5573///
5574/// - `iso` — RFC3339 with milliseconds, UTC (`…Z`). What HubSpot and most HTTP
5575///   APIs accept.
5576/// - `epoch_ms` — a JSON **number**, so a routing condition or a component
5577///   expecting epoch millis gets one rather than a quoted string.
5578/// - `date` — `YYYY-MM-DD`, for a human-facing line in a card or a note body.
5579///
5580/// Taken as a parameter rather than read inside so a test can pin an instant.
5581fn now_namespace(at: DateTime<Utc>) -> Value {
5582    json!({
5583        "iso": at.to_rfc3339_opts(SecondsFormat::Millis, true),
5584        "epoch_ms": at.timestamp_millis(),
5585        "date": at.format("%Y-%m-%d").to_string(),
5586    })
5587}
5588
5589/// Build the template context a node's config and params are rendered against.
5590///
5591/// `now` is sampled once per call, so every field of ONE node's config sees the
5592/// same instant and two fields cannot disagree by a millisecond. Across nodes
5593/// it advances, which is what "now" means.
5594///
5595/// Deliberately not mirrored into [`build_routing_context`]. The designer's
5596/// condition grammar has a fixed set of reserved heads
5597/// (`entry`/`in`/`node`/`response`/`event`); `now` is not among them, so a
5598/// condition naming it is rewritten to `node.<source>.now.…` before it ever
5599/// reaches the runner. Exposing it on this side alone would make `now.x` in a
5600/// condition resolve to nothing while looking supported. Routing needs the
5601/// matching designer change first.
5602fn template_context(state: &ExecutionState, prev: Value) -> Value {
5603    let entry = if state.entry.is_null() {
5604        Value::Object(JsonMap::new())
5605    } else {
5606        // `submitted_fields` is defined over the RAW envelope — the same value
5607        // the other two normalisations read — so compute it before aliasing,
5608        // then alias so `in.input.*` keeps resolving on the bare-message path.
5609        let fields = submitted_fields(&state.entry);
5610        merge_submitted_fields_into_entry(alias_input_to_entry(state.entry.clone()), fields)
5611    };
5612    let mut ctx = JsonMap::new();
5613    ctx.insert("entry".into(), entry.clone());
5614    ctx.insert("in".into(), entry); // alias for entry - used in flow templates
5615    ctx.insert("prev".into(), prev);
5616    ctx.insert("node".into(), Value::Object(state.outputs_map()));
5617    ctx.insert("state".into(), state.context());
5618    ctx.insert("vars".into(), Value::Object(state.vars.clone()));
5619    ctx.insert("now".into(), now_namespace(Utc::now()));
5620    Value::Object(ctx)
5621}
5622
5623/// Seed declared flow variables into `target` (entry-or-insert; never
5624/// overwrites an already-present key), then return the `required` names that
5625/// remain absent from `target`. A required var is satisfied by either a
5626/// declared default (seeded here) or a value already placed in `target`
5627/// (e.g. an operator-provided demo value).
5628fn seed_vars_and_collect_missing_required(
5629    vars_init: &JsonMap<String, Value>,
5630    required: &[String],
5631    target: &mut JsonMap<String, Value>,
5632) -> Vec<String> {
5633    for (name, default) in vars_init.iter() {
5634        target
5635            .entry(name.clone())
5636            .or_insert_with(|| default.clone());
5637    }
5638    required
5639        .iter()
5640        .filter(|name| !target.contains_key(name.as_str()))
5641        .cloned()
5642        .collect()
5643}
5644
5645impl From<Flow> for HostFlow {
5646    fn from(value: Flow) -> Self {
5647        let mut nodes = IndexMap::new();
5648        for (id, node) in value.nodes {
5649            nodes.insert(id.clone(), HostNode::from(node));
5650        }
5651        let start = value
5652            .entrypoints
5653            .get("default")
5654            .and_then(Value::as_str)
5655            .and_then(|id| NodeId::from_str(id).ok())
5656            .or_else(|| nodes.keys().next().cloned());
5657        let vars_init = value
5658            .metadata
5659            .extra
5660            .get("vars_init")
5661            .and_then(|v| v.as_object())
5662            .map(|decls| {
5663                decls
5664                    .iter()
5665                    .filter_map(|(name, decl)| {
5666                        decl.get("default").map(|d| (name.clone(), d.clone()))
5667                    })
5668                    .collect::<JsonMap<String, Value>>()
5669            })
5670            .unwrap_or_default();
5671        let required_vars = value
5672            .metadata
5673            .extra
5674            .get("vars_init")
5675            .and_then(|v| v.as_object())
5676            .map(|decls| {
5677                decls
5678                    .iter()
5679                    .filter(|(_, decl)| decl.get("required") == Some(&Value::Bool(true)))
5680                    .map(|(name, _)| name.clone())
5681                    .collect::<Vec<String>>()
5682            })
5683            .unwrap_or_default();
5684        // Extract flow-level slot_schema from metadata.extra (Phase D).
5685        // The producer side (greentic-flow compile_flow) stores it under
5686        // "greentic.slot_schema" when the FlowDoc has a `slot_schema` field.
5687        let slot_schema = value
5688            .metadata
5689            .extra
5690            .get(SLOT_SCHEMA_METADATA_KEY)
5691            .filter(|v| !v.is_null())
5692            .cloned();
5693        Self {
5694            id: value.id.as_str().to_string(),
5695            start,
5696            nodes,
5697            vars_init,
5698            required_vars,
5699            slot_schema,
5700        }
5701    }
5702}
5703
5704impl From<Node> for HostNode {
5705    fn from(node: Node) -> Self {
5706        let full_ref = node.component.id.as_str().to_string();
5707        let operation_in_mapping = extract_operation_from_mapping(&node.input.mapping);
5708        // A dotted component id is only a packed "<component>.<operation>" string
5709        // when the operation isn't carried structurally elsewhere. greentic-pack
5710        // resolves a component node to a bare component symbol (e.g.
5711        // `ai.greentic.component-templates`) and keeps the operation in the input
5712        // mapping, so splitting on the last dot here would corrupt the reference
5713        // (→ `ai.greentic`, "not found in pack"). Prefer the structured operation —
5714        // from `component.operation` or the input mapping — and only fall back to
5715        // the legacy single-ID split when neither is present.
5716        let is_builtin = full_ref.starts_with("component.exec")
5717            || full_ref.starts_with("flow.")
5718            || full_ref.starts_with("emit.")
5719            || full_ref.starts_with("session.")
5720            || full_ref.starts_with("provider.")
5721            || full_ref.starts_with("dw.")
5722            || full_ref.starts_with("sorla.")
5723            || full_ref.starts_with("operala.")
5724            || full_ref.starts_with("agentic.")
5725            // Same dispatch family as sorla./operala./agentic. above, and listed in
5726            // NATIVE_OP_KEYS like them. Without it an `approval.call` node — which
5727            // packc emits with `operation: None` because the id is already complete
5728            // — gets split into component "approval" + operation "call", and
5729            // "approval" is by construction absent from the pack's component map.
5730            // The gate then fails with `component 'approval' not found in pack` on a
5731            // pack that is perfectly well-formed, so rebuilding never helps.
5732            || full_ref.starts_with("approval.")
5733            || full_ref.starts_with("var.")
5734            || full_ref.starts_with("media.")
5735            // `mcp:<server>/<tool>` is a self-contained ref; never dot-split it
5736            // into a `component.operation` pair.
5737            || full_ref.starts_with("mcp:")
5738            // Same for `a2a:<agent_id>`: an admin agent id may carry a dot
5739            // (`recipe_v2.1`), and splitting one would ask for a component
5740            // named `a2a:recipe_v2` that no pack can contain.
5741            || full_ref.starts_with("a2a:");
5742        // packc emits `operation: None` to mean "the id is already complete" and
5743        // carries the operation in input.mapping instead. Splitting such an id would
5744        // produce a prefix that is never a key in the pack's component map (the map is
5745        // keyed verbatim by `node.component.id`), so only split when the mapping does
5746        // not tell us the operation.
5747        let (component_ref, raw_operation) =
5748            if node.component.operation.is_some() || is_builtin || operation_in_mapping.is_some() {
5749                (full_ref, node.component.operation.clone())
5750            } else if let Some(dot) = full_ref.rfind('.') {
5751                let comp = full_ref[..dot].to_string();
5752                let op = full_ref[dot + 1..].to_string();
5753                (comp, Some(op))
5754            } else {
5755                (full_ref, None)
5756            };
5757        let operation_is_component_exec = raw_operation.as_deref() == Some("component.exec");
5758        let operation_is_emit = raw_operation
5759            .as_deref()
5760            .map(|op| op.starts_with("emit."))
5761            .unwrap_or(false);
5762        let is_component_exec = component_ref == "component.exec" || operation_is_component_exec;
5763
5764        let kind = if is_component_exec {
5765            let target = if component_ref == "component.exec" {
5766                if let Some(op) = raw_operation
5767                    .as_deref()
5768                    .filter(|op| op.starts_with("emit."))
5769                {
5770                    op.to_string()
5771                } else {
5772                    extract_target_component(&node.input.mapping)
5773                        .unwrap_or_else(|| "component.exec".to_string())
5774                }
5775            } else {
5776                extract_target_component(&node.input.mapping)
5777                    .unwrap_or_else(|| component_ref.clone())
5778            };
5779            if target.starts_with("emit.") {
5780                NodeKind::BuiltinEmit {
5781                    kind: emit_kind_from_ref(&target),
5782                }
5783            } else {
5784                NodeKind::Exec {
5785                    target_component: target,
5786                }
5787            }
5788        } else if operation_is_emit {
5789            NodeKind::BuiltinEmit {
5790                kind: emit_kind_from_ref(raw_operation.as_deref().unwrap_or("emit.log")),
5791            }
5792        } else {
5793            match component_ref.as_str() {
5794                "flow.call" => NodeKind::FlowCall,
5795                "flow.goto" => NodeKind::FlowGoto,
5796                "provider.invoke" => NodeKind::ProviderInvoke,
5797                "session.wait" => NodeKind::Wait,
5798                "state.get" => NodeKind::BuiltinStateGet,
5799                "state.set" => NodeKind::BuiltinStateSet,
5800                "var.set" => {
5801                    let name = node
5802                        .input
5803                        .mapping
5804                        .get("name")
5805                        .and_then(Value::as_str)
5806                        .unwrap_or("")
5807                        .to_string();
5808                    let value = node
5809                        .input
5810                        .mapping
5811                        .get("value")
5812                        .cloned()
5813                        .unwrap_or(Value::Null);
5814                    NodeKind::VarSet { name, value }
5815                }
5816                "dw.agent" => NodeKind::DwAgent {
5817                    agent_id: raw_operation.clone().unwrap_or_default(),
5818                    // SP3: honour the flow-doc `conversational` flag (greentic-flow
5819                    // parses it into `greentic_types::Node.conversational`).
5820                    conversational: node.conversational,
5821                },
5822                "dw.agent_graph" => NodeKind::DwAgentGraph {
5823                    graph_id: raw_operation.clone().unwrap_or_default(),
5824                },
5825                "sorla.call" => NodeKind::SorlaCall {
5826                    target: raw_operation.clone().unwrap_or_default(),
5827                },
5828                "operala.call" => NodeKind::OperalaCall {
5829                    target: raw_operation.clone().unwrap_or_default(),
5830                },
5831                "agentic.call" => NodeKind::AgenticCall {
5832                    target: raw_operation.clone().unwrap_or_default(),
5833                },
5834                "telco-x.call" => NodeKind::TelcoXCall {
5835                    target: raw_operation.clone().unwrap_or_default(),
5836                },
5837                "approval.call" => NodeKind::ApprovalCall {
5838                    target: raw_operation.clone().unwrap_or_default(),
5839                },
5840                comp if comp.starts_with("emit.") => NodeKind::BuiltinEmit {
5841                    kind: emit_kind_from_ref(comp),
5842                },
5843                // LOCKED ENCODING v2 (shared with greentic-flow + designer):
5844                // `component == "mcp"` (a valid `ComponentId`) with `server` and
5845                // `tool` carried in the node PAYLOAD/config:
5846                //   payload = { server, tool, arguments, output? }.
5847                // The payload is the source of truth. A legacy
5848                // `operation = "<server>/<tool>"` (or an `mcp:<server>/<tool>`
5849                // component ref) is honored only as a defensive fallback when the
5850                // payload lacks the fields, so older packs keep loading.
5851                "mcp" => mcp_node_kind(&node.input.mapping, raw_operation.as_deref()),
5852                // `mcp:<server>/<tool>` carried verbatim in `component.id`.
5853                // `greentic_types::ComponentId` rejects `:`/`/`, so this form
5854                // only survives when the node-type string bypasses ComponentId
5855                // validation; it is still recognized as a fallback for older
5856                // packs.
5857                comp if comp.starts_with("mcp:") => mcp_node_kind(&node.input.mapping, Some(comp)),
5858                // LOCKED ENCODING v1 (shared with greentic-flow + designer):
5859                // `component == "a2a"` (a valid `ComponentId`) with `agent` and
5860                // `message` carried in the node PAYLOAD/config:
5861                //   payload = { agent, message, output? }.
5862                // The payload is the source of truth; an `operation =
5863                // "<agent_id>"` (or an `a2a:<agent_id>` component ref) is the
5864                // fallback, mirroring the `mcp` node's two encodings.
5865                "a2a" => a2a_node_kind(&node.input.mapping, raw_operation.as_deref()),
5866                comp if comp.starts_with("a2a:") => a2a_node_kind(&node.input.mapping, Some(comp)),
5867                // LOCKED ENCODING v1: `component == "media.create"` with
5868                // `format`/`name`/`text`/`rows`/`output` in the node payload.
5869                "media.create" => NodeKind::MediaCreate,
5870                other => NodeKind::PackComponent {
5871                    component_ref: other.to_string(),
5872                },
5873            }
5874        };
5875        let component_label = match &kind {
5876            NodeKind::Exec { .. } => "component.exec".to_string(),
5877            NodeKind::PackComponent { component_ref } => component_ref.clone(),
5878            NodeKind::ProviderInvoke => "provider.invoke".to_string(),
5879            NodeKind::FlowCall => "flow.call".to_string(),
5880            NodeKind::FlowGoto => "flow.goto".to_string(),
5881            NodeKind::BuiltinEmit { kind } => emit_ref_from_kind(kind),
5882            NodeKind::BuiltinStateGet => "state.get".to_string(),
5883            NodeKind::BuiltinStateSet => "state.set".to_string(),
5884            NodeKind::VarSet { .. } => "var.set".to_string(),
5885            NodeKind::Wait => "session.wait".to_string(),
5886            NodeKind::DwAgent { .. } => "dw.agent".to_string(),
5887            NodeKind::DwAgentGraph { .. } => "dw.agent_graph".to_string(),
5888            NodeKind::SorlaCall { .. } => "sorla.call".to_string(),
5889            NodeKind::OperalaCall { .. } => "operala.call".to_string(),
5890            NodeKind::AgenticCall { .. } => "agentic.call".to_string(),
5891            NodeKind::TelcoXCall { .. } => "telco-x.call".to_string(),
5892            NodeKind::ApprovalCall { .. } => "approval.call".to_string(),
5893            NodeKind::Mcp { server_id, tool } => format!("mcp:{server_id}/{tool}"),
5894            NodeKind::A2a { agent_id } => format!("a2a:{agent_id}"),
5895            NodeKind::MediaCreate => "media.create".to_string(),
5896        };
5897        let operation_name = if is_component_exec && operation_is_component_exec {
5898            None
5899        } else {
5900            raw_operation.clone()
5901        };
5902        // Extract per-node output bindings before the mapping is consumed by
5903        // `payload_expr`. Stored as raw (unrendered) templates so they can be
5904        // applied after the node runs, using the node's own output as `prev`.
5905        let vars_out = node
5906            .input
5907            .mapping
5908            .get("vars_out")
5909            .and_then(Value::as_object)
5910            .cloned();
5911        let response_timeout_secs = response_timeout_from_mapping(&node.input.mapping);
5912        let payload_expr = match kind {
5913            NodeKind::BuiltinEmit { .. } => extract_emit_payload(&node.input.mapping),
5914            // VarSet dispatch re-reads name/value from NodeKind::VarSet directly;
5915            // the payload render is redundant and must not be forwarded as node input.
5916            NodeKind::VarSet { .. } => Value::Null,
5917            _ => {
5918                // Strip the internal `vars_out` meta-key so it is never
5919                // forwarded as an input field to wasm components or other
5920                // non-emit node kinds (which may have strict schemas).
5921                let mut mapping = node.input.mapping.clone();
5922                if let Some(obj) = mapping.as_object_mut() {
5923                    obj.remove("vars_out");
5924                    // Run-audit metadata, same treatment as `vars_out`.
5925                    obj.remove(RESPONSE_TIMEOUT_KEY);
5926                }
5927                mapping
5928            }
5929        };
5930        Self {
5931            kind,
5932            component: component_label,
5933            component_id: if is_component_exec {
5934                "component.exec".to_string()
5935            } else {
5936                component_ref
5937            },
5938            operation_name,
5939            operation_in_mapping,
5940            payload_expr,
5941            routing: node.routing,
5942            vars_out,
5943            response_timeout_secs,
5944        }
5945    }
5946}
5947
5948/// Node config key naming how long a parked user may take to answer
5949/// (audit wire contract v2 §4). Read from the ROOT of the node's compiled
5950/// `input.mapping`, i.e. the node's op body in a `.ygtc` (or its `in_map`
5951/// when it declares one).
5952pub(crate) const RESPONSE_TIMEOUT_KEY: &str = "response_timeout_secs";
5953
5954/// A positive integer `response_timeout_secs`; anything else (absent, zero,
5955/// negative, fractional, a string) is `None` and the caller falls back.
5956fn response_timeout_from_mapping(mapping: &Value) -> Option<u64> {
5957    mapping
5958        .get(RESPONSE_TIMEOUT_KEY)
5959        .and_then(Value::as_u64)
5960        .filter(|secs| *secs > 0)
5961}
5962
5963/// Classify a `component == "mcp"` node into [`NodeKind::Mcp`].
5964///
5965/// LOCKED ENCODING v2: `server` and `tool` are read from the node
5966/// `payload`/config object (the source of truth). When the payload omits them,
5967/// a legacy `operation = "<server>/<tool>"` string (or an
5968/// `mcp:<server>/<tool>` component ref) is parsed as a defensive fallback for
5969/// older packs.
5970///
5971/// When neither source yields a usable `(server, tool)` pair the node falls
5972/// back to an ordinary [`NodeKind::PackComponent`], so a malformed MCP node
5973/// surfaces as a normal unknown-component error at run time rather than
5974/// panicking at load. Flow loading stays total.
5975fn mcp_node_kind(payload: &Value, legacy_ref: Option<&str>) -> NodeKind {
5976    if let Some((server_id, tool)) = crate::runner::mcp_node::server_tool_from_payload(payload) {
5977        return NodeKind::Mcp { server_id, tool };
5978    }
5979    if let Some((server_id, tool)) = legacy_ref.and_then(parse_legacy_mcp_ref) {
5980        return NodeKind::Mcp { server_id, tool };
5981    }
5982    NodeKind::PackComponent {
5983        component_ref: "mcp".to_string(),
5984    }
5985}
5986
5987/// Classify a `component == "a2a"` node into [`NodeKind::A2a`].
5988///
5989/// LOCKED ENCODING v1: `agent` is read from the node `payload`/config object
5990/// (the source of truth). When the payload omits it, the `operation`
5991/// (`"<agent_id>"`) or an `a2a:<agent_id>` component ref is parsed instead.
5992///
5993/// When neither source yields an agent id the node falls back to an ordinary
5994/// [`NodeKind::PackComponent`], so a malformed A2A node surfaces as a normal
5995/// unknown-component error at run time rather than panicking at load. Flow
5996/// loading stays total — the same rule [`mcp_node_kind`] follows, and for the
5997/// same reason: one bad node must not take a pack's other flows with it.
5998fn a2a_node_kind(payload: &Value, legacy_ref: Option<&str>) -> NodeKind {
5999    if let Some(agent_id) = crate::runner::a2a_node::agent_from_payload(payload) {
6000        return NodeKind::A2a { agent_id };
6001    }
6002    if let Some(agent_id) = legacy_ref.and_then(crate::runner::a2a_node::agent_from_ref) {
6003        return NodeKind::A2a { agent_id };
6004    }
6005    NodeKind::PackComponent {
6006        component_ref: "a2a".to_string(),
6007    }
6008}
6009
6010/// Parse a legacy MCP server/tool reference, accepting either the bare
6011/// `"<server>/<tool>"` operation form or the prefixed `mcp:<server>/<tool>`
6012/// component-ref form. Returns `None` when either part is missing or empty.
6013fn parse_legacy_mcp_ref(reference: &str) -> Option<(String, String)> {
6014    let rest = reference.strip_prefix("mcp:").unwrap_or(reference);
6015    let (server, tool) = rest.split_once('/')?;
6016    if server.is_empty() || tool.is_empty() {
6017        return None;
6018    }
6019    Some((server.to_string(), tool.to_string()))
6020}
6021
6022fn extract_target_component(payload: &Value) -> Option<String> {
6023    match payload {
6024        Value::Object(map) => map
6025            .get("component")
6026            .or_else(|| map.get("component_ref"))
6027            .and_then(Value::as_str)
6028            .map(|s| s.to_string()),
6029        _ => None,
6030    }
6031}
6032
6033fn extract_operation_from_mapping(payload: &Value) -> Option<String> {
6034    match payload {
6035        Value::Object(map) => map
6036            .get("operation")
6037            .or_else(|| map.get("op"))
6038            .and_then(Value::as_str)
6039            .map(str::trim)
6040            .filter(|value| !value.is_empty())
6041            .map(|value| value.to_string()),
6042        _ => None,
6043    }
6044}
6045
6046fn extract_emit_payload(payload: &Value) -> Value {
6047    if let Value::Object(map) = payload {
6048        if let Some(input) = map.get("input") {
6049            return input.clone();
6050        }
6051        if let Some(inner) = map.get("payload") {
6052            return inner.clone();
6053        }
6054    }
6055    payload.clone()
6056}
6057
6058fn split_operation_payload(payload: Value) -> (Value, Value) {
6059    if let Value::Object(mut map) = payload.clone()
6060        && map.contains_key("input")
6061    {
6062        let input = map.remove("input").unwrap_or(Value::Null);
6063        let config = map.remove("config").unwrap_or(Value::Null);
6064        let legacy_only = map.keys().all(|key| {
6065            matches!(
6066                key.as_str(),
6067                "operation" | "op" | "component" | "component_ref"
6068            )
6069        });
6070        if legacy_only {
6071            return (input, config);
6072        }
6073    }
6074    (payload, Value::Null)
6075}
6076
6077fn resolve_component_operation(
6078    node_id: &str,
6079    component_label: &str,
6080    payload_operation: Option<String>,
6081    operation_override: Option<&str>,
6082    operation_in_mapping: Option<&str>,
6083) -> Result<String> {
6084    if let Some(op) = operation_override
6085        .map(str::trim)
6086        .filter(|value| !value.is_empty())
6087    {
6088        return Ok(op.to_string());
6089    }
6090
6091    if let Some(op) = payload_operation
6092        .as_deref()
6093        .map(str::trim)
6094        .filter(|value| !value.is_empty())
6095    {
6096        return Ok(op.to_string());
6097    }
6098
6099    let mut message = format!(
6100        "missing operation for node `{}` (component `{}`); expected node.component.operation to be set",
6101        node_id, component_label,
6102    );
6103    if let Some(found) = operation_in_mapping {
6104        message.push_str(&format!(
6105            ". Found operation in input.mapping (`{}`) but this is not used; pack compiler must preserve node.component.operation.",
6106            found
6107        ));
6108    }
6109    bail!(message);
6110}
6111
6112fn emit_kind_from_ref(component_ref: &str) -> EmitKind {
6113    match component_ref {
6114        "emit.log" => EmitKind::Log,
6115        "emit.response" => EmitKind::Response,
6116        other => EmitKind::Other(other.to_string()),
6117    }
6118}
6119
6120fn emit_ref_from_kind(kind: &EmitKind) -> String {
6121    match kind {
6122        EmitKind::Log => "emit.log".to_string(),
6123        EmitKind::Response => "emit.response".to_string(),
6124        EmitKind::Other(other) => other.clone(),
6125    }
6126}
6127
6128/// Returns `true` when `input` looks like an Adaptive Card invocation
6129/// (contains `card_source` or `card_spec` at the top level).
6130fn is_card_invocation(input: &Value) -> bool {
6131    if let Value::Object(map) = input {
6132        return map.contains_key("card_source") || map.contains_key("card_spec");
6133    }
6134    false
6135}
6136
6137/// When the node config declares adaptive-card defaults (`default_card_asset`,
6138/// `default_card_inline`, or `default_source`) but the runtime invocation has
6139/// no `card_source`/`card_spec` yet, lift those defaults into the invocation.
6140/// This produces a schema-valid invocation envelope so the component does not
6141/// fall back to its generic "Welcome" placeholder.
6142///
6143/// Adaptive-card defaults can arrive in either of two places depending on how
6144/// the pack was compiled:
6145/// - top-level `call.config` (post `split_operation_payload`)
6146/// - nested `call.input.config` (when the node mapping kept the
6147///   `{component, config}` shape and `split_operation_payload` left it intact)
6148fn promote_card_config_to_invocation(input: &mut Value, config: &Value) {
6149    if is_card_invocation(input) {
6150        return;
6151    }
6152
6153    let cfg_map = card_defaults_source(input, config);
6154    let Some(cfg) = cfg_map else { return };
6155
6156    let default_asset = cfg
6157        .get("default_card_asset")
6158        .and_then(Value::as_str)
6159        .map(str::trim)
6160        .filter(|value| !value.is_empty())
6161        .map(str::to_string);
6162    let default_inline = cfg
6163        .get("default_card_inline")
6164        .filter(|value| value.is_object() || value.is_array())
6165        .cloned();
6166    let default_source = cfg
6167        .get("default_source")
6168        .and_then(Value::as_str)
6169        .map(str::trim)
6170        .filter(|value| !value.is_empty())
6171        .map(str::to_lowercase);
6172
6173    if default_asset.is_none() && default_inline.is_none() && default_source.is_none() {
6174        return;
6175    }
6176
6177    let card_source = default_source.unwrap_or_else(|| {
6178        if default_inline.is_some() {
6179            "inline".to_string()
6180        } else {
6181            "asset".to_string()
6182        }
6183    });
6184
6185    let mut card_spec = serde_json::Map::new();
6186    match card_source.as_str() {
6187        "asset" => {
6188            if let Some(path) = default_asset {
6189                card_spec.insert("asset_path".into(), Value::String(path));
6190            }
6191        }
6192        "inline" => {
6193            if let Some(inline) = default_inline {
6194                card_spec.insert("inline_json".into(), inline);
6195            }
6196        }
6197        _ => {}
6198    }
6199
6200    if !matches!(input, Value::Object(_)) {
6201        *input = Value::Object(serde_json::Map::new());
6202    }
6203    if let Value::Object(map) = input {
6204        map.insert("card_source".into(), Value::String(card_source));
6205        map.insert("card_spec".into(), Value::Object(card_spec));
6206    }
6207}
6208
6209/// Locate the adaptive-card defaults config object, preferring the top-level
6210/// `call.config` when present, then falling back to a nested `input.config`
6211/// (the shape produced when `split_operation_payload` leaves the mapping
6212/// intact).
6213fn card_defaults_source<'a>(
6214    input: &'a Value,
6215    config: &'a Value,
6216) -> Option<&'a serde_json::Map<String, Value>> {
6217    if let Value::Object(map) = config {
6218        return Some(map);
6219    }
6220    if let Value::Object(map) = input
6221        && let Some(Value::Object(nested)) = map.get("config")
6222    {
6223        return Some(nested);
6224    }
6225    None
6226}
6227
6228/// The conversation's locale as carried by the inbound activity payload.
6229///
6230/// `/input/metadata/locale`, then `/metadata/locale` — the shape
6231/// `inject_card_locale` has always read for card invocations. Factored out so
6232/// the card path and the flow-failure path resolve a conversation's language
6233/// from the *same* pointers; two copies would silently drift into disagreeing
6234/// about what language a user is speaking.
6235///
6236/// A blank value is treated as absent, so a producer that stamps an empty
6237/// string does not out-rank the deployment locale.
6238fn activity_locale(entry: &Value) -> Option<&str> {
6239    entry
6240        .pointer("/input/metadata/locale")
6241        .or_else(|| entry.pointer("/metadata/locale"))
6242        .and_then(Value::as_str)
6243        .filter(|locale| !locale.trim().is_empty())
6244}
6245
6246fn inject_card_locale(payload: &mut Value, entry: &Value) {
6247    if !is_card_invocation(payload) {
6248        return;
6249    }
6250    let Value::Object(map) = payload else { return };
6251    if map.contains_key("locale") {
6252        return;
6253    }
6254    if let Some(locale) = activity_locale(entry) {
6255        map.insert("locale".into(), Value::String(locale.to_string()));
6256    }
6257}
6258
6259/// Select an adaptive-card node's card from a `routeToCardId`/`toCardId`/
6260/// `nextCardId` carried on the flow entry (a card button's submit), so the flow
6261/// renders the routed card instead of the node's `default_card_asset`.
6262///
6263/// This keeps card navigation *inside* the flow — the runner sets the node's
6264/// `card_spec.asset_path` from the routing key, which makes
6265/// [`promote_card_config_to_invocation`] treat the input as an explicit card
6266/// invocation (so it does not overwrite it with the default), and
6267/// [`resolve_card_assets`] then inlines the routed card. It replaces the legacy
6268/// host-side "read the card from the pack and bypass the flow" shortcut.
6269///
6270/// No-ops (leaving the node's default card) when: the node is not the
6271/// adaptive-card component, the payload already carries an explicit
6272/// `card_source`/`card_spec` (author-set), or no routing key is present.
6273fn inject_card_route(payload: &mut Value, entry: &Value, node: &HostNode) {
6274    let is_adaptive_card =
6275        node.component_id().contains("adaptive-card") || node.component.contains("adaptive-card");
6276    if !is_adaptive_card || is_card_invocation(payload) {
6277        return;
6278    }
6279    let route = entry
6280        .pointer("/input/metadata/routeToCardId")
6281        .or_else(|| entry.pointer("/metadata/routeToCardId"))
6282        .or_else(|| entry.pointer("/input/metadata/toCardId"))
6283        .or_else(|| entry.pointer("/metadata/toCardId"))
6284        .or_else(|| entry.pointer("/input/metadata/nextCardId"))
6285        .or_else(|| entry.pointer("/metadata/nextCardId"))
6286        .and_then(Value::as_str)
6287        .map(str::trim)
6288        .filter(|value| !value.is_empty());
6289    let Some(route) = route else {
6290        return;
6291    };
6292
6293    if !matches!(payload, Value::Object(_)) {
6294        *payload = Value::Object(serde_json::Map::new());
6295    }
6296    if let Value::Object(map) = payload {
6297        let mut card_spec = serde_json::Map::new();
6298        card_spec.insert(
6299            "asset_path".into(),
6300            Value::String(format!("assets/cards/{route}.json")),
6301        );
6302        map.insert("card_source".into(), Value::String("asset".into()));
6303        map.insert("card_spec".into(), Value::Object(card_spec));
6304        tracing::debug!(route_to_card = %route, "inject_card_route: routed card asset selected");
6305    }
6306}
6307
6308/// Inject flow-level `slot_schema` as `slot_definitions` into the
6309/// slot-extractor component's input value. Skips injection when the input
6310/// already contains an explicit `slot_definitions` key (back-compat with
6311/// M2.4 NDA demo inline definitions). When the input is `Null`, promotes it
6312/// to an empty object first.
6313fn inject_slot_definitions(input: &mut Value, slot_schema: &Value, flow_id: &str, node_id: &str) {
6314    if input.is_null() {
6315        *input = Value::Object(serde_json::Map::new());
6316    }
6317    let Some(map) = input.as_object_mut() else {
6318        tracing::warn!(
6319            flow_id,
6320            node_id,
6321            "slot-extractor input is not an object; cannot inject slot_definitions"
6322        );
6323        return;
6324    };
6325    if map.contains_key("slot_definitions") {
6326        return;
6327    }
6328    let slot_count = slot_schema.as_array().map_or(0, Vec::len);
6329    tracing::debug!(
6330        flow_id,
6331        slot_count,
6332        "injecting flow-level slot_schema as slot_definitions into slot-extractor input"
6333    );
6334    map.insert("slot_definitions".to_string(), slot_schema.clone());
6335}
6336
6337/// Pre-resolve `card_source: "asset"` entries by reading the referenced JSON
6338/// file from the pack's assets directory and converting to
6339/// `card_source: "inline"` with `inline_json` populated.
6340///
6341/// This handles both top-level card fields and the nested `call.payload`
6342/// structure emitted by cards2pack.
6343fn resolve_card_assets(input: &mut Value, pack: &crate::pack::PackRuntime) {
6344    resolve_card_spec_asset(input, pack);
6345
6346    // Also resolve inside `call.payload` (cards2pack duplicates the card
6347    // invocation there).
6348    if let Value::Object(map) = input
6349        && let Some(Value::Object(call)) = map.get_mut("call")
6350        && let Some(payload) = call.get_mut("payload")
6351    {
6352        resolve_card_spec_asset(payload, pack);
6353    }
6354}
6355
6356/// Resolve a single card_spec asset_path → inline_json.
6357fn resolve_card_spec_asset(value: &mut Value, pack: &crate::pack::PackRuntime) {
6358    let Value::Object(map) = value else { return };
6359
6360    let is_asset = map
6361        .get("card_source")
6362        .and_then(Value::as_str)
6363        .map(|s| s.eq_ignore_ascii_case("asset"))
6364        .unwrap_or(false);
6365    if !is_asset {
6366        return;
6367    }
6368
6369    let asset_path = map
6370        .get("card_spec")
6371        .and_then(|spec| spec.get("asset_path"))
6372        .and_then(Value::as_str)
6373        .map(str::to_string);
6374
6375    let Some(asset_path) = asset_path else { return };
6376
6377    match pack.read_asset(&asset_path) {
6378        Ok(bytes) => {
6379            let card_json: Value = match serde_json::from_slice(&bytes) {
6380                Ok(v) => v,
6381                Err(err) => {
6382                    tracing::warn!(
6383                        asset_path,
6384                        %err,
6385                        "failed to parse card asset as JSON; leaving as asset reference"
6386                    );
6387                    return;
6388                }
6389            };
6390            tracing::debug!(asset_path, "pre-resolved card asset to inline_json");
6391            map.insert("card_source".into(), Value::String("inline".into()));
6392            if let Some(Value::Object(spec)) = map.get_mut("card_spec") {
6393                spec.insert("inline_json".into(), card_json);
6394                spec.remove("asset_path");
6395            }
6396        }
6397        Err(err) => {
6398            tracing::warn!(
6399                asset_path,
6400                %err,
6401                "card asset not found in pack; leaving as asset reference"
6402            );
6403        }
6404    }
6405
6406    // Pre-resolve i18n bundle: the WASM component cannot read pack assets
6407    // directly (no host resolver registered), so inline the i18n JSON into
6408    // the invocation under `card_spec.i18n_inline`. Defense-in-depth: when
6409    // the card omits an explicit `i18n_bundle_path` we still try the
6410    // conventional `assets/i18n/` location so cards that rely on
6411    // auto-generated i18n keys (e.g. cards2pack output) keep working.
6412    let configured_bundle_path = map
6413        .get("card_spec")
6414        .and_then(|spec| spec.get("i18n_bundle_path"))
6415        .and_then(Value::as_str)
6416        .map(|s| s.trim().trim_end_matches('/').to_string())
6417        .filter(|s| !s.is_empty());
6418
6419    let bundle_path = configured_bundle_path
6420        .clone()
6421        .unwrap_or_else(|| "assets/i18n".to_string());
6422
6423    let i18n_entries = load_i18n_bundle_entries(&bundle_path, |path| pack.read_asset(path));
6424
6425    if !i18n_entries.is_empty() {
6426        let locale_keys: Vec<_> = i18n_entries.keys().cloned().collect();
6427        if let Some(Value::Object(spec)) = map.get_mut("card_spec") {
6428            spec.insert("i18n_inline".into(), Value::Object(i18n_entries));
6429            if configured_bundle_path.is_some() {
6430                tracing::info!(%bundle_path, ?locale_keys, "pre-resolved i18n bundle into card_spec.i18n_inline");
6431            } else {
6432                tracing::info!(%bundle_path, ?locale_keys, "auto-discovered i18n bundle and inlined into card_spec.i18n_inline");
6433            }
6434        }
6435    }
6436}
6437
6438fn load_i18n_bundle_entries<F>(bundle_path: &str, mut read_asset: F) -> JsonMap<String, Value>
6439where
6440    F: FnMut(&str) -> Result<Vec<u8>>,
6441{
6442    let mut i18n_entries = JsonMap::new();
6443
6444    if bundle_path.ends_with(".json") {
6445        if let Ok(bytes) = read_asset(bundle_path)
6446            && let Ok(Value::Object(entries)) = serde_json::from_slice::<Value>(&bytes)
6447        {
6448            i18n_entries.insert("en".to_string(), Value::Object(entries));
6449        }
6450        return i18n_entries;
6451    }
6452
6453    let manifest_path = format!("{bundle_path}/_manifest.json");
6454    let locale_codes: Vec<String> = read_asset(&manifest_path)
6455        .ok()
6456        .and_then(|bytes| serde_json::from_slice::<Value>(&bytes).ok())
6457        .and_then(|value| {
6458            let locales = value
6459                .get("locales")
6460                .and_then(Value::as_array)
6461                .cloned()
6462                .or_else(|| value.as_array().cloned());
6463            locales.map(|items| {
6464                items
6465                    .iter()
6466                    .filter_map(Value::as_str)
6467                    .map(String::from)
6468                    .collect()
6469            })
6470        })
6471        .unwrap_or_default();
6472
6473    tracing::info!(%bundle_path, ?locale_codes, "i18n manifest discovered locales");
6474
6475    for locale in &locale_codes {
6476        let candidate = format!("{bundle_path}/{locale}.json");
6477        if let Ok(bytes) = read_asset(&candidate)
6478            && let Ok(Value::Object(entries)) = serde_json::from_slice::<Value>(&bytes)
6479        {
6480            i18n_entries.insert(locale.clone(), Value::Object(entries));
6481        }
6482    }
6483    if !i18n_entries.contains_key("en") {
6484        let en_path = format!("{bundle_path}/en.json");
6485        if let Ok(bytes) = read_asset(&en_path)
6486            && let Ok(Value::Object(entries)) = serde_json::from_slice::<Value>(&bytes)
6487        {
6488            i18n_entries.insert("en".to_string(), Value::Object(entries));
6489        }
6490    }
6491
6492    i18n_entries
6493}
6494
6495/// Outcome of `evaluate_custom_routing` for a node's `Routing::Custom` array.
6496///
6497/// `Next` advances the flow to the named target. `End` terminates the run.
6498/// `Wait` pauses the run at the current node so the next inbound activity
6499/// resumes here and re-evaluates the routing with the new context — this is
6500/// what allows messaging flows (welcome → ... → confirm) to behave like a
6501/// live conversation instead of restarting at the entry point on every
6502/// click.
6503#[derive(Debug)]
6504pub(crate) enum CustomRoutingDecision {
6505    Next(NodeId),
6506    End,
6507    Wait,
6508}
6509
6510/// Evaluate a node's `Routing::Custom` array against the current execution
6511/// context.
6512///
6513/// Parses `Routing::Custom(Value)` as an array of `{condition, to}` objects.
6514/// Conditions are simple equality expressions like `response.action == "about"`.
6515/// Falls back to the first route without a condition (default route).
6516///
6517/// The evaluation context includes:
6518/// - All fields from the node output payload (top-level)
6519/// - `entry` / `in` — the original flow entry (incoming message)
6520/// - `response` — synthesized from entry metadata for convenient condition checks
6521///   (e.g. `response.action` maps to `metadata.action` from the incoming envelope)
6522fn evaluate_custom_routing(
6523    raw: &Value,
6524    output: &NodeOutput,
6525    state: &ExecutionState,
6526    flow_ir: &HostFlow,
6527    node_id: &NodeId,
6528) -> CustomRoutingDecision {
6529    let routes = match raw.as_array() {
6530        Some(arr) => arr,
6531        None => {
6532            tracing::warn!(
6533                flow_id = %flow_ir.id,
6534                node_id = %node_id,
6535                "custom routing is not an array; terminating"
6536            );
6537            return CustomRoutingDecision::End;
6538        }
6539    };
6540
6541    // Build a rich context for condition evaluation:
6542    // Start with output payload, then overlay entry and synthesised "response".
6543    // The default `event` is chosen from the success/error-family port this node
6544    // actually routes on, so happy paths named `on_complete`/`on_submit` and
6545    // failure paths named `on_cancel`/`on_timeout` resolve instead of stalling
6546    // at `Wait`.
6547    let ctx = build_routing_context(
6548        output,
6549        state,
6550        default_success_event(routes),
6551        default_error_event(routes),
6552    );
6553
6554    let mut has_condition = false;
6555    let mut unmatched_conditions: Vec<&str> = Vec::new();
6556    for route in routes {
6557        let condition = route.get("condition").and_then(|v| v.as_str());
6558        let to = route.get("to").and_then(|v| v.as_str());
6559
6560        if route.get("on_message").and_then(Value::as_bool) == Some(true) {
6561            // "Anything that is not one of this card's buttons": taken only when
6562            // THIS turn resumed the card (so a freshly rendered card still
6563            // parks, which an unconditional route would not) and carries no
6564            // action. It counts as conditional for the same reason.
6565            has_condition = true;
6566            unmatched_conditions.push("on_message");
6567            let resumed_here = state.resumed_at.as_deref() == Some(node_id.as_str());
6568            let no_action = resolve_dotted_path(&ctx, "response.action")
6569                .is_none_or(|action| action.trim().is_empty());
6570            if resumed_here
6571                && no_action
6572                && let Some(target) = to
6573                && let Ok(nid) = NodeId::new(target)
6574            {
6575                tracing::debug!(
6576                    flow_id = %flow_ir.id,
6577                    node_id = %node_id,
6578                    target = target,
6579                    "on_message route taken"
6580                );
6581                return CustomRoutingDecision::Next(nid);
6582            }
6583            continue;
6584        }
6585        if let Some(cond) = condition {
6586            has_condition = true;
6587            unmatched_conditions.push(cond);
6588            if evaluate_simple_condition(cond, &ctx)
6589                && let Some(target) = to
6590                && let Ok(nid) = NodeId::new(target)
6591            {
6592                tracing::debug!(
6593                    flow_id = %flow_ir.id,
6594                    node_id = %node_id,
6595                    condition = cond,
6596                    target = target,
6597                    "conditional route matched"
6598                );
6599                return CustomRoutingDecision::Next(nid);
6600            }
6601        } else if let Some(target) = to
6602            && let Ok(nid) = NodeId::new(target)
6603        {
6604            tracing::debug!(
6605                flow_id = %flow_ir.id,
6606                node_id = %node_id,
6607                target = target,
6608                "default route taken"
6609            );
6610            return CustomRoutingDecision::Next(nid);
6611        }
6612    }
6613
6614    // Fall-through. When the routing array contained at least one
6615    // conditional entry, treat the unmatched fall-through as a pause: the
6616    // user's next submission should be re-evaluated against this same
6617    // node's routing rather than restarting the flow from the entry point.
6618    // Routing arrays with no conditions at all (pure unconditional `out`
6619    // terminators) remain true ends.
6620    if has_condition {
6621        tracing::warn!(
6622            flow_id = %flow_ir.id,
6623            node_id = %node_id,
6624            conditions = ?unmatched_conditions,
6625            "no conditional route matched; pausing run at current node for resume"
6626        );
6627        CustomRoutingDecision::Wait
6628    } else {
6629        tracing::warn!(
6630            flow_id = %flow_ir.id,
6631            node_id = %node_id,
6632            "no route matched and no conditions present; terminating"
6633        );
6634        CustomRoutingDecision::End
6635    }
6636}
6637
6638/// Evaluate a simple condition expression used by `Routing::Custom` entries and
6639/// `conditional_branch` guards (e.g. `response.action == "about"`,
6640/// `register.q_age >= 18`, `msg.text contains "hello"`).
6641///
6642/// Dotted paths resolve against the JSON context; an unresolved path is false.
6643/// Operators (detected longest-token-first so `>=`/`<=` win over `>`/`<`):
6644/// - `== ` / `!=` — case-insensitive string equality.
6645/// - `>=` / `<=` / `>` / `<` — numeric ordering; both operands are parsed as
6646///   `f64`, and a non-numeric operand makes the condition false (never a panic).
6647/// - `contains` — case-insensitive substring of the resolved string.
6648fn evaluate_simple_condition(condition: &str, ctx: &Value) -> bool {
6649    let Some((op, path, expected)) = split_at_first_operator(condition) else {
6650        return false;
6651    };
6652    match op {
6653        "==" => string_eq(ctx, path, expected, false),
6654        "!=" => string_eq(ctx, path, expected, true),
6655        ">=" => numeric_cmp(ctx, path, expected, |a, b| a >= b),
6656        "<=" => numeric_cmp(ctx, path, expected, |a, b| a <= b),
6657        ">" => numeric_cmp(ctx, path, expected, |a, b| a > b),
6658        "<" => numeric_cmp(ctx, path, expected, |a, b| a < b),
6659        " contains " => {
6660            let needle = expected.to_lowercase();
6661            resolve_dotted_path(ctx, path)
6662                .is_some_and(|actual| actual.to_lowercase().contains(&needle))
6663        }
6664        _ => false,
6665    }
6666}
6667
6668/// Operators in the order they are tried at one position: longer tokens first
6669/// so `>=`/`<=` win over `>`/`<`.
6670const CONDITION_OPERATORS: [&str; 7] = ["==", "!=", ">=", "<=", ">", "<", " contains "];
6671
6672/// Split a condition at its FIRST operator that is not inside double quotes,
6673/// into `(operator, trimmed path, trimmed value)` with the value's surrounding
6674/// quotes stripped.
6675///
6676/// "First" is by position, not by operator priority: a value that itself
6677/// contains another operator (`x > "a==b"`) must split at the real operator,
6678/// not at the one inside the literal. `None` when there is no operator.
6679fn split_at_first_operator(condition: &str) -> Option<(&'static str, &str, &str)> {
6680    let mut in_quotes = false;
6681    for (idx, ch) in condition.char_indices() {
6682        if ch == '"' {
6683            in_quotes = !in_quotes;
6684            continue;
6685        }
6686        if in_quotes {
6687            continue;
6688        }
6689        let rest = &condition[idx..];
6690        if let Some(op) = CONDITION_OPERATORS.iter().find(|op| rest.starts_with(**op)) {
6691            let path = condition[..idx].trim();
6692            let value = condition[idx + op.len()..].trim().trim_matches('"');
6693            return Some((op, path, value));
6694        }
6695    }
6696    None
6697}
6698
6699/// Case-insensitive string equality of the resolved path against `expected`,
6700/// optionally negated. An unresolved path is treated as not-equal.
6701fn string_eq(ctx: &Value, path: &str, expected: &str, negate: bool) -> bool {
6702    let matches = resolve_dotted_path(ctx, path)
6703        .as_deref()
6704        .is_some_and(|a| a.eq_ignore_ascii_case(expected));
6705    if negate { !matches } else { matches }
6706}
6707
6708/// Numeric comparison of the resolved path against `expected`. Both sides are
6709/// parsed as `f64`; if either fails to parse the condition is false.
6710fn numeric_cmp(ctx: &Value, path: &str, expected: &str, cmp: impl Fn(f64, f64) -> bool) -> bool {
6711    let Some(actual) = resolve_dotted_path(ctx, path).and_then(|a| a.trim().parse::<f64>().ok())
6712    else {
6713        return false;
6714    };
6715    let Ok(rhs) = expected.parse::<f64>() else {
6716        return false;
6717    };
6718    cmp(actual, rhs)
6719}
6720
6721/// Resolve a dotted path like `response.action` against a JSON value.
6722fn resolve_dotted_path(value: &Value, path: &str) -> Option<String> {
6723    let parts: Vec<&str> = path.split('.').collect();
6724    let mut current = value;
6725    for part in &parts {
6726        current = current.get(part)?;
6727    }
6728    match current {
6729        Value::String(s) => Some(s.clone()),
6730        Value::Bool(b) => Some(b.to_string()),
6731        Value::Number(n) => Some(n.to_string()),
6732        _ => Some(current.to_string()),
6733    }
6734}
6735
6736/// Upper bound on nodes executed by ONE `drive_flow` call (one inbound turn).
6737/// Pausing nodes end the call, so only a flow that loops without ever waiting
6738/// (a routing cycle, a self-`flow.goto` chain) can reach it; generous enough
6739/// that no legitimate graph does.
6740const MAX_STEPS_PER_TURN: usize = 10_000;
6741
6742/// Fail a runaway turn with a clear error instead of spinning forever. The
6743/// message deliberately avoids `should_retry`'s trigger words: re-running a
6744/// cycle just burns another full budget.
6745fn check_step_budget(steps_run: usize, flow_id: &str) -> Result<()> {
6746    if steps_run > MAX_STEPS_PER_TURN {
6747        // Terminal: the first 10 000 nodes already ran their effects, and a
6748        // routing cycle is deterministic, so re-running the turn only repeats
6749        // both (see `TerminalFlowError`).
6750        return Err(terminal_flow_error(format!(
6751            "flow_step_limit_exceeded: flow `{flow_id}` ran more than {MAX_STEPS_PER_TURN} nodes in one turn (routing cycle?)"
6752        )));
6753    }
6754    Ok(())
6755}
6756
6757/// Success-family outcome ports, in the priority order used to pick the default
6758/// success `event` for a node that succeeded without emitting an explicit
6759/// `outcome`. `on_success` is first so components whose success name is the
6760/// historical default keep routing unchanged (e.g. http).
6761const SUCCESS_EVENT_PORTS: [&str; 3] = ["on_success", "on_complete", "on_submit"];
6762
6763/// Error-family outcome ports, priority order, mirroring [`SUCCESS_EVENT_PORTS`]
6764/// for the failure (`ok == false`) branch. `on_error` is first so the historical
6765/// default is preserved; `on_cancel` / `on_timeout` let a node whose failure
6766/// port is named differently (qa cancel, http timeout) route instead of stalling.
6767const ERROR_EVENT_PORTS: [&str; 3] = ["on_error", "on_cancel", "on_timeout"];
6768
6769/// Whether a node opts into node_io error routing: a `Routing::Custom` array with
6770/// at least one route targeting an error-family port (`on_error` / `on_cancel` /
6771/// `on_timeout`), either as an explicit `event` field or via an `event == "<port>"`
6772/// condition (the form the designer emits). Such a node surfaces a component
6773/// failure as an `{errors}` output routed to that branch; every other node keeps
6774/// the historical hard-fail (`bail!`) on error — so this change is purely additive.
6775fn node_has_error_route(routing: &Routing) -> bool {
6776    let Routing::Custom(raw) = routing else {
6777        return false;
6778    };
6779    let Some(routes) = raw.as_array() else {
6780        return false;
6781    };
6782    routes.iter().any(|route| {
6783        let by_event = route
6784            .get("event")
6785            .and_then(Value::as_str)
6786            .is_some_and(|e| ERROR_EVENT_PORTS.contains(&e));
6787        let by_condition = route
6788            .get("condition")
6789            .and_then(Value::as_str)
6790            .is_some_and(|c| ERROR_EVENT_PORTS.iter().any(|port| c.contains(port)));
6791        by_event || by_condition
6792    })
6793}
6794
6795/// Derive the success `event` to default to when a node succeeds (`ok == true`)
6796/// but emits no explicit `outcome`. Designer-built nodes whose happy port is
6797/// `on_complete` (native `qa.process` / `llm.openai.chat` / `template_render`)
6798/// or `on_submit` (forms) compile to `event == "<port>"` conditions; with a
6799/// blanket `on_success` default those never match and the node stalls at
6800/// `Wait`. We instead pick the first success-family port the node actually has
6801/// an outgoing `event == "<port>"` edge for, so the happy path routes. Falls
6802/// back to `on_success` when no success-family port is referenced (preserving
6803/// the prior behaviour).
6804fn default_success_event(routes: &[Value]) -> &'static str {
6805    default_event(routes, &SUCCESS_EVENT_PORTS, "on_success")
6806}
6807
6808/// Failure-branch counterpart of [`default_success_event`]: the `event` to
6809/// default to when a node fails (`ok == false`) without an explicit `outcome`.
6810/// Picks the first error-family port the node actually routes on, falling back
6811/// to `on_error`.
6812fn default_error_event(routes: &[Value]) -> &'static str {
6813    default_event(routes, &ERROR_EVENT_PORTS, "on_error")
6814}
6815
6816/// Pick the first port in `ports` (priority order) that the node has an outgoing
6817/// `event == "<port>"` edge for; `fallback` when none is referenced.
6818fn default_event(routes: &[Value], ports: &[&'static str], fallback: &'static str) -> &'static str {
6819    let referenced: Vec<&str> = routes
6820        .iter()
6821        .filter_map(|route| route.get("condition").and_then(Value::as_str))
6822        .filter_map(condition_event_eq)
6823        .collect();
6824    ports
6825        .iter()
6826        .copied()
6827        .find(|port| referenced.contains(port))
6828        .unwrap_or(fallback)
6829}
6830
6831/// Extract `<value>` from an `event == "<value>"` condition; `None` for any
6832/// other shape (different path, `!=`, no `==`).
6833fn condition_event_eq(condition: &str) -> Option<&str> {
6834    let idx = condition.find("==")?;
6835    if condition[..idx].trim() != "event" {
6836        return None;
6837    }
6838    Some(condition[idx + 2..].trim().trim_matches('"'))
6839}
6840
6841/// Where the submit envelope carries its metadata, across both delivery paths.
6842///
6843/// `greentic-start` wraps the activity (`entry.input.metadata`); the direct
6844/// runner path does not (`entry.metadata`). Both the `response.*` synthesis in
6845/// [`build_routing_context`] and [`submitted_fields`] resolve through here, so
6846/// the two can never disagree about which object is the metadata.
6847fn resolve_entry_metadata(entry: &Value) -> Option<&Value> {
6848    entry
6849        .pointer("/input/metadata")
6850        .or_else(|| entry.pointer("/metadata"))
6851}
6852
6853/// The fields a person actually submitted, as one flat map.
6854///
6855/// The envelope root is `entry.input` when that is an object (the wrapped
6856/// `greentic-start` path) and `entry` itself otherwise (the Run Demo path,
6857/// whose inputs sit at the root — see that repo's
6858/// `flow_demo/host.rs::build_submit_payload`). Resolving it is not bookkeeping:
6859/// taking `entry`'s root keys directly on the wrapped path would make one field
6860/// named `input` holding the entire nested activity.
6861///
6862/// The rule:
6863///
6864/// > the envelope root's keys except `metadata` and `text`, unioned with the
6865/// > resolved metadata object's keys except `action`; on collision the envelope
6866/// > root wins.
6867///
6868/// `text` is the message body in both shapes and is already exposed as
6869/// `response.text`. `action` is the route discriminator, already exposed as
6870/// `response.action` — but a key named `action` at the envelope ROOT is counted,
6871/// because on the demo path that is a real keystroke at a different level from
6872/// the routing metadata.
6873///
6874/// NOTE: `response.*` must NOT be rebuilt on top of this. It shares only
6875/// [`resolve_entry_metadata`]. Feeding `response` this map would drop
6876/// `response.action`, which every parking card's conditional routing tests —
6877/// and a failed condition silently takes the false branch.
6878fn submitted_fields(entry: &Value) -> JsonMap<String, Value> {
6879    let mut fields = JsonMap::new();
6880    if let Some(Value::Object(meta)) = resolve_entry_metadata(entry) {
6881        for (key, value) in meta {
6882            if key == "action" || key == SUBMIT_MARKER_KEY {
6883                continue;
6884            }
6885            fields.insert(key.clone(), value.clone());
6886        }
6887    }
6888    let envelope = entry
6889        .get("input")
6890        .filter(|v| v.is_object())
6891        .unwrap_or(entry);
6892    if let Some(map) = envelope.as_object() {
6893        for (key, value) in map {
6894            if key == "metadata" || key == "text" {
6895                continue;
6896            }
6897            fields.insert(key.clone(), value.clone());
6898        }
6899    }
6900    fields
6901}
6902
6903/// Build the context a routing condition is evaluated against.
6904///
6905/// Layout:
6906/// ```text
6907/// {
6908///   ...output.payload...,     // this node's fields, spread at the top level
6909///   "entry":    <flow entry>,
6910///   "in":       <flow entry>, // alias for entry
6911///   "node":     { "<id>": <node_output_view>, ... },  // every prior node
6912///   "response": { <key>: <value>, ... },              // from envelope metadata
6913///   "event":    "<outcome>"   // the port this node routes on
6914/// }
6915/// ```
6916///
6917/// The spread comes FIRST and the named keys are inserted after, so
6918/// **`entry`, `in`, `node`, `response` and `event` are reserved**: a component
6919/// whose payload has a top-level field with one of those names has it shadowed
6920/// here. That is deliberate — the spread is what lets a guard say `q_age >= 18`
6921/// about its own node (and is what the designer's source-node prefix strip
6922/// relies on) — but it means those five names are not usable as payload fields
6923/// in a routed node.
6924///
6925/// `node` is the same `outputs_map()` projection [`template_context`] exposes,
6926/// so a condition resolves `node.<id>.<field>` exactly as a param template
6927/// resolves `{{node.<id>.<field>}}`. Note `vars` is NOT here: `vars.x` in a
6928/// condition does not resolve, whereas `{{vars.x}}` in a param does.
6929fn build_routing_context(
6930    output: &NodeOutput,
6931    state: &ExecutionState,
6932    success_event: &str,
6933    error_event: &str,
6934) -> Value {
6935    let mut ctx = match &output.payload {
6936        Value::Object(map) => map.clone(),
6937        _ => JsonMap::new(),
6938    };
6939
6940    // Alias `in.input` to the entry itself when the entry is the bare message
6941    // (env/revision path) so routing templates that read `in.input.*` resolve,
6942    // mirroring `template_context`. Legacy `{input: <message>}` entries are
6943    // left untouched.
6944    let entry = alias_input_to_entry(state.entry.clone());
6945    ctx.insert("entry".into(), entry.clone());
6946    ctx.insert("in".into(), entry.clone());
6947
6948    // Every prior node's output, keyed by id — the SAME projection
6949    // `template_context` exposes for `{{node.<id>.<field>}}`, so a routing
6950    // condition resolves `node.<id>.<field>` exactly as a param template does.
6951    // Without this a guard could only read the current node's payload (spread
6952    // at the top level, above), so a condition naming any other node resolved
6953    // to nothing and silently took the false branch on every input.
6954    ctx.insert("node".into(), Value::Object(state.outputs_map()));
6955
6956    // Synthesise "response" from the envelope metadata.
6957    // greentic-start demo path: entry.input.metadata.*
6958    // greentic-runner direct path: entry.metadata.*
6959    let metadata = resolve_entry_metadata(&entry);
6960
6961    let mut response = JsonMap::new();
6962    if let Some(Value::Object(meta)) = metadata {
6963        for (k, v) in meta {
6964            // Flatten string values; stringify others
6965            match v {
6966                Value::String(s) => {
6967                    response.insert(k.clone(), Value::String(s.clone()));
6968                }
6969                other => {
6970                    response.insert(k.clone(), other.clone());
6971                }
6972            }
6973        }
6974    }
6975    // Also pull text from the envelope for convenience
6976    if let Some(text) = entry
6977        .pointer("/input/text")
6978        .or_else(|| entry.pointer("/text"))
6979        .filter(|t| !t.is_null())
6980    {
6981        response.insert("text".into(), text.clone());
6982    }
6983    ctx.insert("response".into(), Value::Object(response));
6984
6985    // Inject the node's outcome as `event` so port-name routing
6986    // (`event == "<outcome>"`, emitted by the designer for nodes with multiple
6987    // outgoing edges) resolves. Prefer an explicit outcome the node emitted in
6988    // its output metadata; otherwise derive a default from `ok` — `success_event`
6989    // on success / `error_event` on failure (the success/error-family port the
6990    // node actually has an edge for; see `default_success_event` /
6991    // `default_error_event`). Without this, a multi-edge node falls through to
6992    // `Wait` at runtime.
6993    let event = output
6994        .meta
6995        .get("outcome")
6996        .and_then(Value::as_str)
6997        .map(str::to_string)
6998        .unwrap_or_else(|| {
6999            if output.ok {
7000                success_event
7001            } else {
7002                error_event
7003            }
7004            .to_string()
7005        });
7006    ctx.insert("event".into(), Value::String(event));
7007
7008    Value::Object(ctx)
7009}
7010
7011/// Pure autonomy-gate decision for an `approval.call` node. Returns `true` when
7012/// the request must go to a human (dispatch), `false` when it auto-approves.
7013///
7014/// The gate config fields (`mode`, `risk_threshold`, `confidence_threshold`)
7015/// are compiled by the designer as FLAT fields directly on the node input
7016/// (not nested under a `gate` object); `risk`/`confidence` are already
7017/// flat/dynamic values populated at flow render time.
7018fn approval_requires_human(input: &Value) -> bool {
7019    let mode = input
7020        .get("mode")
7021        .and_then(Value::as_str)
7022        .unwrap_or("always");
7023    match mode {
7024        // Fail closed: a missing, null, string or non-finite value (or
7025        // threshold) can never auto-approve; it goes to a human.
7026        "above_risk" => match (
7027            finite_number(input, "risk"),
7028            finite_number(input, "risk_threshold"),
7029        ) {
7030            (Some(risk), Some(threshold)) => risk >= threshold,
7031            _ => true,
7032        },
7033        "above_confidence" => match (
7034            finite_number(input, "confidence"),
7035            finite_number(input, "confidence_threshold"),
7036        ) {
7037            (Some(confidence), Some(threshold)) => confidence < threshold,
7038            _ => true,
7039        },
7040        // "always" and any unknown mode fail safe: require a human.
7041        _ => true,
7042    }
7043}
7044
7045/// A JSON number under `key`, or `None` when absent, non-numeric or non-finite.
7046fn finite_number(input: &Value, key: &str) -> Option<f64> {
7047    input
7048        .get(key)
7049        .and_then(Value::as_f64)
7050        .filter(|n| n.is_finite())
7051}
7052
7053/// True when `entry` is a runtime-dispatch response envelope rather than a user
7054/// activity. The dispatch response always carries a top-level `ok`
7055/// (`{ok, output, events, error}`); an inbound activity never does. Mirrors the
7056/// conversational `dw.agent` discriminator (`state.entry.get("ok").is_some()`).
7057fn entry_is_approval_response(entry: &Value) -> bool {
7058    entry.get("ok").is_some()
7059}
7060
7061/// One approval a flow is parked on, as recorded at dispatch.
7062#[derive(Clone, Debug, Default, PartialEq, Eq)]
7063pub(crate) struct ParkedApproval {
7064    /// The correlation id the request was published under; `None` for a mark
7065    /// recorded before ids were.
7066    pub(crate) correlation_id: Option<String>,
7067    /// `sha256(decision_token)`, hex; `None` for a mark recorded by a runner
7068    /// that issued no token (greentic-runner#794).
7069    pub(crate) token_fingerprint: Option<String>,
7070}
7071
7072/// Whether `response` may decide the gate `parked` describes.
7073///
7074/// A gate issued a token requires `output.decision_token` to match it —
7075/// missing and wrong are refused alike. A legacy gate (no fingerprint) was
7076/// never issued one and is resumed as before.
7077pub(crate) fn response_authenticates(response: &Value, parked: &ParkedApproval) -> bool {
7078    match parked.token_fingerprint.as_deref() {
7079        None => true,
7080        Some(fingerprint) => {
7081            approval_token::verify(approval_token::from_response(response), fingerprint)
7082        }
7083    }
7084}
7085
7086/// Map an approval response envelope to the routing outcome that becomes
7087/// `event` via `NodeOutput.meta["outcome"]`.
7088///
7089/// A watchdog timeout arrives as `{ok: false, output: null, error: {code: "timeout"}}`
7090/// and wins over any decision. Otherwise the discriminator is `output.decision`
7091/// — NOT `ok`, which greentic-admin sets to `true` for approve *and* deny.
7092///
7093/// Fails closed: an unrecognised or absent decision is `denied`, mirroring
7094/// `approval_requires_human`'s own `_ => true` fail-safe. A corrupt payload must
7095/// never become a pass.
7096fn approval_outcome_from_entry(entry: &Value) -> &'static str {
7097    let timed_out = entry
7098        .pointer("/error/code")
7099        .and_then(Value::as_str)
7100        .is_some_and(|code| code.eq_ignore_ascii_case("timeout"));
7101    if timed_out {
7102        return "timeout";
7103    }
7104    // Fail closed: a failed envelope is never a pass, whatever `output` says.
7105    if entry.get("ok").and_then(Value::as_bool) == Some(false) {
7106        return "denied";
7107    }
7108    match entry.pointer("/output/decision").and_then(Value::as_str) {
7109        Some(decision) if decision.eq_ignore_ascii_case("approved") => "approved",
7110        _ => "denied",
7111    }
7112}
7113
7114#[cfg(test)]
7115mod approval_gate_tests {
7116    use super::{approval_outcome_from_entry, approval_requires_human, entry_is_approval_response};
7117    use serde_json::json;
7118
7119    #[test]
7120    fn above_risk_auto_approves_below_threshold() {
7121        let input = json!({ "risk": 0.5, "mode": "above_risk", "risk_threshold": 0.7 });
7122        assert!(!approval_requires_human(&input));
7123    }
7124
7125    #[test]
7126    fn above_risk_requires_human_at_or_above_threshold() {
7127        let input = json!({ "risk": 0.9, "mode": "above_risk", "risk_threshold": 0.7 });
7128        assert!(approval_requires_human(&input));
7129    }
7130
7131    #[test]
7132    fn above_confidence_requires_human_when_low_confidence() {
7133        let input =
7134            json!({ "confidence": 0.4, "mode": "above_confidence", "confidence_threshold": 0.8 });
7135        assert!(approval_requires_human(&input));
7136    }
7137
7138    #[test]
7139    fn above_risk_fails_closed_on_missing_or_non_numeric_values() {
7140        for input in [
7141            json!({ "mode": "above_risk", "risk_threshold": 0.7 }),
7142            json!({ "mode": "above_risk", "risk": null, "risk_threshold": 0.7 }),
7143            json!({ "mode": "above_risk", "risk": "0.1", "risk_threshold": 0.7 }),
7144            json!({ "mode": "above_risk", "risk": 0.1 }),
7145            json!({ "mode": "above_risk", "risk": 0.1, "risk_threshold": "high" }),
7146            json!({ "mode": "above_risk" }),
7147        ] {
7148            assert!(approval_requires_human(&input), "{input}");
7149        }
7150    }
7151
7152    #[test]
7153    fn above_confidence_fails_closed_on_missing_or_non_numeric_values() {
7154        for input in [
7155            json!({ "mode": "above_confidence", "confidence_threshold": 0.5 }),
7156            json!({ "mode": "above_confidence", "confidence": "0.99", "confidence_threshold": 0.5 }),
7157            json!({ "mode": "above_confidence", "confidence": 0.99 }),
7158            json!({ "mode": "above_confidence", "confidence": null, "confidence_threshold": null }),
7159        ] {
7160            assert!(approval_requires_human(&input), "{input}");
7161        }
7162        let ok =
7163            json!({ "mode": "above_confidence", "confidence": 0.9, "confidence_threshold": 0.5 });
7164        assert!(!approval_requires_human(&ok));
7165    }
7166
7167    #[test]
7168    fn always_and_missing_gate_require_human() {
7169        assert!(approval_requires_human(&json!({ "mode": "always" })));
7170        assert!(approval_requires_human(&json!({})));
7171    }
7172
7173    #[test]
7174    fn entry_is_a_response_only_when_the_envelope_has_ok() {
7175        // The dispatch response envelope always carries a top-level `ok`.
7176        assert!(entry_is_approval_response(
7177            &json!({ "ok": true, "output": { "decision": "approved" } })
7178        ));
7179        assert!(entry_is_approval_response(
7180            &json!({ "ok": false, "error": { "code": "timeout" } })
7181        ));
7182        // A user activity arriving mid-await has no top-level `ok`.
7183        assert!(!entry_is_approval_response(
7184            &json!({ "text": "hi", "metadata": { "action": "go" } })
7185        ));
7186        assert!(!entry_is_approval_response(&json!({})));
7187    }
7188
7189    #[test]
7190    fn outcome_reads_the_decision() {
7191        assert_eq!(
7192            approval_outcome_from_entry(
7193                &json!({ "ok": true, "output": { "decision": "approved" } })
7194            ),
7195            "approved"
7196        );
7197        assert_eq!(
7198            approval_outcome_from_entry(&json!({ "ok": true, "output": { "decision": "denied" } })),
7199            "denied"
7200        );
7201    }
7202
7203    #[test]
7204    fn timeout_wins_over_the_decision() {
7205        // The watchdog envelope has output: null and error.code == "timeout".
7206        assert_eq!(
7207            approval_outcome_from_entry(
7208                &json!({ "ok": false, "output": null, "error": { "code": "timeout" } })
7209            ),
7210            "timeout"
7211        );
7212    }
7213
7214    #[test]
7215    fn unknown_or_missing_decision_fails_closed_to_denied() {
7216        // Fail closed: a corrupt payload must never become a pass.
7217        assert_eq!(
7218            approval_outcome_from_entry(&json!({ "ok": true, "output": { "decision": "maybe" } })),
7219            "denied"
7220        );
7221        assert_eq!(
7222            approval_outcome_from_entry(&json!({ "ok": true, "output": {} })),
7223            "denied"
7224        );
7225        assert_eq!(
7226            approval_outcome_from_entry(&json!({ "ok": true })),
7227            "denied"
7228        );
7229        assert_eq!(
7230            approval_outcome_from_entry(&json!({ "ok": false, "error": { "code": "nats_down" } })),
7231            "denied"
7232        );
7233    }
7234
7235    #[test]
7236    fn a_failed_envelope_is_denied_even_if_it_carries_an_approval() {
7237        // Fail closed: `ok: false` with a non-timeout error must not pass,
7238        // regardless of a stale/forged decision field.
7239        assert_eq!(
7240            approval_outcome_from_entry(&json!({
7241                "ok": false,
7242                "error": { "code": "nats_down" },
7243                "output": { "decision": "approved" }
7244            })),
7245            "denied"
7246        );
7247    }
7248
7249    #[test]
7250    fn decision_match_is_case_insensitive() {
7251        assert_eq!(
7252            approval_outcome_from_entry(
7253                &json!({ "ok": true, "output": { "decision": "Approved" } })
7254            ),
7255            "approved"
7256        );
7257    }
7258}
7259
7260#[cfg(test)]
7261mod tests {
7262    use super::*;
7263    #[test]
7264    fn should_retry_typed_and_message_transient_errors() {
7265        assert!(should_retry(&anyhow!("internal server error")));
7266        assert!(should_retry(&anyhow!("service unavailable: timeout")));
7267        assert!(!should_retry(&anyhow!("bad request")));
7268        assert!(should_retry(&anyhow::Error::new(TransientFlowError(
7269            "upstream hiccup".into()
7270        ))));
7271        let wrapped = anyhow::Error::new(TransientFlowError("x".into())).context("node failed");
7272        assert!(should_retry(&wrapped));
7273        let io = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::TimedOut));
7274        assert!(should_retry(&io));
7275        let denied = anyhow::Error::new(std::io::Error::from(std::io::ErrorKind::PermissionDenied));
7276        assert!(!should_retry(&denied));
7277    }
7278
7279    #[test]
7280    fn branch_target_routes_on_status_then_default() {
7281        let a = NodeId::from_str("a").unwrap();
7282        let b = NodeId::from_str("b").unwrap();
7283        let d = NodeId::from_str("d").unwrap();
7284        let mut on_status = std::collections::BTreeMap::new();
7285        on_status.insert("approved".to_string(), a.clone());
7286        on_status.insert("true".to_string(), b.clone());
7287        let out = NodeOutput::new(json!({ "status": "approved" }));
7288        assert_eq!(branch_target(&on_status, Some(&d), &out), Some(a));
7289        let flag = NodeOutput::new(json!({ "status": true }));
7290        assert_eq!(branch_target(&on_status, Some(&d), &flag), Some(b));
7291        let unknown = NodeOutput::new(json!({ "status": "other" }));
7292        assert_eq!(
7293            branch_target(&on_status, Some(&d), &unknown),
7294            Some(d.clone())
7295        );
7296        let none = NodeOutput::new(json!({}));
7297        assert_eq!(branch_target(&on_status, None, &none), None);
7298    }
7299
7300    #[test]
7301    fn first_unhandled_failure_uses_execution_order_and_skips_handled_nodes() {
7302        let failed = |msg: &str| {
7303            let mut out = NodeOutput::new(json!({}));
7304            out.ok = false;
7305            out.meta = json!({ "error": { "message": msg } });
7306            out
7307        };
7308        let mut state = ExecutionState::new(json!({}));
7309        // Recorded z-then-a: execution order, not key order, decides.
7310        state.record_node_output("z_first".to_string(), failed("first"));
7311        state.record_node_output("a_second".to_string(), failed("second"));
7312
7313        let mut flow = HostFlow {
7314            id: "f".to_string(),
7315            start: None,
7316            nodes: IndexMap::new(),
7317            vars_init: JsonMap::new(),
7318            required_vars: Vec::new(),
7319            slot_schema: None,
7320        };
7321        let (id, _) = state.first_unhandled_failure(&flow).expect("a failure");
7322        assert_eq!(id, "z_first");
7323
7324        // Give `z_first` an error edge: its failure was routed, so the next
7325        // unhandled failure is the one lifted.
7326        let mut handled = HostNode::for_test("comp", Some("op"));
7327        handled.routing = Routing::Custom(json!([
7328            { "condition": "event == \"on_error\"", "to": "recover" }
7329        ]));
7330        flow.nodes
7331            .insert(NodeId::from_str("z_first").unwrap(), handled);
7332        let (id, _) = state.first_unhandled_failure(&flow).expect("a failure");
7333        assert_eq!(id, "a_second");
7334    }
7335
7336    /// The loader and the engine must agree on which op-keys are runner-native.
7337    ///
7338    /// `flow_adapter::NATIVE_OP_KEYS` decides which keys the LOADER preserves
7339    /// verbatim instead of wrapping in a `component.exec` node; the match in
7340    /// `component_label` above is what the ENGINE dispatches. Its doc says to
7341    /// keep the two in lockstep, and nothing enforced it — so `flow.goto`
7342    /// shipped with an engine arm the loader never routed a node to, which is
7343    /// silent: the node builds, loads as a generic component, and simply is not
7344    /// a goto any more.
7345    ///
7346    /// `native_op_key_for` exists to make that mechanical. It is an EXHAUSTIVE
7347    /// match, so adding a `NodeKind` variant fails to compile here until
7348    /// somebody says whether the loader must preserve it — which is the whole
7349    /// point; a test listing strings alone would have gone stale the same way
7350    /// the doc comment did.
7351    fn native_op_key_for(kind: &NodeKind) -> Option<&'static str> {
7352        match kind {
7353            // Not op-keys: these ARE the generic component paths.
7354            NodeKind::Exec { .. } | NodeKind::PackComponent { .. } => None,
7355            // Not simple op-keys: `emit.*` is prefix-matched by
7356            // `is_native_op_key`, and `mcp` / `a2a` are listed in the array but
7357            // reached through TWO spellings (the bare key and the
7358            // `mcp:<server>/<tool>` / `a2a:<agent_id>` ref), so neither maps to
7359            // one string. Both spellings are asserted below.
7360            NodeKind::BuiltinEmit { .. } | NodeKind::Mcp { .. } | NodeKind::A2a { .. } => None,
7361
7362            NodeKind::ProviderInvoke => Some("provider.invoke"),
7363            NodeKind::FlowCall => Some("flow.call"),
7364            NodeKind::FlowGoto => Some("flow.goto"),
7365            NodeKind::BuiltinStateGet => Some("state.get"),
7366            NodeKind::BuiltinStateSet => Some("state.set"),
7367            NodeKind::VarSet { .. } => Some("var.set"),
7368            NodeKind::MediaCreate => Some("media.create"),
7369            NodeKind::Wait => Some("session.wait"),
7370            NodeKind::DwAgent { .. } => Some("dw.agent"),
7371            NodeKind::DwAgentGraph { .. } => Some("dw.agent_graph"),
7372            NodeKind::SorlaCall { .. } => Some("sorla.call"),
7373            NodeKind::OperalaCall { .. } => Some("operala.call"),
7374            NodeKind::AgenticCall { .. } => Some("agentic.call"),
7375            NodeKind::TelcoXCall { .. } => Some("telco-x.call"),
7376            NodeKind::ApprovalCall { .. } => Some("approval.call"),
7377        }
7378    }
7379
7380    #[test]
7381    fn every_engine_dispatched_op_key_is_native_to_the_loader() {
7382        // Mirrors `component_label`'s builtin arms. Each string here is one the
7383        // engine will dispatch itself, so the loader must hand it through
7384        // unwrapped.
7385        for key in [
7386            "provider.invoke",
7387            "flow.call",
7388            "flow.goto",
7389            "state.get",
7390            "state.set",
7391            "var.set",
7392            "session.wait",
7393            "dw.agent",
7394            "dw.agent_graph",
7395            "sorla.call",
7396            "operala.call",
7397            "agentic.call",
7398            "telco-x.call",
7399            "approval.call",
7400            "media.create",
7401        ] {
7402            assert!(
7403                crate::runner::flow_adapter::is_native_op_key(key),
7404                "the engine dispatches `{key}`, but the loader does not treat it \
7405                 as native — it will be wrapped as a generic component and the \
7406                 engine arm becomes unreachable"
7407            );
7408        }
7409        // The two prefix families, which are deliberately not in the array.
7410        assert!(crate::runner::flow_adapter::is_native_op_key(
7411            "emit.response"
7412        ));
7413        assert!(crate::runner::flow_adapter::is_native_op_key(
7414            "mcp:srv/tool"
7415        ));
7416        // `mcp` and `a2a` are dispatched under both their bare key and their
7417        // self-contained ref form; the loader must hand both through.
7418        for key in ["mcp", "mcp:srv/tool", "a2a", "a2a:8d2f0c1e-recipe"] {
7419            assert!(
7420                crate::runner::flow_adapter::is_native_op_key(key),
7421                "the engine dispatches `{key}`, but the loader does not treat it as native"
7422            );
7423        }
7424        // And a genuine pack component must NOT be native.
7425        assert!(!crate::runner::flow_adapter::is_native_op_key("mcp.exec"));
7426        assert!(!crate::runner::flow_adapter::is_native_op_key("a2a.exec"));
7427
7428        // Keeps `native_op_key_for` live: its exhaustiveness is the guard.
7429        assert_eq!(native_op_key_for(&NodeKind::FlowGoto), Some("flow.goto"));
7430    }
7431
7432    // ── the `a2a` flow node's load-time and output-time rules ─────────────
7433
7434    /// The node is dispatched on `component == "a2a"`, so that string has to
7435    /// survive `runtime_flow_to_flow`'s `ComponentId::from_str` at pack load.
7436    /// `mcp` is a valid id for the same reason; `a2a:<agent_id>` is not, which
7437    /// is exactly why the payload — not the ref — is the source of truth.
7438    #[test]
7439    fn the_a2a_component_ref_is_a_valid_component_id() {
7440        assert!(greentic_types::ComponentId::from_str("a2a").is_ok());
7441    }
7442
7443    /// `media.create` is dispatched on its dotted component id, which must be a
7444    /// valid `ComponentId` and be classified (not split into
7445    /// `media` + `create`) by the loader.
7446    #[test]
7447    fn the_media_create_component_ref_is_a_valid_component_id() {
7448        assert!(greentic_types::ComponentId::from_str("media.create").is_ok());
7449        assert!(crate::runner::flow_adapter::is_native_op_key(
7450            "media.create"
7451        ));
7452        assert_eq!(
7453            native_op_key_for(&NodeKind::MediaCreate),
7454            Some("media.create")
7455        );
7456    }
7457
7458    #[cfg(feature = "agentic-worker")]
7459    #[test]
7460    fn a_media_failure_is_an_errored_node_only_with_an_error_route() {
7461        let result = json!({"ok": false, "error": {"code": "invalid_input", "message": "no text"}});
7462        let payload = json!({ "format": "pdf", "output": "file" });
7463        let quiet = media_node_output(bind_node_result(&payload, result.clone()), &result, false);
7464        assert!(quiet.ok);
7465        assert_eq!(quiet.payload["file"]["error"]["code"], "invalid_input");
7466        let routed = media_node_output(bind_node_result(&payload, result.clone()), &result, true);
7467        assert!(!routed.ok);
7468        assert_eq!(routed.payload["error"]["code"], "invalid_input");
7469        assert_eq!(routed.payload["error"]["message"], "no text");
7470        assert!(
7471            routed.payload["file"].is_object(),
7472            "the output key survives"
7473        );
7474        let good = json!({"ok": true, "artifact": {"id": "artifact://x"}});
7475        let out = media_node_output(good.clone(), &good, true);
7476        assert!(out.ok);
7477    }
7478
7479    #[test]
7480    fn a2a_node_kind_prefers_the_payload_over_the_ref() {
7481        let payload = json!({ "agent": "from-payload", "message": "hi" });
7482        assert!(matches!(
7483            a2a_node_kind(&payload, Some("a2a:from-ref")),
7484            NodeKind::A2a { agent_id } if agent_id == "from-payload"
7485        ));
7486    }
7487
7488    #[test]
7489    fn a2a_node_kind_falls_back_to_both_ref_spellings() {
7490        for reference in ["a2a:8d2f0c1e-recipe", "8d2f0c1e-recipe"] {
7491            assert!(
7492                matches!(
7493                    a2a_node_kind(&json!({ "message": "hi" }), Some(reference)),
7494                    NodeKind::A2a { agent_id } if agent_id == "8d2f0c1e-recipe"
7495                ),
7496                "{reference} must resolve the agent id"
7497            );
7498        }
7499    }
7500
7501    /// Flow loading stays total: a node naming no agent anywhere degrades to a
7502    /// generic component, which surfaces at RUN time as an ordinary
7503    /// unknown-component error rather than taking the whole pack down at load.
7504    #[test]
7505    fn an_a2a_node_naming_no_agent_loads_as_a_generic_component() {
7506        for legacy in [None, Some("a2a:"), Some("")] {
7507            assert!(
7508                matches!(
7509                    a2a_node_kind(&json!({ "message": "hi" }), legacy),
7510                    NodeKind::PackComponent { .. }
7511                ),
7512                "legacy={legacy:?} must not classify as an a2a node"
7513            );
7514        }
7515    }
7516
7517    #[cfg(feature = "agentic-worker")]
7518    fn a2a_result(status: &str, extra: (&str, &str)) -> Value {
7519        json!({ "status": status, "agent": "recipe", extra.0: extra.1 })
7520    }
7521
7522    /// The gate `mcp_node_output` already applies, for the same reason: a node
7523    /// with no error route has nowhere to send a failure, and a routing array
7524    /// that matches nothing PARKS the run.
7525    #[cfg(feature = "agentic-worker")]
7526    #[test]
7527    fn without_an_error_route_an_a2a_node_reports_ok_and_keeps_the_value() {
7528        let result = a2a_result("error", ("error", "card unreachable"));
7529        let output = a2a_node_output(bind_node_result(&json!({}), result.clone()), &result, false);
7530        assert!(output.ok);
7531        assert_eq!(output.payload["error"], "card unreachable");
7532    }
7533
7534    /// Only the two statuses that carry an `error` mark the node failed, and
7535    /// they keep DIFFERENT codes: `a2a_agent_failed` is the remote agent
7536    /// deciding something, `a2a_call_failed` is us never reaching it. An
7537    /// operator reading one goes to the remote agent's logs; the other, to
7538    /// this deployment's.
7539    #[cfg(feature = "agentic-worker")]
7540    #[test]
7541    fn only_a_failure_marks_an_a2a_node_errored_and_the_two_failures_keep_their_codes() {
7542        // (status, detail key, expected ok, expected code)
7543        let cases = [
7544            ("completed", "reply", true, None),
7545            ("input_required", "question", true, None),
7546            ("working", "detail", true, None),
7547            ("failed", "error", false, Some("a2a_agent_failed")),
7548            ("error", "error", false, Some("a2a_call_failed")),
7549        ];
7550        for (status, key, ok, code) in cases {
7551            let result = a2a_result(status, (key, "some text"));
7552            let output =
7553                a2a_node_output(bind_node_result(&json!({}), result.clone()), &result, true);
7554            assert_eq!(
7555                output.ok, ok,
7556                "status {status} produced {:?}",
7557                output.payload
7558            );
7559            assert_eq!(
7560                output.payload["status"], status,
7561                "the status must survive so a flow can still route on it"
7562            );
7563            match code {
7564                Some(code) => {
7565                    assert_eq!(output.payload["error"]["code"], code, "status {status}");
7566                    assert_eq!(output.payload["error"]["message"], "some text");
7567                }
7568                None => assert!(
7569                    output.payload["error"].is_null() || output.payload["error"].is_string(),
7570                    "status {status} must not be reshaped into an error envelope: {:?}",
7571                    output.payload
7572                ),
7573            }
7574        }
7575    }
7576
7577    /// A failed node's `output:` binding key must survive beside the error
7578    /// envelope, or `node.<id>.<key>` stops resolving the moment the agent
7579    /// fails — which is exactly when a flow needs to read it.
7580    #[cfg(feature = "agentic-worker")]
7581    #[test]
7582    fn a_failed_a2a_node_keeps_its_output_binding_key() {
7583        let result = a2a_result("failed", ("error", "the agent rejected the request"));
7584        let payload = json!({ "agent": "recipe", "message": "hi", "output": "answer" });
7585        let output = a2a_node_output(bind_node_result(&payload, result.clone()), &result, true);
7586        assert!(!output.ok);
7587        assert_eq!(output.payload["answer"]["status"], "failed");
7588        assert_eq!(output.payload["error"]["code"], "a2a_agent_failed");
7589    }
7590
7591    /// `bind_node_result` is shared with the `mcp` node, so both answer
7592    /// `output:` the same way: named key wraps, absent key passes through.
7593    #[cfg(feature = "agentic-worker")]
7594    #[test]
7595    fn the_output_binding_rule_is_one_rule_for_both_remote_tool_nodes() {
7596        let result = json!({ "status": "completed", "reply": "an omelette" });
7597        assert_eq!(
7598            bind_node_result(&json!({ "output": "answer" }), result.clone()),
7599            json!({ "answer": result })
7600        );
7601        for payload in [json!({}), json!({ "output": "" }), json!("not an object")] {
7602            assert_eq!(bind_node_result(&payload, result.clone()), result);
7603        }
7604    }
7605
7606    /// An unresolved `{{ }}` template renders to the empty string rather than
7607    /// failing, so a blank `message` is the shape a mistyped template takes.
7608    #[cfg(feature = "agentic-worker")]
7609    #[test]
7610    fn a_blank_message_is_recognised_as_nothing_to_send() {
7611        for blank in [json!(null), json!(""), json!("   ")] {
7612            assert!(is_blank(&blank), "{blank} must read as blank");
7613        }
7614        for present in [json!("hi"), json!(0), json!(false), json!({ "a": 1 })] {
7615            assert!(!is_blank(&present), "{present} must read as content");
7616        }
7617    }
7618
7619    // ── `sorla.call`: a route document wins over NATS (Task A5) ────────────
7620    //
7621    // The three-way `execute_sorla_http` unit tests (route resolves + a
7622    // matching capability, no route document, an unknown action) live beside
7623    // `execute_sorla_http` itself in `sorla_node.rs`. These two exercise the
7624    // ENGINE's choice between the HTTP path and NATS around it.
7625
7626    #[cfg(feature = "agentic-worker")]
7627    struct PanicIfDispatchedHandler;
7628
7629    #[cfg(feature = "agentic-worker")]
7630    #[async_trait::async_trait]
7631    impl crate::runner::remote_dispatch::RemoteDispatchHandler for PanicIfDispatchedHandler {
7632        async fn dispatch(
7633            &self,
7634            _request: crate::runner::remote_dispatch::RemoteDispatch,
7635        ) -> anyhow::Result<crate::runner::remote_dispatch::RemoteDispatchAction> {
7636            panic!(
7637                "a route document resolved for this SoR; NATS must never be reached \
7638                 (amendment A1: a route document always wins over NATS)"
7639            );
7640        }
7641    }
7642
7643    #[cfg(feature = "agentic-worker")]
7644    fn sorla_call_node(routing: Routing) -> HostNode {
7645        HostNode {
7646            kind: NodeKind::SorlaCall {
7647                target: "landlord".to_string(),
7648            },
7649            component: "sorla.call".into(),
7650            component_id: "sorla.call".into(),
7651            operation_name: None,
7652            operation_in_mapping: None,
7653            payload_expr: Value::Null,
7654            routing,
7655            vars_out: None,
7656            response_timeout_secs: None,
7657        }
7658    }
7659
7660    #[cfg(feature = "agentic-worker")]
7661    fn sorla_call_ctx() -> FlowContext<'static> {
7662        FlowContext {
7663            tenant: "acme",
7664            pack_id: "test-pack",
7665            flow_id: "f",
7666            node_id: None,
7667            tool: None,
7668            action: None,
7669            session_id: None,
7670            provider_id: None,
7671            reply_scope: None,
7672            retry_config: RetryConfig {
7673                max_attempts: 1,
7674                base_delay_ms: 1,
7675            },
7676            attempt: 1,
7677            observer: None,
7678            mocks: None,
7679            caller: None,
7680        }
7681    }
7682
7683    #[cfg(feature = "agentic-worker")]
7684    #[tokio::test]
7685    async fn a_route_document_wins_over_nats() {
7686        let server = wiremock::MockServer::start().await;
7687        wiremock::Mock::given(wiremock::matchers::method("GET"))
7688            .and(wiremock::matchers::path("/admin/v1/capabilities"))
7689            .respond_with(wiremock::ResponseTemplate::new(200).set_body_json(
7690                crate::runner::sorx_invoker::fixtures::caps_response_one_business_action(),
7691            ))
7692            .mount(&server)
7693            .await;
7694        wiremock::Mock::given(wiremock::matchers::method("POST"))
7695            .and(wiremock::matchers::path("/admin/v1/capabilities/invoke"))
7696            .respond_with(
7697                wiremock::ResponseTemplate::new(200)
7698                    .set_body_json(json!({"ok": true, "result": {"id": "pay-1"}})),
7699            )
7700            .mount(&server)
7701            .await;
7702
7703        let secrets = crate::runner::sorla_route::test_secrets::Handle::with(&[(
7704            "secrets://default/acme/_/sorla/landlord",
7705            &format!(r#"{{"url":"{}","tenant":"acme"}}"#, server.uri()),
7706        )])
7707        .manager();
7708
7709        let mut engine = minimal_engine();
7710        engine.mcp_secrets = Some(secrets);
7711        engine.remote_dispatch_handler = Some(Arc::new(PanicIfDispatchedHandler));
7712
7713        let ctx = sorla_call_ctx();
7714        let node = sorla_call_node(Routing::End);
7715        let mut state = ExecutionState::new(Value::Null);
7716        let payload = json!({
7717            "await": true,
7718            "operation": "record_rent_payment",
7719            "input": {"amount": 5},
7720        });
7721        let event = NodeEvent {
7722            context: &ctx,
7723            node_id: "call",
7724            node: &node,
7725            payload: &payload,
7726        };
7727
7728        let outcome = engine
7729            .dispatch_node(&ctx, "call", &node, &mut state, payload.clone(), &event)
7730            .await
7731            .expect("a resolved route document must dispatch over HTTP, never NATS");
7732
7733        assert!(outcome.output.ok);
7734        assert_eq!(
7735            outcome.output.payload,
7736            json!({"id": "pay-1"}),
7737            "the node output must be the HTTP result"
7738        );
7739    }
7740
7741    /// A secrets BACKEND failure (as opposed to a genuine miss) must never
7742    /// read as "no route document" and fall back to NATS — the backend
7743    /// failing to answer says nothing about whether a route document
7744    /// exists. `PanicIfDispatchedHandler` proves NATS is never touched.
7745    #[cfg(feature = "agentic-worker")]
7746    #[tokio::test]
7747    async fn a_backend_failure_never_falls_back_to_nats() {
7748        let secrets = crate::runner::sorla_route::test_secrets::Handle::with(&[]);
7749        secrets.fail(
7750            "secrets://default/acme/_/sorla/landlord",
7751            "connection refused",
7752        );
7753
7754        let mut engine = minimal_engine();
7755        engine.mcp_secrets = Some(secrets.manager());
7756        engine.remote_dispatch_handler = Some(Arc::new(PanicIfDispatchedHandler));
7757
7758        let ctx = sorla_call_ctx();
7759        let node = sorla_call_node(Routing::End);
7760        let mut state = ExecutionState::new(Value::Null);
7761        let payload = json!({
7762            "await": true,
7763            "operation": "record_rent_payment",
7764            "input": {},
7765        });
7766        let event = NodeEvent {
7767            context: &ctx,
7768            node_id: "call",
7769            node: &node,
7770            payload: &payload,
7771        };
7772
7773        let result = engine
7774            .dispatch_node(&ctx, "call", &node, &mut state, payload.clone(), &event)
7775            .await;
7776        let err = match result {
7777            Err(err) => err,
7778            Ok(_) => panic!("a backend failure must fail the node, not silently succeed"),
7779        };
7780        assert!(err.to_string().contains("could not be read"), "got: {err}");
7781    }
7782
7783    #[cfg(feature = "agentic-worker")]
7784    #[tokio::test]
7785    async fn no_route_and_no_nats_fails_with_sorla_route_missing() {
7786        // `minimal_engine()` sets neither `mcp_secrets` nor
7787        // `remote_dispatch_handler`, so no route document can ever resolve and
7788        // there is no NATS fallback either.
7789        let engine = minimal_engine();
7790        let ctx = sorla_call_ctx();
7791        let payload = json!({
7792            "await": true,
7793            "operation": "record_rent_payment",
7794            "input": {},
7795        });
7796
7797        // No `on_error` route: a hard `Err`.
7798        let node = sorla_call_node(Routing::End);
7799        let mut state = ExecutionState::new(Value::Null);
7800        let event = NodeEvent {
7801            context: &ctx,
7802            node_id: "call",
7803            node: &node,
7804            payload: &payload,
7805        };
7806        let result = engine
7807            .dispatch_node(&ctx, "call", &node, &mut state, payload.clone(), &event)
7808            .await;
7809        let err = match result {
7810            Err(err) => err,
7811            Ok(_) => panic!("no route document and no NATS handler must fail the node"),
7812        };
7813        assert!(
7814            err.to_string().contains("sorla_route_missing"),
7815            "got: {err}"
7816        );
7817
7818        // An `on_error` route: `ok: false` naming `sorla_route_missing`, never
7819        // a hard `Err` — mirrors `mcp_node_output`'s `has_error_route` gate.
7820        let node = sorla_call_node(Routing::Custom(json!([
7821            { "condition": "event == \"on_success\"", "to": "n" },
7822            { "condition": "event == \"on_error\"", "to": "e" },
7823        ])));
7824        let mut state = ExecutionState::new(Value::Null);
7825        let event = NodeEvent {
7826            context: &ctx,
7827            node_id: "call",
7828            node: &node,
7829            payload: &payload,
7830        };
7831        let outcome = engine
7832            .dispatch_node(&ctx, "call", &node, &mut state, payload.clone(), &event)
7833            .await
7834            .expect("an error-routed node must complete, not hard-fail");
7835        assert!(!outcome.output.ok);
7836        let message = outcome
7837            .output
7838            .payload
7839            .get("error")
7840            .and_then(Value::as_str)
7841            .unwrap_or_default();
7842        assert!(message.contains("sorla_route_missing"), "got: {message}");
7843    }
7844
7845    /// The HTTP approval inbox lives in its own slot: installing it must not
7846    /// turn a missing SoR route document into a `sorla` remote dispatch.
7847    #[cfg(feature = "agentic-worker")]
7848    #[tokio::test]
7849    async fn an_approval_inbox_leaves_sorla_route_missing_intact() {
7850        let mut engine = minimal_engine();
7851        engine.set_approval_dispatch_handler(Arc::new(PanicIfDispatchedHandler));
7852        let ctx = sorla_call_ctx();
7853        let payload = json!({
7854            "await": true,
7855            "operation": "record_rent_payment",
7856            "input": {},
7857        });
7858        let node = sorla_call_node(Routing::End);
7859        let mut state = ExecutionState::new(Value::Null);
7860        let event = NodeEvent {
7861            context: &ctx,
7862            node_id: "call",
7863            node: &node,
7864            payload: &payload,
7865        };
7866        let err = match engine
7867            .dispatch_node(&ctx, "call", &node, &mut state, payload.clone(), &event)
7868            .await
7869        {
7870            Err(err) => err,
7871            Ok(_) => panic!("a missing route with only the approval inbox must fail the node"),
7872        };
7873        assert!(
7874            err.to_string().contains("sorla_route_missing"),
7875            "got: {err}"
7876        );
7877    }
7878
7879    /// `approval.call` goes through the approval slot, issued a token; every
7880    /// other runtime ignores that slot.
7881    #[cfg(feature = "agentic-worker")]
7882    #[tokio::test]
7883    async fn only_approval_dispatches_use_the_approval_slot() {
7884        let inbox = Arc::new(ScriptedNatsDispatcher {
7885            calls: Mutex::new(vec![]),
7886        });
7887        let mut engine = minimal_engine();
7888        engine.set_approval_dispatch_handler(inbox.clone());
7889
7890        let ctx = sorla_call_ctx();
7891        let node = HostNode::for_test_approval("hitl");
7892        let mut state = ExecutionState::new(Value::Null);
7893        let payload = json!({ "await": true, "input": { "mode": "always" } });
7894        let event = NodeEvent {
7895            context: &ctx,
7896            node_id: "gate",
7897            node: &node,
7898            payload: &payload,
7899        };
7900        let outcome = engine
7901            .dispatch_node(&ctx, "gate", &node, &mut state, payload.clone(), &event)
7902            .await
7903            .expect("approval.call must dispatch through the approval slot");
7904        assert!(matches!(outcome.control, NodeControl::AwaitHere { .. }));
7905        {
7906            let calls = inbox.calls.lock().unwrap();
7907            assert_eq!(calls.len(), 1);
7908            assert_eq!(calls[0].runtime, APPROVAL_RUNTIME);
7909            assert!(calls[0].decision_token.is_some());
7910            assert!(
7911                crate::runner::runtime_session_resumer::split_dispatch_nonce(
7912                    &calls[0].correlation_id
7913                )
7914                .1
7915                .is_some(),
7916                "the id carries its per-dispatch nonce"
7917            );
7918        }
7919        let parked = state.pending_approvals();
7920        assert_eq!(parked.len(), 1);
7921        assert!(parked[0].token_fingerprint.is_some());
7922
7923        let err = engine
7924            .execute_remote_dispatch(&ctx, "telco-x", "t", json!({"await": true}), true)
7925            .await
7926            .err()
7927            .expect("a non-approval runtime must not use the approval slot");
7928        assert!(
7929            err.to_string()
7930                .contains("no RemoteDispatchHandler configured"),
7931            "got: {err}"
7932        );
7933        assert_eq!(inbox.calls.lock().unwrap().len(), 1);
7934    }
7935
7936    /// With both slots set (NATS alongside), `approval.call` prefers the
7937    /// approval slot; with only the shared slot it still uses that.
7938    #[cfg(feature = "agentic-worker")]
7939    #[tokio::test]
7940    async fn approval_falls_back_to_the_shared_slot() {
7941        let shared = Arc::new(ScriptedNatsDispatcher {
7942            calls: Mutex::new(vec![]),
7943        });
7944        let mut engine = minimal_engine();
7945        engine.set_remote_dispatch_handler(shared.clone());
7946        let ctx = sorla_call_ctx();
7947        let node = HostNode::for_test_approval("hitl");
7948        let mut state = ExecutionState::new(Value::Null);
7949        let payload = json!({ "await": true, "input": { "mode": "always" } });
7950        let event = NodeEvent {
7951            context: &ctx,
7952            node_id: "gate",
7953            node: &node,
7954            payload: &payload,
7955        };
7956        engine
7957            .dispatch_node(&ctx, "gate", &node, &mut state, payload.clone(), &event)
7958            .await
7959            .expect("approval.call must fall back to the shared slot");
7960        assert_eq!(shared.calls.lock().unwrap().len(), 1);
7961    }
7962
7963    use crate::validate::{ValidationConfig, ValidationMode};
7964    use greentic_types::{
7965        Flow, FlowComponentRef, FlowId, FlowKind, FlowMetadata, InputMapping, Node, NodeId,
7966        OutputMapping, Routing, TelemetryHints,
7967    };
7968    use serde_json::json;
7969    use std::collections::{BTreeMap, HashMap as StdHashMap};
7970    use std::str::FromStr;
7971    use std::sync::Mutex;
7972    use tokio::runtime::Runtime;
7973
7974    fn minimal_engine() -> FlowEngine {
7975        FlowEngine {
7976            packs: Vec::new(),
7977            flows: Vec::new(),
7978            flow_sources: HashMap::new(),
7979            messaging_provider_pack_ids: std::collections::HashSet::new(),
7980            flow_cache: RwLock::new(HashMap::new()),
7981            default_env: "local".to_string(),
7982            validation: ValidationConfig {
7983                mode: ValidationMode::Off,
7984            },
7985            cross_pack_resolver: None,
7986            rollout_ids: RolloutIds::default(),
7987            approval_dispatch_handler: None,
7988            remote_dispatch_handler: None,
7989            #[cfg(feature = "agentic-worker")]
7990            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
7991            #[cfg(feature = "agentic-worker")]
7992            agent_node_handler: None,
7993            #[cfg(feature = "agentic-worker")]
7994            graph_node_handler: None,
7995            #[cfg(feature = "agentic-worker")]
7996            mcp_tool_source: None,
7997            #[cfg(feature = "agentic-worker")]
7998            mcp_secrets: None,
7999            #[cfg(feature = "agentic-worker")]
8000            a2a_sources: RwLock::new(HashMap::new()),
8001            #[cfg(feature = "agentic-worker")]
8002            ext_artifact_port: None,
8003            operala_node_handler: None,
8004        }
8005    }
8006
8007    /// A distinguishable no-op manager. The tests below assert WHICH manager
8008    /// an `mcp` node would dispatch with, via `Arc::ptr_eq`.
8009    #[cfg(feature = "agentic-worker")]
8010    struct StubSecrets;
8011
8012    #[cfg(feature = "agentic-worker")]
8013    #[async_trait::async_trait]
8014    impl greentic_secrets_lib::SecretsManager for StubSecrets {
8015        async fn read(&self, _path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
8016            Ok(Vec::new())
8017        }
8018        async fn write(&self, _path: &str, _bytes: &[u8]) -> greentic_secrets_lib::Result<()> {
8019            Ok(())
8020        }
8021        async fn delete(&self, _path: &str) -> greentic_secrets_lib::Result<()> {
8022            Ok(())
8023        }
8024    }
8025
8026    /// `execute_mcp` reads `mcp_secrets_for_dispatch`; before this it read a
8027    /// process-global built from `SECRETS_BACKEND`, which no Cloud Run or
8028    /// Kubernetes deployment sets — so a `secrets://` URI resolved as a literal
8029    /// variable name and every credential lookup missed.
8030    ///
8031    /// `#[serial]` because `mcp_secrets_for_dispatch` reads `SECRETS_BACKEND`,
8032    /// which the env-mutating tests in `mcp_node` set and restore.
8033    #[cfg(feature = "agentic-worker")]
8034    #[test]
8035    #[serial_test::serial]
8036    fn an_injected_manager_is_what_an_mcp_node_dispatches_with() {
8037        let injected: crate::secrets::DynSecretsManager = std::sync::Arc::new(StubSecrets);
8038        let engine = minimal_engine().with_mcp_secrets(Some(injected.clone()));
8039        let chosen = engine
8040            .mcp_secrets_for_dispatch()
8041            .expect("an injected manager is always a choice");
8042        assert!(std::sync::Arc::ptr_eq(&chosen, &injected));
8043    }
8044
8045    /// A standalone runner must be unaffected: with nothing injected the engine
8046    /// still falls back to the env-derived manager exactly as before.
8047    #[cfg(feature = "agentic-worker")]
8048    #[test]
8049    fn no_injection_leaves_the_env_derived_behaviour_alone() {
8050        let engine = minimal_engine();
8051        assert!(engine.mcp_secrets.is_none());
8052    }
8053
8054    /// `None` must LEAVE an already-bound manager in place, mirroring
8055    /// `with_mcp_source`: callers thread this straight through from a host that
8056    /// may not have one.
8057    #[cfg(feature = "agentic-worker")]
8058    #[test]
8059    #[serial_test::serial]
8060    fn binding_no_manager_does_not_clear_one_already_bound() {
8061        let injected: crate::secrets::DynSecretsManager = std::sync::Arc::new(StubSecrets);
8062        let engine = minimal_engine()
8063            .with_mcp_secrets(Some(injected.clone()))
8064            .with_mcp_secrets(None);
8065        let chosen = engine
8066            .mcp_secrets_for_dispatch()
8067            .expect("the bound manager must survive");
8068        assert!(std::sync::Arc::ptr_eq(&chosen, &injected));
8069    }
8070
8071    fn flow_desc(id: &str, pack_id: &str, flow_type: &str, entry: bool) -> FlowDescriptor {
8072        FlowDescriptor {
8073            id: id.into(),
8074            flow_type: flow_type.into(),
8075            pack_id: pack_id.into(),
8076            profile: pack_id.into(),
8077            version: "0.0.0".into(),
8078            description: None,
8079            entry,
8080        }
8081    }
8082
8083    #[test]
8084    fn entry_flow_by_type_disambiguates_entrypoint_from_internal_helpers() {
8085        // Regression: a pack with one public messaging entrypoint (`default`)
8086        // plus internal helper flows of the same type (dispatcher sub-flows)
8087        // must route an inbound, type-only provider event to the entrypoint —
8088        // NOT fail as "flow type messaging is ambiguous; pack_id is required".
8089        let mut engine = minimal_engine();
8090        engine.flows = vec![
8091            flow_desc("default", "weatherapi-pack", "messaging", true),
8092            flow_desc("flow_", "weatherapi-pack", "messaging", false),
8093            flow_desc("flow_error", "weatherapi-pack", "messaging", false),
8094            flow_desc("flow_get_weather", "weatherapi-pack", "messaging", false),
8095        ];
8096
8097        // Multiple flows of the type => the plain lookup is ambiguous...
8098        assert!(
8099            engine.flow_by_type("messaging").is_none(),
8100            "multiple messaging flows must be ambiguous for the plain lookup"
8101        );
8102        // ...but exactly one is an entrypoint, so entry-aware routing resolves.
8103        let resolved = engine
8104            .entry_flow_by_type("messaging")
8105            .expect("single entry flow must resolve");
8106        assert_eq!(resolved.id, "default");
8107        assert_eq!(resolved.pack_id, "weatherapi-pack");
8108    }
8109
8110    #[test]
8111    fn entry_flow_by_type_still_ambiguous_across_two_entrypoints() {
8112        // Two entrypoints of the same type across packs is genuinely ambiguous
8113        // and must still require a pack_id (no silent, arbitrary pick).
8114        let mut engine = minimal_engine();
8115        engine.flows = vec![
8116            flow_desc("default", "pack.a", "messaging", true),
8117            flow_desc("default", "pack.b", "messaging", true),
8118            flow_desc("helper", "pack.a", "messaging", false),
8119        ];
8120        assert!(engine.entry_flow_by_type("messaging").is_none());
8121    }
8122
8123    #[test]
8124    fn entry_flow_by_type_excludes_messaging_provider_pack_flows() {
8125        // Multi-provider bundle: the app pack's entry flow AND a messaging
8126        // *provider* pack's ingress `main` are both entry `messaging` flows.
8127        // The provider flow is that provider's plumbing, not the application
8128        // entrypoint, so a type-only webchat event must resolve to the app flow
8129        // — not bail "flow type messaging is ambiguous; pack_id is required".
8130        let mut engine = minimal_engine();
8131        engine.flows = vec![
8132            flow_desc("main", "hr-onboarding-pack", "messaging", true),
8133            flow_desc("main", "messaging-teams", "messaging", true),
8134        ];
8135        // `messaging-teams` declares a `messaging.*` provider in its manifest;
8136        // the engine records that at build time.
8137        engine
8138            .messaging_provider_pack_ids
8139            .insert("messaging-teams".to_string());
8140
8141        // Plain lookup is still ambiguous (two flows of the type)...
8142        assert!(engine.flow_by_type("messaging").is_none());
8143        // ...but only the app pack's flow is an *application* entrypoint.
8144        let resolved = engine
8145            .entry_flow_by_type("messaging")
8146            .expect("app entry flow must resolve past the provider flow");
8147        assert_eq!(resolved.id, "main");
8148        assert_eq!(resolved.pack_id, "hr-onboarding-pack");
8149    }
8150
8151    #[test]
8152    fn entry_flow_by_type_matches_plain_lookup_for_single_flow() {
8153        // Backward-compat: a lone flow of a type resolves the same way through
8154        // both paths, tagged entry or not.
8155        let mut engine = minimal_engine();
8156        engine.flows = vec![flow_desc("only", "pack.a", "messaging", true)];
8157        assert_eq!(
8158            engine.flow_by_type("messaging").map(|f| f.id.as_str()),
8159            Some("only")
8160        );
8161        assert_eq!(
8162            engine
8163                .entry_flow_by_type("messaging")
8164                .map(|f| f.id.as_str()),
8165            Some("only")
8166        );
8167    }
8168
8169    #[test]
8170    fn to_node_output_legacy_success_becomes_data() {
8171        // Legacy `{ok:true, ...fields}` (no node_io envelope) → Data{data}.
8172        let out = to_node_output(&json!({ "ok": true, "temp": "20C" }));
8173        assert!(out.is_ok(), "legacy ok:true must classify as Data");
8174        let data = out.data().expect("data present");
8175        assert_eq!(data.get("temp").and_then(Value::as_str), Some("20C"));
8176    }
8177
8178    #[test]
8179    fn to_node_output_legacy_error_becomes_errors() {
8180        // Legacy `{ok:false, error:{code,message}}` → Errors{errors:[NodeError]}.
8181        let out = to_node_output(
8182            &json!({ "ok": false, "error": { "code": "E_BAD", "message": "boom" } }),
8183        );
8184        assert!(!out.is_ok(), "legacy ok:false must classify as Errors");
8185        let errs = out.errors();
8186        assert_eq!(errs.len(), 1);
8187        assert_eq!(errs[0].code, "E_BAD");
8188        assert_eq!(errs[0].message, "boom");
8189    }
8190
8191    #[test]
8192    fn to_node_output_native_data_envelope_roundtrips() {
8193        // A node_io-native `{data:{...}}` envelope parses straight to Data.
8194        let out = to_node_output(&json!({ "data": { "x": 1 } }));
8195        assert!(out.is_ok());
8196        assert_eq!(
8197            out.data().and_then(|d| d.get("x")).and_then(Value::as_i64),
8198            Some(1)
8199        );
8200    }
8201
8202    #[test]
8203    fn to_node_output_native_errors_envelope_roundtrips() {
8204        // A node_io-native `{errors:[...]}` envelope parses straight to Errors.
8205        let out = to_node_output(&json!({
8206            "errors": [ { "code": "C", "message": "m", "kind": "validation",
8207                          "retryable": false, "details": {} } ]
8208        }));
8209        assert!(!out.is_ok());
8210        assert_eq!(out.errors()[0].code, "C");
8211        assert_eq!(
8212            out.errors()[0].kind,
8213            greentic_types::node_io::ErrorKind::Validation
8214        );
8215    }
8216
8217    #[test]
8218    fn to_node_output_bare_object_becomes_data() {
8219        // A bare result with no envelope keys → Data{data: <whole value>}.
8220        let out = to_node_output(&json!({ "foo": 1 }));
8221        assert!(out.is_ok());
8222        assert_eq!(
8223            out.data()
8224                .and_then(|d| d.get("foo"))
8225                .and_then(Value::as_i64),
8226            Some(1)
8227        );
8228    }
8229
8230    #[test]
8231    fn templating_renders_with_partials_and_data() {
8232        let mut state = ExecutionState::new(json!({ "city": "London" }));
8233        state.nodes.insert(
8234            "forecast".to_string(),
8235            NodeOutput::new(json!({ "temp": "20C" })),
8236        );
8237
8238        // templating context includes node outputs for runner-side payload rendering.
8239        let ctx = state.context();
8240        assert_eq!(ctx["nodes"]["forecast"]["payload"]["temp"], json!("20C"));
8241    }
8242
8243    #[test]
8244    fn outputs_map_exposes_node_io_data_and_errors_alongside_flat() {
8245        let mut state = ExecutionState::new(json!({}));
8246        state.nodes.insert(
8247            "forecast".to_string(),
8248            NodeOutput::new(json!({ "temp": "20C" })),
8249        );
8250        let outs = state.outputs_map();
8251        // Legacy flat ref `{{node.forecast.temp}}` keeps working.
8252        assert_eq!(outs["forecast"]["temp"], json!("20C"));
8253        // Canonical node_io ref `{{node.forecast.data.temp}}` resolves to the same.
8254        assert_eq!(outs["forecast"]["data"]["temp"], json!("20C"));
8255        // `{{node.forecast.errors}}` is present and empty for a success output.
8256        assert_eq!(outs["forecast"]["errors"], json!([]));
8257    }
8258
8259    #[test]
8260    fn finalize_wraps_emitted_payloads() {
8261        let mut state = ExecutionState::new(json!({}));
8262        state.push_egress(json!({ "text": "first" }));
8263        state.push_egress(json!({ "text": "second" }));
8264        let result = state.finalize_with(Some(json!({ "text": "final" })));
8265        assert_eq!(
8266            result,
8267            json!([
8268                { "text": "first" },
8269                { "text": "second" },
8270                { "text": "final" }
8271            ])
8272        );
8273    }
8274
8275    #[test]
8276    fn finalize_does_not_double_terminal_emit_response() {
8277        // Regression: a terminal `emit.response` node pushes its card to egress
8278        // AND returns it as the node output, which the `End` path passes as
8279        // `final_payload`. The card must appear ONCE, not twice (the webchat
8280        // "double card").
8281        let card = json!({ "renderedCard": { "type": "AdaptiveCard" } });
8282        let mut state = ExecutionState::new(json!({}));
8283        state.push_egress(card.clone());
8284        let result = state.finalize_with(Some(card.clone()));
8285        assert_eq!(result, json!([card]));
8286    }
8287
8288    #[test]
8289    fn finalize_still_appends_distinct_terminal_output() {
8290        // A terminal output that differs from the last emitted response is a
8291        // genuine additional reply and must still be appended.
8292        let mut state = ExecutionState::new(json!({}));
8293        state.push_egress(json!({ "text": "emitted" }));
8294        let result = state.finalize_with(Some(json!({ "text": "final" })));
8295        assert_eq!(result, json!([{ "text": "emitted" }, { "text": "final" }]));
8296    }
8297
8298    #[test]
8299    fn alias_input_to_entry_exposes_input_for_bare_message() {
8300        // Env/revision path: the flow entry IS the message — metadata at the
8301        // top level, no `input` wrapper. After aliasing, the pack's
8302        // `in.input.metadata.*` template resolves the same as `in.metadata.*`.
8303        let msg = json!({ "text": "hi", "metadata": { "operation": "get_weather" } });
8304        let aliased = alias_input_to_entry(msg);
8305        assert_eq!(
8306            aliased.pointer("/metadata/operation"),
8307            Some(&json!("get_weather"))
8308        );
8309        assert_eq!(
8310            aliased.pointer("/input/metadata/operation"),
8311            Some(&json!("get_weather"))
8312        );
8313    }
8314
8315    #[test]
8316    fn alias_input_to_entry_preserves_explicit_input_wrapper() {
8317        // Legacy `{input: <message>}` entries must not be double-wrapped.
8318        let wrapped = json!({ "input": { "metadata": { "operation": "x" } } });
8319        assert_eq!(alias_input_to_entry(wrapped.clone()), wrapped);
8320    }
8321
8322    #[test]
8323    fn alias_input_to_entry_ignores_non_objects() {
8324        assert_eq!(alias_input_to_entry(json!("hi")), json!("hi"));
8325        assert_eq!(alias_input_to_entry(json!(null)), json!(null));
8326    }
8327
8328    /// Render one template string against the context a node parameter sees.
8329    fn render_entry(entry: Value, expr: &str) -> Value {
8330        let st = ExecutionState::new(entry);
8331        let ctx = template_context(&st, Value::Null);
8332        render_template_value(&json!(expr), &ctx, TemplateOptions::default())
8333            .expect("template renders")
8334    }
8335
8336    #[test]
8337    fn entry_root_exposes_submitted_fields_on_the_wrapped_path() {
8338        // greentic-start wraps the activity, so the submitted field lands at
8339        // entry.input.metadata.* and `{{entry.company_size}}` used to render
8340        // the empty string with no warning at any layer.
8341        let entry = json!({
8342            "input": {
8343                "metadata": { "action": "submit", "company_size": "11-50" },
8344                "text": "hi"
8345            },
8346            "tenant": "acme",
8347            "correlation_id": "c-1"
8348        });
8349
8350        assert_eq!(
8351            render_entry(entry.clone(), "{{entry.company_size}}"),
8352            json!("11-50")
8353        );
8354        // `in` is an alias of `entry`, so it must resolve identically.
8355        assert_eq!(
8356            render_entry(entry.clone(), "{{in.company_size}}"),
8357            json!("11-50")
8358        );
8359        // The raw paths a digest-pinned pack already reads keep working.
8360        assert_eq!(
8361            render_entry(entry.clone(), "{{entry.input.metadata.company_size}}"),
8362            json!("11-50")
8363        );
8364        assert_eq!(
8365            render_entry(entry.clone(), "{{in.input.metadata.company_size}}"),
8366            json!("11-50")
8367        );
8368        // The envelope's own keys are untouched.
8369        assert_eq!(
8370            render_entry(entry.clone(), "{{entry.tenant}}"),
8371            json!("acme")
8372        );
8373        assert_eq!(
8374            render_entry(entry.clone(), "{{entry.correlation_id}}"),
8375            json!("c-1")
8376        );
8377        // `text` and `action` are not merged as fields, but stay reachable raw.
8378        assert_eq!(
8379            render_entry(entry.clone(), "{{entry.input.text}}"),
8380            json!("hi")
8381        );
8382        assert_eq!(
8383            render_entry(entry, "{{entry.input.metadata.action}}"),
8384            json!("submit")
8385        );
8386    }
8387
8388    #[test]
8389    fn entry_root_exposes_submitted_fields_on_the_demo_path() {
8390        // Run Demo puts input ids at the entry ROOT beside `metadata`, so the
8391        // root field already resolved — but a metadata-only field did not.
8392        // Both lanes must now agree.
8393        let entry = json!({
8394            "company_size": "11-50",
8395            "metadata": { "action": "submit", "email": "a@b.c" },
8396            "text": "hi"
8397        });
8398
8399        assert_eq!(
8400            render_entry(entry.clone(), "{{entry.company_size}}"),
8401            json!("11-50")
8402        );
8403        assert_eq!(
8404            render_entry(entry.clone(), "{{entry.email}}"),
8405            json!("a@b.c")
8406        );
8407        // Raw paths still resolve on this shape too.
8408        assert_eq!(
8409            render_entry(entry.clone(), "{{entry.metadata.email}}"),
8410            json!("a@b.c")
8411        );
8412        // The envelope body keeps its own meaning rather than being overwritten.
8413        assert_eq!(render_entry(entry, "{{entry.text}}"), json!("hi"));
8414    }
8415
8416    #[test]
8417    fn entry_merge_never_clobbers_an_existing_root_key() {
8418        // A submitted field colliding with an envelope key must lose: `tenant`
8419        // is the caller's identity, not a form input.
8420        let entry = json!({
8421            "input": {
8422                "metadata": { "tenant": "evil", "company_size": "11-50" }
8423            },
8424            "tenant": "acme"
8425        });
8426
8427        assert_eq!(
8428            render_entry(entry.clone(), "{{entry.tenant}}"),
8429            json!("acme")
8430        );
8431        assert_eq!(
8432            render_entry(entry.clone(), "{{entry.company_size}}"),
8433            json!("11-50")
8434        );
8435        // `input` itself must survive as the envelope object.
8436        assert_eq!(
8437            render_entry(entry, "{{entry.input.metadata.company_size}}"),
8438            json!("11-50")
8439        );
8440    }
8441
8442    #[test]
8443    fn entry_and_in_stay_identical_after_the_merge() {
8444        let entry = json!({
8445            "input": { "metadata": { "action": "submit", "email": "a@b.c" } },
8446            "tenant": "acme"
8447        });
8448        let st = ExecutionState::new(entry);
8449        let ctx = template_context(&st, Value::Null);
8450        assert_eq!(
8451            ctx.pointer("/entry"),
8452            ctx.pointer("/in"),
8453            "`in` is an alias of `entry` and must not drift from it"
8454        );
8455    }
8456
8457    #[test]
8458    fn entry_merge_leaves_a_non_object_entry_untouched() {
8459        // A bare string/null entry has no root to merge into; it must pass
8460        // through exactly as `alias_input_to_entry` leaves it.
8461        assert_eq!(
8462            merge_submitted_fields_into_entry(json!("hi"), JsonMap::new()),
8463            json!("hi")
8464        );
8465        let mut fields = JsonMap::new();
8466        fields.insert("x".into(), json!(1));
8467        assert_eq!(
8468            merge_submitted_fields_into_entry(json!(null), fields),
8469            json!(null)
8470        );
8471    }
8472
8473    #[test]
8474    fn finalize_flattens_final_array() {
8475        let mut state = ExecutionState::new(json!({}));
8476        state.push_egress(json!({ "text": "only" }));
8477        let result = state.finalize_with(Some(json!([
8478            { "text": "extra-1" },
8479            { "text": "extra-2" }
8480        ])));
8481        assert_eq!(
8482            result,
8483            json!([
8484                { "text": "only" },
8485                { "text": "extra-1" },
8486                { "text": "extra-2" }
8487            ])
8488        );
8489    }
8490
8491    #[test]
8492    fn inject_card_locale_uses_entry_metadata_without_overwriting_payload() {
8493        let mut payload = json!({
8494            "card_source": "inline",
8495            "card_spec": { "title": "Hello" }
8496        });
8497        inject_card_locale(
8498            &mut payload,
8499            &json!({"input": {"metadata": {"locale": "nl-NL"}}}),
8500        );
8501        assert_eq!(payload["locale"], json!("nl-NL"));
8502
8503        let mut existing = json!({
8504            "card_source": "inline",
8505            "card_spec": { "title": "Hello" },
8506            "locale": "en-GB"
8507        });
8508        inject_card_locale(&mut existing, &json!({"metadata": {"locale": "nl-NL"}}));
8509        assert_eq!(existing["locale"], json!("en-GB"));
8510    }
8511
8512    #[test]
8513    fn load_i18n_bundle_entries_reads_manifest_and_falls_back_to_en() {
8514        let assets = StdHashMap::from([
8515            (
8516                "cards/i18n/_manifest.json".to_string(),
8517                br#"{"locales":["de"]}"#.to_vec(),
8518            ),
8519            (
8520                "cards/i18n/de.json".to_string(),
8521                br#"{"title":"Hallo"}"#.to_vec(),
8522            ),
8523            (
8524                "cards/i18n/en.json".to_string(),
8525                br#"{"title":"Hello"}"#.to_vec(),
8526            ),
8527        ]);
8528
8529        let entries = load_i18n_bundle_entries("cards/i18n", |path| {
8530            assets
8531                .get(path)
8532                .cloned()
8533                .with_context(|| format!("missing asset {path}"))
8534        });
8535
8536        assert_eq!(entries["de"]["title"], json!("Hallo"));
8537        assert_eq!(entries["en"]["title"], json!("Hello"));
8538    }
8539
8540    #[test]
8541    fn load_i18n_bundle_entries_reads_single_file_bundle() {
8542        let entries = load_i18n_bundle_entries("cards/i18n.json", |path| {
8543            if path == "cards/i18n.json" {
8544                Ok(br#"{"title":"Hello"}"#.to_vec())
8545            } else {
8546                bail!("unexpected asset {path}");
8547            }
8548        });
8549
8550        assert_eq!(entries["en"]["title"], json!("Hello"));
8551    }
8552
8553    struct TestCrossPackResolver;
8554
8555    impl CrossPackResolver for TestCrossPackResolver {
8556        fn invoke(
8557            &self,
8558            provider_id: &str,
8559            provider_type: Option<&str>,
8560            op: &str,
8561            input: &[u8],
8562            tenant: &str,
8563            team: Option<&str>,
8564        ) -> Result<Value> {
8565            Ok(json!({
8566                "provider_id": provider_id,
8567                "provider_type": provider_type,
8568                "op": op,
8569                "tenant": tenant,
8570                "team": team,
8571                "input": serde_json::from_slice::<Value>(input)?,
8572            }))
8573        }
8574    }
8575
8576    #[test]
8577    fn cross_pack_resolver_returns_node_output_when_present() {
8578        let mut engine = minimal_engine();
8579        engine.set_cross_pack_resolver(Arc::new(TestCrossPackResolver));
8580
8581        let output = engine
8582            .try_invoke_cross_pack_resolver(
8583                Some("mail"),
8584                Some("messaging"),
8585                "send",
8586                br#"{"subject":"hello"}"#,
8587                "demo",
8588            )
8589            .expect("resolver invocation")
8590            .expect("resolver output");
8591
8592        assert_eq!(
8593            output.payload,
8594            json!({
8595                "provider_id": "mail",
8596                "provider_type": "messaging",
8597                "op": "send",
8598                "tenant": "demo",
8599                "team": null,
8600                "input": { "subject": "hello" },
8601            })
8602        );
8603    }
8604
8605    #[test]
8606    fn flow_goto_builds_a_jump_to_the_named_flow() {
8607        let outcome = execute_flow_goto(json!({
8608            "flow_id": "support",
8609            "node": "ask_order",
8610            "input": { "order": "A-1" },
8611        }))
8612        .expect("goto builds");
8613
8614        let NodeControl::Jump(jump) = outcome.control else {
8615            panic!("flow.goto must produce a Jump, got {:?}", outcome.control);
8616        };
8617        assert_eq!(jump.flow, "support");
8618        assert_eq!(jump.node.as_deref(), Some("ask_order"));
8619        assert_eq!(jump.payload, json!({ "order": "A-1" }));
8620        // The node's own output is the payload the target receives, so a
8621        // template downstream of the goto reads what was actually handed over.
8622        assert_eq!(outcome.output.payload, json!({ "order": "A-1" }));
8623    }
8624
8625    /// `flow` is accepted alongside `flow_id`, matching `flow.call`'s payload so
8626    /// a document reads the same whichever primitive it uses.
8627    #[test]
8628    fn flow_goto_accepts_the_flow_alias_and_defaults_the_entry_node() {
8629        let outcome = execute_flow_goto(json!({ "flow": "support" })).expect("goto builds");
8630        let NodeControl::Jump(jump) = outcome.control else {
8631            panic!("expected a Jump");
8632        };
8633        assert_eq!(jump.flow, "support");
8634        assert!(
8635            jump.node.is_none(),
8636            "no node means `apply_jump` uses the target flow's start"
8637        );
8638        assert_eq!(jump.payload, Value::Null);
8639    }
8640
8641    /// An empty target is refused here rather than reaching `apply_jump`, which
8642    /// would fail later with a message about a flow named "".
8643    #[test]
8644    fn flow_goto_refuses_an_empty_flow_id() {
8645        for payload in [json!({ "flow_id": "" }), json!({ "flow_id": "   " })] {
8646            let err = execute_flow_goto(payload)
8647                .err()
8648                .expect("empty target must not build");
8649            assert!(
8650                err.to_string().contains("flow_id"),
8651                "error must name the field: {err}"
8652            );
8653        }
8654        let err = execute_flow_goto(json!({ "input": {} }))
8655            .err()
8656            .expect("missing target");
8657        assert!(err.to_string().contains("flow.goto"), "got: {err}");
8658    }
8659
8660    /// A blank `node` is the same as omitting it — otherwise `apply_jump` would
8661    /// look for a node whose id is the empty string and fail with a confusing
8662    /// "node not found".
8663    #[test]
8664    fn flow_goto_treats_a_blank_entry_node_as_absent() {
8665        let outcome =
8666            execute_flow_goto(json!({ "flow_id": "support", "node": "  " })).expect("goto builds");
8667        let NodeControl::Jump(jump) = outcome.control else {
8668            panic!("expected a Jump");
8669        };
8670        assert!(jump.node.is_none());
8671    }
8672
8673    /// The redirect ceiling is forwarded so a flow can tighten (or loosen) the
8674    /// default of 3 that `apply_jump` applies.
8675    #[test]
8676    fn flow_goto_forwards_the_redirect_ceiling_and_reason() {
8677        let outcome = execute_flow_goto(json!({
8678            "flow_id": "support",
8679            "max_redirects": 1,
8680            "reason": "menu choice",
8681        }))
8682        .expect("goto builds");
8683        let NodeControl::Jump(jump) = outcome.control else {
8684            panic!("expected a Jump");
8685        };
8686        assert_eq!(jump.max_redirects, Some(1));
8687        assert_eq!(jump.reason.as_deref(), Some("menu choice"));
8688    }
8689
8690    /// Absent a reason, one is supplied — `flow.jump.applied` logs it, and an
8691    /// empty reason there is indistinguishable from a component-emitted jump.
8692    #[test]
8693    fn flow_goto_names_itself_as_the_reason_by_default() {
8694        let outcome = execute_flow_goto(json!({ "flow_id": "support" })).expect("goto builds");
8695        let NodeControl::Jump(jump) = outcome.control else {
8696            panic!("expected a Jump");
8697        };
8698        assert_eq!(jump.reason.as_deref(), Some("flow.goto node"));
8699    }
8700
8701    #[test]
8702    fn parse_component_control_ignores_plain_payload() {
8703        let payload = json!({
8704            "flow": "not-a-control-field",
8705            "node": "n1"
8706        });
8707        let control = parse_component_control(&payload).expect("parse control");
8708        assert!(control.is_none());
8709    }
8710
8711    #[test]
8712    fn parse_component_control_parses_jump_marker() {
8713        let payload = json!({
8714            "greentic_control": {
8715                "action": "jump",
8716                "v": 1,
8717                "flow": "flow.b",
8718                "node": "node-2",
8719                "payload": { "message": "hi" },
8720                "hints": { "k": "v" },
8721                "max_redirects": 2,
8722                "reason": "handoff"
8723            }
8724        });
8725        let control = parse_component_control(&payload)
8726            .expect("parse control")
8727            .expect("missing control");
8728        match control {
8729            NodeControl::Jump(jump) => {
8730                assert_eq!(jump.flow, "flow.b");
8731                assert_eq!(jump.node.as_deref(), Some("node-2"));
8732                assert_eq!(jump.payload, json!({ "message": "hi" }));
8733                assert_eq!(jump.hints, json!({ "k": "v" }));
8734                assert_eq!(jump.max_redirects, Some(2));
8735                assert_eq!(jump.reason.as_deref(), Some("handoff"));
8736            }
8737            other => panic!("expected jump control, got {other:?}"),
8738        }
8739    }
8740
8741    #[test]
8742    fn parse_component_control_rejects_invalid_marker() {
8743        let payload = json!({
8744            "greentic_control": "bad-shape"
8745        });
8746        let err = parse_component_control(&payload).expect_err("expected invalid marker error");
8747        assert!(err.to_string().contains("greentic_control"));
8748    }
8749
8750    #[test]
8751    fn missing_operation_reports_node_and_component() {
8752        let engine = minimal_engine();
8753        let rt = Runtime::new().unwrap();
8754        let retry_config = RetryConfig {
8755            max_attempts: 1,
8756            base_delay_ms: 1,
8757        };
8758        let ctx = FlowContext {
8759            tenant: "tenant",
8760            pack_id: "test-pack",
8761            flow_id: "flow",
8762            node_id: Some("missing-op"),
8763            tool: None,
8764            action: None,
8765            session_id: None,
8766            provider_id: None,
8767            reply_scope: None,
8768            retry_config,
8769            attempt: 1,
8770            observer: None,
8771            mocks: None,
8772            caller: None,
8773        };
8774        let node = HostNode {
8775            kind: NodeKind::Exec {
8776                target_component: "qa.process".into(),
8777            },
8778            component: "component.exec".into(),
8779            component_id: "component.exec".into(),
8780            operation_name: None,
8781            operation_in_mapping: None,
8782            payload_expr: Value::Null,
8783            routing: Routing::End,
8784            vars_out: None,
8785            response_timeout_secs: None,
8786        };
8787        let _state = ExecutionState::new(Value::Null);
8788        let payload = json!({ "component": "qa.process" });
8789        let event = NodeEvent {
8790            context: &ctx,
8791            node_id: "missing-op",
8792            node: &node,
8793            payload: &payload,
8794        };
8795        let err = rt
8796            .block_on(engine.execute_component_exec(
8797                &ctx,
8798                "missing-op",
8799                &node,
8800                payload.clone(),
8801                &event,
8802                ComponentOverrides {
8803                    component: None,
8804                    operation: None,
8805                },
8806            ))
8807            .unwrap_err();
8808        let message = err.to_string();
8809        assert!(
8810            message.contains("missing operation for node `missing-op`"),
8811            "unexpected message: {message}"
8812        );
8813        assert!(
8814            message.contains("(component `component.exec`)"),
8815            "unexpected message: {message}"
8816        );
8817    }
8818
8819    #[test]
8820    fn missing_operation_mentions_mapping_hint() {
8821        let engine = minimal_engine();
8822        let rt = Runtime::new().unwrap();
8823        let retry_config = RetryConfig {
8824            max_attempts: 1,
8825            base_delay_ms: 1,
8826        };
8827        let ctx = FlowContext {
8828            tenant: "tenant",
8829            pack_id: "test-pack",
8830            flow_id: "flow",
8831            node_id: Some("missing-op-hint"),
8832            tool: None,
8833            action: None,
8834            session_id: None,
8835            provider_id: None,
8836            reply_scope: None,
8837            retry_config,
8838            attempt: 1,
8839            observer: None,
8840            mocks: None,
8841            caller: None,
8842        };
8843        let node = HostNode {
8844            kind: NodeKind::Exec {
8845                target_component: "qa.process".into(),
8846            },
8847            component: "component.exec".into(),
8848            component_id: "component.exec".into(),
8849            operation_name: None,
8850            operation_in_mapping: Some("render".into()),
8851            payload_expr: Value::Null,
8852            routing: Routing::End,
8853            vars_out: None,
8854            response_timeout_secs: None,
8855        };
8856        let _state = ExecutionState::new(Value::Null);
8857        let payload = json!({ "component": "qa.process" });
8858        let event = NodeEvent {
8859            context: &ctx,
8860            node_id: "missing-op-hint",
8861            node: &node,
8862            payload: &payload,
8863        };
8864        let err = rt
8865            .block_on(engine.execute_component_exec(
8866                &ctx,
8867                "missing-op-hint",
8868                &node,
8869                payload.clone(),
8870                &event,
8871                ComponentOverrides {
8872                    component: None,
8873                    operation: None,
8874                },
8875            ))
8876            .unwrap_err();
8877        let message = err.to_string();
8878        assert!(
8879            message.contains("missing operation for node `missing-op-hint`"),
8880            "unexpected message: {message}"
8881        );
8882        assert!(
8883            message.contains("Found operation in input.mapping (`render`)"),
8884            "unexpected message: {message}"
8885        );
8886    }
8887
8888    struct CountingObserver {
8889        starts: Mutex<Vec<String>>,
8890        ends: Mutex<Vec<Value>>,
8891    }
8892
8893    impl CountingObserver {
8894        fn new() -> Self {
8895            Self {
8896                starts: Mutex::new(Vec::new()),
8897                ends: Mutex::new(Vec::new()),
8898            }
8899        }
8900    }
8901
8902    impl ExecutionObserver for CountingObserver {
8903        fn on_node_start(&self, event: &NodeEvent<'_>) {
8904            self.starts.lock().unwrap().push(event.node_id.to_string());
8905        }
8906
8907        fn on_node_end(&self, _event: &NodeEvent<'_>, output: &Value) {
8908            self.ends.lock().unwrap().push(output.clone());
8909        }
8910
8911        fn on_node_error(&self, _event: &NodeEvent<'_>, _error: &dyn StdError) {}
8912    }
8913
8914    /// `approval.call` must survive lowering intact.
8915    ///
8916    /// packc emits the gate with `operation: None` because the id is already
8917    /// complete. Before `approval.` joined the `is_builtin` allowlist, lowering
8918    /// dot-split it into component `"approval"` + operation `"call"` — and
8919    /// `"approval"` is by construction absent from the pack's component map,
8920    /// which is keyed verbatim by `node.component.id`. Every human-approval gate
8921    /// then failed at dispatch with `component 'approval' not found in pack` on a
8922    /// perfectly well-formed pack, so rebuilding never helped.
8923    #[test]
8924    fn approval_call_component_id_is_not_dot_split() {
8925        let node = Node {
8926            id: NodeId::from_str("gate").unwrap(),
8927            component: FlowComponentRef {
8928                id: "approval.call".parse().unwrap(),
8929                pack_alias: None,
8930                operation: None,
8931            },
8932            input: InputMapping {
8933                mapping: json!({ "await": true, "input": { "mode": "always" } }),
8934            },
8935            output: OutputMapping {
8936                mapping: Value::Null,
8937            },
8938            err_map: None,
8939            routing: Routing::End,
8940            telemetry: TelemetryHints::default(),
8941            conversational: false,
8942        };
8943        let host_node = HostNode::from(node);
8944        assert_eq!(
8945            host_node.component_id(),
8946            "approval.call",
8947            "approval.call must stay intact; splitting it yields 'approval', which \
8948             is never a key in the pack's component map"
8949        );
8950        assert_eq!(
8951            host_node.operation_name(),
8952            None,
8953            "the id is already complete — lowering must not invent an operation"
8954        );
8955    }
8956
8957    /// A sibling-less `approval.call` node (component id `approval.call`,
8958    /// operation `None` — the shape greentic-flow now emits when the gate has
8959    /// no sibling component) must dispatch as `NodeKind::ApprovalCall` with an
8960    /// empty target, not fall through to `component.exec`/error.
8961    ///
8962    /// Reconciliation note #2 (`approval.call` shape change, Part B): adding
8963    /// `approval.call` to the runtime-native call kinds changes a
8964    /// sibling-less approval node's compiled shape. This pins the runner-host
8965    /// side of that assumption at the engine level.
8966    #[test]
8967    fn approval_call_with_no_operation_dispatches_as_approval_call() {
8968        let node = Node {
8969            id: NodeId::from_str("gate").unwrap(),
8970            component: FlowComponentRef {
8971                id: "approval.call".parse().unwrap(),
8972                pack_alias: None,
8973                operation: None,
8974            },
8975            input: InputMapping {
8976                mapping: json!({ "await": true, "input": { "mode": "always" } }),
8977            },
8978            output: OutputMapping {
8979                mapping: Value::Null,
8980            },
8981            err_map: None,
8982            routing: Routing::End,
8983            telemetry: TelemetryHints::default(),
8984            conversational: false,
8985        };
8986        let host_node = HostNode::from(node);
8987        assert!(
8988            matches!(&host_node.kind, NodeKind::ApprovalCall { target } if target.is_empty()),
8989            "expected NodeKind::ApprovalCall with an empty target, got {:?}",
8990            host_node.kind
8991        );
8992    }
8993
8994    #[test]
8995    fn emits_end_event_for_successful_node() {
8996        let node_id = NodeId::from_str("emit").unwrap();
8997        let node = Node {
8998            id: node_id.clone(),
8999            component: FlowComponentRef {
9000                id: "emit.log".parse().unwrap(),
9001                pack_alias: None,
9002                operation: None,
9003            },
9004            input: InputMapping {
9005                mapping: json!({ "message": "logged" }),
9006            },
9007            output: OutputMapping {
9008                mapping: Value::Null,
9009            },
9010            err_map: None,
9011            routing: Routing::End,
9012            telemetry: TelemetryHints::default(),
9013            conversational: false,
9014        };
9015        let mut nodes = indexmap::IndexMap::default();
9016        nodes.insert(node_id.clone(), node);
9017        let flow = Flow {
9018            schema_version: "1.0".into(),
9019            id: FlowId::from_str("emit.flow").unwrap(),
9020            kind: FlowKind::Messaging,
9021            entrypoints: BTreeMap::from([(
9022                "default".to_string(),
9023                Value::String(node_id.to_string()),
9024            )]),
9025            nodes,
9026            metadata: Default::default(),
9027        };
9028        let host_flow = HostFlow::from(flow);
9029
9030        let engine = FlowEngine {
9031            packs: Vec::new(),
9032            flows: Vec::new(),
9033            flow_sources: HashMap::new(),
9034            messaging_provider_pack_ids: std::collections::HashSet::new(),
9035            flow_cache: RwLock::new(HashMap::from([(
9036                FlowKey {
9037                    pack_id: "test-pack".to_string(),
9038                    flow_id: "emit.flow".to_string(),
9039                },
9040                host_flow,
9041            )])),
9042            default_env: "local".to_string(),
9043            validation: ValidationConfig {
9044                mode: ValidationMode::Off,
9045            },
9046            cross_pack_resolver: None,
9047            rollout_ids: RolloutIds::default(),
9048            approval_dispatch_handler: None,
9049            remote_dispatch_handler: None,
9050            #[cfg(feature = "agentic-worker")]
9051            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
9052            #[cfg(feature = "agentic-worker")]
9053            agent_node_handler: None,
9054            #[cfg(feature = "agentic-worker")]
9055            graph_node_handler: None,
9056            #[cfg(feature = "agentic-worker")]
9057            mcp_tool_source: None,
9058            #[cfg(feature = "agentic-worker")]
9059            mcp_secrets: None,
9060            #[cfg(feature = "agentic-worker")]
9061            a2a_sources: RwLock::new(HashMap::new()),
9062            #[cfg(feature = "agentic-worker")]
9063            ext_artifact_port: None,
9064            operala_node_handler: None,
9065        };
9066        let observer = CountingObserver::new();
9067        let ctx = FlowContext {
9068            tenant: "demo",
9069            pack_id: "test-pack",
9070            flow_id: "emit.flow",
9071            node_id: None,
9072            tool: None,
9073            action: None,
9074            session_id: None,
9075            provider_id: None,
9076            reply_scope: None,
9077            retry_config: RetryConfig {
9078                max_attempts: 1,
9079                base_delay_ms: 1,
9080            },
9081            attempt: 1,
9082            observer: Some(&observer),
9083            mocks: None,
9084            caller: None,
9085        };
9086
9087        let rt = Runtime::new().unwrap();
9088        let result = rt.block_on(engine.execute(ctx, Value::Null)).unwrap();
9089        assert!(matches!(result.status, FlowStatus::Completed));
9090
9091        // The completed FlowExecution exposes its per-node outputs (captured
9092        // from ExecutionState.nodes before finalize_with drops them). This is
9093        // the map the demo reads to surface a mid-flow dw.agent's output.
9094        assert!(
9095            !result.node_outputs.is_empty(),
9096            "completed flow must expose its per-node outputs"
9097        );
9098        assert!(
9099            result
9100                .node_outputs
9101                .values()
9102                .any(|v| v.to_string().contains("logged")),
9103            "node_outputs must carry the executed node's payload: {:?}",
9104            result.node_outputs
9105        );
9106
9107        let starts = observer.starts.lock().unwrap();
9108        let ends = observer.ends.lock().unwrap();
9109        assert_eq!(starts.len(), 1);
9110        assert_eq!(ends.len(), 1);
9111        assert_eq!(ends[0], json!({ "message": "logged" }));
9112    }
9113
9114    #[test]
9115    fn dotted_component_id_with_mapping_operation_is_not_split() {
9116        // greentic-pack resolves a component node to a bare component symbol and
9117        // keeps the operation in the input mapping. The runtime must NOT split the
9118        // dotted symbol on the last dot (which would yield `ai.greentic`, "not
9119        // found in pack"); the structured mapping operation makes the id a
9120        // complete reference.
9121        let node = Node {
9122            conversational: false,
9123            id: NodeId::from_str("render").unwrap(),
9124            component: FlowComponentRef {
9125                id: "ai.greentic.component-templates".parse().unwrap(),
9126                pack_alias: None,
9127                operation: None,
9128            },
9129            input: InputMapping {
9130                mapping: json!({ "operation": "handle_message", "input": "hi" }),
9131            },
9132            output: OutputMapping {
9133                mapping: Value::Null,
9134            },
9135            err_map: None,
9136            routing: Routing::End,
9137            telemetry: TelemetryHints::default(),
9138        };
9139        let host = HostNode::from(node);
9140        assert!(
9141            matches!(&host.kind, NodeKind::PackComponent { component_ref } if component_ref == "ai.greentic.component-templates"),
9142            "dotted component id must stay intact, got kind {:?}",
9143            host.kind
9144        );
9145        assert_eq!(host.component, "ai.greentic.component-templates");
9146        assert_eq!(host.operation_in_mapping(), Some("handle_message"));
9147    }
9148
9149    #[test]
9150    fn packed_component_operation_id_still_splits_without_mapping_operation() {
9151        // Legacy encoding: the operation is packed into the id as
9152        // `<component>.<operation>` and absent from the mapping. The last-dot
9153        // split must still recover it.
9154        let node = Node {
9155            conversational: false,
9156            id: NodeId::from_str("render").unwrap(),
9157            component: FlowComponentRef {
9158                id: "templating.handlebars".parse().unwrap(),
9159                pack_alias: None,
9160                operation: None,
9161            },
9162            input: InputMapping {
9163                mapping: json!({ "text": "hello" }),
9164            },
9165            output: OutputMapping {
9166                mapping: Value::Null,
9167            },
9168            err_map: None,
9169            routing: Routing::End,
9170            telemetry: TelemetryHints::default(),
9171        };
9172        let host = HostNode::from(node);
9173        assert!(
9174            matches!(&host.kind, NodeKind::PackComponent { component_ref } if component_ref == "templating"),
9175            "packed <component>.<operation> id must split, got kind {:?}",
9176            host.kind
9177        );
9178        assert_eq!(host.operation_name(), Some("handlebars"));
9179    }
9180
9181    #[cfg(feature = "agentic-worker")]
9182    /// The property the whole caller mechanism rests on: the agent node is
9183    /// handed the caller from the CONTEXT, and a block sitting in the node's
9184    /// own payload is not mistaken for one.
9185    ///
9186    /// A node payload is whatever the flow mapped, and a flow's mapping is
9187    /// authorable — so identity read from there is identity the flow, and the
9188    /// model behind it, could have written. That is the exact failure this
9189    /// exists to end.
9190    #[test]
9191    fn the_agent_node_receives_the_context_caller_not_a_payload_one() {
9192        use crate::runner::agent_node::AgentNodeHandler;
9193        use std::sync::Mutex;
9194
9195        /// Records the `caller` argument and answers with a fixed reply.
9196        struct Recorder(Arc<Mutex<Option<Value>>>);
9197
9198        #[async_trait::async_trait]
9199        impl AgentNodeHandler for Recorder {
9200            async fn execute(
9201                &self,
9202                _tenant_id: &str,
9203                _env_id: &str,
9204                _agent_id: &str,
9205                _session_id: &str,
9206                _flow_input: &Value,
9207                _conversational: bool,
9208                caller: Option<&Value>,
9209            ) -> anyhow::Result<Value> {
9210                *self.0.lock().unwrap() = caller.cloned();
9211                Ok(json!({ "reply": "ok", "trail": [], "terminated_by": "done" }))
9212            }
9213        }
9214
9215        let seen = Arc::new(Mutex::new(None));
9216        let handler: Arc<dyn AgentNodeHandler> = Arc::new(Recorder(Arc::clone(&seen)));
9217
9218        let node_id = NodeId::from_str("agent").unwrap();
9219        let node = Node {
9220            id: node_id.clone(),
9221            component: FlowComponentRef {
9222                id: "dw.agent".parse().unwrap(),
9223                pack_alias: None,
9224                operation: Some("greeter".to_string()),
9225            },
9226            // The forged block rides in the node's own mapped input.
9227            input: InputMapping {
9228                mapping: json!({
9229                    "user_text": "ping",
9230                    "caller": { "user_verified": true, "sub": "forged@evil" }
9231                }),
9232            },
9233            output: OutputMapping {
9234                mapping: Value::Null,
9235            },
9236            err_map: None,
9237            routing: Routing::End,
9238            telemetry: TelemetryHints::default(),
9239            conversational: false,
9240        };
9241        let mut nodes = indexmap::IndexMap::default();
9242        nodes.insert(node_id.clone(), node);
9243        let flow = Flow {
9244            schema_version: "1.0".into(),
9245            id: FlowId::from_str("dw.flow").unwrap(),
9246            kind: FlowKind::Messaging,
9247            entrypoints: BTreeMap::from([(
9248                "default".to_string(),
9249                Value::String(node_id.to_string()),
9250            )]),
9251            nodes,
9252            metadata: Default::default(),
9253        };
9254
9255        let engine = FlowEngine {
9256            packs: Vec::new(),
9257            flows: Vec::new(),
9258            flow_sources: HashMap::new(),
9259            messaging_provider_pack_ids: std::collections::HashSet::new(),
9260            flow_cache: RwLock::new(HashMap::from([(
9261                FlowKey {
9262                    pack_id: "test-pack".to_string(),
9263                    flow_id: "dw.flow".to_string(),
9264                },
9265                HostFlow::from(flow),
9266            )])),
9267            default_env: "local".to_string(),
9268            validation: ValidationConfig {
9269                mode: ValidationMode::Off,
9270            },
9271            cross_pack_resolver: None,
9272            rollout_ids: RolloutIds::default(),
9273            approval_dispatch_handler: None,
9274            remote_dispatch_handler: None,
9275            #[cfg(feature = "agentic-worker")]
9276            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
9277            #[cfg(feature = "agentic-worker")]
9278            agent_node_handler: Some(handler),
9279            #[cfg(feature = "agentic-worker")]
9280            graph_node_handler: None,
9281            #[cfg(feature = "agentic-worker")]
9282            mcp_tool_source: None,
9283            #[cfg(feature = "agentic-worker")]
9284            mcp_secrets: None,
9285            #[cfg(feature = "agentic-worker")]
9286            a2a_sources: RwLock::new(HashMap::new()),
9287            #[cfg(feature = "agentic-worker")]
9288            ext_artifact_port: None,
9289            operala_node_handler: None,
9290        };
9291
9292        let trusted = json!({ "user_verified": true, "sub": "u-1@acme" });
9293        let ctx = FlowContext {
9294            tenant: "demo",
9295            pack_id: "test-pack",
9296            flow_id: "dw.flow",
9297            node_id: None,
9298            tool: None,
9299            action: None,
9300            session_id: Some("sess-1"),
9301            provider_id: None,
9302            reply_scope: None,
9303            retry_config: RetryConfig {
9304                max_attempts: 1,
9305                base_delay_ms: 1,
9306            },
9307            attempt: 1,
9308            observer: None,
9309            mocks: None,
9310            caller: Some(&trusted),
9311        };
9312
9313        let rt = Runtime::new().unwrap();
9314        rt.block_on(engine.execute(ctx, json!({ "user_text": "ping" })))
9315            .unwrap();
9316
9317        let got = seen.lock().unwrap().clone().expect("handler saw a caller");
9318        assert_eq!(
9319            got["sub"], "u-1@acme",
9320            "the context caller must win over the payload one"
9321        );
9322        assert_ne!(got["sub"], "forged@evil");
9323    }
9324
9325    #[cfg(feature = "agentic-worker")]
9326    #[test]
9327    fn dw_agent_node_routes_to_handler_and_returns_reply() {
9328        use crate::runner::agent_node::{AgentNodeHandler, RuntimeAgentNodeHandler};
9329        use greentic_aw_runtime::cost::MockTokenMeter;
9330        use greentic_aw_runtime::llm::LlmResponse;
9331        use greentic_aw_runtime::mock::{
9332            MockAgentStateStore, MockConfigProvider, MockLlmBackend, MockTelemetry, NoopToolLedger,
9333        };
9334        use greentic_aw_runtime::{
9335            AgentConfig, AgentLimits, AgentRuntime, LlmProviderRef, TenantContext,
9336        };
9337
9338        // --- mock-backed AgentRuntime: the LLM replies "pong" in one step ---
9339        let llm = Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
9340            content: Some("pong".into()),
9341            tool_calls: vec![],
9342            tokens_in: 1,
9343            tokens_out: 1,
9344        })]));
9345        let store = Arc::new(MockAgentStateStore::new());
9346        let telemetry = Arc::new(MockTelemetry::new());
9347
9348        // The dispatch builds TenantContext::new(ctx.tenant, default_env) =
9349        // ("demo", "local"). MockConfigProvider keys by
9350        // `format!("{}:{agent_id}", tenant.key_prefix())` = "aw:demo:local:greeter",
9351        // so seed with the SAME tenant+env+agent_id the engine will look up.
9352        let config_provider = MockConfigProvider::new();
9353        let tenant = TenantContext::new("demo", "local");
9354        config_provider.insert(
9355            &tenant,
9356            "greeter",
9357            AgentConfig {
9358                agent_id: "greeter".into(),
9359                system_prompt: "sys".into(),
9360                tools: vec![],
9361                guardrails: vec![],
9362                llm: LlmProviderRef {
9363                    provider: "mock".into(),
9364                    model: "m".into(),
9365                    credential_ref: None,
9366                },
9367                limits: AgentLimits::default(),
9368                memory: None,
9369                knowledge: None,
9370                conversational: false,
9371                opening_message: None,
9372                on_text_while_parked: Default::default(),
9373            },
9374        );
9375        let config_provider = Arc::new(config_provider);
9376        let token_meter = Arc::new(MockTokenMeter::new(0));
9377        let ledger = Arc::new(NoopToolLedger);
9378        let ext_runtime = Arc::new(greentic_ext_runtime::ExtensionRuntime::for_test().unwrap());
9379        let runtime = Arc::new(AgentRuntime::new(
9380            config_provider,
9381            store,
9382            ext_runtime,
9383            llm,
9384            telemetry,
9385            token_meter,
9386            ledger,
9387            None,
9388        ));
9389        let handler: Arc<dyn AgentNodeHandler> =
9390            Arc::new(RuntimeAgentNodeHandler::new(runtime, None, None, None));
9391
9392        // --- flow with a single dw.agent node (operation = agent_id) ---
9393        let node_id = NodeId::from_str("agent").unwrap();
9394        let node = Node {
9395            id: node_id.clone(),
9396            component: FlowComponentRef {
9397                id: "dw.agent".parse().unwrap(),
9398                pack_alias: None,
9399                operation: Some("greeter".to_string()),
9400            },
9401            input: InputMapping {
9402                mapping: json!({ "user_text": "ping" }),
9403            },
9404            output: OutputMapping {
9405                mapping: Value::Null,
9406            },
9407            err_map: None,
9408            routing: Routing::End,
9409            telemetry: TelemetryHints::default(),
9410            conversational: false,
9411        };
9412        let mut nodes = indexmap::IndexMap::default();
9413        nodes.insert(node_id.clone(), node);
9414        let flow = Flow {
9415            schema_version: "1.0".into(),
9416            id: FlowId::from_str("dw.flow").unwrap(),
9417            kind: FlowKind::Messaging,
9418            entrypoints: BTreeMap::from([(
9419                "default".to_string(),
9420                Value::String(node_id.to_string()),
9421            )]),
9422            nodes,
9423            metadata: Default::default(),
9424        };
9425        let host_flow = HostFlow::from(flow);
9426
9427        let engine = FlowEngine {
9428            packs: Vec::new(),
9429            flows: Vec::new(),
9430            flow_sources: HashMap::new(),
9431            messaging_provider_pack_ids: std::collections::HashSet::new(),
9432            flow_cache: RwLock::new(HashMap::from([(
9433                FlowKey {
9434                    pack_id: "test-pack".to_string(),
9435                    flow_id: "dw.flow".to_string(),
9436                },
9437                host_flow,
9438            )])),
9439            default_env: "local".to_string(),
9440            validation: ValidationConfig {
9441                mode: ValidationMode::Off,
9442            },
9443            cross_pack_resolver: None,
9444            rollout_ids: RolloutIds::default(),
9445            approval_dispatch_handler: None,
9446            remote_dispatch_handler: None,
9447            #[cfg(feature = "agentic-worker")]
9448            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
9449            #[cfg(feature = "agentic-worker")]
9450            agent_node_handler: Some(handler),
9451            #[cfg(feature = "agentic-worker")]
9452            graph_node_handler: None,
9453            #[cfg(feature = "agentic-worker")]
9454            mcp_tool_source: None,
9455            #[cfg(feature = "agentic-worker")]
9456            mcp_secrets: None,
9457            #[cfg(feature = "agentic-worker")]
9458            a2a_sources: RwLock::new(HashMap::new()),
9459            #[cfg(feature = "agentic-worker")]
9460            ext_artifact_port: None,
9461            operala_node_handler: None,
9462        };
9463        let ctx = FlowContext {
9464            tenant: "demo",
9465            pack_id: "test-pack",
9466            flow_id: "dw.flow",
9467            node_id: None,
9468            tool: None,
9469            action: None,
9470            session_id: Some("sess-1"),
9471            provider_id: None,
9472            reply_scope: None,
9473            retry_config: RetryConfig {
9474                max_attempts: 1,
9475                base_delay_ms: 1,
9476            },
9477            attempt: 1,
9478            observer: None,
9479            mocks: None,
9480            caller: None,
9481        };
9482
9483        let rt = Runtime::new().unwrap();
9484        let result = rt
9485            .block_on(engine.execute(ctx, json!({ "user_text": "ping" })))
9486            .unwrap();
9487        assert!(matches!(result.status, FlowStatus::Completed));
9488
9489        // The dw.agent node output is {"reply", "trail", "terminated_by"}; the
9490        // engine finalises a single-node flow's egress into an array wrapping it.
9491        let output_str = serde_json::to_string(&result.output).unwrap();
9492        assert!(
9493            output_str.contains("pong"),
9494            "expected agent reply in flow output, got: {output_str}"
9495        );
9496    }
9497
9498    /// Engine twin of [`dw_agent_node_routes_to_handler_and_returns_reply`]:
9499    /// asserts a `dw.agent_graph` node is detected, routed to the configured
9500    /// [`GraphNodeHandler`] with the engine-derived tenant/env/session and the
9501    /// node's `operation` as the `graph_id`, and its reply lands in the flow
9502    /// output. A lightweight recording stub stands in for the durable executor.
9503    #[cfg(feature = "agentic-worker")]
9504    #[test]
9505    fn dw_agent_graph_node_routes_to_handler_and_returns_reply() {
9506        use std::sync::Mutex;
9507
9508        use crate::runner::graph_node::GraphNodeHandler;
9509
9510        /// Records the dispatch arguments and returns a fixed DwAgent envelope.
9511        struct RecordingGraphHandler {
9512            seen: Mutex<Option<(String, String, String, String)>>,
9513        }
9514
9515        #[async_trait::async_trait]
9516        impl GraphNodeHandler for RecordingGraphHandler {
9517            async fn execute(
9518                &self,
9519                tenant_id: &str,
9520                env_id: &str,
9521                graph_id: &str,
9522                session_id: &str,
9523                _flow_input: &Value,
9524            ) -> Result<Value> {
9525                *self.seen.lock().unwrap() = Some((
9526                    tenant_id.to_string(),
9527                    env_id.to_string(),
9528                    graph_id.to_string(),
9529                    session_id.to_string(),
9530                ));
9531                Ok(json!({
9532                    "reply": "graph-pong",
9533                    "trail": [],
9534                    "terminated_by": "respond",
9535                }))
9536            }
9537        }
9538
9539        let handler = Arc::new(RecordingGraphHandler {
9540            seen: Mutex::new(None),
9541        });
9542        let handler_dyn: Arc<dyn GraphNodeHandler> = handler.clone();
9543
9544        // --- flow with a single dw.agent_graph node (operation = graph_id) ---
9545        let node_id = NodeId::from_str("graph").unwrap();
9546        let node = Node {
9547            id: node_id.clone(),
9548            component: FlowComponentRef {
9549                id: "dw.agent_graph".parse().unwrap(),
9550                pack_alias: None,
9551                operation: Some("triage".to_string()),
9552            },
9553            input: InputMapping {
9554                mapping: json!({ "user_text": "ping" }),
9555            },
9556            output: OutputMapping {
9557                mapping: Value::Null,
9558            },
9559            err_map: None,
9560            routing: Routing::End,
9561            telemetry: TelemetryHints::default(),
9562            conversational: false,
9563        };
9564        let mut nodes = indexmap::IndexMap::default();
9565        nodes.insert(node_id.clone(), node);
9566        let flow = Flow {
9567            schema_version: "1.0".into(),
9568            id: FlowId::from_str("dwg.flow").unwrap(),
9569            kind: FlowKind::Messaging,
9570            entrypoints: BTreeMap::from([(
9571                "default".to_string(),
9572                Value::String(node_id.to_string()),
9573            )]),
9574            nodes,
9575            metadata: Default::default(),
9576        };
9577        let host_flow = HostFlow::from(flow);
9578
9579        let engine = FlowEngine {
9580            packs: Vec::new(),
9581            flows: Vec::new(),
9582            flow_sources: HashMap::new(),
9583            messaging_provider_pack_ids: std::collections::HashSet::new(),
9584            flow_cache: RwLock::new(HashMap::from([(
9585                FlowKey {
9586                    pack_id: "test-pack".to_string(),
9587                    flow_id: "dwg.flow".to_string(),
9588                },
9589                host_flow,
9590            )])),
9591            default_env: "local".to_string(),
9592            validation: ValidationConfig {
9593                mode: ValidationMode::Off,
9594            },
9595            cross_pack_resolver: None,
9596            rollout_ids: RolloutIds::default(),
9597            approval_dispatch_handler: None,
9598            remote_dispatch_handler: None,
9599            #[cfg(feature = "agentic-worker")]
9600            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
9601            #[cfg(feature = "agentic-worker")]
9602            agent_node_handler: None,
9603            #[cfg(feature = "agentic-worker")]
9604            graph_node_handler: Some(handler_dyn),
9605            #[cfg(feature = "agentic-worker")]
9606            mcp_tool_source: None,
9607            #[cfg(feature = "agentic-worker")]
9608            mcp_secrets: None,
9609            #[cfg(feature = "agentic-worker")]
9610            a2a_sources: RwLock::new(HashMap::new()),
9611            #[cfg(feature = "agentic-worker")]
9612            ext_artifact_port: None,
9613            operala_node_handler: None,
9614        };
9615        let ctx = FlowContext {
9616            tenant: "demo",
9617            pack_id: "test-pack",
9618            flow_id: "dwg.flow",
9619            node_id: None,
9620            tool: None,
9621            action: None,
9622            session_id: Some("sess-1"),
9623            provider_id: None,
9624            reply_scope: None,
9625            retry_config: RetryConfig {
9626                max_attempts: 1,
9627                base_delay_ms: 1,
9628            },
9629            attempt: 1,
9630            observer: None,
9631            mocks: None,
9632            caller: None,
9633        };
9634
9635        let rt = Runtime::new().unwrap();
9636        let result = rt
9637            .block_on(engine.execute(ctx, json!({ "user_text": "ping" })))
9638            .unwrap();
9639        assert!(matches!(result.status, FlowStatus::Completed));
9640
9641        // The handler must have been called with the engine-derived
9642        // tenant/env/session and the node's operation as graph_id.
9643        let seen = handler.seen.lock().unwrap().clone();
9644        assert_eq!(
9645            seen,
9646            Some((
9647                "demo".to_string(),
9648                "local".to_string(),
9649                "triage".to_string(),
9650                "sess-1".to_string(),
9651            )),
9652            "dw.agent_graph dispatch must mirror dw.agent's tenant/env/graph_id/session derivation"
9653        );
9654
9655        let output_str = serde_json::to_string(&result.output).unwrap();
9656        assert!(
9657            output_str.contains("graph-pong"),
9658            "expected graph reply in flow output, got: {output_str}"
9659        );
9660    }
9661
9662    /// When `GREENTIC_AW_DISPATCH=nats` is set, a `dw.agent` node must be
9663    /// rerouted through the remote-dispatch path (`"agentic"` runtime) rather
9664    /// than calling the in-process `AgentNodeHandler`. The node payload is
9665    /// wrapped as `input`, `await=true` is injected, and the engine pauses
9666    /// (returns a wait outcome, not a complete one).
9667    #[cfg(feature = "agentic-worker")]
9668    #[test]
9669    fn dw_agent_nats_mode_dispatches_remote() {
9670        use std::sync::Mutex;
9671
9672        use crate::runner::agent_node::DwAgentDispatch;
9673        use crate::runner::remote_dispatch::{
9674            RemoteDispatch, RemoteDispatchAction, RemoteDispatchHandler,
9675        };
9676
9677        /// Recording stub: captures the last dispatch and returns
9678        /// `AwaitingResponse` so the engine pauses.
9679        struct RecordingDispatcher {
9680            seen: Mutex<Option<RemoteDispatch>>,
9681        }
9682
9683        #[async_trait::async_trait]
9684        impl RemoteDispatchHandler for RecordingDispatcher {
9685            async fn dispatch(
9686                &self,
9687                request: RemoteDispatch,
9688            ) -> anyhow::Result<RemoteDispatchAction> {
9689                let corr = request.correlation_id.clone();
9690                *self.seen.lock().unwrap() = Some(request);
9691                Ok(RemoteDispatchAction::AwaitingResponse {
9692                    correlation_id: corr,
9693                })
9694            }
9695        }
9696
9697        let dispatcher = Arc::new(RecordingDispatcher {
9698            seen: Mutex::new(None),
9699        });
9700
9701        // --- two-node flow: dw.agent → emit (resume target) ---
9702        // The agent node must have Routing::Next so the engine knows where to
9703        // resume once the async response arrives (same requirement as sorla.call /
9704        // agentic.call nodes in production).
9705        let resume_id = NodeId::from_str("after-agent").unwrap();
9706        let node_id = NodeId::from_str("agent-nats").unwrap();
9707        let agent_node = Node {
9708            id: node_id.clone(),
9709            component: FlowComponentRef {
9710                id: "dw.agent".parse().unwrap(),
9711                pack_alias: None,
9712                operation: Some("greeter".to_string()),
9713            },
9714            input: InputMapping {
9715                mapping: json!({ "user_text": "hi" }),
9716            },
9717            output: OutputMapping {
9718                mapping: Value::Null,
9719            },
9720            err_map: None,
9721            routing: Routing::Next {
9722                node_id: resume_id.clone(),
9723            },
9724            telemetry: TelemetryHints::default(),
9725            conversational: false,
9726        };
9727        let resume_node = Node {
9728            id: resume_id.clone(),
9729            component: FlowComponentRef {
9730                id: "emit.log".parse().unwrap(),
9731                pack_alias: None,
9732                operation: None,
9733            },
9734            input: InputMapping {
9735                mapping: json!({ "message": "done" }),
9736            },
9737            output: OutputMapping {
9738                mapping: Value::Null,
9739            },
9740            err_map: None,
9741            routing: Routing::End,
9742            telemetry: TelemetryHints::default(),
9743            conversational: false,
9744        };
9745        let mut nodes = indexmap::IndexMap::default();
9746        nodes.insert(node_id.clone(), agent_node);
9747        nodes.insert(resume_id.clone(), resume_node);
9748        let flow = Flow {
9749            schema_version: "1.0".into(),
9750            id: FlowId::from_str("nats-agent.flow").unwrap(),
9751            kind: FlowKind::Messaging,
9752            entrypoints: BTreeMap::from([(
9753                "default".to_string(),
9754                Value::String(node_id.to_string()),
9755            )]),
9756            nodes,
9757            metadata: Default::default(),
9758        };
9759        let host_flow = HostFlow::from(flow);
9760
9761        let engine = FlowEngine {
9762            packs: Vec::new(),
9763            flows: Vec::new(),
9764            flow_sources: HashMap::new(),
9765            messaging_provider_pack_ids: std::collections::HashSet::new(),
9766            flow_cache: RwLock::new(HashMap::from([(
9767                FlowKey {
9768                    pack_id: "test-pack".to_string(),
9769                    flow_id: "nats-agent.flow".to_string(),
9770                },
9771                host_flow,
9772            )])),
9773            default_env: "local".to_string(),
9774            validation: ValidationConfig {
9775                mode: ValidationMode::Off,
9776            },
9777            cross_pack_resolver: None,
9778            rollout_ids: RolloutIds::default(),
9779            approval_dispatch_handler: None,
9780            remote_dispatch_handler: Some(dispatcher.clone() as Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>),
9781            #[cfg(feature = "agentic-worker")]
9782            dw_agent_dispatch: DwAgentDispatch::Nats,
9783            #[cfg(feature = "agentic-worker")]
9784            // No in-process handler wired — Nats path must NOT call it.
9785            agent_node_handler: None,
9786            #[cfg(feature = "agentic-worker")]
9787            graph_node_handler: None,
9788            #[cfg(feature = "agentic-worker")]
9789            mcp_tool_source: None,
9790            #[cfg(feature = "agentic-worker")]
9791            mcp_secrets: None,
9792            #[cfg(feature = "agentic-worker")]
9793            a2a_sources: RwLock::new(HashMap::new()),
9794            #[cfg(feature = "agentic-worker")]
9795            ext_artifact_port: None,
9796            operala_node_handler: None,
9797        };
9798
9799        let ctx = FlowContext {
9800            tenant: "demo",
9801            pack_id: "test-pack",
9802            flow_id: "nats-agent.flow",
9803            node_id: None,
9804            tool: None,
9805            action: None,
9806            session_id: Some("sess-nats"),
9807            provider_id: None,
9808            reply_scope: None,
9809            retry_config: RetryConfig {
9810                max_attempts: 1,
9811                base_delay_ms: 1,
9812            },
9813            attempt: 1,
9814            observer: None,
9815            mocks: None,
9816            caller: None,
9817        };
9818
9819        let rt = Runtime::new().unwrap();
9820        let result = rt
9821            .block_on(engine.execute(ctx, json!({ "user_text": "hi" })))
9822            .unwrap();
9823
9824        // The Nats path pauses the flow (await=true → DispatchOutcome::wait).
9825        assert!(
9826            matches!(result.status, FlowStatus::Waiting(_)),
9827            "expected Waiting outcome from dw.agent Nats mode, got: {:?}",
9828            result.status
9829        );
9830
9831        // The dispatcher must have been called with runtime="agentic" and
9832        // target=<agent_id>, and the node payload wrapped as `input`.
9833        let seen = dispatcher.seen.lock().unwrap();
9834        let dispatch = seen.as_ref().expect("dispatcher was not called");
9835        assert_eq!(
9836            dispatch.runtime, "agentic",
9837            "runtime name must be 'agentic'"
9838        );
9839        assert_eq!(dispatch.target, "greeter", "target must be the agent_id");
9840        assert_eq!(
9841            dispatch.input,
9842            json!({ "user_text": "hi" }),
9843            "node payload must be forwarded as dispatch input"
9844        );
9845    }
9846
9847    fn host_flow_for_test(
9848        flow_id: &str,
9849        node_ids: &[&str],
9850        default_start: Option<&str>,
9851    ) -> HostFlow {
9852        let mut nodes = indexmap::IndexMap::default();
9853        for node_id in node_ids {
9854            let id = NodeId::from_str(node_id).unwrap();
9855            let node = Node {
9856                id: id.clone(),
9857                component: FlowComponentRef {
9858                    id: "emit.log".parse().unwrap(),
9859                    pack_alias: None,
9860                    operation: None,
9861                },
9862                input: InputMapping {
9863                    mapping: json!({ "message": node_id }),
9864                },
9865                output: OutputMapping {
9866                    mapping: Value::Null,
9867                },
9868                err_map: None,
9869                routing: Routing::End,
9870                telemetry: TelemetryHints::default(),
9871                conversational: false,
9872            };
9873            nodes.insert(id, node);
9874        }
9875        let mut entrypoints = BTreeMap::new();
9876        if let Some(start) = default_start {
9877            entrypoints.insert("default".to_string(), Value::String(start.to_string()));
9878        }
9879        HostFlow::from(Flow {
9880            schema_version: "1.0".into(),
9881            id: FlowId::from_str(flow_id).unwrap(),
9882            kind: FlowKind::Messaging,
9883            entrypoints,
9884            nodes,
9885            metadata: Default::default(),
9886        })
9887    }
9888
9889    fn jump_test_engine() -> FlowEngine {
9890        let target_flow = host_flow_for_test("flow.target", &["node-a", "node-b"], None);
9891        FlowEngine {
9892            packs: Vec::new(),
9893            flows: Vec::new(),
9894            flow_sources: HashMap::new(),
9895            messaging_provider_pack_ids: std::collections::HashSet::new(),
9896            flow_cache: RwLock::new(HashMap::from([(
9897                FlowKey {
9898                    pack_id: "test-pack".to_string(),
9899                    flow_id: "flow.target".to_string(),
9900                },
9901                target_flow,
9902            )])),
9903            default_env: "local".to_string(),
9904            validation: ValidationConfig {
9905                mode: ValidationMode::Off,
9906            },
9907            cross_pack_resolver: None,
9908            rollout_ids: RolloutIds::default(),
9909            approval_dispatch_handler: None,
9910            remote_dispatch_handler: None,
9911            #[cfg(feature = "agentic-worker")]
9912            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
9913            #[cfg(feature = "agentic-worker")]
9914            agent_node_handler: None,
9915            #[cfg(feature = "agentic-worker")]
9916            graph_node_handler: None,
9917            #[cfg(feature = "agentic-worker")]
9918            mcp_tool_source: None,
9919            #[cfg(feature = "agentic-worker")]
9920            mcp_secrets: None,
9921            #[cfg(feature = "agentic-worker")]
9922            a2a_sources: RwLock::new(HashMap::new()),
9923            #[cfg(feature = "agentic-worker")]
9924            ext_artifact_port: None,
9925            operala_node_handler: None,
9926        }
9927    }
9928
9929    fn jump_ctx<'a>(flow_id: &'a str) -> FlowContext<'a> {
9930        FlowContext {
9931            tenant: "demo",
9932            pack_id: "test-pack",
9933            flow_id,
9934            node_id: None,
9935            tool: None,
9936            action: None,
9937            session_id: None,
9938            provider_id: None,
9939            reply_scope: None,
9940            retry_config: RetryConfig {
9941                max_attempts: 1,
9942                base_delay_ms: 1,
9943            },
9944            attempt: 1,
9945            observer: None,
9946            mocks: None,
9947            caller: None,
9948        }
9949    }
9950
9951    /// #765: a component invocation is told the verified caller, while the
9952    /// host scope that keys its secrets and state stays what it always was.
9953    #[test]
9954    fn component_exec_ctx_presents_the_verified_caller() {
9955        let block = json!({
9956            "user_verified": true,
9957            "sub": "u-1@acme",
9958            "team": "sales",
9959            "groups": ["employee"]
9960        });
9961        let mut ctx = jump_ctx("caller.flow");
9962        ctx.provider_id = Some("messaging-webchat");
9963        ctx.caller = Some(&block);
9964
9965        let exec = component_exec_ctx(&ctx, "lookup");
9966        let caller = component_caller(&ctx);
9967        let v05 = crate::component_api::exec_ctx_v0_5_as(&exec, caller.as_ref());
9968        assert_eq!(v05.tenant.user_id.as_deref(), Some("u-1@acme"));
9969        assert_eq!(v05.tenant.team_id.as_deref(), Some("sales"));
9970        let v06 =
9971            crate::component_api::envelope_v0_6_as(&exec, caller.as_ref(), "c", "{}").unwrap();
9972        assert_eq!(v06.ctx.user_id.as_deref(), Some("u-1@acme"));
9973        assert_eq!(v06.ctx.team_id.as_deref(), Some("sales"));
9974        // Host scope: unchanged, so tenant-wide secrets and existing
9975        // component state keep resolving.
9976        assert_eq!(exec.tenant.user.as_deref(), Some("messaging-webchat"));
9977        assert_eq!(exec.tenant.team, None);
9978    }
9979
9980    /// Partner blocker #3: an unverified block, or none at all, must not make
9981    /// the caller look like a user named after the provider — which is what
9982    /// made an anonymous caller of a deployed environment indistinguishable
9983    /// from Run Demo. The component is told NO user, the provider is presented
9984    /// in its own 0.5 slot, and the host scope that keys the component's state
9985    /// still carries the provider id, so no state moves.
9986    #[test]
9987    fn component_exec_ctx_without_a_verified_caller_presents_no_user() {
9988        let unverified = json!({ "user_verified": false, "sub": "u-1", "team": "sales" });
9989        for provider in ["messaging-webchat", "greentic-run-demo"] {
9990            for caller in [None, Some(&unverified)] {
9991                let mut ctx = jump_ctx("caller.flow");
9992                ctx.provider_id = Some(provider);
9993                ctx.caller = caller;
9994                let exec = component_exec_ctx(&ctx, "lookup");
9995                let caller = component_caller(&ctx);
9996                assert!(caller.is_none());
9997
9998                let v05 = crate::component_api::exec_ctx_v0_5_for(
9999                    &exec,
10000                    caller.as_ref(),
10001                    ctx.provider_id,
10002                );
10003                assert_eq!(v05.tenant.user_id, None);
10004                assert_eq!(v05.tenant.user, None);
10005                assert_eq!(v05.tenant.provider_id.as_deref(), Some(provider));
10006                assert_eq!(v05.tenant.team_id, None);
10007                assert!(v05.tenant.attributes.is_empty());
10008
10009                let v04 = crate::component_api::exec_ctx_v0_4_for(
10010                    &exec,
10011                    caller.as_ref(),
10012                    ctx.provider_id,
10013                );
10014                assert_eq!(v04.tenant.user, None);
10015
10016                let v06 = crate::component_api::envelope_v0_6_for(
10017                    &exec,
10018                    caller.as_ref(),
10019                    ctx.provider_id,
10020                    "c",
10021                    "{}",
10022                )
10023                .unwrap();
10024                assert_eq!(v06.ctx.user_id, None);
10025
10026                // Host scope: unchanged. `exec.tenant.user` is what keys the
10027                // component's state (greentic-state FQN), so it must still be
10028                // the provider id.
10029                assert_eq!(exec.tenant.user.as_deref(), Some(provider));
10030                assert_eq!(exec.tenant.team, None);
10031            }
10032        }
10033    }
10034
10035    /// A verified caller still wins, and the provider is still named in its
10036    /// own slot beside it.
10037    #[test]
10038    fn component_exec_ctx_with_a_verified_caller_also_names_the_provider() {
10039        let block = json!({ "user_verified": true, "sub": "u-1@acme" });
10040        let mut ctx = jump_ctx("caller.flow");
10041        ctx.provider_id = Some("messaging-webchat");
10042        ctx.caller = Some(&block);
10043        let exec = component_exec_ctx(&ctx, "lookup");
10044        let caller = component_caller(&ctx);
10045        let v05 = crate::component_api::exec_ctx_v0_5_for(&exec, caller.as_ref(), ctx.provider_id);
10046        assert_eq!(v05.tenant.user_id.as_deref(), Some("u-1@acme"));
10047        assert_eq!(v05.tenant.provider_id.as_deref(), Some("messaging-webchat"));
10048        assert_eq!(exec.tenant.user.as_deref(), Some("messaging-webchat"));
10049    }
10050
10051    #[test]
10052    fn with_rollout_ids_binds_revision_identity() {
10053        let engine = minimal_engine().with_rollout_ids(RolloutIds {
10054            customer_id: Some("cust-acme".into()),
10055            deployment_id: Some("01JTKS".into()),
10056            bundle_id: Some("customer.support".into()),
10057            revision_id: Some("01JTKR".into()),
10058        });
10059        assert_eq!(engine.rollout_ids.revision_id.as_deref(), Some("01JTKR"));
10060        assert_eq!(engine.rollout_ids.deployment_id.as_deref(), Some("01JTKS"));
10061        // A freshly-built engine carries no rollout identity (legacy runtime).
10062        assert!(minimal_engine().rollout_ids.is_empty());
10063    }
10064
10065    /// The MCP credential unit is the revision's `bundle_id` — the per-engine
10066    /// identity, since one greentic-start process serves many revisions — and
10067    /// is absent on the legacy tenant-only runtime.
10068    #[cfg(feature = "agentic-worker")]
10069    #[test]
10070    fn mcp_credential_unit_is_the_revisions_bundle_id() {
10071        let engine = minimal_engine().with_rollout_ids(RolloutIds {
10072            customer_id: None,
10073            deployment_id: Some("01JTKS".into()),
10074            bundle_id: Some("customer.support".into()),
10075            revision_id: Some("01JTKR".into()),
10076        });
10077        assert_eq!(engine.mcp_credential_unit(), Some("customer.support"));
10078        assert_eq!(minimal_engine().mcp_credential_unit(), None);
10079    }
10080
10081    /// The composition that matters: what a `flow.goto` NODE produces is a jump
10082    /// the engine actually applies. Proven end to end through `apply_jump`
10083    /// rather than by inspecting the control alone — a `JumpControl` the engine
10084    /// would reject is not a working transfer.
10085    ///
10086    /// The target flow's start node is selected, the handed-over payload
10087    /// becomes the target's input, and the redirect counter advances, which is
10088    /// what makes a goto loop terminate instead of spinning.
10089    #[test]
10090    fn a_flow_goto_node_produces_a_jump_the_engine_applies() {
10091        let outcome = execute_flow_goto(json!({
10092            "flow_id": "flow.target",
10093            "input": { "order": "A-1" },
10094        }))
10095        .expect("goto builds");
10096        let NodeControl::Jump(jump) = outcome.control else {
10097            panic!("expected a Jump");
10098        };
10099
10100        let engine = jump_test_engine();
10101        let mut state = ExecutionState::new(Value::Null);
10102        let rt = Runtime::new().unwrap();
10103        let target = rt
10104            .block_on(engine.apply_jump(&jump_ctx("flow.source"), &mut state, jump))
10105            .expect("the engine must accept the jump a flow.goto node builds");
10106
10107        assert_eq!(target.flow_id, "flow.target");
10108        assert_eq!(
10109            target.node_id.as_str(),
10110            "node-a",
10111            "no explicit node means the target flow's first node"
10112        );
10113        assert_eq!(
10114            state.redirect_count(),
10115            1,
10116            "the loop guard must have counted"
10117        );
10118    }
10119
10120    /// An explicit entry node is honoured, so a menu can hand over to the exact
10121    /// step that answers the option the user picked.
10122    #[test]
10123    fn a_flow_goto_node_can_name_the_entry_node() {
10124        let outcome = execute_flow_goto(json!({ "flow_id": "flow.target", "node": "node-b" }))
10125            .expect("goto builds");
10126        let NodeControl::Jump(jump) = outcome.control else {
10127            panic!("expected a Jump");
10128        };
10129
10130        let engine = jump_test_engine();
10131        let mut state = ExecutionState::new(Value::Null);
10132        let rt = Runtime::new().unwrap();
10133        let target = rt
10134            .block_on(engine.apply_jump(&jump_ctx("flow.source"), &mut state, jump))
10135            .expect("jump applies");
10136        assert_eq!(target.node_id.as_str(), "node-b");
10137    }
10138
10139    #[test]
10140    fn apply_jump_unknown_flow_errors() {
10141        let engine = minimal_engine();
10142        let mut state = ExecutionState::new(Value::Null);
10143        let rt = Runtime::new().unwrap();
10144        let err = rt
10145            .block_on(engine.apply_jump(
10146                &jump_ctx("flow.source"),
10147                &mut state,
10148                JumpControl {
10149                    flow: "flow.missing".into(),
10150                    node: None,
10151                    payload: json!({ "ok": true }),
10152                    hints: Value::Null,
10153                    max_redirects: None,
10154                    reason: None,
10155                },
10156            ))
10157            .unwrap_err();
10158        assert!(
10159            err.to_string().contains("unknown_flow"),
10160            "unexpected error: {err}"
10161        );
10162    }
10163
10164    #[test]
10165    fn deterministic_jump_failures_are_terminal_not_retried() {
10166        let rt = Runtime::new().unwrap();
10167        let jump = |flow: &str, node: Option<&str>| JumpControl {
10168            flow: flow.into(),
10169            node: node.map(str::to_string),
10170            payload: json!({ "ok": true }),
10171            hints: Value::Null,
10172            max_redirects: None,
10173            reason: None,
10174        };
10175
10176        // unknown_flow: the flow is not registered at all.
10177        let engine = minimal_engine();
10178        let mut state = ExecutionState::new(Value::Null);
10179        let err = rt
10180            .block_on(engine.apply_jump(
10181                &jump_ctx("flow.source"),
10182                &mut state,
10183                jump("flow.missing", None),
10184            ))
10185            .unwrap_err();
10186        assert!(err.to_string().contains("unknown_flow"), "{err}");
10187        assert!(
10188            is_terminal_flow_error(&err),
10189            "unknown_flow must be terminal"
10190        );
10191        assert!(!should_retry(&err));
10192
10193        // unknown_node: a node that does not exist, and one that is not even a
10194        // valid node id.
10195        let engine = jump_test_engine();
10196        for node in ["node-missing", "not a valid id!"] {
10197            let mut state = ExecutionState::new(Value::Null);
10198            let err = rt
10199                .block_on(engine.apply_jump(
10200                    &jump_ctx("flow.source"),
10201                    &mut state,
10202                    jump("flow.target", Some(node)),
10203                ))
10204                .unwrap_err();
10205            assert!(err.to_string().contains("unknown_node"), "{err}");
10206            assert!(is_terminal_flow_error(&err), "unknown_node {node:?}");
10207        }
10208
10209        // A flow with no start node and no nodes.
10210        let empty = host_flow_for_test("flow.empty", &[], None);
10211        engine.flow_cache.write().insert(
10212            FlowKey {
10213                pack_id: "test-pack".to_string(),
10214                flow_id: "flow.empty".to_string(),
10215            },
10216            empty,
10217        );
10218        let mut state = ExecutionState::new(Value::Null);
10219        let err = rt
10220            .block_on(engine.apply_jump(
10221                &jump_ctx("flow.source"),
10222                &mut state,
10223                jump("flow.empty", None),
10224            ))
10225            .unwrap_err();
10226        assert!(err.to_string().contains("no start node"), "{err}");
10227        assert!(is_terminal_flow_error(&err));
10228    }
10229
10230    #[test]
10231    fn external_effect_classification_is_narrow_and_explicit() {
10232        assert!(NodeKind::SorlaCall { target: "t".into() }.performs_external_effect());
10233        assert!(NodeKind::AgenticCall { target: "t".into() }.performs_external_effect());
10234        assert!(NodeKind::ApprovalCall { target: "t".into() }.performs_external_effect());
10235        assert!(NodeKind::MediaCreate.performs_external_effect());
10236        assert!(NodeKind::FlowCall.performs_external_effect());
10237        assert!(
10238            !NodeKind::BuiltinEmit {
10239                kind: EmitKind::Response
10240            }
10241            .performs_external_effect()
10242        );
10243        assert!(!NodeKind::BuiltinStateGet.performs_external_effect());
10244        assert!(!NodeKind::Wait.performs_external_effect());
10245    }
10246
10247    #[test]
10248    fn terminal_after_effects_only_changes_failures_that_follow_an_effect() {
10249        let transient = || anyhow!("internal timeout: unavailable");
10250        // Before any effect: untouched, a transient failure still retries.
10251        let before = terminal_after_effects(transient(), false);
10252        assert!(!is_terminal_flow_error(&before));
10253        assert!(should_retry(&before));
10254        // After an effect: terminal, message preserved.
10255        let after = terminal_after_effects(transient(), true);
10256        assert!(is_terminal_flow_error(&after));
10257        assert!(!should_retry(&after));
10258        assert_eq!(after.to_string(), "internal timeout: unavailable");
10259        // Only the outermost message survives the rebuild: the cause chain
10260        // (which can name a host or URL) goes to the operator log, never into
10261        // the text that reaches the user-facing failure envelope.
10262        let chained = anyhow::Error::new(TransientFlowError(
10263            "connect to https://internal.example:8443/x refused".into(),
10264        ))
10265        .context("sorla.call failed");
10266        let rebuilt = terminal_after_effects(chained, true);
10267        assert!(is_terminal_flow_error(&rebuilt));
10268        // User-facing text: outermost only.
10269        assert_eq!(rebuilt.to_string(), "sorla.call failed");
10270        // Operator/redaction paths: the root cause is kept, not duplicated.
10271        assert_eq!(
10272            format!("{rebuilt:#}"),
10273            "sorla.call failed: connect to https://internal.example:8443/x refused"
10274        );
10275        assert_eq!(
10276            crate::run_outcome::error::anyhow_chain_text(&rebuilt),
10277            "sorla.call failed\ncaused by: connect to https://internal.example:8443/x refused"
10278        );
10279        // The retry classifiers still see the typed cause but the terminal
10280        // marker wins.
10281        assert!(!should_retry(&rebuilt));
10282        fn assert_send_sync<T: Send + Sync + 'static>(_: &T) {}
10283        assert_send_sync(&TerminalFlowError {
10284            message: String::new(),
10285            original: None,
10286            after_effects: false,
10287        });
10288    }
10289
10290    #[test]
10291    fn only_a_failure_that_followed_an_effect_carries_the_after_effects_marker() {
10292        // Deterministic pre-effect terminal: terminal, but not "after effects".
10293        let deterministic = terminal_flow_error("flow x has no node `y`");
10294        assert!(is_terminal_flow_error(&deterministic));
10295        assert!(!is_after_effects_failure(&deterministic));
10296        // No effect yet: untouched.
10297        let untouched = terminal_after_effects(deterministic, false);
10298        assert!(!is_after_effects_failure(&untouched));
10299        // Transient failure after an effect: marked, message preserved.
10300        let marked = terminal_after_effects(anyhow!("internal timeout"), true);
10301        assert!(is_after_effects_failure(&marked));
10302        assert_eq!(marked.to_string(), "internal timeout");
10303        // An already-terminal error after an effect picks the marker up too.
10304        let upgraded = terminal_after_effects(terminal_flow_error("step limit"), true);
10305        assert!(is_after_effects_failure(&upgraded));
10306        assert_eq!(upgraded.to_string(), "step limit");
10307        // The marker survives added context and a pre_effect wrapper.
10308        assert!(is_after_effects_failure(&upgraded.context("outer")));
10309        assert!(is_after_effects_failure(&pre_effect(marked)));
10310        assert!(!is_after_effects_failure(&anyhow!("plain")));
10311    }
10312
10313    #[test]
10314    fn pre_effect_marker_keeps_message_and_inner_classification() {
10315        let marked = pre_effect(
10316            anyhow::Error::new(TransientFlowError("429 slow down".into())).context("llm call"),
10317        );
10318        assert!(is_pre_effect_error(&marked));
10319        assert_eq!(marked.to_string(), "llm call");
10320        // The wrapped error's own type is still visible to the classifiers.
10321        assert!(should_retry(&marked));
10322        let with_ctx = marked.context("outer");
10323        assert!(is_pre_effect_error(&with_ctx));
10324        assert!(should_retry(&with_ctx));
10325        // A terminal error stays terminal when marked.
10326        assert!(is_terminal_flow_error(&pre_effect(terminal_flow_error(
10327            "x"
10328        ))));
10329        // Unmarked errors are not pre-effect.
10330        assert!(!is_pre_effect_error(&anyhow!("plain")));
10331    }
10332
10333    type DispatchStep = fn() -> Result<crate::runner::remote_dispatch::RemoteDispatchAction>;
10334
10335    /// Scripted dispatcher: call N returns `script[N]` (the last repeats).
10336    struct ScriptedDispatch {
10337        calls: std::sync::atomic::AtomicUsize,
10338        script: Vec<DispatchStep>,
10339    }
10340
10341    #[async_trait::async_trait]
10342    impl crate::runner::remote_dispatch::RemoteDispatchHandler for ScriptedDispatch {
10343        async fn dispatch(
10344            &self,
10345            _request: crate::runner::remote_dispatch::RemoteDispatch,
10346        ) -> Result<crate::runner::remote_dispatch::RemoteDispatchAction> {
10347            let n = self.calls.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
10348            (self.script[n.min(self.script.len() - 1)])()
10349        }
10350    }
10351
10352    fn dispatched() -> Result<crate::runner::remote_dispatch::RemoteDispatchAction> {
10353        Ok(crate::runner::remote_dispatch::RemoteDispatchAction::Dispatched)
10354    }
10355    fn transient_pre_effect() -> Result<crate::runner::remote_dispatch::RemoteDispatchAction> {
10356        Err(pre_effect(
10357            anyhow::Error::new(TransientFlowError("broker 503".into())).context("publish"),
10358        ))
10359    }
10360    fn transient_unproven() -> Result<crate::runner::remote_dispatch::RemoteDispatchAction> {
10361        Err(anyhow::Error::new(TransientFlowError("broker 503".into())).context("publish"))
10362    }
10363
10364    /// Drive a chain of `agentic.call` nodes (fire-and-forget) against a
10365    /// scripted dispatcher; return the failure and the number of dispatches.
10366    fn drive_dispatch_chain(
10367        handler: Option<Vec<DispatchStep>>,
10368        nodes: usize,
10369    ) -> (anyhow::Error, usize) {
10370        let mut engine = jump_test_engine();
10371        let scripted = handler.map(|script| {
10372            Arc::new(ScriptedDispatch {
10373                calls: std::sync::atomic::AtomicUsize::new(0),
10374                script,
10375            })
10376        });
10377        engine.remote_dispatch_handler = scripted
10378            .clone()
10379            .map(|h| h as Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>);
10380        let ids: Vec<String> = (0..nodes).map(|i| format!("n{i}")).collect();
10381        let specs: Vec<(&str, &str, Value)> = ids
10382            .iter()
10383            .map(|id| (id.as_str(), "agentic.call", json!({ "await": false })))
10384            .collect();
10385        let flow = chain_flow("chain.flow", &specs);
10386        let rt = Runtime::new().unwrap();
10387        let ctx = jump_ctx("chain.flow");
10388        let failure = match rt.block_on(engine.drive_flow(
10389            &ctx,
10390            flow,
10391            ExecutionState::new(Value::Null),
10392            None,
10393            "chain.flow".to_string(),
10394        )) {
10395            Ok(_) => panic!("the chain must fail"),
10396            Err(failure) => failure,
10397        };
10398        let count = scripted
10399            .map(|h| h.calls.load(std::sync::atomic::Ordering::SeqCst))
10400            .unwrap_or(0);
10401        (failure.error, count)
10402    }
10403
10404    #[test]
10405    fn effect_node_failing_before_any_effect_is_retried() {
10406        let (err, calls) = drive_dispatch_chain(Some(vec![transient_pre_effect]), 1);
10407        assert_eq!(calls, 1);
10408        assert!(!is_terminal_flow_error(&err), "{err:#}");
10409        assert!(should_retry(&err), "{err:#}");
10410    }
10411
10412    #[test]
10413    fn effect_node_with_no_handler_is_a_pre_effect_config_error_that_is_not_retried() {
10414        // A missing handler is deterministic configuration: re-running the turn
10415        // cannot help, so it must not retry (its text names none of the
10416        // transient words `should_retry` looks for). It is also provably before
10417        // any effect, so it is marked `pre_effect` and does not become a
10418        // "terminal after effects" failure.
10419        let (err, _) = drive_dispatch_chain(None, 1);
10420        assert!(
10421            err.to_string().contains("no RemoteDispatchHandler"),
10422            "{err}"
10423        );
10424        assert!(is_pre_effect_error(&err), "{err:#}");
10425        assert!(!is_terminal_flow_error(&err), "{err:#}");
10426        assert!(!should_retry(&err), "{err:#}");
10427    }
10428
10429    /// Drive one node of `component` on an engine with nothing registered and
10430    /// return its failure.
10431    fn drive_single_failing_node(component: &str, input: Value) -> anyhow::Error {
10432        let engine = jump_test_engine();
10433        let flow = chain_flow("chain.flow", &[("n0", component, input)]);
10434        let rt = Runtime::new().unwrap();
10435        let ctx = jump_ctx("chain.flow");
10436        match rt.block_on(engine.drive_flow(
10437            &ctx,
10438            flow,
10439            ExecutionState::new(Value::Null),
10440            None,
10441            "chain.flow".to_string(),
10442        )) {
10443            Ok(_) => panic!("the node must fail"),
10444            Err(failure) => failure.error,
10445        }
10446    }
10447
10448    #[test]
10449    fn provider_invoke_failures_before_the_call_are_pre_effect() {
10450        // Payload that does not parse, missing op, and an unregistered flow
10451        // (the binding lookup) all precede the provider call.
10452        for input in [
10453            json!({"op": 5}),
10454            json!({}),
10455            json!({"op": "send", "input": {"a": 1}}),
10456        ] {
10457            let err = drive_single_failing_node("provider.invoke", input.clone());
10458            assert!(is_pre_effect_error(&err), "{input}: {err:#}");
10459        }
10460    }
10461
10462    #[cfg(feature = "agentic-worker")]
10463    #[test]
10464    fn a2a_without_a_registered_pack_fails_pre_effect() {
10465        let err = drive_single_failing_node("a2a", json!({"agent": "x", "message": "hi"}));
10466        assert!(is_pre_effect_error(&err), "{err:#}");
10467    }
10468
10469    #[test]
10470    fn effect_node_failure_that_is_not_proven_pre_effect_is_terminal() {
10471        let (err, calls) = drive_dispatch_chain(Some(vec![transient_unproven]), 1);
10472        assert_eq!(calls, 1);
10473        assert!(is_terminal_flow_error(&err), "{err:#}");
10474        assert!(!should_retry(&err));
10475    }
10476
10477    #[test]
10478    fn failure_after_a_completed_effect_is_terminal_even_if_pre_effect_for_its_node() {
10479        // n0 dispatches (an effect); n1 then fails with a transient error its
10480        // own node can prove precedes ITS effects. n0's effect still counts, so
10481        // the turn must not be re-run (which would dispatch n0 again).
10482        let (err, calls) = drive_dispatch_chain(Some(vec![dispatched, transient_pre_effect]), 2);
10483        assert_eq!(calls, 2);
10484        assert!(is_terminal_flow_error(&err), "{err:#}");
10485        assert!(!should_retry(&err));
10486    }
10487
10488    #[test]
10489    fn failed_effect_nodes_may_have_partial_effects_except_flow_call() {
10490        assert!(NodeKind::MediaCreate.may_have_partial_effect_on_failure());
10491        assert!(NodeKind::SorlaCall { target: "t".into() }.may_have_partial_effect_on_failure());
10492        assert!(!NodeKind::FlowCall.may_have_partial_effect_on_failure());
10493        assert!(!NodeKind::BuiltinStateGet.may_have_partial_effect_on_failure());
10494        assert!(!NodeKind::Wait.may_have_partial_effect_on_failure());
10495    }
10496
10497    fn chain_flow(flow_id: &str, nodes: &[(&str, &str, Value)]) -> HostFlow {
10498        let mut map = indexmap::IndexMap::default();
10499        for (index, (node_id, component, input)) in nodes.iter().enumerate() {
10500            let id = NodeId::from_str(node_id).unwrap();
10501            let routing = match nodes.get(index + 1) {
10502                Some((next, _, _)) => Routing::Next {
10503                    node_id: NodeId::from_str(next).unwrap(),
10504                },
10505                None => Routing::End,
10506            };
10507            map.insert(
10508                id.clone(),
10509                Node {
10510                    id,
10511                    component: FlowComponentRef {
10512                        id: component.parse().unwrap(),
10513                        pack_alias: None,
10514                        operation: None,
10515                    },
10516                    input: InputMapping {
10517                        mapping: input.clone(),
10518                    },
10519                    output: OutputMapping {
10520                        mapping: Value::Null,
10521                    },
10522                    err_map: None,
10523                    routing,
10524                    telemetry: TelemetryHints::default(),
10525                    conversational: false,
10526                },
10527            );
10528        }
10529        HostFlow::from(Flow {
10530            schema_version: "1.0".into(),
10531            id: FlowId::from_str(flow_id).unwrap(),
10532            kind: FlowKind::Messaging,
10533            entrypoints: BTreeMap::from([(
10534                "default".to_string(),
10535                Value::String(nodes[0].0.to_string()),
10536            )]),
10537            nodes: map,
10538            metadata: Default::default(),
10539        })
10540    }
10541
10542    /// Drive `chain.flow` (first node, then a `flow.call` that fails because it
10543    /// names no flow) and return the failure.
10544    fn drive_chain_failure(first_component: &str, first_input: Value) -> anyhow::Error {
10545        let engine = jump_test_engine();
10546        let flow = chain_flow(
10547            "chain.flow",
10548            &[
10549                ("first", first_component, first_input),
10550                ("boom", "flow.call", json!({})),
10551            ],
10552        );
10553        let rt = Runtime::new().unwrap();
10554        let ctx = jump_ctx("chain.flow");
10555        let failure = match rt.block_on(engine.drive_flow(
10556            &ctx,
10557            flow,
10558            ExecutionState::new(Value::Null),
10559            None,
10560            "chain.flow".to_string(),
10561        )) {
10562            Ok(_) => panic!("the flow.call node must fail"),
10563            Err(failure) => failure,
10564        };
10565        failure.error
10566    }
10567
10568    #[test]
10569    fn a_failure_after_an_effectful_node_is_terminal() {
10570        // `flow.call` into a registered flow succeeds and counts as an effect.
10571        let err = drive_chain_failure("flow.call", json!({ "flow": "flow.target" }));
10572        assert!(
10573            err.to_string().contains("flow.call"),
10574            "original message kept: {err}"
10575        );
10576        assert!(is_terminal_flow_error(&err), "must not be re-run: {err:#}");
10577    }
10578
10579    #[test]
10580    fn a_failure_after_a_pure_node_stays_retryable() {
10581        let err = drive_chain_failure("emit.log", json!({ "message": "hi" }));
10582        assert!(
10583            !is_terminal_flow_error(&err),
10584            "no effect happened, the turn may be re-run: {err:#}"
10585        );
10586    }
10587
10588    #[test]
10589    fn invalid_greentic_control_is_terminal() {
10590        for payload in [
10591            json!({ "greentic_control": "bad-shape" }),
10592            json!({ "greentic_control": { "v": 1 } }),
10593            json!({ "greentic_control": { "action": "jump", "v": 2 } }),
10594            json!({ "greentic_control": { "action": "jump", "v": 1 } }),
10595        ] {
10596            let err = parse_component_control(&payload).expect_err("invalid control");
10597            assert!(
10598                err.to_string().contains("jump_failed")
10599                    || err.to_string().contains("greentic_control")
10600            );
10601            assert!(is_terminal_flow_error(&err), "{payload}");
10602            assert!(!should_retry(&err));
10603        }
10604    }
10605
10606    #[test]
10607    fn apply_jump_unknown_node_errors() {
10608        let engine = jump_test_engine();
10609        let mut state = ExecutionState::new(Value::Null);
10610        let rt = Runtime::new().unwrap();
10611        let err = rt
10612            .block_on(engine.apply_jump(
10613                &jump_ctx("flow.source"),
10614                &mut state,
10615                JumpControl {
10616                    flow: "flow.target".into(),
10617                    node: Some("node-missing".into()),
10618                    payload: json!({ "ok": true }),
10619                    hints: Value::Null,
10620                    max_redirects: None,
10621                    reason: None,
10622                },
10623            ))
10624            .unwrap_err();
10625        assert!(
10626            err.to_string().contains("unknown_node"),
10627            "unexpected error: {err}"
10628        );
10629    }
10630
10631    #[test]
10632    fn apply_jump_uses_default_start_fallback() {
10633        let engine = jump_test_engine();
10634        let mut state = ExecutionState::new(Value::Null);
10635        let rt = Runtime::new().unwrap();
10636        let target = rt
10637            .block_on(engine.apply_jump(
10638                &jump_ctx("flow.source"),
10639                &mut state,
10640                JumpControl {
10641                    flow: "flow.target".into(),
10642                    node: None,
10643                    payload: json!({ "k": "v" }),
10644                    hints: Value::Null,
10645                    max_redirects: None,
10646                    reason: None,
10647                },
10648            ))
10649            .expect("jump target");
10650        assert_eq!(target.flow_id, "flow.target");
10651        assert_eq!(target.node_id.as_str(), "node-a");
10652    }
10653
10654    #[test]
10655    fn condition_values_containing_another_operator_split_at_the_real_one() {
10656        let ctx = json!({ "x": "5", "msg": { "text": "a>=b" }, "n": 7 });
10657        assert!(evaluate_simple_condition(r#"msg.text == "a>=b""#, &ctx));
10658        assert!(!evaluate_simple_condition(r#"msg.text != "a>=b""#, &ctx));
10659        // `>` is the operator; the `==` lives inside the quoted literal.
10660        assert!(evaluate_simple_condition(r#"n > "3""#, &ctx));
10661        assert!(!evaluate_simple_condition(r#"n > "a==b""#, &ctx));
10662        assert!(evaluate_simple_condition(r#"x >= 5"#, &ctx));
10663        assert!(evaluate_simple_condition(r#"msg.text contains "=b""#, &ctx));
10664        assert!(!evaluate_simple_condition("no operator here", &ctx));
10665    }
10666
10667    #[test]
10668    fn step_budget_trips_only_past_the_cap() {
10669        assert!(check_step_budget(MAX_STEPS_PER_TURN, "f").is_ok());
10670        let err = check_step_budget(MAX_STEPS_PER_TURN + 1, "f").unwrap_err();
10671        assert!(err.to_string().contains("flow_step_limit_exceeded"));
10672        assert!(!should_retry(&err));
10673        assert!(is_terminal_flow_error(&err));
10674    }
10675
10676    #[test]
10677    fn terminal_marker_overrides_transient_sounding_text() {
10678        let err = terminal_flow_error("internal timeout: unavailable");
10679        assert!(!should_retry(&err));
10680        assert!(!should_retry(&err.context("node failed")));
10681        assert!(should_retry(&anyhow!("internal server error")));
10682    }
10683
10684    #[test]
10685    fn redirect_count_resets_for_a_resumed_turn() {
10686        let mut state = ExecutionState::new(Value::Null);
10687        state.increment_redirect_count();
10688        state.increment_redirect_count();
10689        assert_eq!(state.redirect_count(), 2);
10690        state.reset_redirect_count();
10691        assert_eq!(state.redirect_count(), 0);
10692    }
10693
10694    #[test]
10695    fn apply_jump_redirect_limit_enforced() {
10696        let engine = jump_test_engine();
10697        let mut state = ExecutionState::new(Value::Null);
10698        state.redirect_count = 3;
10699        let rt = Runtime::new().unwrap();
10700        let err = rt
10701            .block_on(engine.apply_jump(
10702                &jump_ctx("flow.source"),
10703                &mut state,
10704                JumpControl {
10705                    flow: "flow.target".into(),
10706                    node: None,
10707                    payload: json!({ "k": "v" }),
10708                    hints: Value::Null,
10709                    max_redirects: Some(3),
10710                    reason: None,
10711                },
10712            ))
10713            .unwrap_err();
10714        assert_eq!(err.to_string(), "redirect_limit");
10715    }
10716
10717    #[test]
10718    fn park_turns_bump_and_reset() {
10719        let mut state = ExecutionState::new(Value::Null);
10720        assert_eq!(state.bump_park_turns("a"), 1);
10721        assert_eq!(state.bump_park_turns("a"), 2);
10722        // A different node's counter is independent.
10723        assert_eq!(state.bump_park_turns("b"), 1);
10724        assert_eq!(state.bump_park_turns("a"), 3);
10725
10726        state.reset_park_turns("a");
10727        assert_eq!(
10728            state.bump_park_turns("a"),
10729            1,
10730            "reset must restart from zero"
10731        );
10732        assert_eq!(
10733            state.bump_park_turns("b"),
10734            2,
10735            "resetting `a` must not disturb `b`'s counter"
10736        );
10737    }
10738
10739    #[test]
10740    fn park_turns_survives_snapshot_roundtrip() {
10741        // park_turns must persist across a park/resume, which is a serde
10742        // round-trip of ExecutionState (same contract as redirect_count /
10743        // vars — see execution_state_vars_survive_serde_round_trip).
10744        let mut state = ExecutionState::new(json!({}));
10745        state.bump_park_turns("agent-1");
10746        state.bump_park_turns("agent-1");
10747
10748        let encoded = serde_json::to_string(&state).expect("serialize");
10749        let decoded: ExecutionState = serde_json::from_str(&encoded).expect("deserialize");
10750        assert_eq!(decoded.park_turns.get("agent-1"), Some(&2));
10751
10752        // A legacy snapshot serialized before `park_turns` existed (no
10753        // `park_turns` key) must still load, defaulting to an empty map.
10754        let legacy = r#"{"entry":{},"input":{},"nodes":{},"egress":[],"redirect_count":0}"#;
10755        let decoded_legacy: ExecutionState = serde_json::from_str(legacy).expect("legacy loads");
10756        assert!(decoded_legacy.park_turns.is_empty());
10757    }
10758
10759    #[test]
10760    fn pending_agent_await_mark_and_take() {
10761        let mut st = ExecutionState::new(serde_json::json!({}));
10762        assert!(!st.take_agent_await("agent"), "unmarked node takes false");
10763        st.mark_agent_await("agent");
10764        assert!(st.take_agent_await("agent"), "marked node takes true");
10765        assert!(!st.take_agent_await("agent"), "take clears the marker");
10766        // Independent per node.
10767        st.mark_agent_await("a");
10768        st.mark_agent_await("b");
10769        assert!(st.take_agent_await("a"));
10770        assert!(st.take_agent_await("b"));
10771    }
10772
10773    #[test]
10774    fn pending_agent_await_survives_snapshot_roundtrip() {
10775        let mut st = ExecutionState::new(serde_json::json!({}));
10776        st.mark_agent_await("agent");
10777        let json = serde_json::to_string(&st).expect("serialize");
10778        let back: ExecutionState = serde_json::from_str(&json).expect("deserialize");
10779        let mut back = back;
10780        assert!(
10781            back.take_agent_await("agent"),
10782            "marker survives serde round-trip"
10783        );
10784        // Legacy snapshot without the key decodes to empty (serde default).
10785        let legacy = r#"{"entry":{},"input":{},"nodes":{},"egress":[],"redirect_count":0,"vars":{},"park_turns":{}}"#;
10786        let mut legacy: ExecutionState = serde_json::from_str(legacy).expect("legacy decode");
10787        assert!(!legacy.take_agent_await("agent"), "absent key → empty");
10788    }
10789
10790    #[test]
10791    fn approval_await_mark_and_take() {
10792        let mut st = ExecutionState::new(json!({}));
10793        assert!(
10794            st.take_approval_await("gate").is_none(),
10795            "unmarked node takes None"
10796        );
10797        st.mark_approval_await("gate", parked("corr::n=abc", Some("fp")));
10798        assert_eq!(
10799            st.take_approval_await("gate"),
10800            Some(parked("corr::n=abc", Some("fp"))),
10801            "marked node takes its recorded correlation and fingerprint"
10802        );
10803        assert!(
10804            st.take_approval_await("gate").is_none(),
10805            "take clears the mark"
10806        );
10807    }
10808
10809    #[test]
10810    fn approval_await_survives_snapshot_roundtrip() {
10811        let mut st = ExecutionState::new(json!({}));
10812        st.mark_approval_await("gate", parked("corr::n=abc", Some("fp")));
10813        let encoded = serde_json::to_string(&st).expect("serialize");
10814        assert!(
10815            !encoded.contains("decision_token"),
10816            "only the fingerprint is persisted"
10817        );
10818        let mut decoded: ExecutionState = serde_json::from_str(&encoded).expect("deserialize");
10819        assert_eq!(
10820            decoded.pending_approvals(),
10821            vec![parked("corr::n=abc", Some("fp"))]
10822        );
10823        assert_eq!(
10824            decoded.take_approval_await("gate"),
10825            Some(parked("corr::n=abc", Some("fp"))),
10826            "the marker, correlation and fingerprint must survive a park/resume snapshot"
10827        );
10828    }
10829
10830    #[test]
10831    fn approval_await_defaults_empty_for_old_snapshots() {
10832        // Snapshots persisted before this field exists must still decode.
10833        let mut decoded: ExecutionState =
10834            serde_json::from_str(r#"{"entry":{},"input":{}}"#).expect("old snapshot decodes");
10835        assert!(decoded.take_approval_await("gate").is_none());
10836    }
10837
10838    #[test]
10839    fn approval_await_decodes_the_pre_correlation_unit_marker() {
10840        // Before the correlation id was recorded the value was `()`, which
10841        // serialises as `null`. Such a snapshot must still read as parked —
10842        // with no recorded id, so the resume path does not verify it.
10843        let mut decoded: ExecutionState = serde_json::from_str(
10844            r#"{"entry":{},"input":{},"pending_approval_await":{"gate":null}}"#,
10845        )
10846        .expect("pre-correlation snapshot decodes");
10847        assert_eq!(decoded.pending_approvals(), vec![ParkedApproval::default()]);
10848        assert_eq!(
10849            decoded.take_approval_await("gate"),
10850            Some(ParkedApproval::default())
10851        );
10852    }
10853
10854    fn parked(correlation: &str, fingerprint: Option<&str>) -> ParkedApproval {
10855        ParkedApproval {
10856            correlation_id: Some(correlation.to_string()),
10857            token_fingerprint: fingerprint.map(str::to_string),
10858        }
10859    }
10860
10861    #[test]
10862    fn a_snapshot_parked_before_tokens_has_no_fingerprint_and_is_not_verified() {
10863        // Written by a runner predating #794: correlation id, no token map.
10864        let decoded: ExecutionState = serde_json::from_str(
10865            r#"{"entry":{},"input":{},"pending_approval_await":{"gate":"corr::n=abc"}}"#,
10866        )
10867        .expect("pre-token snapshot decodes");
10868        let parks = decoded.pending_approvals();
10869        assert_eq!(parks, vec![parked("corr::n=abc", None)]);
10870        assert!(response_authenticates(
10871            &json!({"ok": true, "output": {"decision": "approved"}}),
10872            &parks[0]
10873        ));
10874    }
10875
10876    #[test]
10877    fn a_tokened_gate_resumes_only_on_its_own_token_and_only_once() {
10878        let issued = approval_token::issue();
10879        let mut st = ExecutionState::new(json!({}));
10880        st.mark_approval_await("gate", parked("corr", Some(&issued.fingerprint)));
10881        let right =
10882            json!({"ok": true, "output": {"decision": "approved", "decision_token": issued.token}});
10883        let wrong = json!({"ok": true, "output": {"decision": "approved", "decision_token": approval_token::issue().token}});
10884        let missing = json!({"ok": true, "output": {"decision": "approved"}});
10885
10886        let park = st.take_approval_await("gate").expect("parked");
10887        assert!(!response_authenticates(&missing, &park));
10888        assert!(!response_authenticates(&wrong, &park));
10889        assert!(response_authenticates(&right, &park));
10890        // Spent: the fingerprint left with the park, nothing remains to match.
10891        assert!(st.take_approval_await("gate").is_none());
10892        assert!(st.pending_approvals().is_empty());
10893    }
10894
10895    #[test]
10896    fn dispatch_outcome_await_here_stores_variant() {
10897        // DispatchOutcome::await_here must store NodeControl::AwaitHere with
10898        // both the reason and the correlation_id carried through unchanged
10899        // (Task 4/5 build on this; the drive-loop handler resumes at self —
10900        // see the behavioral coverage in Task 6).
10901        let output = NodeOutput::new(json!({"ok": true}));
10902        let outcome = DispatchOutcome::await_here(
10903            output,
10904            Some("awaiting agent response".to_string()),
10905            "corr-123".to_string(),
10906        );
10907        match outcome.control {
10908            NodeControl::AwaitHere {
10909                reason,
10910                correlation_id,
10911            } => {
10912                assert_eq!(reason.as_deref(), Some("awaiting agent response"));
10913                assert_eq!(correlation_id, "corr-123");
10914            }
10915            other => panic!("expected NodeControl::AwaitHere, got {other:?}"),
10916        }
10917    }
10918
10919    // --- on_message routes: where a card sends a typed answer -------------
10920
10921    fn on_message_routing() -> Value {
10922        json!([
10923            { "condition": "response.action == \"go_a\"", "to": "page_a" },
10924            { "to": "fallback", "on_message": true },
10925            { "out": true }
10926        ])
10927    }
10928
10929    fn empty_flow() -> HostFlow {
10930        HostFlow {
10931            id: "flow.test".to_string(),
10932            start: None,
10933            nodes: IndexMap::new(),
10934            vars_init: JsonMap::new(),
10935            required_vars: Vec::new(),
10936            slot_schema: None,
10937        }
10938    }
10939
10940    fn route_with(resumed_at: Option<&str>, entry: Value) -> CustomRoutingDecision {
10941        let mut state = ExecutionState::new(entry.clone());
10942        state.entry = entry;
10943        state.resumed_at = resumed_at.map(str::to_string);
10944        evaluate_custom_routing(
10945            &on_message_routing(),
10946            &NodeOutput::new(Value::Null),
10947            &state,
10948            &empty_flow(),
10949            &NodeId::from_str("menu").unwrap(),
10950        )
10951    }
10952
10953    #[test]
10954    fn an_on_message_route_does_not_fire_when_the_card_was_just_rendered() {
10955        // Not resumed: an unconditional route here would skip the card entirely.
10956        let decision = route_with(None, json!({ "text": "hello" }));
10957        assert!(
10958            matches!(decision, CustomRoutingDecision::Wait),
10959            "a freshly rendered card must park, got {decision:?}"
10960        );
10961    }
10962
10963    #[test]
10964    fn an_on_message_route_is_taken_when_the_person_types_at_the_parked_card() {
10965        let decision = route_with(Some("menu"), json!({ "text": "2+2 berapa?" }));
10966        match decision {
10967            CustomRoutingDecision::Next(n) => assert_eq!(n.as_str(), "fallback"),
10968            other => panic!("expected fallback, got {other:?}"),
10969        }
10970    }
10971
10972    #[test]
10973    fn a_button_still_wins_over_the_on_message_route() {
10974        let entry = json!({ "text": "", "metadata": { "action": "go_a" } });
10975        match route_with(Some("menu"), entry) {
10976            CustomRoutingDecision::Next(n) => assert_eq!(n.as_str(), "page_a"),
10977            other => panic!("expected page_a, got {other:?}"),
10978        }
10979    }
10980
10981    #[test]
10982    fn an_unknown_action_reparks_instead_of_taking_the_on_message_route() {
10983        let entry = json!({ "text": "", "metadata": { "action": "stale_button" } });
10984        let decision = route_with(Some("menu"), entry);
10985        assert!(
10986            matches!(decision, CustomRoutingDecision::Wait),
10987            "a click that matches nothing is not a typed message, got {decision:?}"
10988        );
10989    }
10990
10991    #[test]
10992    fn a_resume_at_another_node_does_not_take_the_route() {
10993        let decision = route_with(Some("some_other_card"), json!({ "text": "hi" }));
10994        assert!(matches!(decision, CustomRoutingDecision::Wait));
10995    }
10996
10997    #[test]
10998    fn only_a_card_awaiting_its_submit_counts_as_a_resumed_card() {
10999        let mut snapshot = FlowSnapshot {
11000            pack_id: "p".into(),
11001            flow_id: "f".into(),
11002            next_flow: None,
11003            next_node: "menu".into(),
11004            awaiting_submit: true,
11005            state: ExecutionState::new(Value::Null),
11006        };
11007        assert_eq!(resumed_card_node(&snapshot).as_deref(), Some("menu"));
11008        // `session.wait` names its successor, which has not run.
11009        snapshot.awaiting_submit = false;
11010        assert_eq!(resumed_card_node(&snapshot), None);
11011    }
11012
11013    /// Regression: a `Routing::Custom` array containing at least one
11014    /// conditional entry must pause (return `Wait`) when no condition
11015    /// matches, instead of terminating. Concrete bug it guards against:
11016    /// every card click used to terminate the flow because the entry-card's
11017    /// routing array didn't enumerate every downstream action, so users got
11018    /// looped back to the entry on every interaction.
11019    #[test]
11020    fn evaluate_custom_routing_waits_when_conditional_falls_through() {
11021        let raw_routing = json!([
11022            { "condition": "response.action == \"go\"", "to": "next" },
11023            { "out": true }
11024        ]);
11025        let flow_ir = HostFlow {
11026            id: "flow.test".to_string(),
11027            start: None,
11028            nodes: IndexMap::new(),
11029            vars_init: JsonMap::new(),
11030            required_vars: Vec::new(),
11031            slot_schema: None,
11032        };
11033        let current_node = NodeId::from_str("current").unwrap();
11034        let output = NodeOutput::new(Value::Null);
11035
11036        // First case: empty action -> conditional does not match, must wait.
11037        let mut state_empty = ExecutionState::new(json!({ "metadata": { "action": "" } }));
11038        state_empty.entry = json!({ "metadata": { "action": "" } });
11039        let decision_empty =
11040            evaluate_custom_routing(&raw_routing, &output, &state_empty, &flow_ir, &current_node);
11041        assert!(
11042            matches!(decision_empty, CustomRoutingDecision::Wait),
11043            "expected Wait on conditional fall-through, got {decision_empty:?}"
11044        );
11045
11046        // Second case: action == "go" -> conditional matches, must advance.
11047        let mut state_go = ExecutionState::new(json!({ "metadata": { "action": "go" } }));
11048        state_go.entry = json!({ "metadata": { "action": "go" } });
11049        let decision_go =
11050            evaluate_custom_routing(&raw_routing, &output, &state_go, &flow_ir, &current_node);
11051        match decision_go {
11052            CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "next"),
11053            other => panic!("expected Next(\"next\"), got {other:?}"),
11054        }
11055    }
11056
11057    #[test]
11058    fn node_output_with_error_marks_ok_false_and_stashes_in_meta() {
11059        let err: Box<dyn std::error::Error + 'static> =
11060            Box::<dyn std::error::Error + 'static>::from("weatherapi returned 401 Unauthorized");
11061        let out = NodeOutput::with_error("call_weather", err.as_ref());
11062        assert!(!out.ok);
11063        assert_eq!(out.payload, Value::Null);
11064        assert_eq!(out.meta["error"]["kind"], "flow_node_failed");
11065        assert_eq!(out.meta["error"]["node_id"], "call_weather");
11066        assert_eq!(
11067            out.meta["error"]["message"],
11068            "weatherapi returned 401 Unauthorized"
11069        );
11070    }
11071
11072    #[test]
11073    fn lift_first_node_error_promotes_node_meta_to_output_metadata() {
11074        // Two nodes ran; the first failed, the second produced a default-
11075        // looking output (flow author wrote no error routing). The executor
11076        // must lift the first failure into output.metadata so the messaging
11077        // provider renders the error card without any flow-author changes.
11078        let mut nodes: HashMap<String, NodeOutput> = HashMap::new();
11079        let err: Box<dyn std::error::Error + 'static> =
11080            Box::<dyn std::error::Error + 'static>::from("weatherapi returned 401 Unauthorized");
11081        nodes.insert(
11082            "call_weather".to_string(),
11083            NodeOutput::with_error("call_weather", err.as_ref()),
11084        );
11085        nodes.insert(
11086            "render_current_card".to_string(),
11087            NodeOutput::new(json!({ "text": "message" })),
11088        );
11089
11090        let final_output = json!({ "text": "message" });
11091        let enriched = lift_first_node_error_from_nodes(final_output, &nodes);
11092        assert_eq!(
11093            enriched["metadata"]["error_kind"], "flow_node_failed",
11094            "first failing node's kind must be lifted"
11095        );
11096        assert_eq!(
11097            enriched["metadata"]["error_message"],
11098            "weatherapi returned 401 Unauthorized"
11099        );
11100        assert_eq!(enriched["metadata"]["node_id"], "call_weather");
11101        // Preserves the original payload bits so downstream renderers still
11102        // see what the flow produced.
11103        assert_eq!(enriched["text"], "message");
11104    }
11105
11106    #[test]
11107    fn lift_first_node_error_is_noop_when_all_nodes_ok() {
11108        let mut nodes: HashMap<String, NodeOutput> = HashMap::new();
11109        nodes.insert(
11110            "ok_node".to_string(),
11111            NodeOutput::new(json!({ "text": "all good" })),
11112        );
11113        let output = json!({ "text": "all good" });
11114        let lifted = lift_first_node_error_from_nodes(output.clone(), &nodes);
11115        assert_eq!(lifted, output);
11116    }
11117
11118    /// An engine holding one flow whose start node is missing, so `drive_flow`
11119    /// returns `Err` on node lookup. Shared by the terminal-failure tests below.
11120    fn broken_flow_engine(pack_id_str: &str, flow_id_str: &str) -> FlowEngine {
11121        let host_flow = host_flow_for_test(flow_id_str, &["only-node"], Some("does-not-exist"));
11122        FlowEngine {
11123            operala_node_handler: None,
11124            packs: Vec::new(),
11125            flows: Vec::new(),
11126            flow_sources: HashMap::new(),
11127            messaging_provider_pack_ids: std::collections::HashSet::new(),
11128            flow_cache: RwLock::new(HashMap::from([(
11129                FlowKey {
11130                    pack_id: pack_id_str.to_string(),
11131                    flow_id: flow_id_str.to_string(),
11132                },
11133                host_flow,
11134            )])),
11135            default_env: "local".to_string(),
11136            validation: ValidationConfig {
11137                mode: ValidationMode::Off,
11138            },
11139            cross_pack_resolver: None,
11140            rollout_ids: RolloutIds::default(),
11141            approval_dispatch_handler: None,
11142            remote_dispatch_handler: None,
11143            #[cfg(feature = "agentic-worker")]
11144            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
11145            #[cfg(feature = "agentic-worker")]
11146            agent_node_handler: None,
11147            #[cfg(feature = "agentic-worker")]
11148            graph_node_handler: None,
11149            #[cfg(feature = "agentic-worker")]
11150            mcp_tool_source: None,
11151            #[cfg(feature = "agentic-worker")]
11152            mcp_secrets: None,
11153            #[cfg(feature = "agentic-worker")]
11154            a2a_sources: RwLock::new(HashMap::new()),
11155            #[cfg(feature = "agentic-worker")]
11156            ext_artifact_port: None,
11157        }
11158    }
11159
11160    /// A single-attempt, session-bound context for `broken_flow_engine`.
11161    fn terminal_failure_ctx<'a>(pack_id_str: &'a str, flow_id_str: &'a str) -> FlowContext<'a> {
11162        FlowContext {
11163            tenant: "demo",
11164            pack_id: pack_id_str,
11165            flow_id: flow_id_str,
11166            node_id: None,
11167            tool: None,
11168            action: None,
11169            session_id: Some("conv-1"),
11170            provider_id: None,
11171            reply_scope: None,
11172            retry_config: RetryConfig {
11173                max_attempts: 1,
11174                base_delay_ms: 1,
11175            },
11176            attempt: 1,
11177            observer: None,
11178            mocks: None,
11179            caller: None,
11180        }
11181    }
11182
11183    /// A node that fails mid-turn must not erase what the nodes before it
11184    /// produced: the terminal-failure envelope carries their outputs, so a
11185    /// caller reading per-node traces still sees the steps that really ran.
11186    #[tokio::test]
11187    async fn a_terminal_failure_keeps_the_outputs_of_the_nodes_that_ran() {
11188        let (pack_id_str, flow_id_str) = ("test-pack", "partial.flow");
11189        let node = |id: &str, component: &str, routing: Routing| {
11190            let id = NodeId::from_str(id).unwrap();
11191            (
11192                id.clone(),
11193                Node {
11194                    id,
11195                    component: FlowComponentRef {
11196                        id: component.parse().unwrap(),
11197                        pack_alias: None,
11198                        operation: None,
11199                    },
11200                    input: InputMapping {
11201                        mapping: json!({ "message": "hello" }),
11202                    },
11203                    output: OutputMapping {
11204                        mapping: Value::Null,
11205                    },
11206                    err_map: None,
11207                    routing,
11208                    telemetry: TelemetryHints::default(),
11209                    conversational: false,
11210                },
11211            )
11212        };
11213        let mut nodes = indexmap::IndexMap::default();
11214        let (first_id, first) = node(
11215            "first",
11216            "emit.log",
11217            Routing::Next {
11218                node_id: NodeId::from_str("second").unwrap(),
11219            },
11220        );
11221        nodes.insert(first_id, first);
11222        let (second_id, second) = node("second", "no.such.component", Routing::End);
11223        nodes.insert(second_id, second);
11224        let flow = HostFlow::from(Flow {
11225            schema_version: "1.0".into(),
11226            id: FlowId::from_str(flow_id_str).unwrap(),
11227            kind: FlowKind::Messaging,
11228            entrypoints: BTreeMap::from([("default".to_string(), Value::String("first".into()))]),
11229            nodes,
11230            metadata: Default::default(),
11231        });
11232        let engine = broken_flow_engine(pack_id_str, flow_id_str);
11233        engine.flow_cache.write().insert(
11234            FlowKey {
11235                pack_id: pack_id_str.to_string(),
11236                flow_id: flow_id_str.to_string(),
11237            },
11238            flow,
11239        );
11240        let ctx = terminal_failure_ctx(pack_id_str, flow_id_str);
11241        let result = engine
11242            .execute(ctx, Value::Null)
11243            .await
11244            .expect("a session flow surfaces the failure as an envelope");
11245        assert_eq!(
11246            result.output["metadata"]["error_kind"],
11247            "flow_execution_failed"
11248        );
11249        assert!(
11250            result.node_outputs.contains_key("first"),
11251            "the node that ran before the failure must keep its output, got {:?}",
11252            result.node_outputs
11253        );
11254    }
11255
11256    #[tokio::test]
11257    async fn execute_user_facing_flow_failure_returns_completed_with_error_envelope() {
11258        // With session_id present, execute() must convert the terminal Err to a
11259        // Completed FlowExecution carrying error_kind/error_message in
11260        // output.metadata plus user-safe text.
11261        let flow_id_str = "broken.flow";
11262        let pack_id_str = "test-pack";
11263        let engine = broken_flow_engine(pack_id_str, flow_id_str);
11264        let ctx = terminal_failure_ctx(pack_id_str, flow_id_str);
11265        let result = engine
11266            .execute(ctx, Value::Null)
11267            .await
11268            .expect("must not propagate Err");
11269        assert!(matches!(result.status, FlowStatus::Completed));
11270        assert_eq!(
11271            result.output["metadata"]["error_kind"],
11272            "flow_execution_failed"
11273        );
11274        let msg = result.output["metadata"]["error_message"]
11275            .as_str()
11276            .unwrap_or("");
11277        assert!(!msg.is_empty(), "error_message must be populated");
11278        assert_eq!(result.output["metadata"]["flow_id"], "broken.flow");
11279        // Without a `text`, this envelope reaches nobody: every messaging
11280        // provider refuses a payload with no text/card, webchat included (its
11281        // required-content guard runs BEFORE its error-card path). The comment
11282        // above once claimed the user "sees the error card"; that only held for
11283        // the `lift_first_node_error_from_nodes` envelope, which enriches an
11284        // output that already carries text.
11285        assert_eq!(
11286            result.output["text"],
11287            user_facing_flow_failure_text(&Value::Null),
11288            "a terminal session-flow failure must carry the resolved user-facing message"
11289        );
11290        // Localisation must not be able to reintroduce the silence: whatever
11291        // locale this process resolved to, `text` has to be a non-empty string.
11292        let shown = result.output["text"].as_str().unwrap_or_default();
11293        assert!(
11294            !shown.trim().is_empty(),
11295            "an empty `text` is silent on every channel"
11296        );
11297        // And the engine's own wording must NOT be what the user is shown.
11298        assert!(
11299            !shown.contains("does-not-exist"),
11300            "raw engine text must stay in metadata.error_message"
11301        );
11302    }
11303
11304    /// The conversation's own locale — not the deployment's — decides the
11305    /// language a failing flow apologises in.
11306    ///
11307    /// Drives the real `execute` failure path, so it also pins that
11308    /// `original_input` (and not something else) is what gets consulted.
11309    #[tokio::test]
11310    async fn execute_user_facing_flow_failure_answers_in_the_conversation_locale() {
11311        let flow_id_str = "broken.flow";
11312        let pack_id_str = "test-pack";
11313        let engine = broken_flow_engine(pack_id_str, flow_id_str);
11314
11315        // Same `metadata.locale` shape the card path already honours.
11316        let result = engine
11317            .execute(
11318                terminal_failure_ctx(pack_id_str, flow_id_str),
11319                json!({ "metadata": { "locale": "id-ID" } }),
11320            )
11321            .await
11322            .expect("must not propagate Err");
11323        let shown = result.output["text"].as_str().unwrap_or_default();
11324        assert_eq!(
11325            shown,
11326            user_facing_flow_failure_text_for("id"),
11327            "an Indonesian conversation must be answered in Indonesian"
11328        );
11329        assert_ne!(
11330            shown,
11331            crate::runner::i18n::FLOW_EXECUTION_FAILED_EN,
11332            "the conversation locale was ignored"
11333        );
11334
11335        // The nested shape is honoured too, and the raw engine error still must
11336        // not leak into a localized `text`.
11337        let nested = engine
11338            .execute(
11339                terminal_failure_ctx(pack_id_str, flow_id_str),
11340                json!({ "input": { "metadata": { "locale": "ja" } } }),
11341            )
11342            .await
11343            .expect("must not propagate Err");
11344        let nested_text = nested.output["text"].as_str().unwrap_or_default();
11345        assert_eq!(nested_text, user_facing_flow_failure_text_for("ja"));
11346        assert!(!nested_text.trim().is_empty());
11347        assert!(
11348            !nested_text.contains("does-not-exist"),
11349            "raw engine text must stay in metadata.error_message in every locale"
11350        );
11351
11352        // A locale nobody translated still gets a reply, in English.
11353        let unknown = engine
11354            .execute(
11355                terminal_failure_ctx(pack_id_str, flow_id_str),
11356                json!({ "metadata": { "locale": "kl-GL" } }),
11357            )
11358            .await
11359            .expect("must not propagate Err");
11360        assert_eq!(
11361            unknown.output["text"],
11362            crate::runner::i18n::FLOW_EXECUTION_FAILED_EN
11363        );
11364    }
11365
11366    #[test]
11367    fn activity_locale_reads_both_shapes_and_treats_blank_as_absent() {
11368        assert_eq!(
11369            activity_locale(&json!({ "metadata": { "locale": "nl-NL" } })),
11370            Some("nl-NL")
11371        );
11372        assert_eq!(
11373            activity_locale(&json!({ "input": { "metadata": { "locale": "en-GB" } } })),
11374            Some("en-GB")
11375        );
11376        // The nested shape wins, matching inject_card_locale's ordering.
11377        assert_eq!(
11378            activity_locale(&json!({
11379                "input": { "metadata": { "locale": "ja" } },
11380                "metadata": { "locale": "id" },
11381            })),
11382            Some("ja")
11383        );
11384        // A blank stamp must not out-rank the deployment locale.
11385        assert_eq!(
11386            activity_locale(&json!({ "metadata": { "locale": "  " } })),
11387            None
11388        );
11389        assert_eq!(
11390            activity_locale(&json!({ "metadata": { "locale": "" } })),
11391            None
11392        );
11393        assert_eq!(
11394            activity_locale(&json!({ "metadata": { "locale": 7 } })),
11395            None
11396        );
11397        assert_eq!(activity_locale(&Value::Null), None);
11398        assert_eq!(activity_locale(&json!({})), None);
11399    }
11400
11401    /// The locale table must localize, and must never be able to reintroduce
11402    /// the silent-on-every-channel bug.
11403    ///
11404    /// Drives `user_facing_flow_failure_text_for` directly rather than the env,
11405    /// so every entry is covered without an `unsafe` `set_var`.
11406    #[test]
11407    fn user_facing_flow_failure_text_is_localized_and_never_empty() {
11408        let english = user_facing_flow_failure_text_for("en");
11409        assert_eq!(english, crate::runner::i18n::FLOW_EXECUTION_FAILED_EN);
11410
11411        // Every shipped translation must differ from English — otherwise the
11412        // table is present but not wired up, which is the bug this replaces.
11413        for locale in ["id", "es", "ja", "zh"] {
11414            let translated = user_facing_flow_failure_text_for(locale);
11415            assert_ne!(
11416                translated, english,
11417                "`{locale}` must resolve to its own wording, not English"
11418            );
11419        }
11420
11421        // Region subtags and separators normalize to the primary subtag.
11422        assert_eq!(user_facing_flow_failure_text_for("id-ID"), {
11423            user_facing_flow_failure_text_for("id")
11424        });
11425        assert_eq!(user_facing_flow_failure_text_for("zh_TW"), {
11426            user_facing_flow_failure_text_for("zh")
11427        });
11428
11429        // Unknown, absent and container-default locales fall back to English
11430        // rather than to nothing.
11431        for locale in ["", "xx", "klingon", "C", "C.UTF-8", "POSIX"] {
11432            assert_eq!(
11433                user_facing_flow_failure_text_for(locale),
11434                english,
11435                "`{locale}` must fall back to English"
11436            );
11437        }
11438
11439        // The invariant that matters on every channel, across the whole table.
11440        for locale in ["en", "id", "es", "ja", "zh", "", "xx", "C.UTF-8"] {
11441            let text = user_facing_flow_failure_text_for(locale);
11442            assert!(
11443                !text.trim().is_empty(),
11444                "`{locale}` resolved to empty text, which is silent on every channel"
11445            );
11446        }
11447    }
11448
11449    #[test]
11450    fn mcp_tool_error_recognises_generator_error_shape() {
11451        // greentic-mcp-generator's tool_error_with_status emits this exact
11452        // shape when the upstream HTTP call to weatherapi.com returns 401.
11453        let value = json!({
11454            "error": {
11455                "code": "tool_error",
11456                "message": "API request returned status 401",
11457                "status": 401
11458            }
11459        });
11460        let (code, message) = mcp_tool_error(&value).expect("must detect MCP error shape");
11461        assert_eq!(code, "tool_error");
11462        assert!(message.contains("API request returned status 401"));
11463        assert!(message.contains("(status 401)"));
11464    }
11465
11466    #[test]
11467    fn mcp_tool_error_skips_success_responses() {
11468        // A success response uses `result`, not `error`.
11469        let value = json!({ "result": { "current": { "temp_c": 19.0 } } });
11470        assert!(mcp_tool_error(&value).is_none());
11471    }
11472
11473    #[test]
11474    fn mcp_tool_error_skips_non_object_and_unrelated_shapes() {
11475        assert!(mcp_tool_error(&Value::Null).is_none());
11476        assert!(mcp_tool_error(&json!({"unrelated": true})).is_none());
11477        // `error` must be an object; a string isn't enough.
11478        assert!(mcp_tool_error(&json!({"error": "oops"})).is_none());
11479    }
11480
11481    /// `normalize_mcp_tool_error` must produce exactly the shape
11482    /// `component_error` recognises, carrying the already status-qualified
11483    /// message (not the raw one), and must not drop unrelated fields (e.g.
11484    /// `error.status`).
11485    #[test]
11486    fn normalize_mcp_tool_error_matches_component_error_shape() {
11487        let value = json!({
11488            "error": { "code": "tool_error", "message": "boom", "status": 502 }
11489        });
11490        let normalized = normalize_mcp_tool_error(&value, "tool_error", "boom (status 502)");
11491        assert_eq!(
11492            component_error(&normalized),
11493            Some(("tool_error".to_string(), "boom (status 502)".to_string())),
11494            "the normalized payload must be recognised by component_error verbatim"
11495        );
11496        // `status` on the original error object survives the reshape.
11497        assert_eq!(normalized["error"]["status"], json!(502));
11498    }
11499
11500    /// `mcp_node::invoke_with_secrets` is infallible: every failure (no route,
11501    /// missing credential, dead endpoint, bad args) comes back as
11502    /// `{"error": "<string>"}` in `result`. `execute_mcp` used to report
11503    /// `ok: true` regardless, so a Digital Worker run showed 33/33 green
11504    /// nodes and rendered its quote card with every field blank.
11505    ///
11506    /// A node WITH an `on_error`-family route must now see `ok: false`, and
11507    /// the failure must be normalized into `component_error`'s
11508    /// `{ok:false, error:{code,message}}` shape (via `normalize_mcp_tool_error`)
11509    /// so `to_node_output`/`node_output_view` populate `{errors}` exactly like
11510    /// a failed component call does — one definition of what a failed node's
11511    /// errors look like, not a second one for this code path.
11512    ///
11513    /// `bound` here has no `output:` binding key, so it degrades to the bare
11514    /// tool result (`{"error": "..."}`); `mcp_node_output_preserves_the_output_binding_key`
11515    /// below covers the wrapped case.
11516    #[cfg(feature = "agentic-worker")]
11517    #[test]
11518    fn mcp_node_output_reports_failure_when_the_node_has_an_error_route() {
11519        let result = json!({ "error": "MCP is not configured on this runner" });
11520        let bound = result.clone();
11521
11522        let out = mcp_node_output(bound, &result, true);
11523
11524        assert!(
11525            !out.ok,
11526            "a failed MCP call with an error route must not report ok"
11527        );
11528        assert_eq!(
11529            component_error(&out.payload),
11530            Some((
11531                "mcp_call_failed".to_string(),
11532                "MCP is not configured on this runner".to_string()
11533            )),
11534            "the payload must be recognised by component_error verbatim, got {:?}",
11535            out.payload
11536        );
11537        assert_eq!(
11538            out.meta.pointer("/error/message").and_then(Value::as_str),
11539            Some("MCP is not configured on this runner"),
11540            "the message must reach meta.error where lift_first_node_error_from_nodes reads it"
11541        );
11542
11543        let view = node_output_view(&out.payload);
11544        let errors = view["errors"].as_array().expect("errors must be an array");
11545        assert_eq!(errors.len(), 1, "errors must be populated, got {view:?}");
11546        assert_eq!(
11547            errors[0]["message"], "MCP is not configured on this runner",
11548            "{{{{node.<id>.errors[0].message}}}} must surface the real message"
11549        );
11550    }
11551
11552    /// The failure shape is not always a plain string: greentic-mcp-generator's
11553    /// `tool_error_with_status` emits `{"error":{"code","message","status"}}`
11554    /// (Phase 2's weatherapi-401 case, `mcp_tool_error_recognises_generator_error_shape`).
11555    /// `mcp_node_output` must reuse `mcp_tool_error` for this shape rather than
11556    /// falling into the plain-string arm, which would stuff the whole
11557    /// serialized error object into `message` and discard the real
11558    /// `tool_error` code for a hardcoded `mcp_call_failed`.
11559    ///
11560    /// Compared against calling `mcp_tool_error` directly on the same value —
11561    /// not a hand-typed string — so this test cannot drift from the detector
11562    /// it is supposed to match.
11563    #[cfg(feature = "agentic-worker")]
11564    #[test]
11565    fn mcp_node_output_uses_mcp_tool_error_for_the_object_shaped_error() {
11566        let result = json!({
11567            "error": {
11568                "code": "tool_error",
11569                "message": "API request returned status 401",
11570                "status": 401
11571            }
11572        });
11573        let bound = result.clone();
11574
11575        let (expected_code, expected_message) =
11576            mcp_tool_error(&result).expect("the detector must recognise this shape");
11577
11578        let out = mcp_node_output(bound, &result, true);
11579
11580        assert!(
11581            !out.ok,
11582            "an object-shaped MCP tool error with an error route must not report ok"
11583        );
11584        assert_eq!(
11585            component_error(&out.payload),
11586            Some((expected_code.clone(), expected_message.clone())),
11587            "the code/message must be exactly what mcp_tool_error derives, got {:?}",
11588            out.payload
11589        );
11590        // Pin the values themselves too, so a future change to mcp_tool_error's
11591        // formatting is visible here as well as in its own test.
11592        assert_eq!(expected_code, "tool_error");
11593        assert!(expected_message.contains("API request returned status 401"));
11594        assert!(expected_message.contains("(status 401)"));
11595
11596        let view = node_output_view(&out.payload);
11597        let errors = view["errors"].as_array().expect("errors must be an array");
11598        assert_eq!(errors.len(), 1, "errors must be populated, got {view:?}");
11599        assert_eq!(errors[0]["message"], expected_message);
11600    }
11601
11602    /// The `output:` binding key wraps the tool result under a named field
11603    /// (e.g. `quote_result_data`). Requirement 1 (keep the bound payload
11604    /// untouched) and requirement 2 (populate `{errors}`) both hold at once:
11605    /// `normalize_mcp_tool_error` is handed `bound` itself, so the wrapped
11606    /// field survives verbatim alongside the new top-level `ok`/`error`
11607    /// fields the errors envelope needs. `node.<id>.quote_result_data` and
11608    /// `node.<id>.errors[0].message` must both resolve from the same output.
11609    #[cfg(feature = "agentic-worker")]
11610    #[test]
11611    fn mcp_node_output_preserves_the_output_binding_key_alongside_the_error_envelope() {
11612        let result = json!({ "error": "connection refused" });
11613        let bound = json!({ "quote_result_data": result.clone() });
11614
11615        let out = mcp_node_output(bound.clone(), &result, true);
11616
11617        assert!(!out.ok);
11618        assert_eq!(
11619            out.payload["quote_result_data"], result,
11620            "the output-key binding must survive untouched, got {:?}",
11621            out.payload
11622        );
11623        assert_eq!(out.payload["ok"], json!(false));
11624        assert_eq!(out.payload["error"]["code"], "mcp_call_failed");
11625        assert_eq!(out.payload["error"]["message"], "connection refused");
11626
11627        let view = node_output_view(&out.payload);
11628        assert_eq!(
11629            view["quote_result_data"], result,
11630            "{{{{node.<id>.quote_result_data}}}} must still resolve, got {view:?}"
11631        );
11632        let errors = view["errors"].as_array().expect("errors must be an array");
11633        assert_eq!(errors[0]["message"], "connection refused");
11634    }
11635
11636    /// R3's answer to the third routing shape: a node whose `Routing::Custom`
11637    /// carries only success-family routes (or `Routing::Next`, which never
11638    /// has an error route by construction — see
11639    /// `node_has_error_route_detects_error_family_ports`) has nowhere to
11640    /// route a failure. `evaluate_custom_routing`'s fall-through for a
11641    /// routing array with conditions but no match is `CustomRoutingDecision::
11642    /// Wait`, which PARKS the run — worse than the pre-R3 silent wrong
11643    /// answer for an operator who never wired up error handling. So the
11644    /// failure is surfaced only when `has_error_route` is true; a node
11645    /// without one keeps reporting `ok: true`, byte-for-byte the pre-R3
11646    /// behaviour.
11647    #[cfg(feature = "agentic-worker")]
11648    #[test]
11649    fn mcp_node_output_ignores_failure_when_the_node_has_no_error_route() {
11650        let result = json!({ "error": "MCP is not configured on this runner" });
11651        let bound = json!({ "quote_result_data": result.clone() });
11652
11653        let out = mcp_node_output(bound.clone(), &result, false);
11654
11655        assert!(
11656            out.ok,
11657            "a node with no error route must keep reporting ok, unchanged from pre-R3"
11658        );
11659        assert_eq!(
11660            out.payload, bound,
11661            "the payload must be exactly the bound value, no envelope reshaping"
11662        );
11663        assert_eq!(out.meta, Value::Null);
11664    }
11665
11666    /// The success path must stay exactly as it was, regardless of
11667    /// `has_error_route`: a node that opted into error routing but whose
11668    /// call succeeded must not be affected.
11669    #[cfg(feature = "agentic-worker")]
11670    #[test]
11671    fn mcp_node_output_stays_ok_on_success_regardless_of_error_route() {
11672        let result = json!({ "annual_premium": 1234 });
11673        let bound = json!({ "quote_result_data": result.clone() });
11674
11675        for has_error_route in [true, false] {
11676            let out = mcp_node_output(bound.clone(), &result, has_error_route);
11677            assert!(out.ok, "a successful MCP call must report ok");
11678            assert_eq!(out.payload, bound);
11679            assert_eq!(out.meta, Value::Null);
11680        }
11681    }
11682
11683    /// Case 2 of the third-routing-shape analysis: a node WITH an `on_error`
11684    /// route takes it — this is the point of R3.
11685    #[cfg(feature = "agentic-worker")]
11686    #[test]
11687    fn mcp_failure_with_on_error_route_routes_to_the_error_branch() {
11688        let raw_routing = json!([
11689            { "condition": "event == \"on_success\"", "to": "ok_node" },
11690            { "condition": "event == \"on_error\"", "to": "err_node" }
11691        ]);
11692        let routing = Routing::Custom(raw_routing.clone());
11693        let flow_ir = HostFlow {
11694            id: "flow.test".to_string(),
11695            start: None,
11696            nodes: IndexMap::new(),
11697            vars_init: JsonMap::new(),
11698            required_vars: Vec::new(),
11699            slot_schema: None,
11700        };
11701        let current = NodeId::from_str("current").unwrap();
11702        let state = ExecutionState::new(json!({}));
11703
11704        let result = json!({ "error": "MCP is not configured on this runner" });
11705        let has_error_route = node_has_error_route(&routing);
11706        assert!(has_error_route);
11707        let out = mcp_node_output(result.clone(), &result, has_error_route);
11708
11709        match evaluate_custom_routing(&raw_routing, &out, &state, &flow_ir, &current) {
11710            CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "err_node"),
11711            other => panic!("expected the on_error route, got {other:?}"),
11712        }
11713    }
11714
11715    /// Case 3 of the third-routing-shape analysis, pinned end to end through
11716    /// `evaluate_custom_routing`: a node whose `Routing::Custom` array has
11717    /// only success-family routes never flips to `ok: false`, so it stays on
11718    /// the success path — never `CustomRoutingDecision::Wait` (parked).
11719    #[cfg(feature = "agentic-worker")]
11720    #[test]
11721    fn mcp_failure_with_success_only_routing_never_parks() {
11722        let raw_routing = json!([
11723            { "condition": "event == \"on_success\"", "to": "ok_node" }
11724        ]);
11725        let routing = Routing::Custom(raw_routing.clone());
11726        let flow_ir = HostFlow {
11727            id: "flow.test".to_string(),
11728            start: None,
11729            nodes: IndexMap::new(),
11730            vars_init: JsonMap::new(),
11731            required_vars: Vec::new(),
11732            slot_schema: None,
11733        };
11734        let current = NodeId::from_str("current").unwrap();
11735        let state = ExecutionState::new(json!({}));
11736
11737        let result = json!({ "error": "MCP is not configured on this runner" });
11738        let has_error_route = node_has_error_route(&routing);
11739        assert!(
11740            !has_error_route,
11741            "a success-only Custom routing has no error branch"
11742        );
11743        let out = mcp_node_output(result.clone(), &result, has_error_route);
11744        assert!(out.ok, "no error route means the failure is not surfaced");
11745
11746        match evaluate_custom_routing(&raw_routing, &out, &state, &flow_ir, &current) {
11747            CustomRoutingDecision::Next(nid) => assert_eq!(
11748                nid.as_str(),
11749                "ok_node",
11750                "the flow must continue on the success path, not park"
11751            ),
11752            other => panic!(
11753                "a node with no error route must never park on an MCP failure, got {other:?}"
11754            ),
11755        }
11756    }
11757
11758    #[tokio::test]
11759    async fn execute_non_user_facing_flow_failure_still_propagates() {
11760        // No session_id => internal job. Errors still propagate as Err so
11761        // operator alerting / metrics pipelines stay intact.
11762        let flow_id_str = "broken.flow";
11763        let pack_id_str = "test-pack";
11764        let host_flow = host_flow_for_test(flow_id_str, &["only-node"], Some("does-not-exist"));
11765        let engine = FlowEngine {
11766            operala_node_handler: None,
11767            packs: Vec::new(),
11768            flows: Vec::new(),
11769            flow_sources: HashMap::new(),
11770            messaging_provider_pack_ids: std::collections::HashSet::new(),
11771            flow_cache: RwLock::new(HashMap::from([(
11772                FlowKey {
11773                    pack_id: pack_id_str.to_string(),
11774                    flow_id: flow_id_str.to_string(),
11775                },
11776                host_flow,
11777            )])),
11778            default_env: "local".to_string(),
11779            validation: ValidationConfig {
11780                mode: ValidationMode::Off,
11781            },
11782            cross_pack_resolver: None,
11783            rollout_ids: RolloutIds::default(),
11784            approval_dispatch_handler: None,
11785            remote_dispatch_handler: None,
11786            #[cfg(feature = "agentic-worker")]
11787            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
11788            #[cfg(feature = "agentic-worker")]
11789            agent_node_handler: None,
11790            #[cfg(feature = "agentic-worker")]
11791            graph_node_handler: None,
11792            #[cfg(feature = "agentic-worker")]
11793            mcp_tool_source: None,
11794            #[cfg(feature = "agentic-worker")]
11795            mcp_secrets: None,
11796            #[cfg(feature = "agentic-worker")]
11797            a2a_sources: RwLock::new(HashMap::new()),
11798            #[cfg(feature = "agentic-worker")]
11799            ext_artifact_port: None,
11800        };
11801        let ctx = FlowContext {
11802            tenant: "demo",
11803            pack_id: pack_id_str,
11804            flow_id: flow_id_str,
11805            node_id: None,
11806            tool: None,
11807            action: None,
11808            session_id: None,
11809            provider_id: None,
11810            reply_scope: None,
11811            retry_config: RetryConfig {
11812                max_attempts: 1,
11813                base_delay_ms: 1,
11814            },
11815            attempt: 1,
11816            observer: None,
11817            mocks: None,
11818            caller: None,
11819        };
11820        let result = engine.execute(ctx, Value::Null).await;
11821        assert!(result.is_err(), "non-user-facing flow must propagate Err");
11822    }
11823
11824    // ---- Phase D: slot_schema injection tests ----
11825
11826    #[test]
11827    fn host_flow_extracts_slot_schema_from_metadata_extra() {
11828        use greentic_types::FlowMetadata;
11829        use std::collections::BTreeSet;
11830
11831        let schema = json!([
11832            {"name": "counterparty", "slot_type": "string", "required": true},
11833            {"name": "due_date", "slot_type": "date", "required": true}
11834        ]);
11835        let flow = Flow {
11836            schema_version: "flow-v1".into(),
11837            id: FlowId::from_str("test.flow").unwrap(),
11838            kind: FlowKind::Messaging,
11839            entrypoints: BTreeMap::new(),
11840            nodes: IndexMap::default(),
11841            metadata: FlowMetadata {
11842                title: None,
11843                description: None,
11844                tags: BTreeSet::new(),
11845                extra: json!({(SLOT_SCHEMA_METADATA_KEY): schema}),
11846            },
11847        };
11848        let host = HostFlow::from(flow);
11849        assert_eq!(
11850            host.slot_schema.as_ref(),
11851            Some(&schema),
11852            "HostFlow must extract slot_schema from metadata.extra"
11853        );
11854    }
11855
11856    #[test]
11857    fn host_flow_slot_schema_is_none_when_absent() {
11858        let flow = Flow {
11859            schema_version: "flow-v1".into(),
11860            id: FlowId::from_str("test.flow").unwrap(),
11861            kind: FlowKind::Messaging,
11862            entrypoints: BTreeMap::new(),
11863            nodes: IndexMap::default(),
11864            metadata: Default::default(),
11865        };
11866        let host = HostFlow::from(flow);
11867        assert!(
11868            host.slot_schema.is_none(),
11869            "HostFlow.slot_schema must be None when metadata.extra has no greentic.slot_schema"
11870        );
11871    }
11872
11873    #[test]
11874    fn inject_slot_definitions_adds_to_object_input() {
11875        let schema = json!([
11876            {"name": "city", "slot_type": "string"}
11877        ]);
11878        let mut input = json!({"utterance": "hello"});
11879        inject_slot_definitions(&mut input, &schema, "f", "n");
11880        assert_eq!(
11881            input,
11882            json!({"utterance": "hello", "slot_definitions": schema}),
11883            "slot_definitions must be injected into existing object"
11884        );
11885    }
11886
11887    #[test]
11888    fn inject_slot_definitions_wraps_null_input() {
11889        let schema = json!([{"name": "x", "slot_type": "string"}]);
11890        let mut input = Value::Null;
11891        inject_slot_definitions(&mut input, &schema, "f", "n");
11892        assert_eq!(
11893            input,
11894            json!({"slot_definitions": schema}),
11895            "null input must become an object with slot_definitions"
11896        );
11897    }
11898
11899    #[test]
11900    fn inject_slot_definitions_preserves_explicit_inline() {
11901        let flow_schema = json!([{"name": "city", "slot_type": "string"}]);
11902        let inline_defs = json!([{"name": "country", "slot_type": "string"}]);
11903        let mut input = json!({
11904            "utterance": "hello",
11905            "slot_definitions": inline_defs
11906        });
11907        inject_slot_definitions(&mut input, &flow_schema, "f", "n");
11908        assert_eq!(
11909            input["slot_definitions"], inline_defs,
11910            "explicit inline slot_definitions must not be overwritten"
11911        );
11912    }
11913
11914    #[test]
11915    fn inject_slot_definitions_skips_non_object_input() {
11916        let schema = json!([{"name": "x", "slot_type": "string"}]);
11917        let mut input = json!("a string");
11918        inject_slot_definitions(&mut input, &schema, "f", "n");
11919        assert_eq!(
11920            input,
11921            json!("a string"),
11922            "non-object input must be left unchanged"
11923        );
11924    }
11925
11926    fn make_flow_doc_for_test(
11927        id: &str,
11928        node_name: &str,
11929        component: &str,
11930        slot_schema: Option<Value>,
11931    ) -> greentic_flow::model::FlowDoc {
11932        use greentic_flow::model::{FlowDoc, NodeDoc};
11933
11934        let mut nodes = IndexMap::new();
11935        nodes.insert(
11936            node_name.to_string(),
11937            NodeDoc {
11938                raw: {
11939                    let mut m = IndexMap::new();
11940                    m.insert(
11941                        "component.exec".to_string(),
11942                        json!({ "component": component }),
11943                    );
11944                    m
11945                },
11946                routing: json!([{ "out": true }]),
11947                ..Default::default()
11948            },
11949        );
11950
11951        FlowDoc {
11952            id: id.into(),
11953            title: None,
11954            description: None,
11955            flow_type: "messaging".into(),
11956            start: Some(node_name.into()),
11957            parameters: json!({}),
11958            tags: Vec::new(),
11959            schema_version: None,
11960            entrypoints: IndexMap::new(),
11961            meta: None,
11962            slot_schema,
11963            nodes,
11964        }
11965    }
11966
11967    /// Integration test: exercises the real `greentic_flow::compile_flow`
11968    /// producer path with a `FlowDoc` carrying `slot_schema`, then converts
11969    /// through `HostFlow::from` and verifies the runtime-side `slot_schema`
11970    /// field is populated — closing the gap Codex flagged where the existing
11971    /// unit tests constructed `FlowMetadata` directly.
11972    #[test]
11973    fn compile_flow_round_trips_slot_schema_into_host_flow() {
11974        let slot_defs = json!([
11975            { "name": "counterparty", "slot_type": "string", "required": true,
11976              "pattern": ".+" },
11977            { "name": "due_date", "slot_type": "date", "required": true,
11978              "pattern": "\\d{4}-\\d{2}-\\d{2}" }
11979        ]);
11980        let doc = make_flow_doc_for_test(
11981            "slot-test",
11982            "extractor",
11983            "slot-extractor",
11984            Some(slot_defs.clone()),
11985        );
11986
11987        let flow = greentic_flow::compile_flow(doc).expect("compile_flow must succeed");
11988        assert_eq!(
11989            flow.metadata.extra.get(SLOT_SCHEMA_METADATA_KEY),
11990            Some(&slot_defs),
11991            "compile_flow must forward slot_schema into metadata.extra"
11992        );
11993
11994        let host = HostFlow::from(flow);
11995        assert_eq!(
11996            host.slot_schema.as_ref(),
11997            Some(&slot_defs),
11998            "HostFlow.slot_schema must survive the compile_flow -> HostFlow round-trip"
11999        );
12000    }
12001
12002    /// Verify that `compile_flow` without `slot_schema` produces a `Flow`
12003    /// whose `metadata.extra` has no `greentic.slot_schema` key, and that
12004    /// `HostFlow.slot_schema` stays `None` through the real compile path.
12005    #[test]
12006    fn compile_flow_without_slot_schema_leaves_host_flow_none() {
12007        let doc = make_flow_doc_for_test("no-slots", "echo", "echo", None);
12008
12009        let flow = greentic_flow::compile_flow(doc).expect("compile_flow must succeed");
12010        assert!(
12011            flow.metadata.extra.get(SLOT_SCHEMA_METADATA_KEY).is_none(),
12012            "metadata.extra must not contain greentic.slot_schema when FlowDoc.slot_schema is None"
12013        );
12014
12015        let host = HostFlow::from(flow);
12016        assert!(
12017            host.slot_schema.is_none(),
12018            "HostFlow.slot_schema must be None when FlowDoc has no slot_schema"
12019        );
12020    }
12021
12022    /// A node with 2+ outgoing edges compiles (in the designer) to
12023    /// `event == "<outcome>"` conditions. The runner must inject `event` into
12024    /// the routing context — from the node's emitted outcome, else a default
12025    /// derived from `ok` — so those conditions resolve instead of falling
12026    /// through to `Wait`. Without the injection, multi-edge nodes silently
12027    /// pause at runtime.
12028    #[test]
12029    fn multi_edge_node_routes_on_injected_event() {
12030        let raw_routing = json!([
12031            { "condition": "event == \"on_success\"", "to": "next" },
12032            { "condition": "event == \"on_error\"", "to": "err" }
12033        ]);
12034        let flow_ir = HostFlow {
12035            id: "flow.test".to_string(),
12036            start: None,
12037            nodes: IndexMap::new(),
12038            vars_init: JsonMap::new(),
12039            required_vars: Vec::new(),
12040            slot_schema: None,
12041        };
12042        let current = NodeId::from_str("current").unwrap();
12043        let state = ExecutionState::new(json!({}));
12044
12045        // ok:true with no explicit outcome → default event "on_success" → "next".
12046        let ok_out = NodeOutput::new(json!({ "x": 1 }));
12047        match evaluate_custom_routing(&raw_routing, &ok_out, &state, &flow_ir, &current) {
12048            CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "next"),
12049            other => panic!("expected Next(\"next\"), got {other:?}"),
12050        }
12051
12052        // An explicit outcome in the node metadata wins over the ok-default.
12053        let routed = NodeOutput::with_meta(json!({}), json!({ "outcome": "on_error" }));
12054        match evaluate_custom_routing(&raw_routing, &routed, &state, &flow_ir, &current) {
12055            CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "err"),
12056            other => panic!("expected Next(\"err\"), got {other:?}"),
12057        }
12058    }
12059
12060    #[test]
12061    fn approval_outcomes_route_three_ways() {
12062        // The contract this feature exists for: an approval node's decision
12063        // selects the branch. `meta["outcome"]` wins over the ok-derived
12064        // default, so `ok: true` still routes to "denied" when denied.
12065        let raw_routing = json!([
12066            { "condition": "event == \"approved\"", "to": "do_it" },
12067            { "condition": "event == \"denied\"", "to": "reject" },
12068            { "condition": "event == \"timeout\"", "to": "escalate" }
12069        ]);
12070        let flow_ir = HostFlow {
12071            slot_schema: None,
12072            id: "flow.test".to_string(),
12073            start: None,
12074            nodes: IndexMap::new(),
12075            vars_init: JsonMap::new(),
12076            required_vars: Vec::new(),
12077        };
12078        let current = NodeId::from_str("gate").unwrap();
12079        let state = ExecutionState::new(json!({}));
12080
12081        for (outcome, expected) in [
12082            ("approved", "do_it"),
12083            ("denied", "reject"),
12084            ("timeout", "escalate"),
12085        ] {
12086            let out = NodeOutput::with_meta(json!({}), json!({ "outcome": outcome }));
12087            match evaluate_custom_routing(&raw_routing, &out, &state, &flow_ir, &current) {
12088                CustomRoutingDecision::Next(nid) => assert_eq!(
12089                    nid.as_str(),
12090                    expected,
12091                    "outcome {outcome} must route to {expected}"
12092                ),
12093                other => panic!("outcome {outcome}: expected Next({expected}), got {other:?}"),
12094            }
12095        }
12096    }
12097
12098    /// A node whose component reports a failure (`{ok:false, error}`) and which
12099    /// has an `on_error`-family route must surface a node_io `Errors` output
12100    /// (`ok == false`) and route to that branch instead of aborting the flow.
12101    #[test]
12102    fn errored_output_routes_to_on_error_branch() {
12103        let raw_routing = json!([
12104            { "condition": "event == \"on_success\"", "to": "ok_node" },
12105            { "condition": "event == \"on_error\"", "to": "err_node" }
12106        ]);
12107        let flow_ir = HostFlow {
12108            id: "flow.test".to_string(),
12109            start: None,
12110            nodes: IndexMap::new(),
12111            vars_init: JsonMap::new(),
12112            required_vars: Vec::new(),
12113            slot_schema: None,
12114        };
12115        let current = NodeId::from_str("current").unwrap();
12116        let state = ExecutionState::new(json!({}));
12117
12118        let errored =
12119            NodeOutput::errored(json!({ "ok": false, "error": { "code": "E", "message": "m" } }));
12120        match evaluate_custom_routing(&raw_routing, &errored, &state, &flow_ir, &current) {
12121            CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "err_node"),
12122            other => panic!("expected on_error route, got {other:?}"),
12123        }
12124    }
12125
12126    /// A failure payload carrying its own `outcome` (e.g. a component that
12127    /// distinguishes `on_timeout` from a generic `on_error`) must route to
12128    /// THAT branch, not to the default error branch. `NodeOutput::errored`
12129    /// must therefore surface `outcome` in `meta` exactly like the success
12130    /// path's `outcome_meta` already does.
12131    #[test]
12132    fn errored_output_with_outcome_routes_to_that_branch() {
12133        let raw_routing = json!([
12134            { "condition": "event == \"on_success\"", "to": "ok_node" },
12135            { "condition": "event == \"on_timeout\"", "to": "timeout_node" },
12136            { "condition": "event == \"on_error\"", "to": "err_node" }
12137        ]);
12138        let flow_ir = HostFlow {
12139            id: "flow.test".to_string(),
12140            start: None,
12141            nodes: IndexMap::new(),
12142            vars_init: JsonMap::new(),
12143            required_vars: Vec::new(),
12144            slot_schema: None,
12145        };
12146        let current = NodeId::from_str("current").unwrap();
12147        let state = ExecutionState::new(json!({}));
12148
12149        let errored = NodeOutput::errored(json!({
12150            "ok": false,
12151            "outcome": "on_timeout",
12152            "error": { "code": "E", "message": "m" }
12153        }));
12154        match evaluate_custom_routing(&raw_routing, &errored, &state, &flow_ir, &current) {
12155            CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "timeout_node"),
12156            other => panic!("expected on_timeout route, got {other:?}"),
12157        }
12158    }
12159
12160    /// `meta.error` and `meta.outcome` are competing uses of the same `meta`
12161    /// field (see `NodeOutput::with_error` vs the success path's
12162    /// `outcome_meta`). `NodeOutput::errored` must merge them rather than let
12163    /// one clobber the other: an outcome-carrying failure payload that ALSO
12164    /// carries its own `error` object must still let
12165    /// `lift_first_node_error_from_nodes` read a real error message from it,
12166    /// not just fall back to the generic "flow node failed" default.
12167    #[test]
12168    fn errored_output_preserves_meta_error_alongside_outcome() {
12169        let errored = NodeOutput::errored(json!({
12170            "ok": false,
12171            "outcome": "on_timeout",
12172            "error": { "code": "E1", "message": "boom" }
12173        }));
12174        assert_eq!(
12175            errored.meta.get("outcome").and_then(Value::as_str),
12176            Some("on_timeout"),
12177            "outcome must survive so routing can pick the on_timeout branch"
12178        );
12179        assert_eq!(
12180            errored.meta["error"]["message"], "boom",
12181            "error must survive alongside outcome, not be clobbered by it"
12182        );
12183
12184        let mut nodes: HashMap<String, NodeOutput> = HashMap::new();
12185        nodes.insert("run".to_string(), errored);
12186        let lifted = lift_first_node_error_from_nodes(json!({}), &nodes);
12187        assert_eq!(
12188            lifted["metadata"]["error_message"], "boom",
12189            "lift_first_node_error_from_nodes must read the real message, not the generic fallback"
12190        );
12191        assert_eq!(lifted["metadata"]["node_id"], "run");
12192    }
12193
12194    /// The plain, common `component_error` shape — `{ok:false, error:{code,message}}`,
12195    /// no `outcome` — is exactly what `execute_component_call`'s `component_error`
12196    /// branch actually hands to `NodeOutput::errored`. Before R2, `errored` hardcoded
12197    /// `meta = Value::Null`, so this exact routed failure always surfaced the generic
12198    /// "flow node failed" default here regardless of what the component said.
12199    /// `errored_output_preserves_meta_error_alongside_outcome` above only covers the
12200    /// outcome+error combination; this covers the far more common outcome-less one.
12201    #[test]
12202    fn component_error_routed_failure_surfaces_real_message_via_lift() {
12203        let errored = NodeOutput::errored(json!({
12204            "ok": false,
12205            "error": { "code": "E1", "message": "disk full" }
12206        }));
12207        let mut nodes: HashMap<String, NodeOutput> = HashMap::new();
12208        nodes.insert("run".to_string(), errored);
12209        let lifted = lift_first_node_error_from_nodes(json!({}), &nodes);
12210        assert_eq!(
12211            lifted["metadata"]["error_message"], "disk full",
12212            "a component_error-routed failure must surface its real message, \
12213             not the generic \"flow node failed\" default"
12214        );
12215        assert_eq!(lifted["metadata"]["node_id"], "run");
12216    }
12217
12218    #[test]
12219    fn node_has_error_route_detects_error_family_ports() {
12220        let with_err = Routing::Custom(json!([
12221            { "condition": "event == \"on_success\"", "to": "n" },
12222            { "condition": "event == \"on_error\"", "to": "e" }
12223        ]));
12224        assert!(
12225            node_has_error_route(&with_err),
12226            "on_error route must be detected"
12227        );
12228
12229        let only_success = Routing::Custom(json!([
12230            { "condition": "event == \"on_success\"", "to": "n" }
12231        ]));
12232        assert!(
12233            !node_has_error_route(&only_success),
12234            "a success-only Custom routing has no error branch"
12235        );
12236
12237        let plain = Routing::Next {
12238            node_id: NodeId::from_str("n").unwrap(),
12239        };
12240        assert!(
12241            !node_has_error_route(&plain),
12242            "Routing::Next has no error branch"
12243        );
12244    }
12245
12246    /// When a successful node emits no explicit `outcome`, the runner must
12247    /// derive the success `event` from the success-family port the node
12248    /// actually has an outgoing edge for (priority `on_success` → `on_complete`
12249    /// → `on_submit`), not blindly default to `on_success`. This is what lets
12250    /// native nodes whose happy port is `on_complete` (qa.process,
12251    /// llm.openai.chat, template_render) — or `on_submit` (forms) — route
12252    /// instead of silently stalling at `Wait`, while leaving `on_success`
12253    /// components (e.g. http) unchanged.
12254    #[test]
12255    fn success_default_matches_available_outcome_port() {
12256        let flow_ir = HostFlow {
12257            id: "flow.test".to_string(),
12258            start: None,
12259            nodes: IndexMap::new(),
12260            vars_init: JsonMap::new(),
12261            required_vars: Vec::new(),
12262            slot_schema: None,
12263        };
12264        let current = NodeId::from_str("current").unwrap();
12265        let state = ExecutionState::new(json!({}));
12266        // ok:true, no explicit outcome — the case every native happy path hits.
12267        let ok_out = NodeOutput::new(json!({ "answer": "hi" }));
12268
12269        // qa/llm/template shape: happy port is `on_complete`, no `on_success` edge.
12270        let on_complete_routing = json!([
12271            { "condition": "event == \"on_complete\"", "to": "next" },
12272            { "condition": "event == \"on_cancel\"", "to": "cancelled" }
12273        ]);
12274        match evaluate_custom_routing(&on_complete_routing, &ok_out, &state, &flow_ir, &current) {
12275            CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "next"),
12276            other => panic!("expected Next(\"next\") via on_complete default, got {other:?}"),
12277        }
12278
12279        // form shape: happy port is `on_submit`.
12280        let on_submit_routing = json!([
12281            { "condition": "event == \"on_submit\"", "to": "saved" },
12282            { "condition": "event == \"on_cancel\"", "to": "cancelled" }
12283        ]);
12284        match evaluate_custom_routing(&on_submit_routing, &ok_out, &state, &flow_ir, &current) {
12285            CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "saved"),
12286            other => panic!("expected Next(\"saved\") via on_submit default, got {other:?}"),
12287        }
12288
12289        // http shape: `on_success` present → still routes on_success (priority,
12290        // no regression for components whose success name is the old default).
12291        let on_success_routing = json!([
12292            { "condition": "event == \"on_success\"", "to": "ok" },
12293            { "condition": "event == \"on_error\"", "to": "err" }
12294        ]);
12295        match evaluate_custom_routing(&on_success_routing, &ok_out, &state, &flow_ir, &current) {
12296            CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "ok"),
12297            other => panic!("expected Next(\"ok\") via on_success default, got {other:?}"),
12298        }
12299    }
12300
12301    /// `evaluate_simple_condition` is a pure expression-parser test: it checks
12302    /// operator parsing over an arbitrary, hand-built JSON context. This
12303    /// context is **not** the shape `build_routing_context` produces at
12304    /// runtime — it is not node-keyed, and the keys below (`a`/`b`/`c`) are
12305    /// deliberately arbitrary so they cannot be mistaken for node ids. For
12306    /// coverage of the real routing context (prior node outputs exposed
12307    /// under `node.<id>`), see
12308    /// `routing_context_exposes_prior_node_outputs_under_node`.
12309    ///
12310    /// What this test does pin (PR #486): beyond `==`/`!=`, the parser must
12311    /// handle numeric ordering (`>=` `<=` `>` `<`) and `contains`
12312    /// (case-insensitive substring); otherwise those conditions silently
12313    /// evaluate to false and route wrong.
12314    #[test]
12315    fn condition_evaluator_supports_comparisons_and_contains() {
12316        let ctx = json!({
12317            "a": { "age": 18 },
12318            "b": { "status": "ok" },
12319            "c": { "text": "Hello World" }
12320        });
12321
12322        // Numeric ordering (operands parsed as numbers).
12323        assert!(evaluate_simple_condition("a.age >= 18", &ctx));
12324        assert!(!evaluate_simple_condition("a.age > 18", &ctx));
12325        assert!(evaluate_simple_condition("a.age <= 18", &ctx));
12326        assert!(!evaluate_simple_condition("a.age < 18", &ctx));
12327
12328        // contains: case-insensitive substring over the resolved string.
12329        assert!(evaluate_simple_condition("c.text contains \"world\"", &ctx));
12330        assert!(!evaluate_simple_condition("c.text contains \"bye\"", &ctx));
12331
12332        // Existing equality semantics unchanged (regression guard).
12333        assert!(evaluate_simple_condition("b.status == \"ok\"", &ctx));
12334        assert!(!evaluate_simple_condition("b.status != \"ok\"", &ctx));
12335        // A non-numeric operand on an ordering op is false, not a panic.
12336        assert!(!evaluate_simple_condition("b.status >= 1", &ctx));
12337    }
12338
12339    /// A routing condition must be able to read ANY prior node's output, not
12340    /// just the immediate predecessor's payload. `state.nodes` has always held
12341    /// them; the routing context simply never exposed them, so
12342    /// `node.<id>.<field>` resolved to nothing and the guard silently took the
12343    /// false branch on every input.
12344    ///
12345    /// This drives the REAL `build_routing_context` — see
12346    /// `condition_evaluator_supports_comparisons_and_contains` for why a
12347    /// hand-built context proves nothing here.
12348    #[test]
12349    fn routing_context_exposes_prior_node_outputs_under_node() {
12350        let mut state = ExecutionState::new(json!({}));
12351        state
12352            .nodes
12353            .insert("register".into(), NodeOutput::new(json!({ "q_age": 21 })));
12354
12355        let current = NodeOutput::new(json!({ "status": "ok" }));
12356        let ctx = build_routing_context(&current, &state, "on_success", "on_error");
12357
12358        // The cross-node form, matching `{{node.<id>.<field>}}` in params.
12359        assert!(
12360            evaluate_simple_condition("node.register.q_age >= 18", &ctx),
12361            "a prior node's output must be readable via node.<id>.<field>: {ctx:?}"
12362        );
12363        // The node_io envelope resolves too — same projection as params.
12364        assert!(
12365            evaluate_simple_condition("node.register.data.q_age >= 18", &ctx),
12366            "the data envelope must resolve like it does in params: {ctx:?}"
12367        );
12368    }
12369
12370    #[test]
12371    fn routing_context_keeps_the_predecessor_shorthand() {
12372        // Negative-ish: the existing form must not regress. The current node's
12373        // payload stays spread at the top level, which is what PR #665's
12374        // source-node prefix strip relies on.
12375        let mut state = ExecutionState::new(json!({}));
12376        state
12377            .nodes
12378            .insert("register".into(), NodeOutput::new(json!({ "q_age": 21 })));
12379
12380        let current = NodeOutput::new(json!({ "q_age": 30 }));
12381        let ctx = build_routing_context(&current, &state, "on_success", "on_error");
12382
12383        assert!(
12384            evaluate_simple_condition("q_age >= 30", &ctx),
12385            "the bare form must still resolve against the current payload: {ctx:?}"
12386        );
12387    }
12388
12389    #[test]
12390    fn routing_context_does_not_resolve_a_missing_node() {
12391        // Negative: a ref to a node with no output must NOT resolve — it must
12392        // stay false, not accidentally match something.
12393        let state = ExecutionState::new(json!({}));
12394        let current = NodeOutput::new(json!({ "status": "ok" }));
12395        let ctx = build_routing_context(&current, &state, "on_success", "on_error");
12396
12397        assert!(
12398            !evaluate_simple_condition("node.ghost.x == \"y\"", &ctx),
12399            "a missing node must not resolve: {ctx:?}"
12400        );
12401    }
12402
12403    /// Symmetric to the success default: when a node FAILS (`ok == false`)
12404    /// without an explicit outcome, route to the error-family port the node
12405    /// actually has an edge for (priority `on_error` → `on_cancel` →
12406    /// `on_timeout`), not blindly `on_error`. Lets a node whose failure port is
12407    /// `on_cancel` (qa) or `on_timeout` (http) route instead of stalling.
12408    #[test]
12409    fn failure_default_matches_available_outcome_port() {
12410        let flow_ir = HostFlow {
12411            id: "flow.test".to_string(),
12412            start: None,
12413            nodes: IndexMap::new(),
12414            vars_init: JsonMap::new(),
12415            required_vars: Vec::new(),
12416            slot_schema: None,
12417        };
12418        let current = NodeId::from_str("current").unwrap();
12419        let state = ExecutionState::new(json!({}));
12420        // ok:false, no explicit outcome — the failure case.
12421        let err_out = NodeOutput {
12422            ok: false,
12423            payload: json!({}),
12424            meta: Value::Null,
12425            created: Vec::new(),
12426        };
12427
12428        // qa shape: failure port is `on_cancel`, no `on_error` edge.
12429        let on_cancel_routing = json!([
12430            { "condition": "event == \"on_complete\"", "to": "next" },
12431            { "condition": "event == \"on_cancel\"", "to": "cancelled" }
12432        ]);
12433        match evaluate_custom_routing(&on_cancel_routing, &err_out, &state, &flow_ir, &current) {
12434            CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "cancelled"),
12435            other => panic!("expected Next(\"cancelled\") via on_cancel default, got {other:?}"),
12436        }
12437
12438        // http shape: `on_error` present → on_error (priority, unchanged).
12439        let on_error_routing = json!([
12440            { "condition": "event == \"on_success\"", "to": "ok" },
12441            { "condition": "event == \"on_error\"", "to": "err" }
12442        ]);
12443        match evaluate_custom_routing(&on_error_routing, &err_out, &state, &flow_ir, &current) {
12444            CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "err"),
12445            other => panic!("expected Next(\"err\") via on_error default, got {other:?}"),
12446        }
12447
12448        // on_timeout-only failure port.
12449        let on_timeout_routing = json!([
12450            { "condition": "event == \"on_success\"", "to": "ok" },
12451            { "condition": "event == \"on_timeout\"", "to": "timed_out" }
12452        ]);
12453        match evaluate_custom_routing(&on_timeout_routing, &err_out, &state, &flow_ir, &current) {
12454            CustomRoutingDecision::Next(nid) => assert_eq!(nid.as_str(), "timed_out"),
12455            other => panic!("expected Next(\"timed_out\") via on_timeout default, got {other:?}"),
12456        }
12457    }
12458
12459    #[test]
12460    fn outcome_meta_surfaces_component_emitted_outcome() {
12461        // A component opts into outcome routing by adding `outcome` to its
12462        // output envelope; the runner surfaces it as node meta for routing.
12463        assert_eq!(
12464            outcome_meta(&json!({ "ok": true, "outcome": "on_complete" })),
12465            json!({ "outcome": "on_complete" })
12466        );
12467        // No `outcome` → null meta → engine uses the ok-derived default.
12468        assert_eq!(
12469            outcome_meta(&json!({ "ok": true, "body": {} })),
12470            Value::Null
12471        );
12472    }
12473
12474    /// Live end-to-end test: `dw.agent` NATS dispatch path.
12475    ///
12476    /// Requires a real NATS server (JetStream not needed for this test — core
12477    /// NATS pub/sub is sufficient) and an `aw-serve` consumer (or the in-process
12478    /// fake bridge below acts as one).
12479    ///
12480    /// # Run recipe
12481    ///
12482    /// ```text
12483    /// # Terminal 1 – NATS server (JetStream-enabled for prod parity, but core works too)
12484    /// nats-server -js
12485    ///
12486    /// # Terminal 2 – aw-serve test-mock (replies "pong" for any agent)
12487    /// AW_SERVE_AGENT_ID=greeter AW_SERVE_REPLY=pong \
12488    ///   GREENTIC_EVENTS_NATS_URL=nats://127.0.0.1:4222 \
12489    ///   GREENTIC_AW_JETSTREAM=off \
12490    ///   cargo run -p greentic-aw-runtime --features serve,test-mock --bin aw-serve
12491    ///
12492    /// # Terminal 3 – run this ignored test
12493    /// GREENTIC_EVENTS_NATS_URL=nats://127.0.0.1:4222 \
12494    ///   cargo test -p greentic-runner-host --lib \
12495    ///   tests::dw_agent_scale_to_zero_nats_e2e \
12496    ///   -- --nocapture --ignored
12497    /// ```
12498    ///
12499    /// When `GREENTIC_EVENTS_NATS_URL` is unset the test skips immediately.
12500    /// The test wires its own in-process fake bridge so the `aw-serve` binary is
12501    /// optional; running with the real `aw-serve` exercises the full out-of-process
12502    /// path. Both variants must produce a resumed reply of `"pong"`.
12503    #[cfg(feature = "agentic-worker")]
12504    #[tokio::test]
12505    #[ignore = "requires live NATS; run with --ignored after `nats-server -js`"]
12506    async fn dw_agent_scale_to_zero_nats_e2e() {
12507        use crate::runner::agent_node::DwAgentDispatch;
12508        use crate::runner::dispatch_listener::{SessionResumer, run_response_listener};
12509        use crate::runner::remote_dispatch::NatsDispatcher;
12510        use futures::StreamExt as _;
12511        use greentic_types::{
12512            RuntimeDispatchResponse, TenantCtx as DispatchTenantCtx, request_topic, response_topic,
12513        };
12514        use tokio::sync::Notify;
12515
12516        let nats_url = match std::env::var("GREENTIC_EVENTS_NATS_URL") {
12517            Ok(url) => url,
12518            Err(_) => {
12519                eprintln!(
12520                    "skipping dw_agent_scale_to_zero_nats_e2e: GREENTIC_EVENTS_NATS_URL not set"
12521                );
12522                return;
12523            }
12524        };
12525
12526        // ── 1. Build a two-node flow: dw.agent → emit.log (resume target) ──
12527        // The agent node must have Routing::Next so the engine knows the resume
12528        // target (same requirement as agentic.call / sorla.call in production).
12529        let resume_id = NodeId::from_str("after-agent").unwrap();
12530        let agent_node_id = NodeId::from_str("agent-e2e").unwrap();
12531        let agent_node = Node {
12532            id: agent_node_id.clone(),
12533            component: FlowComponentRef {
12534                id: "dw.agent".parse().unwrap(),
12535                pack_alias: None,
12536                operation: Some("greeter".to_string()),
12537            },
12538            input: InputMapping {
12539                mapping: json!({ "user_text": "ping" }),
12540            },
12541            output: OutputMapping {
12542                mapping: Value::Null,
12543            },
12544            err_map: None,
12545            routing: Routing::Next {
12546                node_id: resume_id.clone(),
12547            },
12548            telemetry: TelemetryHints::default(),
12549            conversational: false,
12550        };
12551        let resume_node = Node {
12552            id: resume_id.clone(),
12553            component: FlowComponentRef {
12554                id: "emit.log".parse().unwrap(),
12555                pack_alias: None,
12556                operation: None,
12557            },
12558            input: InputMapping {
12559                mapping: json!({ "message": "resumed" }),
12560            },
12561            output: OutputMapping {
12562                mapping: Value::Null,
12563            },
12564            err_map: None,
12565            routing: Routing::End,
12566            telemetry: TelemetryHints::default(),
12567            conversational: false,
12568        };
12569        let mut nodes = indexmap::IndexMap::default();
12570        nodes.insert(agent_node_id.clone(), agent_node);
12571        nodes.insert(resume_id.clone(), resume_node);
12572        let flow = greentic_types::Flow {
12573            schema_version: "1.0".into(),
12574            id: greentic_types::FlowId::from_str("e2e-agent.flow").unwrap(),
12575            kind: greentic_types::FlowKind::Messaging,
12576            entrypoints: BTreeMap::from([(
12577                "default".to_string(),
12578                Value::String(agent_node_id.to_string()),
12579            )]),
12580            nodes,
12581            metadata: Default::default(),
12582        };
12583        let host_flow = HostFlow::from(flow);
12584
12585        // ── 2. Connect NATS clients ──
12586        let dispatcher_client = async_nats::connect(&nats_url)
12587            .await
12588            .expect("NATS: dispatcher client");
12589        let bridge_client = async_nats::connect(&nats_url)
12590            .await
12591            .expect("NATS: fake bridge client");
12592        let listener_client = async_nats::connect(&nats_url)
12593            .await
12594            .expect("NATS: response listener client");
12595
12596        // ── 3. Fake bridge: subscribe to agentic request subject, reply "pong" ──
12597        let agentic_request_subject = request_topic("agentic");
12598        let agentic_response_subject = response_topic("agentic");
12599        let mut req_sub = bridge_client
12600            .subscribe(agentic_request_subject.clone())
12601            .await
12602            .expect("fake bridge: subscribe to agentic request subject");
12603        let bridge_reply_client = bridge_client.clone();
12604        let reply_subject = agentic_response_subject.clone();
12605        tokio::spawn(async move {
12606            while let Some(msg) = req_sub.next().await {
12607                let headers = msg.headers.as_ref();
12608                let get_hdr = |name: &str| {
12609                    headers
12610                        .and_then(|h| h.get(name))
12611                        .map(|v| v.as_str().to_owned())
12612                        .unwrap_or_default()
12613                };
12614                let correlation_id = get_hdr("Greentic-Correlation-Id");
12615                let tenant = get_hdr("Greentic-Tenant");
12616                let env = get_hdr("Greentic-Env");
12617
12618                let response_payload = RuntimeDispatchResponse {
12619                    ok: true,
12620                    output: json!({
12621                        "reply": "pong",
12622                        "trail": [],
12623                        "terminated_by": "final_reply"
12624                    }),
12625                    events: vec![],
12626                    error: None,
12627                };
12628                let body =
12629                    serde_json::to_vec(&response_payload).expect("serialize fake bridge response");
12630
12631                let mut resp_headers = async_nats::HeaderMap::new();
12632                resp_headers.insert("Greentic-Correlation-Id", correlation_id.as_str());
12633                resp_headers.insert("Greentic-Tenant", tenant.as_str());
12634                resp_headers.insert("Greentic-Env", env.as_str());
12635
12636                bridge_reply_client
12637                    .publish_with_headers(reply_subject.clone(), resp_headers, body.into())
12638                    .await
12639                    .expect("fake bridge: publish response");
12640            }
12641        });
12642
12643        // ── 4. Recording resumer + run_response_listener ──
12644        struct RecordingResumer {
12645            calls: std::sync::Mutex<Vec<(String, Value)>>,
12646            notify: Notify,
12647        }
12648
12649        impl RecordingResumer {
12650            fn new() -> Self {
12651                Self {
12652                    calls: std::sync::Mutex::new(vec![]),
12653                    notify: Notify::new(),
12654                }
12655            }
12656        }
12657
12658        #[async_trait::async_trait]
12659        impl SessionResumer for RecordingResumer {
12660            async fn resume(
12661                &self,
12662                _tenant: DispatchTenantCtx,
12663                correlation_id: &str,
12664                output: Value,
12665            ) -> anyhow::Result<()> {
12666                self.calls
12667                    .lock()
12668                    .unwrap()
12669                    .push((correlation_id.to_string(), output));
12670                self.notify.notify_one();
12671                Ok(())
12672            }
12673        }
12674
12675        let resumer = Arc::new(RecordingResumer::new());
12676        let resumer_for_listener = resumer.clone();
12677        tokio::spawn(async move {
12678            run_response_listener(listener_client, "agentic".to_owned(), resumer_for_listener)
12679                .await
12680                .expect("response listener exited unexpectedly");
12681        });
12682
12683        // Give subscriptions a moment to register.
12684        tokio::time::sleep(tokio::time::Duration::from_millis(150)).await;
12685
12686        // ── 5. Build FlowEngine with NatsDispatcher + DwAgentDispatch::Nats ──
12687        let nats_engine_dispatcher = Arc::new(NatsDispatcher::new(dispatcher_client));
12688        let engine = FlowEngine {
12689            packs: Vec::new(),
12690            flows: Vec::new(),
12691            flow_sources: StdHashMap::new(),
12692            messaging_provider_pack_ids: std::collections::HashSet::new(),
12693            flow_cache: RwLock::new(StdHashMap::from([(
12694                FlowKey {
12695                    pack_id: "e2e-pack".to_string(),
12696                    flow_id: "e2e-agent.flow".to_string(),
12697                },
12698                host_flow,
12699            )])),
12700            default_env: "local".to_string(),
12701            validation: crate::validate::ValidationConfig {
12702                mode: crate::validate::ValidationMode::Off,
12703            },
12704            cross_pack_resolver: None,
12705            rollout_ids: RolloutIds::default(),
12706            approval_dispatch_handler: None,
12707            remote_dispatch_handler: Some(
12708                nats_engine_dispatcher
12709                    as Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>,
12710            ),
12711            dw_agent_dispatch: DwAgentDispatch::Nats,
12712            agent_node_handler: None,
12713            graph_node_handler: None,
12714            mcp_tool_source: None,
12715            mcp_secrets: None,
12716            #[cfg(feature = "agentic-worker")]
12717            a2a_sources: RwLock::new(HashMap::new()),
12718            #[cfg(feature = "agentic-worker")]
12719            ext_artifact_port: None,
12720            operala_node_handler: None,
12721        };
12722
12723        let ctx = FlowContext {
12724            tenant: "demo",
12725            pack_id: "e2e-pack",
12726            flow_id: "e2e-agent.flow",
12727            node_id: None,
12728            tool: None,
12729            action: None,
12730            session_id: Some("e2e-sess-1"),
12731            provider_id: None,
12732            reply_scope: None,
12733            retry_config: RetryConfig {
12734                max_attempts: 1,
12735                base_delay_ms: 1,
12736            },
12737            attempt: 1,
12738            observer: None,
12739            mocks: None,
12740            caller: None,
12741        };
12742
12743        // ── 6. Execute: the dw.agent NATS path must PAUSE the flow ──
12744        let result = engine
12745            .execute(ctx, json!({ "user_text": "ping" }))
12746            .await
12747            .expect("engine.execute succeeded");
12748
12749        assert!(
12750            matches!(result.status, FlowStatus::Waiting(_)),
12751            "expected FlowStatus::Waiting from dw.agent Nats path, got: {:?}",
12752            result.status
12753        );
12754        eprintln!("dw.agent: flow paused (Waiting) — dispatch published to NATS");
12755
12756        // ── 7. Wait for the fake bridge reply to reach the resumer (up to 5 s) ──
12757        let wait = tokio::time::timeout(
12758            tokio::time::Duration::from_secs(5),
12759            resumer.notify.notified(),
12760        )
12761        .await;
12762
12763        assert!(
12764            wait.is_ok(),
12765            "timed out waiting for fake bridge reply — is NATS running? ({nats_url})"
12766        );
12767
12768        // ── 8. Assert the resumed reply == "pong" ──
12769        let calls = resumer.calls.lock().unwrap();
12770        assert_eq!(
12771            calls.len(),
12772            1,
12773            "resumer should have been called exactly once"
12774        );
12775        let (ref _corr, ref output) = calls[0];
12776        assert_eq!(
12777            output["output"]["reply"],
12778            json!("pong"),
12779            "resumed reply must match the aw-serve canned reply"
12780        );
12781        eprintln!(
12782            "PASSED: dw.agent scale-to-zero NATS e2e — reply={:?}",
12783            output["output"]["reply"]
12784        );
12785    }
12786
12787    #[test]
12788    fn execution_state_vars_survive_serde_round_trip() {
12789        // vars must persist across a park/resume, which is a serde round-trip of ExecutionState.
12790        let mut st = ExecutionState::new(json!({}));
12791        st.vars.insert("counter".into(), json!(3));
12792        st.vars.insert("region".into(), json!("us-east-1"));
12793
12794        let encoded = serde_json::to_string(&st).expect("serialize");
12795        let decoded: ExecutionState = serde_json::from_str(&encoded).expect("deserialize");
12796
12797        assert_eq!(decoded.vars.get("counter"), Some(&json!(3)));
12798        assert_eq!(decoded.vars.get("region"), Some(&json!("us-east-1")));
12799    }
12800
12801    #[test]
12802    fn execution_state_vars_default_empty_for_old_snapshots() {
12803        // A snapshot serialized before `vars` existed (no `vars` key) must still load.
12804        let legacy = r#"{"entry":{},"input":{},"nodes":{},"egress":[],"redirect_count":0}"#;
12805        let decoded: ExecutionState = serde_json::from_str(legacy).expect("legacy loads");
12806        assert!(decoded.vars.is_empty());
12807    }
12808
12809    #[test]
12810    fn template_context_exposes_vars_namespace_typed() {
12811        let mut st = ExecutionState::new(serde_json::json!({}));
12812        st.vars.insert("count".into(), serde_json::json!(5));
12813        st.vars.insert("name".into(), serde_json::json!("aws"));
12814
12815        let ctx = template_context(&st, serde_json::Value::Null);
12816        // {{vars.count}} must resolve to the JSON number 5, not the string "5".
12817        let rendered_num = render_template_value(
12818            &serde_json::json!("{{vars.count}}"),
12819            &ctx,
12820            TemplateOptions::default(),
12821        )
12822        .expect("render num");
12823        assert_eq!(rendered_num, serde_json::json!(5));
12824
12825        let rendered_str = render_template_value(
12826            &serde_json::json!("prefix-{{vars.name}}"),
12827            &ctx,
12828            TemplateOptions::default(),
12829        )
12830        .expect("render str");
12831        assert_eq!(rendered_str, serde_json::json!("prefix-aws"));
12832    }
12833
12834    #[test]
12835    fn vars_namespace_does_not_shadow_existing_namespaces() {
12836        let st = ExecutionState::new(serde_json::json!({"user": {"id": 7}}));
12837        let ctx = template_context(&st, serde_json::Value::Null);
12838        let obj = ctx.as_object().expect("ctx object");
12839        for key in ["entry", "in", "prev", "node", "state", "vars", "now"] {
12840            assert!(obj.contains_key(key), "context must expose `{key}`");
12841        }
12842    }
12843
12844    // ── now namespace tests ────────────────────────────────────────────────
12845
12846    /// A pinned instant, so the shapes below are asserted rather than described.
12847    fn fixed_instant() -> DateTime<Utc> {
12848        DateTime::parse_from_rfc3339("2026-09-09T10:53:04.250Z")
12849            .expect("a literal RFC3339 instant")
12850            .with_timezone(&Utc)
12851    }
12852
12853    #[test]
12854    fn now_namespace_carries_iso_epoch_ms_and_date() {
12855        let now = now_namespace(fixed_instant());
12856        assert_eq!(now["iso"], serde_json::json!("2026-09-09T10:53:04.250Z"));
12857        assert_eq!(now["epoch_ms"], serde_json::json!(1_788_951_184_250i64));
12858        assert_eq!(now["date"], serde_json::json!("2026-09-09"));
12859    }
12860
12861    /// `hs_timestamp` is the field this exists for: HubSpot's notes and tasks
12862    /// require it, the component supplies no default, and until now a flow had
12863    /// no expression that could produce one.
12864    #[test]
12865    fn a_node_config_can_render_a_timestamp_it_was_never_given() {
12866        let st = ExecutionState::new(serde_json::json!({}));
12867        let ctx = template_context(&st, serde_json::Value::Null);
12868
12869        let rendered = render_template_value(
12870            &serde_json::json!({ "hs_timestamp": "{{now.iso}}" }),
12871            &ctx,
12872            TemplateOptions::default(),
12873        )
12874        .expect("render");
12875
12876        let stamp = rendered["hs_timestamp"]
12877            .as_str()
12878            .expect("an ISO string, not an object");
12879        assert!(
12880            DateTime::parse_from_rfc3339(stamp).is_ok(),
12881            "`{stamp}` must parse as RFC3339 — an API rejecting it is the \
12882             failure this field exists to prevent"
12883        );
12884    }
12885
12886    /// The exact-expression path returns the JSON value itself rather than its
12887    /// rendered text, so a component expecting epoch millis gets a NUMBER. A
12888    /// quoted string here would be a decode error at the component boundary.
12889    #[test]
12890    fn epoch_ms_resolves_as_a_number_not_a_string() {
12891        let st = ExecutionState::new(serde_json::json!({}));
12892        let ctx = template_context(&st, serde_json::Value::Null);
12893
12894        let rendered = render_template_value(
12895            &serde_json::json!("{{now.epoch_ms}}"),
12896            &ctx,
12897            TemplateOptions::default(),
12898        )
12899        .expect("render");
12900
12901        assert!(
12902            rendered.is_i64(),
12903            "expected a JSON number, got {rendered:?}"
12904        );
12905    }
12906
12907    /// Regression for the silence this closes. Strict mode is off, so before
12908    /// the namespace existed every `{{now.*}}` rendered as the empty string
12909    /// with no error at any layer — the author saw a blank field and an API
12910    /// error naming something else.
12911    #[test]
12912    fn a_now_reference_no_longer_renders_as_the_empty_string() {
12913        let st = ExecutionState::new(serde_json::json!({}));
12914        let ctx = template_context(&st, serde_json::Value::Null);
12915
12916        for expression in ["{{now.iso}}", "{{now.date}}"] {
12917            let rendered = render_template_value(
12918                &serde_json::json!(expression),
12919                &ctx,
12920                TemplateOptions::default(),
12921            )
12922            .expect("render");
12923            assert_ne!(
12924                rendered,
12925                serde_json::json!(""),
12926                "`{expression}` must resolve to something"
12927            );
12928        }
12929    }
12930
12931    /// One sample per context build, so two fields of the same node's config
12932    /// cannot disagree by a millisecond.
12933    #[test]
12934    fn one_context_sees_a_single_instant() {
12935        let st = ExecutionState::new(serde_json::json!({}));
12936        let ctx = template_context(&st, serde_json::Value::Null);
12937
12938        let rendered = render_template_value(
12939            &serde_json::json!({ "a": "{{now.iso}}", "b": "{{now.iso}}" }),
12940            &ctx,
12941            TemplateOptions::default(),
12942        )
12943        .expect("render");
12944
12945        assert_eq!(rendered["a"], rendered["b"]);
12946    }
12947
12948    // ── vars_init tests ────────────────────────────────────────────────────
12949
12950    /// Build a minimal flow with the given free-form `metadata.extra` value.
12951    /// Mirrors the construction used by neighbouring engine tests: a schema-1.0
12952    /// Messaging flow with no nodes and no entrypoints, only the metadata set.
12953    fn flow_with_extra(extra: serde_json::Value) -> Flow {
12954        Flow {
12955            schema_version: "1.0".into(),
12956            id: FlowId::from_str("test.flow").unwrap(),
12957            kind: FlowKind::Messaging,
12958            entrypoints: BTreeMap::new(),
12959            nodes: indexmap::IndexMap::default(),
12960            metadata: FlowMetadata {
12961                title: None,
12962                description: None,
12963                tags: Default::default(),
12964                extra,
12965            },
12966        }
12967    }
12968
12969    #[test]
12970    fn seed_vars_seeds_defaults_and_reports_missing_required() {
12971        use serde_json::json;
12972        let mut vars_init = JsonMap::new();
12973        vars_init.insert("region".into(), json!("us-east-1"));
12974
12975        // "name" is required but has no default; "region" required WITH a default.
12976        let required = vec!["name".to_string(), "region".to_string()];
12977        let mut target = JsonMap::new();
12978
12979        let missing = seed_vars_and_collect_missing_required(&vars_init, &required, &mut target);
12980
12981        assert_eq!(
12982            target.get("region"),
12983            Some(&json!("us-east-1")),
12984            "default seeded"
12985        );
12986        assert_eq!(
12987            missing,
12988            vec!["name".to_string()],
12989            "only the defaultless required var is missing"
12990        );
12991    }
12992
12993    #[test]
12994    fn seed_vars_respects_preexisting_value_for_required() {
12995        use serde_json::json;
12996        let vars_init = JsonMap::new(); // no defaults declared
12997        let required = vec!["name".to_string()];
12998        let mut target = JsonMap::new();
12999        target.insert("name".into(), json!("Budi")); // operator-provided value already present
13000
13001        let missing = seed_vars_and_collect_missing_required(&vars_init, &required, &mut target);
13002
13003        assert!(
13004            missing.is_empty(),
13005            "a required var with a provided value is not missing"
13006        );
13007        assert_eq!(
13008            target.get("name"),
13009            Some(&json!("Budi")),
13010            "provided value not overwritten"
13011        );
13012    }
13013
13014    #[test]
13015    fn from_flow_extracts_vars_init() {
13016        let flow = flow_with_extra(serde_json::json!({
13017            "vars_init": {
13018                "region":  { "type": "string", "default": "us-east-1" },
13019                "counter": { "type": "number", "default": 0 }
13020            }
13021        }));
13022        let host: HostFlow = HostFlow::from(flow);
13023        assert_eq!(
13024            host.vars_init.get("region"),
13025            Some(&serde_json::json!("us-east-1"))
13026        );
13027        assert_eq!(host.vars_init.get("counter"), Some(&serde_json::json!(0)));
13028    }
13029
13030    #[test]
13031    fn from_flow_vars_init_absent() {
13032        let flow = flow_with_extra(serde_json::json!({}));
13033        let host: HostFlow = HostFlow::from(flow);
13034        assert!(host.vars_init.is_empty());
13035    }
13036
13037    #[test]
13038    fn from_flow_collects_required_vars() {
13039        let flow = flow_with_extra(serde_json::json!({
13040            "vars_init": {
13041                "name":   { "type": "string", "required": true },
13042                "region": { "type": "string", "default": "us-east-1" },
13043                "note":   { "type": "string", "required": false }
13044            }
13045        }));
13046        let host: HostFlow = HostFlow::from(flow);
13047        assert_eq!(host.required_vars, vec!["name".to_string()]);
13048    }
13049
13050    #[test]
13051    fn execute_once_fails_on_missing_required_var() {
13052        let node_id = NodeId::from_str("n1").unwrap();
13053        let node = Node {
13054            id: node_id.clone(),
13055            component: FlowComponentRef {
13056                id: "emit.log".parse().unwrap(),
13057                pack_alias: None,
13058                operation: None,
13059            },
13060            input: InputMapping {
13061                mapping: json!({ "message": "{{vars.region}}" }),
13062            },
13063            output: OutputMapping {
13064                mapping: Value::Null,
13065            },
13066            err_map: None,
13067            routing: Routing::End,
13068            telemetry: TelemetryHints::default(),
13069            conversational: false,
13070        };
13071        let mut nodes = indexmap::IndexMap::default();
13072        nodes.insert(node_id.clone(), node);
13073        let flow = Flow {
13074            schema_version: "1.0".into(),
13075            id: FlowId::from_str("vars.flow").unwrap(),
13076            kind: FlowKind::Messaging,
13077            entrypoints: BTreeMap::from([(
13078                "default".to_string(),
13079                Value::String(node_id.to_string()),
13080            )]),
13081            nodes,
13082            metadata: FlowMetadata {
13083                title: None,
13084                description: None,
13085                tags: Default::default(),
13086                extra: json!({
13087                    "vars_init": {
13088                        "region": { "type": "string", "required": true }
13089                    }
13090                }),
13091            },
13092        };
13093        let host_flow = HostFlow::from(flow);
13094
13095        let engine = FlowEngine {
13096            messaging_provider_pack_ids: Default::default(),
13097            rollout_ids: RolloutIds::default(),
13098            packs: Vec::new(),
13099            flows: Vec::new(),
13100            flow_sources: HashMap::new(),
13101            flow_cache: RwLock::new(HashMap::from([(
13102                FlowKey {
13103                    pack_id: "test-pack".to_string(),
13104                    flow_id: "vars.flow".to_string(),
13105                },
13106                host_flow,
13107            )])),
13108            default_env: "local".to_string(),
13109            validation: ValidationConfig {
13110                mode: ValidationMode::Off,
13111            },
13112            cross_pack_resolver: None,
13113            approval_dispatch_handler: None,
13114            remote_dispatch_handler: None,
13115            #[cfg(feature = "agentic-worker")]
13116            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
13117            #[cfg(feature = "agentic-worker")]
13118            agent_node_handler: None,
13119            #[cfg(feature = "agentic-worker")]
13120            graph_node_handler: None,
13121            #[cfg(feature = "agentic-worker")]
13122            mcp_tool_source: None,
13123            #[cfg(feature = "agentic-worker")]
13124            mcp_secrets: None,
13125            #[cfg(feature = "agentic-worker")]
13126            a2a_sources: RwLock::new(HashMap::new()),
13127            #[cfg(feature = "agentic-worker")]
13128            ext_artifact_port: None,
13129            operala_node_handler: None,
13130        };
13131
13132        let observer = CountingObserver::new();
13133        let ctx = FlowContext {
13134            tenant: "demo",
13135            pack_id: "test-pack",
13136            flow_id: "vars.flow",
13137            node_id: None,
13138            tool: None,
13139            action: None,
13140            session_id: None,
13141            provider_id: None,
13142            reply_scope: None,
13143            retry_config: RetryConfig {
13144                max_attempts: 1,
13145                base_delay_ms: 1,
13146            },
13147            attempt: 1,
13148            observer: Some(&observer),
13149            mocks: None,
13150            caller: None,
13151        };
13152
13153        let rt = Runtime::new().unwrap();
13154        let err = rt
13155            .block_on(engine.execute(ctx, Value::Null))
13156            .expect_err("a required var with no default and no value must fail the run");
13157        let msg = err.to_string();
13158        assert!(msg.contains("region"), "error names the missing var: {msg}");
13159        assert!(
13160            !should_retry(&err),
13161            "missing-required-var is deterministic and must not be retried"
13162        );
13163        assert!(
13164            observer.ends.lock().unwrap().is_empty(),
13165            "flow aborted before the node ran"
13166        );
13167    }
13168
13169    #[test]
13170    fn execute_once_seeds_declared_vars() {
13171        // A flow with vars_init seeds state.vars before the first node runs.
13172        // We verify this by using an emit.log node whose message template
13173        // references {{vars.region}}: if the var is seeded, the rendered
13174        // output will contain "us-east-1".
13175        let node_id = NodeId::from_str("n1").unwrap();
13176        let node = Node {
13177            id: node_id.clone(),
13178            component: FlowComponentRef {
13179                id: "emit.log".parse().unwrap(),
13180                pack_alias: None,
13181                operation: None,
13182            },
13183            input: InputMapping {
13184                mapping: json!({ "message": "{{vars.region}}" }),
13185            },
13186            output: OutputMapping {
13187                mapping: Value::Null,
13188            },
13189            err_map: None,
13190            routing: Routing::End,
13191            telemetry: TelemetryHints::default(),
13192            conversational: false,
13193        };
13194        let mut nodes = indexmap::IndexMap::default();
13195        nodes.insert(node_id.clone(), node);
13196        let flow = Flow {
13197            schema_version: "1.0".into(),
13198            id: FlowId::from_str("vars.flow").unwrap(),
13199            kind: FlowKind::Messaging,
13200            entrypoints: BTreeMap::from([(
13201                "default".to_string(),
13202                Value::String(node_id.to_string()),
13203            )]),
13204            nodes,
13205            metadata: FlowMetadata {
13206                title: None,
13207                description: None,
13208                tags: Default::default(),
13209                extra: json!({
13210                    "vars_init": {
13211                        "region": { "type": "string", "default": "us-east-1" }
13212                    }
13213                }),
13214            },
13215        };
13216        let host_flow = HostFlow::from(flow);
13217
13218        let engine = FlowEngine {
13219            messaging_provider_pack_ids: Default::default(),
13220            rollout_ids: RolloutIds::default(),
13221            packs: Vec::new(),
13222            flows: Vec::new(),
13223            flow_sources: HashMap::new(),
13224            flow_cache: RwLock::new(HashMap::from([(
13225                FlowKey {
13226                    pack_id: "test-pack".to_string(),
13227                    flow_id: "vars.flow".to_string(),
13228                },
13229                host_flow,
13230            )])),
13231            default_env: "local".to_string(),
13232            validation: ValidationConfig {
13233                mode: ValidationMode::Off,
13234            },
13235            cross_pack_resolver: None,
13236            approval_dispatch_handler: None,
13237            remote_dispatch_handler: None,
13238            #[cfg(feature = "agentic-worker")]
13239            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
13240            #[cfg(feature = "agentic-worker")]
13241            agent_node_handler: None,
13242            #[cfg(feature = "agentic-worker")]
13243            graph_node_handler: None,
13244            #[cfg(feature = "agentic-worker")]
13245            mcp_tool_source: None,
13246            #[cfg(feature = "agentic-worker")]
13247            mcp_secrets: None,
13248            #[cfg(feature = "agentic-worker")]
13249            a2a_sources: RwLock::new(HashMap::new()),
13250            #[cfg(feature = "agentic-worker")]
13251            ext_artifact_port: None,
13252            operala_node_handler: None,
13253        };
13254
13255        let observer = CountingObserver::new();
13256        let ctx = FlowContext {
13257            tenant: "demo",
13258            pack_id: "test-pack",
13259            flow_id: "vars.flow",
13260            node_id: None,
13261            tool: None,
13262            action: None,
13263            session_id: None,
13264            provider_id: None,
13265            reply_scope: None,
13266            retry_config: RetryConfig {
13267                max_attempts: 1,
13268                base_delay_ms: 1,
13269            },
13270            attempt: 1,
13271            observer: Some(&observer),
13272            mocks: None,
13273            caller: None,
13274        };
13275
13276        let rt = Runtime::new().unwrap();
13277        let result = rt.block_on(engine.execute(ctx, Value::Null)).unwrap();
13278        assert!(matches!(result.status, FlowStatus::Completed));
13279
13280        let ends = observer.ends.lock().unwrap();
13281        assert_eq!(ends.len(), 1);
13282        assert_eq!(
13283            ends[0].get("message").and_then(Value::as_str),
13284            Some("us-east-1"),
13285            "vars.region must be seeded to its default and rendered in the node payload"
13286        );
13287    }
13288
13289    // ── var_set tests ──────────────────────────────────────────────────────
13290
13291    /// Build a two-node flow: var_set → emit.log, with optional vars_init.
13292    ///
13293    /// `var_set_input` is the raw input mapping for the var.set node,
13294    /// e.g. `json!({ "name": "greeting", "value": "hi" })`.
13295    /// `emit_input` is the input mapping for the emit.log node.
13296    /// `vars_init_extra` is optional flow-level vars_init metadata.
13297    fn var_set_flow(
13298        var_set_input: Value,
13299        emit_input: Value,
13300        vars_init_extra: Option<Value>,
13301    ) -> Flow {
13302        let set_id = NodeId::from_str("set1").unwrap();
13303        let emit_id = NodeId::from_str("emit1").unwrap();
13304
13305        let set_node = Node {
13306            id: set_id.clone(),
13307            component: FlowComponentRef {
13308                id: "var.set".parse().unwrap(),
13309                pack_alias: None,
13310                operation: None,
13311            },
13312            input: InputMapping {
13313                mapping: var_set_input,
13314            },
13315            output: OutputMapping {
13316                mapping: Value::Null,
13317            },
13318            err_map: None,
13319            routing: Routing::Next {
13320                node_id: emit_id.clone(),
13321            },
13322            telemetry: TelemetryHints::default(),
13323            conversational: false,
13324        };
13325
13326        let emit_node = Node {
13327            id: emit_id.clone(),
13328            component: FlowComponentRef {
13329                id: "emit.log".parse().unwrap(),
13330                pack_alias: None,
13331                operation: None,
13332            },
13333            input: InputMapping {
13334                mapping: emit_input,
13335            },
13336            output: OutputMapping {
13337                mapping: Value::Null,
13338            },
13339            err_map: None,
13340            routing: Routing::End,
13341            telemetry: TelemetryHints::default(),
13342            conversational: false,
13343        };
13344
13345        let mut nodes = indexmap::IndexMap::default();
13346        nodes.insert(set_id.clone(), set_node);
13347        nodes.insert(emit_id.clone(), emit_node);
13348
13349        let extra = vars_init_extra.unwrap_or(serde_json::json!({}));
13350
13351        Flow {
13352            schema_version: "1.0".into(),
13353            id: FlowId::from_str("var.set.flow").unwrap(),
13354            kind: FlowKind::Messaging,
13355            entrypoints: BTreeMap::from([(
13356                "default".to_string(),
13357                Value::String(set_id.to_string()),
13358            )]),
13359            nodes,
13360            metadata: FlowMetadata {
13361                title: None,
13362                description: None,
13363                tags: Default::default(),
13364                extra,
13365            },
13366        }
13367    }
13368
13369    fn run_var_set_flow(flow: Flow) -> (FlowStatus, Vec<Value>) {
13370        let host_flow = HostFlow::from(flow);
13371        let engine = FlowEngine {
13372            messaging_provider_pack_ids: Default::default(),
13373            rollout_ids: RolloutIds::default(),
13374            packs: Vec::new(),
13375            flows: Vec::new(),
13376            flow_sources: StdHashMap::new(),
13377            flow_cache: RwLock::new(StdHashMap::from([(
13378                FlowKey {
13379                    pack_id: "test-pack".to_string(),
13380                    flow_id: "var.set.flow".to_string(),
13381                },
13382                host_flow,
13383            )])),
13384            default_env: "local".to_string(),
13385            validation: ValidationConfig {
13386                mode: ValidationMode::Off,
13387            },
13388            cross_pack_resolver: None,
13389            approval_dispatch_handler: None,
13390            remote_dispatch_handler: None,
13391            #[cfg(feature = "agentic-worker")]
13392            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
13393            #[cfg(feature = "agentic-worker")]
13394            agent_node_handler: None,
13395            #[cfg(feature = "agentic-worker")]
13396            graph_node_handler: None,
13397            #[cfg(feature = "agentic-worker")]
13398            mcp_tool_source: None,
13399            #[cfg(feature = "agentic-worker")]
13400            mcp_secrets: None,
13401            #[cfg(feature = "agentic-worker")]
13402            a2a_sources: RwLock::new(HashMap::new()),
13403            #[cfg(feature = "agentic-worker")]
13404            ext_artifact_port: None,
13405            operala_node_handler: None,
13406        };
13407        let observer = CountingObserver::new();
13408        let ctx = FlowContext {
13409            tenant: "demo",
13410            pack_id: "test-pack",
13411            flow_id: "var.set.flow",
13412            node_id: None,
13413            tool: None,
13414            action: None,
13415            session_id: None,
13416            provider_id: None,
13417            reply_scope: None,
13418            retry_config: RetryConfig {
13419                max_attempts: 1,
13420                base_delay_ms: 1,
13421            },
13422            attempt: 1,
13423            observer: Some(&observer),
13424            mocks: None,
13425            caller: None,
13426        };
13427        let rt = Runtime::new().unwrap();
13428        let result = rt.block_on(engine.execute(ctx, Value::Null)).unwrap();
13429        let ends = observer.ends.lock().unwrap().clone();
13430        (result.status, ends)
13431    }
13432
13433    #[test]
13434    fn var_set_node_writes_literal_value_into_vars() {
13435        // A var_set node with a literal value: greeting="hi".
13436        // The following emit.log node uses {{vars.greeting}} and its output
13437        // proves the var was written.
13438        let flow = var_set_flow(
13439            json!({ "name": "greeting", "value": "hi" }),
13440            json!({ "message": "{{vars.greeting}}" }),
13441            None,
13442        );
13443        let (status, ends) = run_var_set_flow(flow);
13444
13445        assert!(
13446            matches!(status, FlowStatus::Completed),
13447            "flow must complete"
13448        );
13449        assert_eq!(ends.len(), 2, "both nodes must fire");
13450        // var_set node output
13451        assert_eq!(ends[0].get("ok"), Some(&json!(true)), "var_set output ok");
13452        // emit.log node output: vars.greeting was written
13453        assert_eq!(
13454            ends[1].get("message").and_then(Value::as_str),
13455            Some("hi"),
13456            "vars.greeting must be written and renderable in the next node"
13457        );
13458    }
13459
13460    #[test]
13461    fn var_set_node_writes_templated_value_with_type_preserved() {
13462        // vars_init seeds counter=1 (a number).
13463        // var_set copies it into "copy" via {{vars.counter}}.
13464        // The emit.log node uses {{vars.copy}} as the sole message template;
13465        // render_template_value returns the typed JSON number, not a string.
13466        let flow = var_set_flow(
13467            json!({ "name": "copy", "value": "{{vars.counter}}" }),
13468            json!({ "message": "{{vars.copy}}" }),
13469            Some(json!({
13470                "vars_init": {
13471                    "counter": { "type": "number", "default": 1 }
13472                }
13473            })),
13474        );
13475        let (status, ends) = run_var_set_flow(flow);
13476
13477        assert!(
13478            matches!(status, FlowStatus::Completed),
13479            "flow must complete"
13480        );
13481        assert_eq!(ends.len(), 2, "both nodes must fire");
13482        // emit.log message must be the typed number 1, not the string "1"
13483        assert_eq!(
13484            ends[1].get("message"),
13485            Some(&json!(1)),
13486            "vars.copy must preserve the JSON number type from vars.counter"
13487        );
13488    }
13489
13490    #[test]
13491    fn var_set_empty_name_is_skipped_not_written() {
13492        // A var_set node with an empty (or whitespace-only) name must complete
13493        // without panic and must NOT insert a "" key into state.vars.
13494        let engine = minimal_engine();
13495        let rt = Runtime::new().unwrap();
13496        let retry_config = RetryConfig {
13497            max_attempts: 1,
13498            base_delay_ms: 1,
13499        };
13500        let ctx = FlowContext {
13501            tenant: "demo",
13502            pack_id: "test-pack",
13503            flow_id: "var.set.flow",
13504            node_id: Some("set1"),
13505            tool: None,
13506            action: None,
13507            session_id: None,
13508            provider_id: None,
13509            reply_scope: None,
13510            retry_config,
13511            attempt: 1,
13512            observer: None,
13513            mocks: None,
13514            caller: None,
13515        };
13516        let node = HostNode {
13517            kind: NodeKind::VarSet {
13518                name: "".to_string(),
13519                value: json!("garbage"),
13520            },
13521            component: "var.set".into(),
13522            component_id: "var.set".into(),
13523            operation_name: None,
13524            operation_in_mapping: None,
13525            payload_expr: Value::Null,
13526            routing: Routing::End,
13527            vars_out: None,
13528            response_timeout_secs: None,
13529        };
13530        let mut state = ExecutionState::new(Value::Null);
13531        let payload = Value::Null;
13532        let event = NodeEvent {
13533            context: &ctx,
13534            node_id: "set1",
13535            node: &node,
13536            payload: &payload,
13537        };
13538
13539        let outcome = rt
13540            .block_on(engine.dispatch_node(
13541                &ctx,
13542                "set1",
13543                &node,
13544                &mut state,
13545                payload.clone(),
13546                &event,
13547            ))
13548            .expect("dispatch_node must not error on empty var name");
13549
13550        // Must return {ok: true} (not an error).
13551        assert_eq!(
13552            outcome.output.payload,
13553            json!({ "ok": true }),
13554            "dispatch must return ok:true even when name is empty"
13555        );
13556        // Must NOT have inserted a \"\" key into state.vars.
13557        assert!(
13558            state.vars.get("").is_none(),
13559            "empty var name must not create a \"\" key in state.vars"
13560        );
13561    }
13562
13563    #[test]
13564    fn var_set_node_has_empty_payload_expr() {
13565        // Lowering a var.set Node must yield a HostNode whose payload_expr is
13566        // Value::Null. The VarSet dispatch arm reads name/value directly from
13567        // NodeKind::VarSet, so forwarding the mapping as payload_expr is redundant.
13568        let node_id = NodeId::from_str("set1").unwrap();
13569        let node = Node {
13570            id: node_id.clone(),
13571            component: FlowComponentRef {
13572                id: "var.set".parse().unwrap(),
13573                pack_alias: None,
13574                operation: None,
13575            },
13576            input: InputMapping {
13577                mapping: json!({ "name": "greeting", "value": "hi" }),
13578            },
13579            output: OutputMapping {
13580                mapping: Value::Null,
13581            },
13582            err_map: None,
13583            routing: Routing::End,
13584            telemetry: TelemetryHints::default(),
13585            conversational: false,
13586        };
13587
13588        let host_node = HostNode::from(node);
13589
13590        // payload_expr must be Null.
13591        assert_eq!(
13592            host_node.payload_expr,
13593            Value::Null,
13594            "var.set node must have Null payload_expr after lowering"
13595        );
13596        // NodeKind::VarSet must still carry the original name and value.
13597        match &host_node.kind {
13598            NodeKind::VarSet { name, value } => {
13599                assert_eq!(name.as_str(), "greeting", "name must be preserved in kind");
13600                assert_eq!(value, &json!("hi"), "value must be preserved in kind");
13601            }
13602            other => panic!("expected NodeKind::VarSet, got {other:?}"),
13603        }
13604    }
13605
13606    // ── vars_out tests ──────────────────────────────────────────────────────
13607
13608    /// Build a two-node flow: emit.log (with vars_out) → emit.log.
13609    ///
13610    /// `emit1_input` is the raw input mapping for the first emit.log node
13611    /// (should include the `vars_out` binding).
13612    /// `emit2_input` is the input mapping for the second emit.log node
13613    /// (reads from `vars.*` to prove bindings were applied).
13614    fn vars_out_flow(emit1_input: Value, emit2_input: Value) -> Flow {
13615        let emit1_id = NodeId::from_str("emit1").unwrap();
13616        let emit2_id = NodeId::from_str("emit2").unwrap();
13617
13618        let emit1_node = Node {
13619            id: emit1_id.clone(),
13620            component: FlowComponentRef {
13621                id: "emit.log".parse().unwrap(),
13622                pack_alias: None,
13623                operation: None,
13624            },
13625            input: InputMapping {
13626                mapping: emit1_input,
13627            },
13628            output: OutputMapping {
13629                mapping: Value::Null,
13630            },
13631            err_map: None,
13632            routing: Routing::Next {
13633                node_id: emit2_id.clone(),
13634            },
13635            telemetry: TelemetryHints::default(),
13636            conversational: false,
13637        };
13638
13639        let emit2_node = Node {
13640            id: emit2_id.clone(),
13641            component: FlowComponentRef {
13642                id: "emit.log".parse().unwrap(),
13643                pack_alias: None,
13644                operation: None,
13645            },
13646            input: InputMapping {
13647                mapping: emit2_input,
13648            },
13649            output: OutputMapping {
13650                mapping: Value::Null,
13651            },
13652            err_map: None,
13653            routing: Routing::End,
13654            telemetry: TelemetryHints::default(),
13655            conversational: false,
13656        };
13657
13658        let mut nodes = indexmap::IndexMap::default();
13659        nodes.insert(emit1_id.clone(), emit1_node);
13660        nodes.insert(emit2_id.clone(), emit2_node);
13661
13662        // Reuse the same flow_id as var_set_flow so we can pass it directly to
13663        // `run_var_set_flow`, which registers the flow under that key.
13664        Flow {
13665            schema_version: "1.0".into(),
13666            id: FlowId::from_str("var.set.flow").unwrap(),
13667            kind: FlowKind::Messaging,
13668            entrypoints: BTreeMap::from([(
13669                "default".to_string(),
13670                Value::String(emit1_id.to_string()),
13671            )]),
13672            nodes,
13673            metadata: FlowMetadata {
13674                title: None,
13675                description: None,
13676                tags: Default::default(),
13677                extra: serde_json::json!({}),
13678            },
13679        }
13680    }
13681
13682    #[test]
13683    fn vars_out_binds_node_output_into_vars() {
13684        // `emit.log` outputs its rendered payload directly. Node 1 emits
13685        // `{ message: "hello" }` and declares `vars_out = { lastReply:
13686        // "{{prev.message}}" }`. After it runs, `state.vars["lastReply"]`
13687        // must equal "hello". Node 2 reads that var so the assertion is driven
13688        // from the second node's output rather than internal state.
13689        let flow = vars_out_flow(
13690            json!({
13691                "message": "hello",
13692                "vars_out": { "lastReply": "{{prev.message}}" }
13693            }),
13694            json!({ "message": "{{vars.lastReply}}" }),
13695        );
13696        let (status, ends) = run_var_set_flow(flow);
13697
13698        assert!(
13699            matches!(status, FlowStatus::Completed),
13700            "flow must complete"
13701        );
13702        assert_eq!(ends.len(), 2, "both nodes must fire");
13703        // Node 2's message must equal the value captured by vars_out in node 1.
13704        assert_eq!(
13705            ends[1].get("message").and_then(Value::as_str),
13706            Some("hello"),
13707            "vars_out binding from node 1 must be readable in node 2"
13708        );
13709    }
13710
13711    #[test]
13712    fn vars_out_is_stripped_from_component_node_payload() {
13713        // A component (non-emit) node whose input.mapping contains both a
13714        // real field ("message") and the internal "vars_out" meta-key must NOT
13715        // forward "vars_out" as part of its payload_expr. This prevents the key
13716        // from leaking into wasm components with strict additionalProperties schemas.
13717        //
13718        // We use a PackComponent-style node (component ref = "my.component") so
13719        // the non-emit arm of `impl From<Node> for HostNode` is exercised.
13720        let node_id = NodeId::from_str("comp1").unwrap();
13721        let node = Node {
13722            id: node_id.clone(),
13723            component: FlowComponentRef {
13724                id: "my.component".parse().unwrap(),
13725                pack_alias: None,
13726                operation: None,
13727            },
13728            input: InputMapping {
13729                mapping: json!({
13730                    "message": "hello",
13731                    "vars_out": { "lastReply": "{{prev.message}}" }
13732                }),
13733            },
13734            output: OutputMapping {
13735                mapping: Value::Null,
13736            },
13737            err_map: None,
13738            routing: Routing::End,
13739            telemetry: TelemetryHints::default(),
13740            conversational: false,
13741        };
13742
13743        let host_node = HostNode::from(node);
13744
13745        // The vars_out binding must be preserved on the HostNode itself.
13746        assert!(
13747            host_node.vars_out.is_some(),
13748            "vars_out binding must be carried on the HostNode"
13749        );
13750        assert!(
13751            host_node
13752                .vars_out
13753                .as_ref()
13754                .unwrap()
13755                .contains_key("lastReply"),
13756            "vars_out must contain the declared binding"
13757        );
13758
13759        // The payload_expr must NOT contain the "vars_out" key.
13760        assert!(
13761            host_node.payload_expr.get("vars_out").is_none(),
13762            "vars_out must not appear in payload_expr (would leak to wasm component input)"
13763        );
13764
13765        // The real input field must still be present in the payload_expr.
13766        assert_eq!(
13767            host_node
13768                .payload_expr
13769                .get("message")
13770                .and_then(Value::as_str),
13771            Some("hello"),
13772            "real input fields must remain in payload_expr"
13773        );
13774    }
13775
13776    #[test]
13777    fn dotted_component_id_is_not_split_when_mapping_carries_operation() {
13778        // packc sets `node.component.operation = None` to mean "the id is already
13779        // complete" (normalize_legacy_component_exec_ids), and puts the operation in
13780        // input.mapping. Lowering must therefore keep the reverse-DNS id intact and
13781        // take the operation from the mapping. Splitting on the last dot yields a
13782        // component_ref that is by construction absent from the pack's component map,
13783        // so the node fails with "component '<truncated>' not found in pack".
13784        let node_id = NodeId::from_str("present_koncar").unwrap();
13785        let node = Node {
13786            id: node_id,
13787            component: FlowComponentRef {
13788                id: "ai.greentic.koncar.component-present".parse().unwrap(),
13789                pack_alias: None,
13790                operation: None,
13791            },
13792            input: InputMapping {
13793                mapping: json!({
13794                    "component": "ai.greentic.koncar.component-present",
13795                    "operation": "present",
13796                    "query": "hello"
13797                }),
13798            },
13799            output: OutputMapping {
13800                mapping: Value::Null,
13801            },
13802            err_map: None,
13803            routing: Routing::End,
13804            telemetry: TelemetryHints::default(),
13805            conversational: false,
13806        };
13807
13808        let host_node = HostNode::from(node);
13809
13810        assert_eq!(
13811            host_node.component_id(),
13812            "ai.greentic.koncar.component-present",
13813            "dotted component id must survive lowering intact"
13814        );
13815        match &host_node.kind {
13816            NodeKind::PackComponent { component_ref } => assert_eq!(
13817                component_ref, "ai.greentic.koncar.component-present",
13818                "PackComponent must look up the full id, not a dot-split prefix"
13819            ),
13820            other => panic!("expected NodeKind::PackComponent, got {other:?}"),
13821        }
13822        assert_eq!(
13823            host_node.operation_in_mapping(),
13824            Some("present"),
13825            "the operation must still be readable from the mapping"
13826        );
13827    }
13828
13829    /// Build a three-node flow: var_set → session.wait → emit.log.
13830    /// `vars_init` seeds `counter = 1`; `var_set` writes `greeting = "hello"`.
13831    /// The wait parks the flow; resume runs emit.log which reads both vars.
13832    fn vars_survive_flow() -> Flow {
13833        let set_id = NodeId::from_str("set1").unwrap();
13834        let wait_id = NodeId::from_str("wait1").unwrap();
13835        let emit_id = NodeId::from_str("emit1").unwrap();
13836
13837        let set_node = Node {
13838            id: set_id.clone(),
13839            component: FlowComponentRef {
13840                id: "var.set".parse().unwrap(),
13841                pack_alias: None,
13842                operation: None,
13843            },
13844            input: InputMapping {
13845                mapping: json!({ "name": "greeting", "value": "hello" }),
13846            },
13847            output: OutputMapping {
13848                mapping: Value::Null,
13849            },
13850            err_map: None,
13851            routing: Routing::Next {
13852                node_id: wait_id.clone(),
13853            },
13854            telemetry: TelemetryHints::default(),
13855            conversational: false,
13856        };
13857
13858        let wait_node = Node {
13859            id: wait_id.clone(),
13860            component: FlowComponentRef {
13861                id: "session.wait".parse().unwrap(),
13862                pack_alias: None,
13863                operation: None,
13864            },
13865            input: InputMapping {
13866                mapping: Value::Null,
13867            },
13868            output: OutputMapping {
13869                mapping: Value::Null,
13870            },
13871            err_map: None,
13872            routing: Routing::Next {
13873                node_id: emit_id.clone(),
13874            },
13875            telemetry: TelemetryHints::default(),
13876            conversational: false,
13877        };
13878
13879        let emit_node = Node {
13880            id: emit_id.clone(),
13881            component: FlowComponentRef {
13882                id: "emit.log".parse().unwrap(),
13883                pack_alias: None,
13884                operation: None,
13885            },
13886            input: InputMapping {
13887                mapping: json!({
13888                    "greeting": "{{vars.greeting}}",
13889                    "counter": "{{vars.counter}}"
13890                }),
13891            },
13892            output: OutputMapping {
13893                mapping: Value::Null,
13894            },
13895            err_map: None,
13896            routing: Routing::End,
13897            telemetry: TelemetryHints::default(),
13898            conversational: false,
13899        };
13900
13901        let mut nodes = indexmap::IndexMap::default();
13902        nodes.insert(set_id.clone(), set_node);
13903        nodes.insert(wait_id.clone(), wait_node);
13904        nodes.insert(emit_id.clone(), emit_node);
13905
13906        Flow {
13907            schema_version: "1.0".into(),
13908            id: FlowId::from_str("vars.survive.flow").unwrap(),
13909            kind: FlowKind::Messaging,
13910            entrypoints: BTreeMap::from([(
13911                "default".to_string(),
13912                Value::String(set_id.to_string()),
13913            )]),
13914            nodes,
13915            metadata: FlowMetadata {
13916                title: None,
13917                description: None,
13918                tags: Default::default(),
13919                extra: json!({
13920                    "vars_init": {
13921                        "counter": { "type": "number", "default": 1 }
13922                    }
13923                }),
13924            },
13925        }
13926    }
13927
13928    #[test]
13929    fn vars_survive_park_and_resume_end_to_end() {
13930        // vars_init seeds counter=1; var_set writes greeting="hello"; the flow
13931        // parks at session.wait; resume drives emit.log which reads both vars.
13932        let flow = vars_survive_flow();
13933        let host_flow = HostFlow::from(flow);
13934        let flow_id = "vars.survive.flow";
13935        let pack_id = "test-pack";
13936        let engine = FlowEngine {
13937            messaging_provider_pack_ids: Default::default(),
13938            rollout_ids: RolloutIds::default(),
13939            packs: Vec::new(),
13940            flows: Vec::new(),
13941            flow_sources: StdHashMap::new(),
13942            flow_cache: RwLock::new(StdHashMap::from([(
13943                FlowKey {
13944                    pack_id: pack_id.to_string(),
13945                    flow_id: flow_id.to_string(),
13946                },
13947                host_flow,
13948            )])),
13949            default_env: "local".to_string(),
13950            validation: ValidationConfig {
13951                mode: ValidationMode::Off,
13952            },
13953            cross_pack_resolver: None,
13954            approval_dispatch_handler: None,
13955            remote_dispatch_handler: None,
13956            #[cfg(feature = "agentic-worker")]
13957            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
13958            #[cfg(feature = "agentic-worker")]
13959            agent_node_handler: None,
13960            #[cfg(feature = "agentic-worker")]
13961            graph_node_handler: None,
13962            #[cfg(feature = "agentic-worker")]
13963            mcp_tool_source: None,
13964            #[cfg(feature = "agentic-worker")]
13965            mcp_secrets: None,
13966            #[cfg(feature = "agentic-worker")]
13967            a2a_sources: RwLock::new(HashMap::new()),
13968            #[cfg(feature = "agentic-worker")]
13969            ext_artifact_port: None,
13970            operala_node_handler: None,
13971        };
13972        let rt = Runtime::new().unwrap();
13973
13974        // First execution: must park at session.wait after var_set fires.
13975        let ctx1 = FlowContext {
13976            tenant: "demo",
13977            pack_id,
13978            flow_id,
13979            node_id: None,
13980            tool: None,
13981            action: None,
13982            session_id: None,
13983            provider_id: None,
13984            reply_scope: None,
13985            retry_config: RetryConfig {
13986                max_attempts: 1,
13987                base_delay_ms: 1,
13988            },
13989            attempt: 1,
13990            observer: None,
13991            mocks: None,
13992            caller: None,
13993        };
13994        let result1 = rt.block_on(engine.execute(ctx1, Value::Null)).unwrap();
13995        let snapshot = match result1.status {
13996            FlowStatus::Waiting(w) => w.snapshot,
13997            other => panic!("expected Waiting after session.wait, got {other:?}"),
13998        };
13999
14000        // Both vars must be present in the snapshot before resume.
14001        assert_eq!(
14002            snapshot.state.vars.get("greeting"),
14003            Some(&json!("hello")),
14004            "greeting var must be in snapshot"
14005        );
14006        assert_eq!(
14007            snapshot.state.vars.get("counter"),
14008            Some(&json!(1)),
14009            "counter var (from vars_init) must be in snapshot"
14010        );
14011
14012        // Resume: emit.log must read both vars from the restored state.
14013        let observer2 = CountingObserver::new();
14014        let ctx2 = FlowContext {
14015            tenant: "demo",
14016            pack_id,
14017            flow_id,
14018            node_id: None,
14019            tool: None,
14020            action: None,
14021            session_id: None,
14022            provider_id: None,
14023            reply_scope: None,
14024            retry_config: RetryConfig {
14025                max_attempts: 1,
14026                base_delay_ms: 1,
14027            },
14028            attempt: 1,
14029            observer: Some(&observer2),
14030            mocks: None,
14031            caller: None,
14032        };
14033        let result2 = rt
14034            .block_on(engine.resume(ctx2, snapshot, Value::Null))
14035            .unwrap();
14036        assert!(
14037            matches!(result2.status, FlowStatus::Completed),
14038            "flow must complete after resume"
14039        );
14040        let ends2 = observer2.ends.lock().unwrap().clone();
14041        assert_eq!(ends2.len(), 1, "only emit.log fires after resume");
14042        assert_eq!(
14043            ends2[0].get("greeting").and_then(Value::as_str),
14044            Some("hello"),
14045            "vars.greeting must survive the park/resume"
14046        );
14047        assert_eq!(
14048            ends2[0].get("counter"),
14049            Some(&json!(1)),
14050            "vars.counter (vars_init) must survive the park/resume"
14051        );
14052    }
14053
14054    #[cfg(feature = "agentic-worker")]
14055    struct StubAgentHandler {
14056        payload: serde_json::Value,
14057    }
14058    #[cfg(feature = "agentic-worker")]
14059    #[async_trait::async_trait]
14060    impl crate::runner::agent_node::AgentNodeHandler for StubAgentHandler {
14061        async fn execute(
14062            &self,
14063            _tenant_id: &str,
14064            _env_id: &str,
14065            _agent_id: &str,
14066            _session_id: &str,
14067            _flow_input: &serde_json::Value,
14068            _conversational: bool,
14069            _caller: Option<&serde_json::Value>,
14070        ) -> anyhow::Result<serde_json::Value> {
14071            Ok(self.payload.clone())
14072        }
14073    }
14074
14075    /// Build a 2-node flow: a `dw.agent` node (id "agent", conversational as
14076    /// given) routing to an emit "thanks" node that ends the flow.
14077    #[cfg(feature = "agentic-worker")]
14078    fn conversational_dw_flow(conversational: bool) -> HostFlow {
14079        let mut nodes = IndexMap::new();
14080        let agent_id = NodeId::from_str("agent").unwrap();
14081        let thanks_id = NodeId::from_str("thanks").unwrap();
14082        nodes.insert(
14083            agent_id.clone(),
14084            HostNode {
14085                kind: NodeKind::DwAgent {
14086                    agent_id: "a".to_string(),
14087                    conversational,
14088                },
14089                component: "dw.agent".to_string(),
14090                component_id: "dw.agent".to_string(),
14091                operation_name: Some("a".to_string()),
14092                operation_in_mapping: None,
14093                payload_expr: json!({ "user_text": "hi" }),
14094                routing: Routing::Next {
14095                    node_id: thanks_id.clone(),
14096                },
14097                vars_out: None,
14098                response_timeout_secs: None,
14099            },
14100        );
14101        nodes.insert(
14102            thanks_id.clone(),
14103            HostNode {
14104                kind: NodeKind::BuiltinEmit {
14105                    kind: EmitKind::Response,
14106                },
14107                component: "emit.response".to_string(),
14108                component_id: "emit.response".to_string(),
14109                operation_name: None,
14110                operation_in_mapping: None,
14111                payload_expr: json!({ "text": "thanks" }),
14112                routing: Routing::End,
14113                vars_out: None,
14114                response_timeout_secs: None,
14115            },
14116        );
14117        HostFlow {
14118            slot_schema: None,
14119            id: "conv.flow".to_string(),
14120            start: Some(agent_id),
14121            nodes,
14122            vars_init: JsonMap::new(),
14123            required_vars: Vec::new(),
14124        }
14125    }
14126
14127    /// Build an engine holding `flow` with a stub agent handler returning `payload`.
14128    /// Mirrors the FlowEngine literal in `vars_survive_park_and_resume_end_to_end`.
14129    #[cfg(feature = "agentic-worker")]
14130    fn conv_engine(flow: HostFlow, payload: serde_json::Value) -> FlowEngine {
14131        conv_engine_with(flow, std::sync::Arc::new(StubAgentHandler { payload }))
14132    }
14133
14134    /// [`conv_engine`] with a caller-supplied agent handler.
14135    #[cfg(feature = "agentic-worker")]
14136    fn conv_engine_with(
14137        flow: HostFlow,
14138        handler: std::sync::Arc<dyn crate::runner::agent_node::AgentNodeHandler>,
14139    ) -> FlowEngine {
14140        FlowEngine {
14141            messaging_provider_pack_ids: Default::default(),
14142            rollout_ids: RolloutIds::default(),
14143            packs: Vec::new(),
14144            flows: Vec::new(),
14145            flow_sources: StdHashMap::new(),
14146            flow_cache: RwLock::new(StdHashMap::from([(
14147                FlowKey {
14148                    pack_id: "test-pack".to_string(),
14149                    flow_id: "conv.flow".to_string(),
14150                },
14151                flow,
14152            )])),
14153            default_env: "local".to_string(),
14154            validation: ValidationConfig {
14155                mode: ValidationMode::Off,
14156            },
14157            cross_pack_resolver: None,
14158            approval_dispatch_handler: None,
14159            remote_dispatch_handler: None,
14160            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
14161            agent_node_handler: Some(handler),
14162            graph_node_handler: None,
14163            mcp_tool_source: None,
14164            mcp_secrets: None,
14165            #[cfg(feature = "agentic-worker")]
14166            a2a_sources: RwLock::new(HashMap::new()),
14167            #[cfg(feature = "agentic-worker")]
14168            ext_artifact_port: None,
14169            operala_node_handler: None,
14170        }
14171    }
14172
14173    #[cfg(feature = "agentic-worker")]
14174    fn conv_ctx<'a>() -> FlowContext<'a> {
14175        FlowContext {
14176            tenant: "demo",
14177            pack_id: "test-pack",
14178            flow_id: "conv.flow",
14179            node_id: None,
14180            tool: None,
14181            action: None,
14182            session_id: Some("sess-conv"),
14183            provider_id: None,
14184            reply_scope: None,
14185            retry_config: RetryConfig {
14186                max_attempts: 1,
14187                base_delay_ms: 1,
14188            },
14189            attempt: 1,
14190            observer: None,
14191            mocks: None,
14192            caller: None,
14193        }
14194    }
14195
14196    #[cfg(feature = "agentic-worker")]
14197    #[test]
14198    fn conversational_dw_agent_parks_and_loops_on_normal_reply() {
14199        let engine = conv_engine(
14200            conversational_dw_flow(true),
14201            json!({ "reply": "hello there", "trail": [], "terminated_by": "final_reply" }),
14202        );
14203        let rt = Runtime::new().unwrap();
14204        let result = rt
14205            .block_on(engine.execute(conv_ctx(), Value::Null))
14206            .unwrap();
14207        let snapshot = match result.status {
14208            FlowStatus::Waiting(w) => w.snapshot,
14209            other => panic!("expected Waiting (park-loop), got {other:?}"),
14210        };
14211        assert_eq!(
14212            snapshot.next_node, "agent",
14213            "must re-enter the dw.agent node itself"
14214        );
14215        // The reply is rendered in the parked output.
14216        assert!(
14217            serde_json::to_string(&result.output)
14218                .unwrap()
14219                .contains("hello there"),
14220            "the agent reply must be rendered before parking: {:?}",
14221            result.output
14222        );
14223    }
14224
14225    #[cfg(feature = "agentic-worker")]
14226    #[test]
14227    fn conversational_dw_agent_advances_on_conversation_ended() {
14228        let engine = conv_engine(
14229            conversational_dw_flow(true),
14230            json!({ "reply": "bye", "trail": [], "terminated_by": "conversation_ended" }),
14231        );
14232        let rt = Runtime::new().unwrap();
14233        let result = rt
14234            .block_on(engine.execute(conv_ctx(), Value::Null))
14235            .unwrap();
14236        assert!(
14237            matches!(result.status, FlowStatus::Completed),
14238            "conversation_ended must advance to the successor and complete, got {:?}",
14239            result.status
14240        );
14241    }
14242
14243    #[cfg(feature = "agentic-worker")]
14244    #[test]
14245    fn non_conversational_dw_agent_never_loops() {
14246        // Even with terminated_by == conversation_ended, a non-conversational
14247        // node just routes onward (today's one-shot behaviour) — never parks.
14248        for tb in ["final_reply", "conversation_ended"] {
14249            let engine = conv_engine(
14250                conversational_dw_flow(false),
14251                json!({ "reply": "x", "trail": [], "terminated_by": tb }),
14252            );
14253            let rt = Runtime::new().unwrap();
14254            let result = rt
14255                .block_on(engine.execute(conv_ctx(), Value::Null))
14256                .unwrap();
14257            assert!(
14258                matches!(result.status, FlowStatus::Completed),
14259                "non-conversational must complete (route onward) for terminated_by={tb}, got {:?}",
14260                result.status
14261            );
14262        }
14263    }
14264
14265    /// Agent handler that answers scripted node outputs in turn and records
14266    /// the `resume_payload` each turn was handed.
14267    #[cfg(feature = "agentic-worker")]
14268    struct ToolParkAgentHandler {
14269        outputs: std::sync::Mutex<Vec<serde_json::Value>>,
14270        resumes: std::sync::Mutex<Vec<Option<serde_json::Value>>>,
14271    }
14272    #[cfg(feature = "agentic-worker")]
14273    impl ToolParkAgentHandler {
14274        fn new(outputs: Vec<serde_json::Value>) -> Self {
14275            Self {
14276                outputs: std::sync::Mutex::new(outputs),
14277                resumes: std::sync::Mutex::new(Vec::new()),
14278            }
14279        }
14280    }
14281    #[cfg(feature = "agentic-worker")]
14282    #[async_trait::async_trait]
14283    impl crate::runner::agent_node::AgentNodeHandler for ToolParkAgentHandler {
14284        async fn execute(
14285            &self,
14286            _tenant_id: &str,
14287            _env_id: &str,
14288            _agent_id: &str,
14289            _session_id: &str,
14290            _flow_input: &serde_json::Value,
14291            _conversational: bool,
14292            _caller: Option<&serde_json::Value>,
14293        ) -> anyhow::Result<serde_json::Value> {
14294            anyhow::bail!("the engine must call execute_with_resume")
14295        }
14296
14297        async fn execute_with_resume(
14298            &self,
14299            _tenant_id: &str,
14300            _env_id: &str,
14301            _agent_id: &str,
14302            _session_id: &str,
14303            _flow_input: &serde_json::Value,
14304            _conversational: bool,
14305            _caller: Option<&serde_json::Value>,
14306            resume_payload: Option<&serde_json::Value>,
14307        ) -> anyhow::Result<serde_json::Value> {
14308            self.resumes.lock().unwrap().push(resume_payload.cloned());
14309            let mut outputs = self.outputs.lock().unwrap();
14310            anyhow::ensure!(!outputs.is_empty(), "no scripted agent output");
14311            Ok(outputs.remove(0))
14312        }
14313    }
14314
14315    #[cfg(feature = "agentic-worker")]
14316    fn awaiting_tool_output() -> serde_json::Value {
14317        json!({
14318            "reply": "please pick a room",
14319            "trail": [],
14320            "terminated_by": "awaiting_tool_input",
14321            "pending_presentation": { "type": "AdaptiveCard", "body": [{ "text": "Room?" }] }
14322        })
14323    }
14324
14325    /// A `dw.agent` whose `flow:` tool parked on a card parks the FLOW at the
14326    /// agent node — even when the node is not conversational — renders the
14327    /// card as the turn output, and on a card submit hands that submit to the
14328    /// agent as the tool's answer. The park does not spend the conversational
14329    /// `MAX_PARK_TURNS` budget.
14330    #[cfg(feature = "agentic-worker")]
14331    #[test]
14332    fn dw_agent_awaiting_tool_input_parks_renders_the_card_and_resumes_with_the_submit() {
14333        let handler = std::sync::Arc::new(ToolParkAgentHandler::new(vec![
14334            awaiting_tool_output(),
14335            json!({ "reply": "booked", "trail": [], "terminated_by": "final_reply" }),
14336        ]));
14337        let engine = conv_engine_with(conversational_dw_flow(false), handler.clone());
14338        let rt = Runtime::new().unwrap();
14339
14340        let first = rt
14341            .block_on(engine.execute(conv_ctx(), json!({ "text": "book a room" })))
14342            .unwrap();
14343        let snapshot = match first.status {
14344            FlowStatus::Waiting(w) => w.snapshot,
14345            other => panic!("expected the flow to park on the tool, got {other:?}"),
14346        };
14347        assert_eq!(snapshot.next_node, "agent", "re-enter the agent node");
14348        assert_eq!(
14349            first.output,
14350            json!({ "type": "AdaptiveCard", "body": [{ "text": "Room?" }] }),
14351            "the card, not the agent envelope, is the turn output"
14352        );
14353        assert_eq!(
14354            first.node_outputs["agent"]["pending_presentation"]["type"], "AdaptiveCard",
14355            "the node output keeps the full envelope: {:?}",
14356            first.node_outputs
14357        );
14358        assert!(snapshot.state.pending_tool_await.contains_key("agent"));
14359        assert!(
14360            snapshot.state.park_turns.is_empty(),
14361            "a tool park is not a conversational turn"
14362        );
14363
14364        let submit = json!({ "metadata": { "action": "submit" }, "room": "101" });
14365        let second = rt
14366            .block_on(engine.resume(conv_ctx(), snapshot, submit.clone()))
14367            .unwrap();
14368        assert!(
14369            matches!(second.status, FlowStatus::Completed),
14370            "the resumed non-conversational agent routes onward, got {:?}",
14371            second.status
14372        );
14373        assert_eq!(*handler.resumes.lock().unwrap(), vec![None, Some(submit)]);
14374    }
14375
14376    /// The agent chat ingress (`/agent/chat`, `/agent/chat/stream`) turns a
14377    /// request's `resume_payload` into the turn payload; the engine must hand
14378    /// exactly that to the parked agent, i.e. `AgentInput.resume_payload`.
14379    #[cfg(feature = "agentic-worker")]
14380    #[test]
14381    fn an_agent_chat_resume_payload_reaches_the_parked_agent() {
14382        let handler = std::sync::Arc::new(ToolParkAgentHandler::new(vec![
14383            awaiting_tool_output(),
14384            json!({ "reply": "booked", "trail": [], "terminated_by": "final_reply" }),
14385        ]));
14386        let engine = conv_engine_with(conversational_dw_flow(false), handler.clone());
14387        let rt = Runtime::new().unwrap();
14388        let first = rt
14389            .block_on(engine.execute(conv_ctx(), json!({ "text": "book a room" })))
14390            .unwrap();
14391        let FlowStatus::Waiting(wait) = first.status else {
14392            panic!("expected a park");
14393        };
14394        let submit = json!({ "metadata": { "action": "submit" }, "room": "101" });
14395        let payload =
14396            crate::http::agent_chat::turn_payload(String::new(), submit.as_object().cloned());
14397        rt.block_on(engine.resume(conv_ctx(), wait.snapshot, payload))
14398            .unwrap();
14399        assert_eq!(*handler.resumes.lock().unwrap(), vec![None, Some(submit)]);
14400    }
14401
14402    /// A typed message arriving while the tool is parked reaches the agent as
14403    /// a message (no resume payload), so the agent cancels the parked tool.
14404    #[cfg(feature = "agentic-worker")]
14405    #[test]
14406    fn a_typed_message_during_a_tool_park_is_not_a_resume_payload() {
14407        let handler = std::sync::Arc::new(ToolParkAgentHandler::new(vec![
14408            awaiting_tool_output(),
14409            json!({ "reply": "ok, cancelled", "trail": [], "terminated_by": "final_reply" }),
14410        ]));
14411        let engine = conv_engine_with(conversational_dw_flow(false), handler.clone());
14412        let rt = Runtime::new().unwrap();
14413        let first = rt
14414            .block_on(engine.execute(conv_ctx(), json!({ "text": "book a room" })))
14415            .unwrap();
14416        let FlowStatus::Waiting(wait) = first.status else {
14417            panic!("expected a park");
14418        };
14419        rt.block_on(engine.resume(conv_ctx(), wait.snapshot, json!({ "text": "never mind" })))
14420            .unwrap();
14421        assert_eq!(*handler.resumes.lock().unwrap(), vec![None, None]);
14422    }
14423
14424    #[cfg(feature = "agentic-worker")]
14425    fn side_turn_output() -> serde_json::Value {
14426        json!({
14427            "reply": "the signature is in Settings",
14428            "trail": [],
14429            "terminated_by": "awaiting_tool_input",
14430            "side_turn": true,
14431            "pending_presentation": { "type": "AdaptiveCard", "body": [{ "text": "Room?" }] }
14432        })
14433    }
14434
14435    #[cfg(feature = "agentic-worker")]
14436    #[test]
14437    fn a_plain_park_still_renders_only_the_card() {
14438        let out = awaiting_tool_output();
14439        assert_eq!(rendered_park(&out), out["pending_presentation"]);
14440    }
14441
14442    #[cfg(feature = "agentic-worker")]
14443    #[test]
14444    fn a_side_turn_park_renders_the_reply_then_the_card() {
14445        let out = side_turn_output();
14446        let rendered = rendered_park(&out);
14447        let items = rendered.as_array().expect("reply + card");
14448        assert_eq!(items.len(), 2);
14449        assert_eq!(items[0]["reply"], "the signature is in Settings");
14450        assert!(items[0].get("pending_presentation").is_none());
14451        assert_eq!(items[1], out["pending_presentation"]);
14452    }
14453
14454    /// `emit.response` renders its messages as an ARRAY, so a parked card is
14455    /// often a list. The side-turn output must stay one flat list of replies
14456    /// (`normalize_replies` turns each top-level item into one activity); a
14457    /// nested list would reach the channel as a single activity holding an array.
14458    #[cfg(feature = "agentic-worker")]
14459    #[test]
14460    fn a_side_turn_with_a_list_card_renders_one_flat_list() {
14461        let mut out = side_turn_output();
14462        out["pending_presentation"] = json!([{ "text": "pick a room" }, { "text": "or cancel" }]);
14463        let rendered = rendered_park(&out);
14464        let items = rendered.as_array().expect("flat list");
14465        assert_eq!(items.len(), 3, "reply + both card messages: {rendered}");
14466        assert_eq!(items[0]["reply"], "the signature is in Settings");
14467        assert_eq!(items[1], json!({ "text": "pick a room" }));
14468        assert_eq!(items[2], json!({ "text": "or cancel" }));
14469        assert!(items.iter().all(|item| !item.is_array()), "no nested list");
14470    }
14471
14472    /// A typed message answered as a side turn leaves the flow parked at the
14473    /// agent node with the await re-armed, so the NEXT card submit still
14474    /// reaches the agent as a resume payload.
14475    #[cfg(feature = "agentic-worker")]
14476    #[test]
14477    fn a_side_turn_keeps_the_await_armed_so_a_submit_still_resumes() {
14478        let handler = std::sync::Arc::new(ToolParkAgentHandler::new(vec![
14479            awaiting_tool_output(),
14480            side_turn_output(),
14481            json!({ "reply": "booked", "trail": [], "terminated_by": "final_reply" }),
14482        ]));
14483        let engine = conv_engine_with(conversational_dw_flow(false), handler.clone());
14484        let rt = Runtime::new().unwrap();
14485        let first = rt
14486            .block_on(engine.execute(conv_ctx(), json!({ "text": "book a room" })))
14487            .unwrap();
14488        let FlowStatus::Waiting(wait) = first.status else {
14489            panic!("expected a park");
14490        };
14491        let second = rt
14492            .block_on(engine.resume(
14493                conv_ctx(),
14494                wait.snapshot,
14495                json!({ "text": "how do I get a signature?" }),
14496            ))
14497            .unwrap();
14498        assert!(
14499            second.output.is_array(),
14500            "reply and card: {}",
14501            second.output
14502        );
14503        let FlowStatus::Waiting(wait) = second.status else {
14504            panic!("the side turn must keep the flow parked");
14505        };
14506        rt.block_on(engine.resume(
14507            conv_ctx(),
14508            wait.snapshot,
14509            json!({ "metadata": { "action": "submit" } }),
14510        ))
14511        .unwrap();
14512        let resumes = handler.resumes.lock().unwrap();
14513        assert_eq!(resumes.len(), 3);
14514        assert!(resumes[0].is_none() && resumes[1].is_none());
14515        assert!(resumes[2].is_some(), "the submit must resume the tool");
14516    }
14517
14518    /// What `greentic-start` really hands the engine for a typed message: the
14519    /// whole `ChannelMessageEnvelope` under `input`, with its transport
14520    /// identity (`id`, `tenant`, `channel`, `session_id`, ...) and, for a
14521    /// signed-in caller, the provider's `extensions.caller` block.
14522    #[cfg(any(feature = "agentic-worker", test))]
14523    fn wrapped_typed_message(text: &str) -> serde_json::Value {
14524        json!({
14525            "input": {
14526                "id": "msg-2",
14527                "tenant": { "env": "local", "tenant": "acme", "tenant_id": "acme" },
14528                "channel": "webchat",
14529                "session_id": "sess-1",
14530                "from": { "id": "user-1", "kind": "user" },
14531                "to": [],
14532                "correlation_id": "corr-1",
14533                "attachments": [],
14534                "metadata": {},
14535                "extensions": { "caller": { "sub": "user-1", "user_verified": true } },
14536                "text": text
14537            }
14538        })
14539    }
14540
14541    /// The defect behind "any text I type re-shows the same card". On the
14542    /// `greentic-start` path every inbound message is a whole envelope, so the
14543    /// envelope's own keys were counted as submitted fields and EVERY typed
14544    /// message looked like a card submit: the parked `flow:` tool was resumed
14545    /// with the text instead of being cancelled.
14546    #[test]
14547    fn a_typed_message_in_a_channel_envelope_is_not_a_card_submit() {
14548        assert!(!is_card_submit(&wrapped_typed_message("2+2 berapa?")));
14549        // Channel context the provider may stamp on a typed message's metadata.
14550        let mut with_context = wrapped_typed_message("hi");
14551        with_context["input"]["metadata"] =
14552            json!({ "locale": "en-US", "team": "support", "env": "prod", "autoStart": false });
14553        assert!(!is_card_submit(&with_context));
14554        // A real submit through the same envelope is still a submit: by its
14555        // route, and by input values carried without one.
14556        let mut by_action = wrapped_typed_message("");
14557        by_action["input"]["metadata"] = json!({ "action": "start_request" });
14558        assert!(is_card_submit(&by_action));
14559        let mut by_values = wrapped_typed_message("");
14560        by_values["input"]["metadata"] = json!({ "room": "101" });
14561        assert!(is_card_submit(&by_values));
14562        // The same envelope delivered FLAT (it is the entry itself, not under
14563        // `input`): the shape the generic JSON ingress hands the engine.
14564        let flat_typed = wrapped_typed_message("2+2 berapa?")["input"].clone();
14565        assert!(!is_card_submit(&flat_typed));
14566        let mut flat_submit = flat_typed.clone();
14567        flat_submit["metadata"] = json!({ "action": "start_request" });
14568        assert!(is_card_submit(&flat_submit));
14569        // Run Demo's flat entry keeps its inputs at the root: a field that
14570        // happens to share an envelope key's name is still an input there.
14571        assert!(is_card_submit(
14572            &json!({ "channel": "email", "metadata": {} })
14573        ));
14574    }
14575
14576    /// What the webchat provider stamps on EVERY message (typed or clicked):
14577    /// `messaging-provider-webchat` `ops/envelope.rs` (universal, tenant,
14578    /// tenant_channel_id, route, extensions, channel.*) and `ops/ingest.rs`
14579    /// (user_id, user_verified, flow_hint, locale). Verified against
14580    /// greentic-messaging-providers develop e4f7b389.
14581    #[cfg(any(feature = "agentic-worker", test))]
14582    fn provider_stamped_metadata() -> serde_json::Value {
14583        json!({
14584            "universal": "true",
14585            "env": "prod",
14586            "tenant": "acme",
14587            "route": "sess-1",
14588            "user_id": "user-1",
14589            "user_verified": "true",
14590            "flow_hint": "main",
14591            "locale": "en-US",
14592            "extensions": "{\"caller\":{\"sub\":\"user-1\"}}",
14593            "channel.channel_data": "{}"
14594        })
14595    }
14596
14597    #[test]
14598    fn a_typed_message_with_provider_stamped_metadata_is_not_a_card_submit() {
14599        let mut typed = wrapped_typed_message("how do I get a mail signature?");
14600        typed["input"]["metadata"] = provider_stamped_metadata();
14601        assert!(!is_card_submit(&typed));
14602        // Same envelope delivered flat.
14603        let flat = typed["input"].clone();
14604        assert!(!is_card_submit(&flat));
14605    }
14606
14607    #[test]
14608    fn a_click_is_still_a_card_submit_beside_provider_stamped_metadata() {
14609        let mut by_action = wrapped_typed_message("");
14610        let mut meta = provider_stamped_metadata();
14611        meta["action"] = json!("start_request");
14612        by_action["input"]["metadata"] = meta;
14613        assert!(is_card_submit(&by_action));
14614
14615        let mut by_values = wrapped_typed_message("");
14616        let mut meta = provider_stamped_metadata();
14617        meta["room"] = json!("101");
14618        by_values["input"]["metadata"] = meta;
14619        assert!(is_card_submit(&by_values));
14620    }
14621
14622    #[test]
14623    fn channel_context_prefix_matches_only_the_channel_namespace() {
14624        let mut typed = wrapped_typed_message("hi");
14625        typed["input"]["metadata"] = json!({ "mychannel.x": "1" });
14626        assert!(is_card_submit(&typed));
14627        typed["input"]["metadata"] = json!({ "channel.x": "1" });
14628        assert!(!is_card_submit(&typed));
14629    }
14630
14631    /// The webchat provider marks a card submit explicitly (`greentic_submit`),
14632    /// so a submit that carries no fields of its own is still a submit.
14633    #[test]
14634    fn the_provider_submit_marker_makes_an_empty_submit_a_submit() {
14635        let mut click = wrapped_typed_message("message");
14636        let mut meta = provider_stamped_metadata();
14637        meta["greentic_submit"] = json!("true");
14638        click["input"]["metadata"] = meta;
14639        assert!(is_card_submit(&click));
14640        let flat = click["input"].clone();
14641        assert!(is_card_submit(&flat));
14642        // Without the marker the same envelope is typed text.
14643        let mut typed = wrapped_typed_message("message");
14644        typed["input"]["metadata"] = provider_stamped_metadata();
14645        assert!(!is_card_submit(&typed));
14646        // Only the string "true" counts.
14647        let mut other = wrapped_typed_message("message");
14648        let mut meta = provider_stamped_metadata();
14649        meta["greentic_submit"] = json!("false");
14650        other["input"]["metadata"] = meta;
14651        assert!(!is_card_submit(&other));
14652    }
14653
14654    #[test]
14655    fn the_submit_marker_is_not_a_submitted_answer() {
14656        let entry = json!({ "metadata": { "room": "101", "greentic_submit": "true" } });
14657        let fields = submitted_fields(&entry);
14658        assert!(fields.contains_key("room"));
14659        assert!(!fields.contains_key("greentic_submit"));
14660    }
14661
14662    /// `route` and `tenant` are only context when they carry the value the
14663    /// provider derives from the envelope (`route` = conversation id =
14664    /// `session_id`; `tenant` = `tenant.tenant`). A card input that merely
14665    /// shares the name overwrites them with its own value, and that click
14666    /// must stay a submit or the parked tool is cancelled by a button press.
14667    #[test]
14668    fn a_card_input_named_like_a_stamped_key_with_its_own_value_is_a_submit() {
14669        for (key, value) in [("route", "billing"), ("tenant", "other-corp")] {
14670            let mut click = wrapped_typed_message("");
14671            click["input"]["metadata"] = json!({ key: value });
14672            assert!(is_card_submit(&click), "{key}={value} must count as input");
14673            let flat = click["input"].clone();
14674            assert!(
14675                is_card_submit(&flat),
14676                "flat {key}={value} must count as input"
14677            );
14678        }
14679        // The same keys carrying the envelope's own identity are context.
14680        let mut typed = wrapped_typed_message("hi");
14681        typed["input"]["metadata"] = json!({ "route": "sess-1", "tenant": "acme" });
14682        assert!(!is_card_submit(&typed));
14683    }
14684
14685    /// Stamped only on the auto-start envelope or never on the activities
14686    /// path: not context for a message that can reach a parked node, so a card
14687    /// input of that name is input.
14688    #[test]
14689    fn keys_the_activities_path_never_stamps_are_input() {
14690        for key in ["tenant_id", "conversation_id", "tenant_channel_id"] {
14691            let mut click = wrapped_typed_message("");
14692            click["input"]["metadata"] = json!({ key: "x" });
14693            assert!(is_card_submit(&click), "{key} must count as input");
14694        }
14695    }
14696
14697    /// The engine-level view of the same defect: a typed message in a channel
14698    /// envelope while a `flow:` tool is parked reaches the agent as a message
14699    /// (no resume payload), so the agent cancels the tool.
14700    #[cfg(feature = "agentic-worker")]
14701    #[test]
14702    fn a_typed_envelope_message_during_a_tool_park_is_not_a_resume_payload() {
14703        let handler = std::sync::Arc::new(ToolParkAgentHandler::new(vec![
14704            awaiting_tool_output(),
14705            json!({ "reply": "that is outside my scope", "trail": [], "terminated_by": "final_reply" }),
14706        ]));
14707        let engine = conv_engine_with(conversational_dw_flow(false), handler.clone());
14708        let rt = Runtime::new().unwrap();
14709        let first = rt
14710            .block_on(engine.execute(conv_ctx(), wrapped_typed_message("book a room")))
14711            .unwrap();
14712        let FlowStatus::Waiting(wait) = first.status else {
14713            panic!("expected a park");
14714        };
14715        rt.block_on(engine.resume(
14716            conv_ctx(),
14717            wait.snapshot,
14718            wrapped_typed_message("2+2 berapa?"),
14719        ))
14720        .unwrap();
14721        assert_eq!(*handler.resumes.lock().unwrap(), vec![None, None]);
14722    }
14723
14724    #[test]
14725    fn is_card_submit_tells_a_submit_from_a_typed_message() {
14726        assert!(is_card_submit(
14727            &json!({ "metadata": { "action": "submit" } })
14728        ));
14729        assert!(is_card_submit(
14730            &json!({ "input": { "metadata": { "action": "go" } } })
14731        ));
14732        assert!(is_card_submit(&json!({ "room": "101", "metadata": {} })));
14733        assert!(!is_card_submit(&json!({ "text": "never mind" })));
14734        assert!(!is_card_submit(
14735            &json!({ "text": "hi", "metadata": { "action": "  " } })
14736        ));
14737    }
14738
14739    #[test]
14740    fn pending_tool_await_mark_take_and_legacy_snapshot() {
14741        let mut st = ExecutionState::new(json!({}));
14742        assert!(!st.take_tool_await("agent"));
14743        st.mark_tool_await("agent");
14744        let back: ExecutionState =
14745            serde_json::from_str(&serde_json::to_string(&st).unwrap()).unwrap();
14746        let mut back = back;
14747        assert!(back.take_tool_await("agent"), "survives the snapshot");
14748        assert!(!back.take_tool_await("agent"), "take clears it");
14749        let legacy = r#"{"entry":{},"input":{},"nodes":{},"egress":[],"redirect_count":0}"#;
14750        let legacy: ExecutionState = serde_json::from_str(legacy).expect("legacy loads");
14751        assert!(legacy.pending_tool_await.is_empty());
14752    }
14753
14754    /// Safety-backstop behavioral test: a conversational `dw.agent` that
14755    /// never emits `conversation_ended` must keep parking up to
14756    /// `MAX_PARK_TURNS` turns, then force-advance to the successor instead
14757    /// of trapping the flow forever.
14758    #[cfg(feature = "agentic-worker")]
14759    #[test]
14760    fn conversational_dw_agent_force_advances_after_park_loop_cap() {
14761        let engine = conv_engine(
14762            conversational_dw_flow(true),
14763            json!({ "reply": "still thinking", "trail": [], "terminated_by": "final_reply" }),
14764        );
14765        let rt = Runtime::new().unwrap();
14766
14767        let result = rt
14768            .block_on(engine.execute(conv_ctx(), Value::Null))
14769            .unwrap();
14770        let mut snapshot = match result.status {
14771            FlowStatus::Waiting(w) => w.snapshot,
14772            other => panic!("expected Waiting after turn 1, got {other:?}"),
14773        };
14774
14775        // Turns 2..MAX_PARK_TURNS (exclusive) must keep parking.
14776        for turn in 2..MAX_PARK_TURNS {
14777            let result = rt
14778                .block_on(engine.resume(conv_ctx(), snapshot, json!({ "text": "still here" })))
14779                .unwrap();
14780            snapshot = match result.status {
14781                FlowStatus::Waiting(w) => w.snapshot,
14782                other => panic!("expected Waiting at turn {turn}, got {other:?}"),
14783            };
14784        }
14785
14786        // The MAX_PARK_TURNS-th turn must force-advance instead of parking again.
14787        let result = rt
14788            .block_on(engine.resume(conv_ctx(), snapshot, json!({ "text": "still here" })))
14789            .unwrap();
14790        assert!(
14791            matches!(result.status, FlowStatus::Completed),
14792            "park-loop cap must force-advance to the successor at turn {MAX_PARK_TURNS}, got {:?}",
14793            result.status
14794        );
14795    }
14796
14797    // ── NATS conversational `dw.agent` park-loop (Task 6) ──────────────────
14798    //
14799    // These tests drive the SAME `conversational_dw_flow`/`conv_ctx` harness as
14800    // the in-process tests above, but with `DwAgentDispatch::Nats` and a stub
14801    // `RemoteDispatchHandler` that never touches a live NATS server — it just
14802    // records the dispatch and immediately returns `AwaitingResponse`, exactly
14803    // like `dw_agent_nats_mode_dispatches_remote` above. The "NATS response
14804    // arriving" half of the round trip is simulated by calling `engine.resume`
14805    // directly with a hand-built envelope `{ok, output, events, error}` — the
14806    // exact shape `dispatch_listener::decode_response` builds and that lands in
14807    // `state.entry` on a real resume (spike finding §Q2). No live NATS server is
14808    // needed or used.
14809
14810    /// Records every dispatch and immediately returns `AwaitingResponse`, so the
14811    /// engine parks without a live NATS server. Mirrors `RecordingDispatcher` in
14812    /// `dw_agent_nats_mode_dispatches_remote`, kept separate (and named for
14813    /// re-use across the tests below) since three tests share it.
14814    #[cfg(feature = "agentic-worker")]
14815    struct ScriptedNatsDispatcher {
14816        calls: Mutex<Vec<crate::runner::remote_dispatch::RemoteDispatch>>,
14817    }
14818
14819    #[cfg(feature = "agentic-worker")]
14820    #[async_trait::async_trait]
14821    impl crate::runner::remote_dispatch::RemoteDispatchHandler for ScriptedNatsDispatcher {
14822        async fn dispatch(
14823            &self,
14824            request: crate::runner::remote_dispatch::RemoteDispatch,
14825        ) -> anyhow::Result<crate::runner::remote_dispatch::RemoteDispatchAction> {
14826            let correlation_id = request.correlation_id.clone();
14827            self.calls.lock().unwrap().push(request);
14828            Ok(
14829                crate::runner::remote_dispatch::RemoteDispatchAction::AwaitingResponse {
14830                    correlation_id,
14831                },
14832            )
14833        }
14834    }
14835
14836    /// Build an engine holding `flow` in `DwAgentDispatch::Nats` mode, wired to
14837    /// `dispatcher`. Mirrors `conv_engine` (the in-process counterpart) so the
14838    /// two harnesses are structurally comparable.
14839    #[cfg(feature = "agentic-worker")]
14840    fn nats_conv_engine(
14841        flow: HostFlow,
14842        dispatcher: std::sync::Arc<dyn crate::runner::remote_dispatch::RemoteDispatchHandler>,
14843    ) -> FlowEngine {
14844        FlowEngine {
14845            messaging_provider_pack_ids: Default::default(),
14846            rollout_ids: RolloutIds::default(),
14847            packs: Vec::new(),
14848            flows: Vec::new(),
14849            flow_sources: StdHashMap::new(),
14850            flow_cache: RwLock::new(StdHashMap::from([(
14851                FlowKey {
14852                    pack_id: "test-pack".to_string(),
14853                    flow_id: "conv.flow".to_string(),
14854                },
14855                flow,
14856            )])),
14857            default_env: "local".to_string(),
14858            validation: ValidationConfig {
14859                mode: ValidationMode::Off,
14860            },
14861            cross_pack_resolver: None,
14862            approval_dispatch_handler: None,
14863            remote_dispatch_handler: Some(dispatcher),
14864            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::Nats,
14865            agent_node_handler: None,
14866            graph_node_handler: None,
14867            mcp_tool_source: None,
14868            mcp_secrets: None,
14869            #[cfg(feature = "agentic-worker")]
14870            a2a_sources: RwLock::new(HashMap::new()),
14871            #[cfg(feature = "agentic-worker")]
14872            ext_artifact_port: None,
14873            operala_node_handler: None,
14874        }
14875    }
14876
14877    /// Build the envelope a real NATS response resume lands in `state.entry`,
14878    /// per spike finding §Q2: `{ok, output: {reply, trail, terminated_by},
14879    /// events, error}` (mirrors `dispatch_listener::decode_response`).
14880    #[cfg(feature = "agentic-worker")]
14881    fn agent_response_envelope(reply: &str, terminated_by: &str) -> Value {
14882        json!({
14883            "ok": true,
14884            "output": { "reply": reply, "trail": [], "terminated_by": terminated_by },
14885            "events": [],
14886            "error": Value::Null,
14887        })
14888    }
14889
14890    /// Turn 1 (fresh, no prior await marker): the conversational Nats arm must
14891    /// mark the pending await, dispatch to NATS exactly once, and park via
14892    /// `NodeControl::AwaitHere` — resuming at the node itself (not the routing
14893    /// successor) with no reply surfaced yet (the response hasn't arrived).
14894    #[cfg(feature = "agentic-worker")]
14895    #[test]
14896    fn conversational_dw_agent_nats_turn1_parks_via_await_here() {
14897        let dispatcher = Arc::new(ScriptedNatsDispatcher {
14898            calls: Mutex::new(vec![]),
14899        });
14900        let engine = nats_conv_engine(conversational_dw_flow(true), dispatcher.clone());
14901        let rt = Runtime::new().unwrap();
14902
14903        let result = rt
14904            .block_on(engine.execute(conv_ctx(), Value::Null))
14905            .unwrap();
14906        let snapshot = match result.status {
14907            FlowStatus::Waiting(w) => w.snapshot,
14908            other => panic!("expected Waiting after fresh dispatch, got {other:?}"),
14909        };
14910        assert_eq!(
14911            snapshot.next_node, "agent",
14912            "AwaitHere must resume at self, not the routing successor"
14913        );
14914        assert_eq!(
14915            dispatcher.calls.lock().unwrap().len(),
14916            1,
14917            "a fresh user turn must dispatch to NATS exactly once"
14918        );
14919        assert_eq!(
14920            result.output,
14921            Value::Null,
14922            "no reply is known yet on the initial dispatch — the async response hasn't arrived"
14923        );
14924    }
14925
14926    /// Full turn cycle, behavioral: fresh dispatch → AwaitHere park; simulated
14927    /// "not ended" NATS response resume → LoopHere park (reply surfaced,
14928    /// session-keyed park awaiting the next user message); a user-reply resume
14929    /// dispatches to NATS again; a `conversation_ended` response resume →
14930    /// Completed (advanced to the successor). This is the exact turn-by-turn
14931    /// script called for in Task 6's brief.
14932    #[cfg(feature = "agentic-worker")]
14933    #[test]
14934    fn conversational_dw_agent_nats_park_loop_full_turn_cycle() {
14935        let dispatcher = Arc::new(ScriptedNatsDispatcher {
14936            calls: Mutex::new(vec![]),
14937        });
14938        let engine = nats_conv_engine(conversational_dw_flow(true), dispatcher.clone());
14939        let rt = Runtime::new().unwrap();
14940
14941        // Turn 1: fresh user turn → dispatch to NATS → AwaitHere (self, park).
14942        let result = rt
14943            .block_on(engine.execute(conv_ctx(), Value::Null))
14944            .unwrap();
14945        let snapshot = match result.status {
14946            FlowStatus::Waiting(w) => w.snapshot,
14947            other => panic!("expected Waiting (AwaitHere) after turn 1 dispatch, got {other:?}"),
14948        };
14949        assert_eq!(snapshot.next_node, "agent");
14950        assert_eq!(dispatcher.calls.lock().unwrap().len(), 1);
14951
14952        // Simulated NATS response resume, "not ended": LoopHere (session-keyed
14953        // park awaiting the next user message), reply surfaced.
14954        let result = rt
14955            .block_on(engine.resume(
14956                conv_ctx(),
14957                snapshot,
14958                agent_response_envelope("hello there", "final_reply"),
14959            ))
14960            .unwrap();
14961        let snapshot = match result.status {
14962            FlowStatus::Waiting(w) => w.snapshot,
14963            other => panic!("expected Waiting (LoopHere) after not-ended response, got {other:?}"),
14964        };
14965        assert_eq!(
14966            snapshot.next_node, "agent",
14967            "LoopHere also re-enters the node itself"
14968        );
14969        assert!(
14970            serde_json::to_string(&result.output)
14971                .unwrap()
14972                .contains("hello there"),
14973            "the agent's reply must be surfaced once the response resume lands: {:?}",
14974            result.output
14975        );
14976        assert_eq!(
14977            dispatcher.calls.lock().unwrap().len(),
14978            1,
14979            "the response landing must not itself trigger another NATS dispatch"
14980        );
14981
14982        // User-reply resume: a fresh user turn dispatches to NATS again.
14983        let result = rt
14984            .block_on(engine.resume(conv_ctx(), snapshot, json!({ "text": "user says more" })))
14985            .unwrap();
14986        let snapshot = match result.status {
14987            FlowStatus::Waiting(w) => w.snapshot,
14988            other => panic!("expected Waiting (AwaitHere) after turn 2 dispatch, got {other:?}"),
14989        };
14990        assert_eq!(snapshot.next_node, "agent");
14991        assert_eq!(
14992            dispatcher.calls.lock().unwrap().len(),
14993            2,
14994            "a second fresh user turn must dispatch to NATS again"
14995        );
14996
14997        // Simulated NATS response resume, `conversation_ended`: advance to the
14998        // successor and complete.
14999        let result = rt
15000            .block_on(engine.resume(
15001                conv_ctx(),
15002                snapshot,
15003                agent_response_envelope("bye", "conversation_ended"),
15004            ))
15005            .unwrap();
15006        assert!(
15007            matches!(result.status, FlowStatus::Completed),
15008            "conversation_ended response must advance to the successor and complete, got {:?}",
15009            result.status
15010        );
15011        assert_eq!(
15012            dispatcher.calls.lock().unwrap().len(),
15013            2,
15014            "conversation end must not trigger another NATS dispatch"
15015        );
15016    }
15017
15018    /// Safety-backstop parity with the in-process cap test: a NATS
15019    /// conversational `dw.agent` whose response never carries
15020    /// `conversation_ended` must keep parking (dispatch → AwaitHere →
15021    /// response-resume → LoopHere) up to `MAX_PARK_TURNS` "not ended" responses,
15022    /// then force-advance to the successor instead of trapping the flow.
15023    #[cfg(feature = "agentic-worker")]
15024    #[test]
15025    fn conversational_dw_agent_nats_force_advances_after_park_loop_cap() {
15026        let dispatcher = Arc::new(ScriptedNatsDispatcher {
15027            calls: Mutex::new(vec![]),
15028        });
15029        let engine = nats_conv_engine(conversational_dw_flow(true), dispatcher.clone());
15030        let rt = Runtime::new().unwrap();
15031
15032        // Turn 1: fresh dispatch (does not itself count toward the park cap —
15033        // the cap is bumped only on a "not ended" response, matching the
15034        // in-process semantics).
15035        let result = rt
15036            .block_on(engine.execute(conv_ctx(), Value::Null))
15037            .unwrap();
15038        let mut snapshot = match result.status {
15039            FlowStatus::Waiting(w) => w.snapshot,
15040            other => panic!("expected Waiting after turn 1 dispatch, got {other:?}"),
15041        };
15042
15043        // Responses 1..MAX_PARK_TURNS (exclusive) must keep looping: a "not
15044        // ended" response resume (LoopHere), then a user-message resume that
15045        // re-dispatches to NATS (AwaitHere) for the next response.
15046        for turn in 1..MAX_PARK_TURNS {
15047            let result = rt
15048                .block_on(engine.resume(
15049                    conv_ctx(),
15050                    snapshot,
15051                    agent_response_envelope("still thinking", "final_reply"),
15052                ))
15053                .unwrap();
15054            snapshot = match result.status {
15055                FlowStatus::Waiting(w) => w.snapshot,
15056                other => panic!("expected Waiting (LoopHere) at response #{turn}, got {other:?}"),
15057            };
15058            let result = rt
15059                .block_on(engine.resume(conv_ctx(), snapshot, json!({ "text": "still here" })))
15060                .unwrap();
15061            snapshot = match result.status {
15062                FlowStatus::Waiting(w) => w.snapshot,
15063                other => {
15064                    panic!("expected Waiting (AwaitHere) after user turn #{turn}, got {other:?}")
15065                }
15066            };
15067        }
15068
15069        // The MAX_PARK_TURNS-th "not ended" response must force-advance instead
15070        // of parking again.
15071        let result = rt
15072            .block_on(engine.resume(
15073                conv_ctx(),
15074                snapshot,
15075                agent_response_envelope("still thinking", "final_reply"),
15076            ))
15077            .unwrap();
15078        assert!(
15079            matches!(result.status, FlowStatus::Completed),
15080            "park-loop cap must force-advance to the successor at response {MAX_PARK_TURNS}, got {:?}",
15081            result.status
15082        );
15083        assert_eq!(
15084            dispatcher.calls.lock().unwrap().len(),
15085            1 + (MAX_PARK_TURNS as usize - 1),
15086            "exactly one NATS dispatch per user turn across the whole park-loop"
15087        );
15088    }
15089
15090    /// Parity: for the same scripted two-turn conversation (turn 1 replies
15091    /// "hello there", not ended; turn 2 replies "bye", `conversation_ended`),
15092    /// the NATS and in-process dispatch paths must be *observationally*
15093    /// identical — same sequence of user-visible statuses, and the same
15094    /// surfaced reply text on the parked turn.
15095    ///
15096    /// Caveat (documented, not hidden): the NATS path has one extra *internal*
15097    /// resume between user turns — the async response landing (AwaitHere →
15098    /// LoopHere) — that the in-process path does synchronously inside a single
15099    /// `execute`/`resume` call. That extra step is invisible to the flow's
15100    /// outward status/reply, which is exactly what this test asserts; it does
15101    /// NOT assert the two paths take the same number of `resume` calls.
15102    #[cfg(feature = "agentic-worker")]
15103    #[test]
15104    fn conversational_dw_agent_nats_and_inprocess_transcripts_match_for_same_script() {
15105        let rt = Runtime::new().unwrap();
15106
15107        // ── In-process transcript ──
15108        let inproc_handler = Arc::new(ScriptedAgentHandler {
15109            script: Mutex::new(std::collections::VecDeque::from(vec![
15110                json!({ "reply": "hello there", "trail": [], "terminated_by": "final_reply" }),
15111                json!({ "reply": "bye", "trail": [], "terminated_by": "conversation_ended" }),
15112            ])),
15113        });
15114        let inproc_engine = conv_engine_scripted(conversational_dw_flow(true), inproc_handler);
15115        let r1 = rt
15116            .block_on(inproc_engine.execute(conv_ctx(), Value::Null))
15117            .unwrap();
15118        let inproc_snapshot = match r1.status {
15119            FlowStatus::Waiting(ref w) => w.snapshot.clone(),
15120            ref other => panic!("in-process turn 1: expected Waiting, got {other:?}"),
15121        };
15122        let r2 = rt
15123            .block_on(inproc_engine.resume(conv_ctx(), inproc_snapshot, json!({ "text": "more" })))
15124            .unwrap();
15125
15126        // ── NATS transcript, same script ──
15127        let dispatcher = Arc::new(ScriptedNatsDispatcher {
15128            calls: Mutex::new(vec![]),
15129        });
15130        let nats_engine = nats_conv_engine(conversational_dw_flow(true), dispatcher);
15131        let n1 = rt
15132            .block_on(nats_engine.execute(conv_ctx(), Value::Null))
15133            .unwrap();
15134        let n1_snapshot = match n1.status {
15135            FlowStatus::Waiting(w) => w.snapshot,
15136            other => panic!("nats turn 1 dispatch: expected Waiting, got {other:?}"),
15137        };
15138        let n1r = rt
15139            .block_on(nats_engine.resume(
15140                conv_ctx(),
15141                n1_snapshot,
15142                agent_response_envelope("hello there", "final_reply"),
15143            ))
15144            .unwrap();
15145        let n1r_snapshot = match n1r.status {
15146            FlowStatus::Waiting(ref w) => w.snapshot.clone(),
15147            ref other => panic!("nats turn 1 response resume: expected Waiting, got {other:?}"),
15148        };
15149        let n2 = rt
15150            .block_on(nats_engine.resume(conv_ctx(), n1r_snapshot, json!({ "text": "more" })))
15151            .unwrap();
15152        let n2_snapshot = match n2.status {
15153            FlowStatus::Waiting(w) => w.snapshot,
15154            other => panic!("nats turn 2 dispatch: expected Waiting, got {other:?}"),
15155        };
15156        let n2r = rt
15157            .block_on(nats_engine.resume(
15158                conv_ctx(),
15159                n2_snapshot,
15160                agent_response_envelope("bye", "conversation_ended"),
15161            ))
15162            .unwrap();
15163
15164        // Same user-visible status per turn.
15165        assert!(matches!(r1.status, FlowStatus::Waiting(_)));
15166        assert!(
15167            matches!(n1r.status, FlowStatus::Waiting(_)),
15168            "nats turn 1's user-visible status must also be Waiting"
15169        );
15170        assert!(matches!(r2.status, FlowStatus::Completed));
15171        assert!(
15172            matches!(n2r.status, FlowStatus::Completed),
15173            "nats turn 2 must also complete, matching the in-process transcript"
15174        );
15175
15176        // Same surfaced reply text on the parked turn.
15177        assert!(
15178            serde_json::to_string(&r1.output)
15179                .unwrap()
15180                .contains("hello there"),
15181            "in-process turn 1 must surface the reply: {:?}",
15182            r1.output
15183        );
15184        assert!(
15185            serde_json::to_string(&n1r.output)
15186                .unwrap()
15187                .contains("hello there"),
15188            "nats turn 1 must surface the identical reply once the response resume lands: {:?}",
15189            n1r.output
15190        );
15191    }
15192
15193    /// Build the error envelope shape a NATS response resume can also land in
15194    /// `state.entry`: `{ok:false, output:null, events:[], error:{code,
15195    /// message}}` (mirrors `agent_response_envelope`, but for the failure
15196    /// path — a genuine agent/transport error. This code sets no deadline of
15197    /// its own, but the same `{ok:false}` shape is also what a flow-authored
15198    /// timeout, or any other error source, would arrive as — Fix B handles it
15199    /// identically either way.
15200    #[cfg(feature = "agentic-worker")]
15201    fn agent_error_envelope(message: &str, code: Option<&str>) -> Value {
15202        json!({
15203            "ok": false,
15204            "output": Value::Null,
15205            "events": [],
15206            "error": { "code": code, "message": message },
15207        })
15208    }
15209
15210    #[cfg(feature = "agentic-worker")]
15211    #[test]
15212    fn error_envelope_prefers_the_partial_reply_over_the_machine_string() {
15213        let entry = json!({
15214            "ok": false,
15215            "output": { "reply": "Here is what I found so far", "trail": [1] },
15216            "error": { "code": "timeout", "message": "agent step ended without a reply: timeout" },
15217        });
15218        let (message, payload) = agent_error_envelope_reply(&entry);
15219        assert_eq!(message, "Here is what I found so far");
15220        assert_eq!(payload["reply"], "Here is what I found so far");
15221        assert_eq!(payload["error"]["code"], "timeout", "error info is kept");
15222        assert_eq!(payload["trail"], json!([1]));
15223    }
15224
15225    #[cfg(feature = "agentic-worker")]
15226    #[test]
15227    fn error_envelope_without_a_usable_reply_shows_a_user_safe_line() {
15228        for output in [
15229            Value::Null,
15230            json!({ "reply": "" }),
15231            json!({ "reply": "  " }),
15232        ] {
15233            let entry = json!({
15234                "ok": false, "output": output,
15235                "error": { "code": "timeout", "message": "agent step ended without a reply: timeout" },
15236                "metadata": { "locale": "id" },
15237            });
15238            let (message, payload) = agent_error_envelope_reply(&entry);
15239            assert!(
15240                !message.contains("agent step ended") && !message.trim().is_empty(),
15241                "machine string must not reach the user: {message}"
15242            );
15243            assert!(message.starts_with("Maaf"), "localized via i18n: {message}");
15244            assert_eq!(payload["reply"], message.as_str());
15245            assert_eq!(
15246                payload["error"]["code"], "timeout",
15247                "operators keep the code"
15248            );
15249            assert_eq!(
15250                payload["error"]["message"],
15251                "agent step ended without a reply: timeout"
15252            );
15253        }
15254        let (message, payload) = agent_error_envelope_reply(&json!({ "ok": false }));
15255        assert!(!message.trim().is_empty());
15256        assert_eq!(payload["reply"], message.as_str());
15257    }
15258
15259    /// The operator log carries the machine error, never the localized reply.
15260    #[cfg(feature = "agentic-worker")]
15261    #[test]
15262    fn agent_error_log_fields_are_the_machine_error() {
15263        let entry =
15264            json!({"ok": false, "error": {"code": "timeout", "message": "no reply in 30s"}});
15265        assert_eq!(
15266            agent_error_log_fields(&entry),
15267            ("timeout".to_string(), "no reply in 30s".to_string())
15268        );
15269        assert_eq!(
15270            agent_error_log_fields(&json!({"ok": false, "error": "boom"})),
15271            ("unknown".to_string(), "boom".to_string())
15272        );
15273        assert_eq!(
15274            agent_error_log_fields(&json!({"ok": false})),
15275            ("unknown".to_string(), String::new())
15276        );
15277    }
15278
15279    /// Fix A (interleave guard): a user message arriving before the agent's
15280    /// NATS response must NOT be misread as that response. With the
15281    /// pending-await marker set (turn 1's fresh dispatch), a resume whose
15282    /// `state.entry` is a plain user-message shape (no `"ok"` key) must fall
15283    /// through to the fresh-dispatch branch — re-dispatching to NATS as a new
15284    /// turn and parking via `AwaitHere` again — instead of being consumed as
15285    /// a (null) agent reply. The marker must also survive: it was NOT
15286    /// consumed by the misrouted resume, only by the eventual real response.
15287    #[cfg(feature = "agentic-worker")]
15288    #[test]
15289    fn conversational_dw_agent_nats_interleaved_user_message_is_not_misread_as_response() {
15290        let dispatcher = Arc::new(ScriptedNatsDispatcher {
15291            calls: Mutex::new(vec![]),
15292        });
15293        let engine = nats_conv_engine(conversational_dw_flow(true), dispatcher.clone());
15294        let rt = Runtime::new().unwrap();
15295
15296        // Turn 1: fresh dispatch marks the pending-await and parks (AwaitHere).
15297        let result = rt
15298            .block_on(engine.execute(conv_ctx(), Value::Null))
15299            .unwrap();
15300        let snapshot = match result.status {
15301            FlowStatus::Waiting(w) => w.snapshot,
15302            other => panic!("expected Waiting after turn 1 dispatch, got {other:?}"),
15303        };
15304        assert!(
15305            snapshot.state.pending_agent_await.contains_key("agent"),
15306            "turn 1 dispatch must mark the pending await"
15307        );
15308        assert_eq!(dispatcher.calls.lock().unwrap().len(), 1);
15309
15310        // A stray user message arrives BEFORE the agent's NATS response —
15311        // same shape a real inbound activity would resume with, no `"ok"` key.
15312        let result = rt
15313            .block_on(engine.resume(
15314                conv_ctx(),
15315                snapshot,
15316                json!({ "text": "are you still there?" }),
15317            ))
15318            .unwrap();
15319        let snapshot = match result.status {
15320            FlowStatus::Waiting(w) => w.snapshot,
15321            other => panic!(
15322                "a stray user message must re-dispatch as a fresh turn (Waiting/AwaitHere), got {other:?}"
15323            ),
15324        };
15325        assert_eq!(
15326            snapshot.next_node, "agent",
15327            "the fresh re-dispatch still awaits at self"
15328        );
15329        assert_eq!(
15330            dispatcher.calls.lock().unwrap().len(),
15331            2,
15332            "the stray user message must trigger its OWN fresh NATS dispatch, not be swallowed"
15333        );
15334        assert!(
15335            snapshot.state.pending_agent_await.contains_key("agent"),
15336            "the marker must still be set for the real response to land against"
15337        );
15338        assert_eq!(
15339            result.output,
15340            Value::Null,
15341            "no reply is surfaced — this was not a misread null agent turn"
15342        );
15343        assert!(
15344            !snapshot.state.park_turns.contains_key("agent"),
15345            "a stray user message must not touch the park-loop cap"
15346        );
15347    }
15348
15349    /// Fix B (error envelope handling): a `{ok:false, ...}` response — any
15350    /// agent/transport error, or a timeout-shaped envelope from any source
15351    /// (this code no longer sets its own deadline) — must surface the error
15352    /// message as the reply, re-park via `LoopHere` (fail-safe: await the
15353    /// next user message, do not force-advance), and must NOT bump the
15354    /// park-loop turn counter. Exercises two full error cycles (error →
15355    /// user turn → error) to confirm the cap counter never advances even
15356    /// after repeated failures.
15357    #[cfg(feature = "agentic-worker")]
15358    #[test]
15359    fn conversational_dw_agent_nats_error_envelope_surfaces_and_reparks_without_cap_bump() {
15360        let dispatcher = Arc::new(ScriptedNatsDispatcher {
15361            calls: Mutex::new(vec![]),
15362        });
15363        let engine = nats_conv_engine(conversational_dw_flow(true), dispatcher.clone());
15364        let rt = Runtime::new().unwrap();
15365
15366        // Turn 1: fresh dispatch → AwaitHere.
15367        let result = rt
15368            .block_on(engine.execute(conv_ctx(), Value::Null))
15369            .unwrap();
15370        let snapshot = match result.status {
15371            FlowStatus::Waiting(w) => w.snapshot,
15372            other => panic!("expected Waiting after turn 1 dispatch, got {other:?}"),
15373        };
15374
15375        // A plain agent/transport error resumes the flow.
15376        let result = rt
15377            .block_on(engine.resume(conv_ctx(), snapshot, agent_error_envelope("boom", None)))
15378            .unwrap();
15379        let snapshot = match result.status {
15380            FlowStatus::Waiting(w) => w.snapshot,
15381            other => panic!("an error envelope must re-park (Waiting/LoopHere), got {other:?}"),
15382        };
15383        assert_eq!(
15384            snapshot.next_node, "agent",
15385            "LoopHere re-enters the node itself"
15386        );
15387        assert!(
15388            serde_json::to_string(&result.output)
15389                .unwrap()
15390                .contains("boom"),
15391            "the error message must be surfaced as the reply: {:?}",
15392            result.output
15393        );
15394        assert!(
15395            !snapshot.state.park_turns.contains_key("agent"),
15396            "an error response must NOT bump the park-loop cap counter"
15397        );
15398
15399        // A user turn in between re-dispatches (as usual).
15400        let result = rt
15401            .block_on(engine.resume(conv_ctx(), snapshot, json!({ "text": "hello?" })))
15402            .unwrap();
15403        let snapshot = match result.status {
15404            FlowStatus::Waiting(w) => w.snapshot,
15405            other => panic!("expected Waiting (AwaitHere) after user turn, got {other:?}"),
15406        };
15407        assert_eq!(dispatcher.calls.lock().unwrap().len(), 2);
15408
15409        // A timeout-coded envelope (this code sets no deadline of its own —
15410        // this shape would only arrive from a flow-authored deadline or some
15411        // other upstream source) behaves identically to a plain error.
15412        let result = rt
15413            .block_on(engine.resume(
15414                conv_ctx(),
15415                snapshot,
15416                agent_error_envelope("timeout waiting for agent response", Some("timeout")),
15417            ))
15418            .unwrap();
15419        let snapshot = match result.status {
15420            FlowStatus::Waiting(w) => w.snapshot,
15421            other => {
15422                panic!("a timeout envelope must also re-park (Waiting/LoopHere), got {other:?}")
15423            }
15424        };
15425        assert!(
15426            serde_json::to_string(&result.output)
15427                .unwrap()
15428                .contains("timeout waiting for agent response"),
15429            "the timeout message must be surfaced as the reply: {:?}",
15430            result.output
15431        );
15432        assert!(
15433            !snapshot.state.park_turns.contains_key("agent"),
15434            "two error/timeout responses in a row (with an intervening user turn) must still \
15435             not have bumped the park-loop cap counter"
15436        );
15437    }
15438
15439    /// Scriptable `AgentNodeHandler` stub: returns the next queued payload on
15440    /// each call, so a single in-process engine can simulate a multi-turn
15441    /// conversation with a different agent output per turn (unlike
15442    /// `StubAgentHandler`, which always returns the same fixed payload).
15443    #[cfg(feature = "agentic-worker")]
15444    struct ScriptedAgentHandler {
15445        script: Mutex<std::collections::VecDeque<serde_json::Value>>,
15446    }
15447    #[cfg(feature = "agentic-worker")]
15448    #[async_trait::async_trait]
15449    impl crate::runner::agent_node::AgentNodeHandler for ScriptedAgentHandler {
15450        async fn execute(
15451            &self,
15452            _tenant_id: &str,
15453            _env_id: &str,
15454            _agent_id: &str,
15455            _session_id: &str,
15456            _flow_input: &serde_json::Value,
15457            _conversational: bool,
15458            _caller: Option<&serde_json::Value>,
15459        ) -> anyhow::Result<serde_json::Value> {
15460            Ok(self
15461                .script
15462                .lock()
15463                .unwrap()
15464                .pop_front()
15465                .expect("ScriptedAgentHandler: script exhausted"))
15466        }
15467    }
15468
15469    /// Build an in-process engine holding `flow`, wired to a `ScriptedAgentHandler`
15470    /// so each agent turn can return a different payload. Mirrors `conv_engine`
15471    /// (which uses a fixed payload for every call).
15472    #[cfg(feature = "agentic-worker")]
15473    fn conv_engine_scripted(
15474        flow: HostFlow,
15475        handler: std::sync::Arc<ScriptedAgentHandler>,
15476    ) -> FlowEngine {
15477        FlowEngine {
15478            messaging_provider_pack_ids: Default::default(),
15479            rollout_ids: RolloutIds::default(),
15480            packs: Vec::new(),
15481            flows: Vec::new(),
15482            flow_sources: StdHashMap::new(),
15483            flow_cache: RwLock::new(StdHashMap::from([(
15484                FlowKey {
15485                    pack_id: "test-pack".to_string(),
15486                    flow_id: "conv.flow".to_string(),
15487                },
15488                flow,
15489            )])),
15490            default_env: "local".to_string(),
15491            validation: ValidationConfig {
15492                mode: ValidationMode::Off,
15493            },
15494            cross_pack_resolver: None,
15495            approval_dispatch_handler: None,
15496            remote_dispatch_handler: None,
15497            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
15498            agent_node_handler: Some(handler),
15499            graph_node_handler: None,
15500            mcp_tool_source: None,
15501            mcp_secrets: None,
15502            #[cfg(feature = "agentic-worker")]
15503            a2a_sources: RwLock::new(HashMap::new()),
15504            #[cfg(feature = "agentic-worker")]
15505            ext_artifact_port: None,
15506            operala_node_handler: None,
15507        }
15508    }
15509
15510    // -----------------------------------------------------------------------
15511    // operala.call in-process handler wiring
15512    // -----------------------------------------------------------------------
15513
15514    struct StubOperalaHandler {
15515        payload: serde_json::Value,
15516    }
15517    #[async_trait::async_trait]
15518    impl crate::runner::operala_node::OperalaNodeHandler for StubOperalaHandler {
15519        async fn execute(
15520            &self,
15521            _tenant: &str,
15522            _env: &str,
15523            _target: &str,
15524            _operation: &str,
15525            _session_id: &str,
15526            _input: &serde_json::Value,
15527        ) -> anyhow::Result<serde_json::Value> {
15528            Ok(self.payload.clone())
15529        }
15530    }
15531
15532    /// One recorded `OperalaNodeHandler::execute` call.
15533    #[derive(Clone, Debug)]
15534    struct OperalaCallRecord {
15535        tenant: String,
15536        env: String,
15537        target: String,
15538        operation: String,
15539        session_id: String,
15540        input: serde_json::Value,
15541    }
15542
15543    #[derive(Default)]
15544    struct RecordingOperalaHandler {
15545        calls: std::sync::Mutex<Vec<OperalaCallRecord>>,
15546    }
15547
15548    #[async_trait::async_trait]
15549    impl crate::runner::operala_node::OperalaNodeHandler for RecordingOperalaHandler {
15550        async fn execute(
15551            &self,
15552            tenant: &str,
15553            env: &str,
15554            target: &str,
15555            operation: &str,
15556            session_id: &str,
15557            input: &serde_json::Value,
15558        ) -> anyhow::Result<serde_json::Value> {
15559            self.calls
15560                .lock()
15561                .map_err(|_| anyhow::anyhow!("recording handler lock poisoned"))?
15562                .push(OperalaCallRecord {
15563                    tenant: tenant.to_string(),
15564                    env: env.to_string(),
15565                    target: target.to_string(),
15566                    operation: operation.to_string(),
15567                    session_id: session_id.to_string(),
15568                    input: input.clone(),
15569                });
15570            Ok(json!({ "ok": true, "reply": "recorded" }))
15571        }
15572    }
15573
15574    /// Build a single-node flow: an `operala.call` node (given `target`) that
15575    /// ends the flow directly. Mirrors `conversational_dw_flow`'s shape for
15576    /// the (non-conversational) operala path.
15577    fn operala_flow(target: &str) -> HostFlow {
15578        operala_flow_with_payload(
15579            target,
15580            json!({ "operation": "", "input": { "goal": "hi" } }),
15581        )
15582    }
15583
15584    /// Like [`operala_flow`] but with a caller-chosen node payload.
15585    fn operala_flow_with_payload(target: &str, payload_expr: Value) -> HostFlow {
15586        let mut nodes = IndexMap::new();
15587        let node_id = NodeId::from_str("op").unwrap();
15588        nodes.insert(
15589            node_id.clone(),
15590            HostNode {
15591                kind: NodeKind::OperalaCall {
15592                    target: target.to_string(),
15593                },
15594                component: "operala.call".to_string(),
15595                component_id: "operala.call".to_string(),
15596                operation_name: Some(target.to_string()),
15597                operation_in_mapping: None,
15598                payload_expr,
15599                routing: Routing::End,
15600                vars_out: None,
15601                response_timeout_secs: None,
15602            },
15603        );
15604        HostFlow {
15605            slot_schema: None,
15606            id: "operala.flow".to_string(),
15607            start: Some(node_id),
15608            nodes,
15609            vars_init: JsonMap::new(),
15610            required_vars: Vec::new(),
15611        }
15612    }
15613
15614    /// Build an engine holding `flow` with the given optional in-process
15615    /// operala handler and no NATS `RemoteDispatchHandler` — a `None` handler
15616    /// exercises the existing NATS-fallback error path.
15617    fn operala_engine(
15618        flow: HostFlow,
15619        handler: Option<std::sync::Arc<dyn crate::runner::operala_node::OperalaNodeHandler>>,
15620    ) -> FlowEngine {
15621        FlowEngine {
15622            messaging_provider_pack_ids: Default::default(),
15623            rollout_ids: RolloutIds::default(),
15624            packs: Vec::new(),
15625            flows: Vec::new(),
15626            flow_sources: StdHashMap::new(),
15627            flow_cache: RwLock::new(StdHashMap::from([(
15628                FlowKey {
15629                    pack_id: "test-pack".to_string(),
15630                    flow_id: "operala.flow".to_string(),
15631                },
15632                flow,
15633            )])),
15634            default_env: "local".to_string(),
15635            validation: ValidationConfig {
15636                mode: ValidationMode::Off,
15637            },
15638            cross_pack_resolver: None,
15639            approval_dispatch_handler: None,
15640            remote_dispatch_handler: None,
15641            #[cfg(feature = "agentic-worker")]
15642            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
15643            #[cfg(feature = "agentic-worker")]
15644            agent_node_handler: None,
15645            #[cfg(feature = "agentic-worker")]
15646            graph_node_handler: None,
15647            #[cfg(feature = "agentic-worker")]
15648            mcp_tool_source: None,
15649            #[cfg(feature = "agentic-worker")]
15650            mcp_secrets: None,
15651            #[cfg(feature = "agentic-worker")]
15652            a2a_sources: RwLock::new(HashMap::new()),
15653            #[cfg(feature = "agentic-worker")]
15654            ext_artifact_port: None,
15655            operala_node_handler: handler,
15656        }
15657    }
15658
15659    fn operala_ctx<'a>() -> FlowContext<'a> {
15660        FlowContext {
15661            tenant: "demo",
15662            pack_id: "test-pack",
15663            flow_id: "operala.flow",
15664            node_id: None,
15665            tool: None,
15666            action: None,
15667            session_id: Some("sess-op"),
15668            provider_id: None,
15669            reply_scope: None,
15670            retry_config: RetryConfig {
15671                max_attempts: 1,
15672                base_delay_ms: 1,
15673            },
15674            attempt: 1,
15675            observer: None,
15676            mocks: None,
15677            caller: None,
15678        }
15679    }
15680
15681    #[test]
15682    fn operala_call_with_in_process_handler_completes_inline() {
15683        let handler = std::sync::Arc::new(StubOperalaHandler {
15684            payload: json!({ "reply": "stub" }),
15685        });
15686        let engine = operala_engine(operala_flow("deep_worker"), Some(handler));
15687        let execution = tokio::runtime::Runtime::new()
15688            .unwrap()
15689            .block_on(engine.execute(operala_ctx(), Value::Null))
15690            .expect("operala.call with an in-process handler must complete");
15691        assert!(matches!(execution.status, FlowStatus::Completed));
15692        assert_eq!(execution.output, json!({ "reply": "stub" }));
15693    }
15694
15695    #[test]
15696    fn operala_call_hands_the_handler_run_and_the_nodes_input() {
15697        // greentic-dw-authoring stamps `operation: "invoke"`; the invoker only
15698        // accepts "" | "run". The deep-worker settings (B2) ride in `input`.
15699        let deep_worker = json!({ "iterationBudget": 3, "reflection": false, "delegation": false });
15700        let recorder = std::sync::Arc::new(RecordingOperalaHandler::default());
15701        let engine = operala_engine(
15702            operala_flow_with_payload(
15703                "w1",
15704                json!({
15705                    "operation": "invoke",
15706                    "input": { "goal": "summarise the quarter", "deep_worker": deep_worker.clone() }
15707                }),
15708            ),
15709            Some(recorder.clone()),
15710        );
15711        let execution = tokio::runtime::Runtime::new()
15712            .unwrap()
15713            .block_on(engine.execute(operala_ctx(), Value::Null))
15714            .expect("operala.call with an in-process handler must complete");
15715        assert!(matches!(execution.status, FlowStatus::Completed));
15716
15717        let calls = recorder.calls.lock().unwrap().clone();
15718        assert_eq!(calls.len(), 1, "exactly one dispatch: {calls:?}");
15719        let call = &calls[0];
15720        assert_eq!(call.operation, "run", "invoke must be normalised to run");
15721        assert_eq!(call.target, "w1");
15722        assert_eq!(call.tenant, "demo");
15723        assert_eq!(call.env, "local");
15724        assert_eq!(call.session_id, "sess-op");
15725        assert_eq!(call.input["goal"], json!("summarise the quarter"));
15726        assert_eq!(
15727            call.input["deep_worker"], deep_worker,
15728            "settings must reach the invoker verbatim"
15729        );
15730        assert!(
15731            call.input.get("operation").is_none(),
15732            "the handler gets payload.input, not the envelope"
15733        );
15734    }
15735
15736    #[test]
15737    fn operala_call_without_handler_or_nats_fails() {
15738        let engine = operala_engine(operala_flow("deep_worker"), None);
15739        let execution = tokio::runtime::Runtime::new()
15740            .unwrap()
15741            .block_on(engine.execute(operala_ctx(), Value::Null))
15742            .expect("session flow returns a completed error envelope, not an Err");
15743        // `operala_ctx` carries a `session_id`, so main's retry-exhaustion policy
15744        // wraps the execution error into a `Completed` flow carrying the
15745        // `flow_execution_failed` envelope (graceful degradation for session
15746        // flows) rather than propagating an `Err`. The operala misconfiguration
15747        // is still surfaced loudly — in the error payload.
15748        assert!(matches!(execution.status, FlowStatus::Completed));
15749        let msg = execution.output["metadata"]["error_message"]
15750            .as_str()
15751            .unwrap_or_default();
15752        assert!(
15753            msg.contains("operala.call node dispatched but no RemoteDispatchHandler configured"),
15754            "unexpected output: {:?}",
15755            execution.output
15756        );
15757    }
15758
15759    #[test]
15760    fn submitted_fields_reads_root_inputs_on_the_demo_path() {
15761        // Run Demo puts input ids at the entry ROOT beside `metadata`
15762        // (greentic-designer flow_demo/host.rs::build_submit_payload).
15763        let entry = json!({
15764            "amount": "500",
15765            "reason": "looks good",
15766            "metadata": { "action": "approve" }
15767        });
15768        let fields = submitted_fields(&entry);
15769        assert_eq!(fields.get("amount"), Some(&json!("500")));
15770        assert_eq!(fields.get("reason"), Some(&json!("looks good")));
15771        assert!(
15772            !fields.contains_key("metadata"),
15773            "the envelope key is not a field"
15774        );
15775        assert!(
15776            !fields.contains_key("action"),
15777            "the route discriminator is not a field"
15778        );
15779    }
15780
15781    #[test]
15782    fn submitted_fields_reads_metadata_on_the_wrapped_path() {
15783        // greentic-start wraps the activity: entry.input.metadata.*
15784        let entry = json!({
15785            "input": {
15786                "metadata": { "action": "approve", "email": "a@b.c" },
15787                "text": "hi"
15788            }
15789        });
15790        let fields = submitted_fields(&entry);
15791        assert_eq!(fields.get("email"), Some(&json!("a@b.c")));
15792        assert!(!fields.contains_key("action"));
15793        assert!(!fields.contains_key("text"), "envelope text is not a field");
15794        assert!(
15795            !fields.contains_key("input"),
15796            "the envelope root must be resolved, or `input` becomes one giant field"
15797        );
15798    }
15799
15800    #[test]
15801    fn submitted_fields_lets_the_envelope_root_win_a_collision() {
15802        let entry = json!({
15803            "email": "root@x",
15804            "metadata": { "action": "go", "email": "meta@x" }
15805        });
15806        assert_eq!(
15807            submitted_fields(&entry).get("email"),
15808            Some(&json!("root@x"))
15809        );
15810    }
15811
15812    #[test]
15813    fn submitted_fields_counts_a_root_input_named_action() {
15814        // `action` is the route discriminator ONLY in metadata. At the root it is
15815        // a real keystroke on the demo path.
15816        let entry = json!({ "action": "typed", "metadata": { "action": "approve" } });
15817        assert_eq!(
15818            submitted_fields(&entry).get("action"),
15819            Some(&json!("typed"))
15820        );
15821    }
15822
15823    #[test]
15824    fn submitted_fields_is_empty_for_a_button_with_no_inputs() {
15825        let entry = json!({ "metadata": { "action": "approve" } });
15826        assert!(submitted_fields(&entry).is_empty());
15827    }
15828
15829    /// A card node with no declared `answer_fields` — i.e. a pack built before
15830    /// this feature existed. `attach_pending_card_answers` must treat this as
15831    /// "no allow-list" (today's permissive behaviour), not "zero fields".
15832    fn plain_card_node() -> HostNode {
15833        HostNode {
15834            kind: NodeKind::Exec {
15835                target_component: "card".to_string(),
15836            },
15837            component: "component.exec".to_string(),
15838            component_id: "component.exec".to_string(),
15839            operation_name: None,
15840            operation_in_mapping: None,
15841            payload_expr: Value::Null,
15842            routing: Routing::End,
15843            vars_out: None,
15844            response_timeout_secs: None,
15845        }
15846    }
15847
15848    #[test]
15849    fn an_old_snapshot_without_the_flag_deserializes_as_not_awaiting_submit() {
15850        // Snapshots persisted before this field existed must keep their exact
15851        // current behaviour: no answers attached.
15852        let raw = json!({
15853            "pack_id": "p",
15854            "flow_id": "f",
15855            "next_node": "card",
15856            "state": {}
15857        });
15858        let snap: FlowSnapshot = serde_json::from_value(raw).expect("legacy snapshot decodes");
15859        assert!(!snap.awaiting_submit);
15860    }
15861
15862    /// A resumed node's submitted fields must be readable from its output by a
15863    /// LATER node, through the ordinary `{{node.<id>.<field>}}` grammar.
15864    ///
15865    /// This is the whole feature, and it is also the ordering proof: the resume
15866    /// RE-DISPATCHES the parked node and `state.nodes.insert` replaces its stored
15867    /// output, so an implementation that attaches the answers before the dispatch
15868    /// makes this test fail. Do not "simplify" the merge earlier.
15869    #[test]
15870    fn submitted_answers_survive_the_resume_redispatch_and_reach_a_later_node() {
15871        let mut state = ExecutionState::new(json!({}));
15872        // The parked node has already run once; its stored output is what the
15873        // resume dispatch will REPLACE.
15874        state.nodes.insert(
15875            "card".to_string(),
15876            NodeOutput::new(json!({ "event": "rendered" })),
15877        );
15878        state.pending_card_answers = Some(PendingCardAnswers {
15879            node_id: "card".to_string(),
15880            answers: submitted_fields(&json!({
15881                "email": "a@b.c",
15882                "metadata": { "action": "submit" }
15883            })),
15884        });
15885
15886        // Simulate the re-dispatch: a FRESH output object, exactly as the loop
15887        // builds one, then the merge at its real call position.
15888        let mut fresh = NodeOutput::new(json!({ "event": "rendered" }));
15889        attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut fresh);
15890        state.nodes.insert("card".to_string(), fresh);
15891
15892        // Read it the way a downstream node's config would.
15893        let ctx = template_context(&state, Value::Null);
15894        let rendered = render_template_value(
15895            &json!("{{node.card.answers.email}}"),
15896            &ctx,
15897            TemplateOptions::default(),
15898        )
15899        .expect("render");
15900        assert_eq!(rendered, json!("a@b.c"));
15901    }
15902
15903    #[test]
15904    fn the_card_render_context_carries_the_answers_too() {
15905        // One write, two read surfaces: `outputs_map()` feeds {{node.…}} and
15906        // `context()` feeds the `state` handed to the adaptive-card component.
15907        let mut state = ExecutionState::new(json!({}));
15908        state.pending_card_answers = Some(PendingCardAnswers {
15909            node_id: "card".to_string(),
15910            answers: submitted_fields(&json!({ "email": "a@b.c" })),
15911        });
15912        let mut output = NodeOutput::new(json!({ "event": "rendered" }));
15913        attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut output);
15914        state.nodes.insert("card".to_string(), output);
15915
15916        let ctx = state.context();
15917        assert_eq!(
15918            ctx["nodes"]["card"]["payload"]["answers"]["email"],
15919            json!("a@b.c")
15920        );
15921    }
15922
15923    #[test]
15924    fn answers_are_absent_before_any_submit() {
15925        // Absent is not empty: absent means never submitted, {} means submitted
15926        // with no fields. Do not collapse the two.
15927        let mut state = ExecutionState::new(json!({}));
15928        let mut output = NodeOutput::new(json!({ "event": "rendered" }));
15929        attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut output);
15930        assert!(output.payload.get("answers").is_none());
15931    }
15932
15933    #[test]
15934    fn a_button_with_no_inputs_yields_an_empty_answers_object() {
15935        let mut state = ExecutionState::new(json!({}));
15936        state.pending_card_answers = Some(PendingCardAnswers {
15937            node_id: "card".to_string(),
15938            answers: submitted_fields(&json!({ "metadata": { "action": "approve" } })),
15939        });
15940        let mut output = NodeOutput::new(json!({ "event": "rendered" }));
15941        attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut output);
15942        assert_eq!(output.payload["answers"], json!({}));
15943    }
15944
15945    #[test]
15946    fn the_pending_answers_are_consumed_exactly_once() {
15947        // A loop back through the same node without a resume must not re-attach
15948        // stale answers.
15949        let mut state = ExecutionState::new(json!({}));
15950        state.pending_card_answers = Some(PendingCardAnswers {
15951            node_id: "card".to_string(),
15952            answers: submitted_fields(&json!({ "email": "a@b.c" })),
15953        });
15954        let mut first = NodeOutput::new(json!({ "event": "rendered" }));
15955        attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut first);
15956        assert!(first.payload.get("answers").is_some());
15957
15958        let mut second = NodeOutput::new(json!({ "event": "rendered" }));
15959        attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut second);
15960        assert!(
15961            second.payload.get("answers").is_none(),
15962            "consumed, not read"
15963        );
15964    }
15965
15966    #[test]
15967    fn answers_attach_even_when_the_redispatch_failed() {
15968        // The answers are real regardless of whether the re-render succeeded.
15969        // Dropping them would let a transient render error destroy what someone
15970        // typed.
15971        let mut state = ExecutionState::new(json!({}));
15972        state.pending_card_answers = Some(PendingCardAnswers {
15973            node_id: "card".to_string(),
15974            answers: submitted_fields(&json!({ "email": "a@b.c" })),
15975        });
15976        let mut output = NodeOutput::new(json!({ "ok": false, "error": { "code": "boom" } }));
15977        attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut output);
15978        assert_eq!(output.payload["answers"]["email"], json!("a@b.c"));
15979    }
15980
15981    #[test]
15982    fn answers_are_not_attached_to_a_different_node() {
15983        let mut state = ExecutionState::new(json!({}));
15984        state.pending_card_answers = Some(PendingCardAnswers {
15985            node_id: "card".to_string(),
15986            answers: submitted_fields(&json!({ "email": "a@b.c" })),
15987        });
15988        let mut other = NodeOutput::new(json!({ "event": "rendered" }));
15989        attach_pending_card_answers(&mut state, "next_step", &plain_card_node(), &mut other);
15990        assert!(other.payload.get("answers").is_none());
15991        assert!(
15992            state.pending_card_answers.is_some(),
15993            "still pending for its own node"
15994        );
15995    }
15996
15997    /// THE defect this feature closes. On the `greentic-start` path
15998    /// `entry.input` is a whole `ChannelMessageEnvelope` (see
15999    /// `greentic-types::messaging`), not a flat map of input ids — so without
16000    /// an allow-list, `submitted_fields` unions transport identity
16001    /// (`tenant`, `session_id`, `from`, `attachments`, ...), routing keys
16002    /// (`nextCardId`, `route`), channel keys (`env`, `team`, `locale`,
16003    /// `autoStart`), and greentic-start's own injected pack setup answers
16004    /// (`url`, `model`, `provider`, `api_key_secret` — a `secrets://...`
16005    /// reference) into `answers`, under a key documented as "the fields
16006    /// someone typed into this card". With a declared `answer_fields`
16007    /// allow-list, none of that must survive — only the two genuine card
16008    /// inputs.
16009    #[test]
16010    fn answers_intersect_the_declared_allow_list_on_a_wrapped_start_envelope() {
16011        let entry = json!({
16012            "input": {
16013                "id": "msg-1",
16014                "tenant": "acme",
16015                "channel": "webchat",
16016                "session_id": "sess-1",
16017                "from": "user-1",
16018                "to": "bot-1",
16019                "correlation_id": "corr-1",
16020                "attachments": [],
16021                "metadata": {
16022                    "action": "submit",
16023                    "nextCardId": "confirm",
16024                    "route": "default",
16025                    "env": "prod",
16026                    "team": "support",
16027                    "locale": "en-US",
16028                    "autoStart": true,
16029                    "url": "https://api.example.com",
16030                    "model": "gpt-4",
16031                    "provider": "openai",
16032                    "api_key_secret": "secrets://tenant/acme/openai_key",
16033                    "full_name": "Ada Lovelace",
16034                    "email": "ada@example.com"
16035                },
16036                "text": "submitted"
16037            }
16038        });
16039
16040        let mut state = ExecutionState::new(json!({}));
16041        state.pending_card_answers = Some(PendingCardAnswers {
16042            node_id: "card".to_string(),
16043            answers: submitted_fields(&entry),
16044        });
16045
16046        let node = HostNode {
16047            payload_expr: json!({ "answer_fields": ["full_name", "email"] }),
16048            ..plain_card_node()
16049        };
16050        let mut output = NodeOutput::new(json!({ "event": "rendered" }));
16051        attach_pending_card_answers(&mut state, "card", &node, &mut output);
16052
16053        let answers = output.payload["answers"]
16054            .as_object()
16055            .expect("answers must be an object");
16056        assert_eq!(
16057            answers,
16058            &serde_json::Map::from_iter([
16059                ("full_name".to_string(), json!("Ada Lovelace")),
16060                ("email".to_string(), json!("ada@example.com")),
16061            ]),
16062            "answers must contain exactly the two declared card inputs, and \
16063             nothing from transport identity, routing, or pack config: {answers:?}"
16064        );
16065    }
16066
16067    #[test]
16068    fn answer_fields_absent_keeps_todays_permissive_behaviour() {
16069        // Pre-upgrade packs, and any path that never runs the designer
16070        // injector, must keep exactly today's behaviour: no allow-list means
16071        // no filtering, even on a wrapped envelope carrying non-input keys.
16072        let entry = json!({
16073            "input": {
16074                "tenant": "acme",
16075                "metadata": { "action": "submit", "email": "a@b.c" },
16076                "text": "hi"
16077            }
16078        });
16079        let mut state = ExecutionState::new(json!({}));
16080        state.pending_card_answers = Some(PendingCardAnswers {
16081            node_id: "card".to_string(),
16082            answers: submitted_fields(&entry),
16083        });
16084        let mut output = NodeOutput::new(json!({ "event": "rendered" }));
16085        attach_pending_card_answers(&mut state, "card", &plain_card_node(), &mut output);
16086
16087        assert_eq!(output.payload["answers"]["tenant"], json!("acme"));
16088        assert_eq!(output.payload["answers"]["email"], json!("a@b.c"));
16089    }
16090
16091    #[test]
16092    fn answer_fields_declared_empty_yields_no_answers() {
16093        // A card that genuinely declares zero inputs must produce `{}` — an
16094        // empty allow-list is not the same as an absent one, and must not be
16095        // collapsed into the unfiltered set.
16096        let mut state = ExecutionState::new(json!({}));
16097        state.pending_card_answers = Some(PendingCardAnswers {
16098            node_id: "card".to_string(),
16099            answers: submitted_fields(&json!({
16100                "email": "a@b.c",
16101                "metadata": { "action": "approve" }
16102            })),
16103        });
16104        let node = HostNode {
16105            payload_expr: json!({ "answer_fields": [] }),
16106            ..plain_card_node()
16107        };
16108        let mut output = NodeOutput::new(json!({ "event": "rendered" }));
16109        attach_pending_card_answers(&mut state, "card", &node, &mut output);
16110
16111        assert_eq!(output.payload["answers"], json!({}));
16112    }
16113
16114    /// The three-way distinction `declared_answer_fields` exists to preserve:
16115    /// absent (ordinary pre-upgrade pack) and malformed (a designer-side bug)
16116    /// both fall back to the SAME permissive, unfiltered `answers` — that part
16117    /// is asserted here — but only the malformed case is meant to be logged
16118    /// (`tracing::warn!` in `attach_pending_card_answers`). This test can only
16119    /// assert the behavioural half: nothing in this crate's dev-dependencies
16120    /// captures `tracing` output (no `tracing-test`/subscriber-capture
16121    /// harness is wired up here), and adding one purely to assert a log line
16122    /// felt like more machinery than the assertion warrants. The `Malformed`
16123    /// arm's `tracing::warn!` call is exercised (not just present in source)
16124    /// by the "malformed" case below, since the same match arm both logs and
16125    /// returns the unfiltered map — a change that broke or removed the log
16126    /// call, if it also broke the fallback, would fail this test.
16127    #[test]
16128    fn absent_and_malformed_answer_fields_both_stay_permissive_but_declared_filters() {
16129        let entry = json!({ "email": "a@b.c", "phone": "555-1234" });
16130
16131        // Absent: no `answer_fields` key at all.
16132        let mut absent_state = ExecutionState::new(json!({}));
16133        absent_state.pending_card_answers = Some(PendingCardAnswers {
16134            node_id: "card".to_string(),
16135            answers: submitted_fields(&entry),
16136        });
16137        let mut absent_output = NodeOutput::new(json!({ "event": "rendered" }));
16138        attach_pending_card_answers(
16139            &mut absent_state,
16140            "card",
16141            &plain_card_node(),
16142            &mut absent_output,
16143        );
16144        assert_eq!(
16145            absent_output.payload["answers"],
16146            json!({ "email": "a@b.c", "phone": "555-1234" }),
16147            "absent must stay fully permissive"
16148        );
16149
16150        // Malformed: the key is present but is not an array of strings (e.g.
16151        // an unresolved template, or a wrong-typed value from a designer bug).
16152        let mut malformed_state = ExecutionState::new(json!({}));
16153        malformed_state.pending_card_answers = Some(PendingCardAnswers {
16154            node_id: "card".to_string(),
16155            answers: submitted_fields(&entry),
16156        });
16157        let malformed_node = HostNode {
16158            payload_expr: json!({ "answer_fields": "{{unresolved.template}}" }),
16159            ..plain_card_node()
16160        };
16161        let mut malformed_output = NodeOutput::new(json!({ "event": "rendered" }));
16162        attach_pending_card_answers(
16163            &mut malformed_state,
16164            "card",
16165            &malformed_node,
16166            &mut malformed_output,
16167        );
16168        assert_eq!(
16169            malformed_output.payload["answers"],
16170            json!({ "email": "a@b.c", "phone": "555-1234" }),
16171            "malformed must ALSO stay fully permissive, same as absent"
16172        );
16173
16174        // Declared: a valid, non-empty allow-list actually filters.
16175        let mut declared_state = ExecutionState::new(json!({}));
16176        declared_state.pending_card_answers = Some(PendingCardAnswers {
16177            node_id: "card".to_string(),
16178            answers: submitted_fields(&entry),
16179        });
16180        let declared_node = HostNode {
16181            payload_expr: json!({ "answer_fields": ["email"] }),
16182            ..plain_card_node()
16183        };
16184        let mut declared_output = NodeOutput::new(json!({ "event": "rendered" }));
16185        attach_pending_card_answers(
16186            &mut declared_state,
16187            "card",
16188            &declared_node,
16189            &mut declared_output,
16190        );
16191        assert_eq!(
16192            declared_output.payload["answers"],
16193            json!({ "email": "a@b.c" }),
16194            "declared must filter down to exactly the allow-listed keys"
16195        );
16196    }
16197
16198    #[test]
16199    fn pending_from_snapshot_names_next_node_when_awaiting_submit() {
16200        let snapshot = FlowSnapshot {
16201            pack_id: "p".to_string(),
16202            flow_id: "f".to_string(),
16203            next_flow: None,
16204            next_node: "card".to_string(),
16205            awaiting_submit: true,
16206            state: ExecutionState::new(json!({})),
16207        };
16208        let input = json!({ "email": "a@b.c", "metadata": { "action": "submit" } });
16209        let pending = pending_from_snapshot(&snapshot, &input).expect("should park answers");
16210        assert_eq!(pending.node_id, "card");
16211        assert_eq!(pending.answers.get("email"), Some(&json!("a@b.c")));
16212    }
16213
16214    #[test]
16215    fn pending_from_snapshot_is_none_when_not_awaiting_submit() {
16216        let snapshot = FlowSnapshot {
16217            pack_id: "p".to_string(),
16218            flow_id: "f".to_string(),
16219            next_flow: None,
16220            next_node: "successor".to_string(),
16221            awaiting_submit: false,
16222            state: ExecutionState::new(json!({})),
16223        };
16224        let input = json!({ "email": "a@b.c" });
16225        assert!(pending_from_snapshot(&snapshot, &input).is_none());
16226    }
16227
16228    /// Build a two-node flow: `card` (`Routing::Custom`, parks until
16229    /// `response.action == "submit"`) -> `next` (reads
16230    /// `{{node.card.answers.email}}`). `card`'s first pass has no
16231    /// `response.action`, so its conditional routing falls through and it
16232    /// parks with `awaiting_submit: true`.
16233    fn card_answers_flow() -> Flow {
16234        let card_id = NodeId::from_str("card").unwrap();
16235        let next_id = NodeId::from_str("next").unwrap();
16236
16237        let card_node = Node {
16238            id: card_id.clone(),
16239            component: FlowComponentRef {
16240                id: "emit.log".parse().unwrap(),
16241                pack_alias: None,
16242                operation: None,
16243            },
16244            input: InputMapping {
16245                mapping: json!({ "event": "rendered" }),
16246            },
16247            output: OutputMapping {
16248                mapping: Value::Null,
16249            },
16250            err_map: None,
16251            routing: Routing::Custom(json!([
16252                { "condition": "response.action == \"submit\"", "to": next_id.to_string() }
16253            ])),
16254            telemetry: TelemetryHints::default(),
16255            conversational: false,
16256        };
16257
16258        let next_node = Node {
16259            id: next_id.clone(),
16260            component: FlowComponentRef {
16261                id: "emit.log".parse().unwrap(),
16262                pack_alias: None,
16263                operation: None,
16264            },
16265            input: InputMapping {
16266                mapping: json!({ "got_email": "{{node.card.answers.email}}" }),
16267            },
16268            output: OutputMapping {
16269                mapping: Value::Null,
16270            },
16271            err_map: None,
16272            routing: Routing::End,
16273            telemetry: TelemetryHints::default(),
16274            conversational: false,
16275        };
16276
16277        let mut nodes = indexmap::IndexMap::default();
16278        nodes.insert(card_id.clone(), card_node);
16279        nodes.insert(next_id.clone(), next_node);
16280
16281        Flow {
16282            schema_version: "1.0".into(),
16283            id: FlowId::from_str("card.answers.flow").unwrap(),
16284            kind: FlowKind::Messaging,
16285            entrypoints: BTreeMap::from([(
16286                "default".to_string(),
16287                Value::String(card_id.to_string()),
16288            )]),
16289            nodes,
16290            metadata: FlowMetadata {
16291                title: None,
16292                description: None,
16293                tags: Default::default(),
16294                extra: json!({}),
16295            },
16296        }
16297    }
16298
16299    /// The covering test for both findings from Task 3 code review: this
16300    /// drives the REAL `FlowEngine::resume` -> `drive_flow` -> dispatch-loop
16301    /// path, not a hand-simulated `ExecutionState`. It pins BOTH the `resume`
16302    /// wiring (`state.pending_card_answers = pending_card_answers;`, engine.rs
16303    /// near `resume`) AND the merge position immediately before
16304    /// `state.nodes.insert` in the dispatch loop: deleting or moving either
16305    /// makes this test fail, unlike the hand-simulated
16306    /// `submitted_answers_survive_the_resume_redispatch_and_reach_a_later_node`,
16307    /// whose ordering sensitivity is a property of its own three
16308    /// hand-written statements rather than of the engine.
16309    #[test]
16310    fn card_answers_survive_a_real_park_and_resume_and_reach_a_later_node() {
16311        let flow = card_answers_flow();
16312        let host_flow = HostFlow::from(flow);
16313        let flow_id = "card.answers.flow";
16314        let pack_id = "test-pack";
16315        let engine = FlowEngine {
16316            messaging_provider_pack_ids: Default::default(),
16317            rollout_ids: RolloutIds::default(),
16318            packs: Vec::new(),
16319            flows: Vec::new(),
16320            flow_sources: StdHashMap::new(),
16321            flow_cache: RwLock::new(StdHashMap::from([(
16322                FlowKey {
16323                    pack_id: pack_id.to_string(),
16324                    flow_id: flow_id.to_string(),
16325                },
16326                host_flow,
16327            )])),
16328            default_env: "local".to_string(),
16329            validation: ValidationConfig {
16330                mode: ValidationMode::Off,
16331            },
16332            cross_pack_resolver: None,
16333            approval_dispatch_handler: None,
16334            remote_dispatch_handler: None,
16335            #[cfg(feature = "agentic-worker")]
16336            dw_agent_dispatch: crate::runner::agent_node::DwAgentDispatch::InProcess,
16337            #[cfg(feature = "agentic-worker")]
16338            agent_node_handler: None,
16339            #[cfg(feature = "agentic-worker")]
16340            graph_node_handler: None,
16341            #[cfg(feature = "agentic-worker")]
16342            mcp_tool_source: None,
16343            #[cfg(feature = "agentic-worker")]
16344            mcp_secrets: None,
16345            #[cfg(feature = "agentic-worker")]
16346            a2a_sources: RwLock::new(HashMap::new()),
16347            #[cfg(feature = "agentic-worker")]
16348            ext_artifact_port: None,
16349            operala_node_handler: None,
16350        };
16351        let rt = Runtime::new().unwrap();
16352
16353        let ctx1 = FlowContext {
16354            tenant: "demo",
16355            pack_id,
16356            flow_id,
16357            node_id: None,
16358            tool: None,
16359            action: None,
16360            session_id: None,
16361            provider_id: None,
16362            reply_scope: None,
16363            retry_config: RetryConfig {
16364                max_attempts: 1,
16365                base_delay_ms: 1,
16366            },
16367            attempt: 1,
16368            observer: None,
16369            mocks: None,
16370            caller: None,
16371        };
16372        // First turn: no `response.action` yet, so `card`'s conditional
16373        // routing falls through and it parks awaiting the submit.
16374        let result1 = rt.block_on(engine.execute(ctx1, Value::Null)).unwrap();
16375        let snapshot = match result1.status {
16376            FlowStatus::Waiting(w) => w.snapshot,
16377            other => panic!("expected Waiting at the card node, got {other:?}"),
16378        };
16379        assert!(
16380            snapshot.awaiting_submit,
16381            "the card's conditional fall-through must set awaiting_submit"
16382        );
16383        assert_eq!(snapshot.next_node, "card");
16384
16385        // Resume with the submitted fields. `resume` must park them, the
16386        // dispatch loop must re-run `card`, and `attach_pending_card_answers`
16387        // must merge them into its FRESH re-dispatched output before `next`
16388        // runs.
16389        let ctx2 = FlowContext {
16390            tenant: "demo",
16391            pack_id,
16392            flow_id,
16393            node_id: None,
16394            tool: None,
16395            action: None,
16396            session_id: None,
16397            provider_id: None,
16398            reply_scope: None,
16399            retry_config: RetryConfig {
16400                max_attempts: 1,
16401                base_delay_ms: 1,
16402            },
16403            attempt: 1,
16404            observer: None,
16405            mocks: None,
16406            caller: None,
16407        };
16408        let input = json!({ "email": "a@b.c", "metadata": { "action": "submit" } });
16409        let result2 = rt.block_on(engine.resume(ctx2, snapshot, input)).unwrap();
16410        assert!(
16411            matches!(result2.status, FlowStatus::Completed),
16412            "the submit must route past the card to `next`"
16413        );
16414        assert_eq!(
16415            result2.node_outputs["card"]["answers"]["email"],
16416            json!("a@b.c"),
16417            "the card's own re-dispatched output must carry the merged answers"
16418        );
16419        assert_eq!(
16420            result2.node_outputs["next"]["got_email"],
16421            json!("a@b.c"),
16422            "`next`, a LATER node, must read the answers through {{node.card.answers.email}}"
16423        );
16424    }
16425}
16426
16427use tracing::Instrument;
16428
16429pub struct FlowContext<'a> {
16430    pub tenant: &'a str,
16431    pub pack_id: &'a str,
16432    pub flow_id: &'a str,
16433    pub node_id: Option<&'a str>,
16434    pub tool: Option<&'a str>,
16435    pub action: Option<&'a str>,
16436    pub session_id: Option<&'a str>,
16437    pub provider_id: Option<&'a str>,
16438    /// Reply scope of the originating inbound activity, when known.
16439    ///
16440    /// Carried so async-dispatch nodes (`sorla.call await`) can encode the
16441    /// inbound `thread`/`reply_to` into the published correlation id. Without
16442    /// it, a wait saved against a threaded scope cannot be re-keyed on resume
16443    /// (the resumer would synthesize an empty thread/reply_to and miss the
16444    /// saved wait). See `execute_sorla_call` and `RuntimeSessionResumer`.
16445    pub reply_scope: Option<&'a greentic_types::ReplyScope>,
16446    pub retry_config: RetryConfig,
16447    pub attempt: u32,
16448    pub observer: Option<&'a dyn ExecutionObserver>,
16449    pub mocks: Option<&'a MockLayer>,
16450    /// The caller the messaging PROVIDER verified for this run, as raw JSON.
16451    ///
16452    /// Established once at the run's entry from the provider's own envelope
16453    /// (`crate::caller_identity::caller_block`) and carried BESIDE the flow's
16454    /// data, never through it: a flow's node mapping is authorable, so identity
16455    /// read from a node payload is identity the flow — and the model behind it
16456    /// — could have written.
16457    ///
16458    /// Raw JSON rather than `greentic_aw_runtime::VerifiedCaller` because that
16459    /// crate is optional behind `agentic-worker` while this struct is not; the
16460    /// typed parse happens at the agent node, which is already gated.
16461    ///
16462    /// `None` is ordinary: a provider predating the contract, or an autonomous
16463    /// turn. It becomes an anonymous caller downstream, never an error.
16464    pub caller: Option<&'a serde_json::Value>,
16465}
16466
16467#[derive(Copy, Clone)]
16468pub struct RetryConfig {
16469    pub max_attempts: u32,
16470    pub base_delay_ms: u64,
16471}
16472
16473/// Look across all node outputs, find the first one that finished with
16474/// `ok=false`, and lift its `meta.error` fields into
16475/// `output.metadata.error_kind` / `.error_message` / `.node_id`. Returns the
16476/// (possibly enriched) output unchanged otherwise.
16477///
16478/// This is how the executor "shows" an unhandled flow-node failure to the
16479/// caller without the flow author having to add error routing: the chat-side
16480/// provider (messaging-providers `extract_error_envelope`) picks the lifted
16481/// fields off `output.metadata` and renders a styled error card.
16482///
16483/// Takes a borrow of the node-output map rather than the whole
16484/// `ExecutionState` because the callers have already consumed `state` via
16485/// `state.finalize_with(...)`; we capture a cheap clone of `state.nodes` up
16486/// front and pass it in here.
16487#[cfg(test)]
16488fn lift_first_node_error_from_nodes(output: Value, nodes: &HashMap<String, NodeOutput>) -> Value {
16489    // No execution order is available here, so pick deterministically by id.
16490    let failure = nodes
16491        .iter()
16492        .filter(|(_, out)| !out.ok)
16493        .min_by(|a, b| a.0.cmp(b.0))
16494        .map(|(id, out)| (id.clone(), out.clone()));
16495    lift_node_error(output, failure.as_ref())
16496}
16497
16498/// Lift `failure` (a node id and its failed output) into `output.metadata`;
16499/// see [`lift_first_node_error_from_nodes`]. Production callers choose the
16500/// failure with [`ExecutionState::first_unhandled_failure`]: execution order,
16501/// skipping nodes whose failure an error edge already routed.
16502fn lift_node_error(output: Value, failure: Option<&(String, NodeOutput)>) -> Value {
16503    let Some((node_id, failed)) = failure else {
16504        return output;
16505    };
16506    let err_meta = failed.meta.get("error");
16507    let message = err_meta
16508        .and_then(|e| e.get("message"))
16509        .and_then(|v| v.as_str())
16510        .unwrap_or("flow node failed");
16511    let kind = err_meta
16512        .and_then(|e| e.get("kind"))
16513        .and_then(|v| v.as_str())
16514        .unwrap_or("flow_node_failed");
16515
16516    let mut output = match output {
16517        Value::Object(map) => map,
16518        Value::Null => JsonMap::new(),
16519        other => {
16520            let mut wrap = JsonMap::new();
16521            wrap.insert("payload".to_string(), other);
16522            wrap
16523        }
16524    };
16525    let metadata_entry = output
16526        .entry("metadata".to_string())
16527        .or_insert_with(|| Value::Object(JsonMap::new()));
16528    let metadata_map = match metadata_entry {
16529        Value::Object(map) => map,
16530        _ => {
16531            *metadata_entry = Value::Object(JsonMap::new());
16532            metadata_entry.as_object_mut().unwrap()
16533        }
16534    };
16535    metadata_map
16536        .entry("error_kind".to_string())
16537        .or_insert(Value::String(kind.to_string()));
16538    metadata_map
16539        .entry("error_message".to_string())
16540        .or_insert(Value::String(message.to_string()));
16541    metadata_map
16542        .entry("node_id".to_string())
16543        .or_insert(Value::String(node_id.clone()));
16544    Value::Object(output)
16545}
16546
16547/// Marks a failure as transient, i.e. worth re-running the flow for. Wrap a
16548/// source error in this (via `anyhow::Error::new`) where a failure is known to
16549/// be retryable; nothing is retried on the strength of its message text.
16550#[derive(Debug, thiserror::Error)]
16551#[error("{0}")]
16552pub struct TransientFlowError(pub String);
16553
16554/// Wraps an error that is PROVEN to have happened before the failing node did
16555/// anything outside the turn (nothing was published, no tool or provider call
16556/// was made). The engine reads the marker to leave `effects_performed` unset
16557/// for that failure, so a transient pre-effect error still retries the turn.
16558/// Display is the wrapped error's, unchanged; its cause chain stays reachable
16559/// to [`should_retry`] / [`is_terminal_flow_error`] (see `error_causes`).
16560#[derive(Debug)]
16561pub struct PreEffectError(anyhow::Error);
16562
16563impl std::fmt::Display for PreEffectError {
16564    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16565        std::fmt::Display::fmt(&self.0, f)
16566    }
16567}
16568
16569impl std::error::Error for PreEffectError {
16570    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
16571        // The wrapped error itself is NOT repeated as a source (its message is
16572        // this error's Display); `error_causes` looks inside instead.
16573        self.0.source()
16574    }
16575}
16576
16577/// Mark `err` as having occurred before any external effect of the node. Use it
16578/// only where that is provable; when in doubt, do not (the default is to assume
16579/// the node may have done part of its work).
16580pub fn pre_effect(err: impl Into<anyhow::Error>) -> anyhow::Error {
16581    anyhow::Error::new(PreEffectError(err.into()))
16582}
16583
16584/// Whether `err` was marked with [`pre_effect`] (at any depth of its chain).
16585pub fn is_pre_effect_error(err: &anyhow::Error) -> bool {
16586    err.chain().any(|cause| cause.is::<PreEffectError>())
16587}
16588
16589/// Every cause in `err`, looking through [`PreEffectError`] wrappers into the
16590/// error they wrap (which `source()` deliberately skips).
16591fn error_causes(err: &anyhow::Error) -> Vec<&(dyn std::error::Error + 'static)> {
16592    fn walk<'a>(err: &'a anyhow::Error, out: &mut Vec<&'a (dyn std::error::Error + 'static)>) {
16593        for cause in err.chain() {
16594            out.push(cause);
16595            if let Some(wrapped) = cause.downcast_ref::<PreEffectError>() {
16596                walk(&wrapped.0, out);
16597            }
16598        }
16599    }
16600    let mut out = Vec::new();
16601    walk(err, &mut out);
16602    out
16603}
16604
16605/// Marks a failure as terminal: deterministic (a routing cycle, an unknown
16606/// node, a missing required variable) or raised after side effects already ran
16607/// (a step budget spent). Re-running the turn cannot help and would repeat the
16608/// effects, so neither the engine's own retry loop nor the state machine's
16609/// whole-turn `retry_with_jitter` re-runs it; the state machine sees it as
16610/// [`RunnerError::FlowTerminal`](crate::engine::error::RunnerError::FlowTerminal).
16611/// The `Display` text is the bare message, so existing message assertions hold.
16612///
16613/// It may carry the error it replaced ([`terminal_flow_error_from_after_effects`]). `Display`
16614/// stays the OUTERMOST message only, because `to_string()` is what reaches the
16615/// user-facing failure envelope and a cause chain can name a host or URL;
16616/// `source()` exposes the original causes so `{err:#}` and
16617/// `anyhow_chain_text` (operator logs, the redacted run error) still see the
16618/// root cause.
16619#[derive(Debug)]
16620pub struct TerminalFlowError {
16621    message: String,
16622    original: Option<anyhow::Error>,
16623    /// An earlier node of the SAME run had already performed an external
16624    /// effect when this failure happened (see [`terminal_after_effects`]).
16625    /// A deterministic pre-effect failure (unknown node) is terminal too but
16626    /// leaves this `false`: nothing ran that a re-delivery would repeat.
16627    after_effects: bool,
16628}
16629
16630impl std::fmt::Display for TerminalFlowError {
16631    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
16632        f.write_str(&self.message)
16633    }
16634}
16635
16636impl std::error::Error for TerminalFlowError {
16637    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
16638        // The original's own message is this error's Display, so skip it and
16639        // continue with ITS causes (same trick as `PreEffectError`).
16640        self.original.as_ref().and_then(|err| {
16641            let top: &(dyn std::error::Error + 'static) = err.as_ref();
16642            top.source()
16643        })
16644    }
16645}
16646
16647/// Build an `anyhow::Error` carrying a [`TerminalFlowError`].
16648pub(crate) fn terminal_flow_error(message: impl Into<String>) -> anyhow::Error {
16649    anyhow::Error::new(TerminalFlowError {
16650        message: message.into(),
16651        original: None,
16652        after_effects: false,
16653    })
16654}
16655
16656/// Make `err` terminal while keeping its cause chain reachable through
16657/// `source()` (see [`TerminalFlowError`]; `Display` is `err`'s outermost message,
16658/// unchanged), recording that an earlier node of the run had performed an
16659/// external effect.
16660fn terminal_flow_error_from_after_effects(err: anyhow::Error) -> anyhow::Error {
16661    anyhow::Error::new(TerminalFlowError {
16662        message: err.to_string(),
16663        original: Some(err),
16664        after_effects: true,
16665    })
16666}
16667
16668/// Whether the failure is terminal AND followed an external effect of the same
16669/// run. A resumed run that fails this way has already spent the effect, so the
16670/// park it was resumed from must not outlive the turn (the next message would
16671/// resume the same wait and repeat the effect).
16672pub fn is_after_effects_failure(err: &anyhow::Error) -> bool {
16673    error_causes(err).into_iter().any(|cause| {
16674        cause
16675            .downcast_ref::<TerminalFlowError>()
16676            .is_some_and(|terminal| terminal.after_effects)
16677    })
16678}
16679
16680/// Whether any cause in the chain is a [`TerminalFlowError`].
16681pub fn is_terminal_flow_error(err: &anyhow::Error) -> bool {
16682    error_causes(err)
16683        .into_iter()
16684        .any(|cause| cause.is::<TerminalFlowError>())
16685}
16686
16687/// Retry transient failures: anything typed as transient (an explicit
16688/// [`TransientFlowError`], a timeout, a transient I/O kind) or whose message
16689/// names a transient condition ("transient", "unavailable", "internal",
16690/// "timeout"). The message check is the long-standing behaviour that
16691/// `FlowRetryConfig` callers (fault injection, state-store flakiness) rely on.
16692fn should_retry(err: &anyhow::Error) -> bool {
16693    // A terminal marker wins over any transient-sounding message text.
16694    if is_terminal_flow_error(err) {
16695        return false;
16696    }
16697    let typed = error_causes(err).into_iter().any(|cause| {
16698        if cause.is::<TransientFlowError>() || cause.is::<tokio::time::error::Elapsed>() {
16699            return true;
16700        }
16701        cause.downcast_ref::<std::io::Error>().is_some_and(|io| {
16702            matches!(
16703                io.kind(),
16704                std::io::ErrorKind::TimedOut
16705                    | std::io::ErrorKind::ConnectionReset
16706                    | std::io::ErrorKind::ConnectionAborted
16707                    | std::io::ErrorKind::ConnectionRefused
16708                    | std::io::ErrorKind::Interrupted
16709                    | std::io::ErrorKind::WouldBlock
16710            )
16711        })
16712    });
16713    if typed {
16714        return true;
16715    }
16716    let lower = err.to_string().to_lowercase();
16717    lower.contains("transient")
16718        || lower.contains("unavailable")
16719        || lower.contains("internal")
16720        || lower.contains("timeout")
16721}
16722
16723#[cfg(feature = "fault-injection")]
16724fn injected_error(err: crate::testing::fault_injection::InjectedError) -> anyhow::Error {
16725    use crate::testing::fault_injection::FaultErrorKind;
16726    match err.kind {
16727        FaultErrorKind::Transient | FaultErrorKind::Timeout => {
16728            anyhow::Error::new(TransientFlowError(err.to_string()))
16729        }
16730        _ => anyhow!(err.to_string()),
16731    }
16732}
16733
16734impl From<FlowRetryConfig> for RetryConfig {
16735    fn from(value: FlowRetryConfig) -> Self {
16736        Self {
16737            max_attempts: value.max_attempts.max(1),
16738            base_delay_ms: value.base_delay_ms.max(50),
16739        }
16740    }
16741}