Skip to main content

greentic_runner_host/runner/
graph_node.rs

1use anyhow::Result;
2use serde_json::Value;
3
4/// Bridges a `DwAgentGraph` flow node into the graph executor.
5///
6/// The concrete impl (constructed in the runner binary / pack loader, Task 8)
7/// wraps [`greentic_aw_runtime::graph::GraphExecutor`]. The engine holds it as
8/// a trait object so `engine.rs` stays free of AW-runtime construction details
9/// — mirroring [`super::agent_node::AgentNodeHandler`].
10#[async_trait::async_trait]
11pub trait GraphNodeHandler: Send + Sync {
12    /// Execute (or resume) a graph run for this session. `flow_input`
13    /// expects `{"user_text": "..."}`; returns
14    /// `{"reply", "trail", "terminated_by"}` — the same envelope as DwAgent.
15    async fn execute(
16        &self,
17        tenant_id: &str,
18        env_id: &str,
19        graph_id: &str,
20        session_id: &str,
21        flow_input: &Value,
22    ) -> Result<Value>;
23}
24
25// ---------------------------------------------------------------------------
26// agentic-worker feature: full DwAgentGraph / GraphExecutor integration
27// ---------------------------------------------------------------------------
28
29#[cfg(feature = "agentic-worker")]
30mod aw {
31    use std::collections::HashMap;
32    use std::sync::Arc;
33    use std::time::Duration;
34
35    use anyhow::Result;
36    use greentic_aw_runtime::CachingGraphProvider;
37    use greentic_aw_runtime::HttpGraphProvider;
38    use greentic_aw_runtime::ToolLedger;
39    use greentic_aw_runtime::config_provider::InMemoryConfigProvider;
40    use greentic_aw_runtime::error::{AgentError, ConfigError};
41    use greentic_aw_runtime::graph::{
42        AgentTurnFn, AgentTurnRequest, AgentTurnResult, ApprovalFn, ApprovalOutcome,
43        ApprovalRequest, BoxFut, CheckpointError, CheckpointStore, GraphConfig, GraphExecError,
44        GraphExecutor, GraphRole, GraphRunState, RunStatus, SupervisorFn, SupervisorRequest,
45        SupervisorResult, ToolCallRequest, ToolFn,
46    };
47    use greentic_aw_runtime::state::{AgentStateStore, ChatMessage, ConversationState};
48    use greentic_aw_runtime::tools::dispatch_tool_call;
49    use greentic_aw_runtime::{
50        AgentConfig, AgentInput, AgentLimits, AgentOutput, AgentRuntime, LlmBackend,
51        LlmProviderRef, StepObserver, Telemetry, TenantContext, TokenMeter, ToolRef,
52    };
53    use greentic_ext_runtime::ExtensionRuntime;
54    use serde_json::{Value, json};
55
56    use crate::runner::knowledge_index::IndexMount;
57    use crate::trace::agent_audit::AgentAuditObserver;
58    use crate::trace::audit_sink::AuditSink;
59
60    use super::GraphNodeHandler;
61
62    use super::super::agent_node::tenant_ctx_for_audit;
63
64    /// Fixed, user-safe reply returned when a graph run fails. The detailed
65    /// error is logged but never surfaced to the flow output, so internal
66    /// failure modes do not leak to end users. Mirrors
67    /// [`super::super::agent_node`]'s `SANITISED_ERROR_REPLY`.
68    const SANITISED_ERROR_REPLY: &str = "Something went wrong. Please try again.";
69
70    /// Reply returned when the requested graph is not available (no such graph
71    /// in the provider). User-safe; the missing-graph id is logged separately.
72    const GRAPH_UNAVAILABLE_REPLY: &str =
73        "This worker isn't available right now. Please try again later.";
74
75    /// Resolution sentinel emitted by the agent's reply when it considers the
76    /// issue fully resolved. Matched case-insensitively and stripped from the
77    /// visible reply. Copied verbatim from the greentic-designer spike
78    /// (`src/orchestrate/agent_graph/agent_turn.rs`).
79    const RESOLVED_SENTINEL: &str = "[[RESOLVED]]";
80
81    /// Upper bound on the number of fresh-run-id suffixes tried when a session's
82    /// run id is already in a terminal state (see [`derive_run_id`]).
83    const MAX_RUN_ID_SUFFIX: u32 = 100;
84
85    /// Error returned by [`RuntimeGraphNodeHandler::derive_run_id`].
86    ///
87    /// Kept local to `runner-host`: `GraphExecError` (from `greentic-aw-runtime`)
88    /// has no suffix-exhaustion variant and we should not pollute the upstream
89    /// crate with a runner-host-specific concern.
90    #[derive(Debug, thiserror::Error)]
91    enum RunIdError {
92        /// Checkpoint IO failed while scanning for a free slot.
93        ///
94        /// Note: `checkpoint.load` returns `CheckpointError` directly (not
95        /// `GraphExecError`), so we convert both via their respective `From`
96        /// impls. `GraphExecError::Checkpoint` wraps `CheckpointError` upstream;
97        /// here we keep the original for a tighter error surface.
98        #[error(transparent)]
99        Checkpoint(#[from] CheckpointError),
100        /// All `MAX_RUN_ID_SUFFIX` slots for this session are occupied (terminal).
101        /// Distinct from `GraphExecError::IterationCap` (graph visit limit) so
102        /// the caller can surface a targeted user reply.
103        #[error("all run-id slots exhausted for base run `{base_run_id}`")]
104        SuffixExhausted { base_run_id: String },
105    }
106
107    /// `true` when `reply` contains the resolution sentinel (case-insensitive).
108    fn detect_resolved(reply: &str) -> bool {
109        reply
110            .to_ascii_lowercase()
111            .contains(&RESOLVED_SENTINEL.to_ascii_lowercase())
112    }
113
114    /// Strip the sentinel from `reply` (first case-insensitive occurrence) and
115    /// trim surrounding whitespace so the user-visible text is clean.
116    fn strip_sentinel(reply: &str) -> String {
117        let lower = reply.to_ascii_lowercase();
118        if let Some(idx) = lower.find(&RESOLVED_SENTINEL.to_ascii_lowercase()) {
119            let mut out = reply.to_string();
120            out.replace_range(idx..idx + RESOLVED_SENTINEL.len(), "");
121            return out.trim().to_string();
122        }
123        reply.trim().to_string()
124    }
125
126    // -----------------------------------------------------------------------
127    // GraphConfigSource
128    // -----------------------------------------------------------------------
129
130    /// Resolves a [`GraphConfig`] for a `(tenant, graph_id)` pair.
131    ///
132    /// Object-safe (returns [`BoxFut`]) so it can be held as
133    /// `Arc<dyn GraphConfigSource>`. The pack loader (Task 8) fills the
134    /// concrete implementation; tests use [`InMemoryGraphProvider`].
135    pub trait GraphConfigSource: Send + Sync {
136        fn graph_config<'a>(
137            &'a self,
138            tenant: &'a TenantContext,
139            graph_id: &'a str,
140        ) -> BoxFut<'a, Result<GraphConfig, ConfigError>>;
141    }
142
143    /// [`GraphConfigSource`] backed by an in-memory `graph_id -> GraphConfig`
144    /// map. Graphs are operator-global for the MVP: lookup is keyed purely by
145    /// `graph_id`; the `tenant` argument is accepted (to satisfy the trait
146    /// contract) but not used for keying. Reuses [`ConfigError::AgentNotFound`]
147    /// as the crate's canonical "not found" variant.
148    pub struct InMemoryGraphProvider {
149        graphs: HashMap<String, GraphConfig>,
150    }
151
152    impl InMemoryGraphProvider {
153        /// Wrap a `graph_id -> GraphConfig` map in a [`GraphConfigSource`].
154        pub fn new(graphs: HashMap<String, GraphConfig>) -> Self {
155            Self { graphs }
156        }
157    }
158
159    impl GraphConfigSource for InMemoryGraphProvider {
160        fn graph_config<'a>(
161            &'a self,
162            _tenant: &'a TenantContext,
163            graph_id: &'a str,
164        ) -> BoxFut<'a, Result<GraphConfig, ConfigError>> {
165            let found = self.graphs.get(graph_id).cloned();
166            let graph_id_owned = graph_id.to_string();
167            Box::pin(async move { found.ok_or(ConfigError::AgentNotFound(graph_id_owned)) })
168        }
169    }
170
171    // -----------------------------------------------------------------------
172    // GraphConfigSource adapter for CachingGraphProvider<HttpGraphProvider>
173    // -----------------------------------------------------------------------
174
175    /// Adapts [`CachingGraphProvider<HttpGraphProvider>`] into the
176    /// [`GraphConfigSource`] trait so it can be stored as an
177    /// `Arc<dyn GraphConfigSource>` alongside [`InMemoryGraphProvider`].
178    ///
179    /// This is a 5-line adapter that bridges the inherent-method API of
180    /// `CachingGraphProvider` (defined in `greentic-aw-runtime`) into the
181    /// trait object used by `runner-host`.
182    impl GraphConfigSource for CachingGraphProvider<HttpGraphProvider> {
183        fn graph_config<'a>(
184            &'a self,
185            tenant: &'a TenantContext,
186            graph_id: &'a str,
187        ) -> BoxFut<'a, Result<GraphConfig, ConfigError>> {
188            Box::pin(async move { self.graph_config(tenant, graph_id).await })
189        }
190    }
191
192    // -----------------------------------------------------------------------
193    // LayeredGraphProvider
194    // -----------------------------------------------------------------------
195
196    /// Tries the primary [`GraphConfigSource`], falling back to the secondary
197    /// when the primary reports the graph missing or has an infrastructure
198    /// failure. A `Misconfigured` error is propagated, never masked by the
199    /// fallback — matching [`greentic_aw_runtime::LayeredConfigProvider`]'s
200    /// semantics exactly.
201    ///
202    /// Fallback triggers:
203    /// - `ConfigError::AgentNotFound` — graph absent from the primary (HTTP
204    ///   registry doesn't know it yet; local pack may have it).
205    /// - `ConfigError::Internal` — transient infrastructure failure (network
206    ///   timeout, 5xx) — local pack can serve as a degraded fallback.
207    ///
208    /// Non-fallback (surfaces immediately):
209    /// - `ConfigError::Misconfigured` — corrupt document or bad auth token;
210    ///   the operator must fix the document — silently serving stale local
211    ///   data would mask the problem.
212    pub struct LayeredGraphProvider<P: GraphConfigSource, F: GraphConfigSource> {
213        primary: P,
214        fallback: F,
215    }
216
217    impl<P: GraphConfigSource, F: GraphConfigSource> LayeredGraphProvider<P, F> {
218        pub fn new(primary: P, fallback: F) -> Self {
219            Self { primary, fallback }
220        }
221    }
222
223    impl<P: GraphConfigSource, F: GraphConfigSource> GraphConfigSource for LayeredGraphProvider<P, F> {
224        fn graph_config<'a>(
225            &'a self,
226            tenant: &'a TenantContext,
227            graph_id: &'a str,
228        ) -> BoxFut<'a, Result<GraphConfig, ConfigError>> {
229            Box::pin(async move {
230                match self.primary.graph_config(tenant, graph_id).await {
231                    Ok(cfg) => Ok(cfg),
232                    Err(ConfigError::AgentNotFound(_)) | Err(ConfigError::Internal(_)) => {
233                        self.fallback.graph_config(tenant, graph_id).await
234                    }
235                    // Misconfigured + any future ConfigError variant: surface,
236                    // never mask. New variants fall through here and propagate
237                    // by default; revisit only if a new variant should fall back.
238                    Err(other) => Err(other),
239                }
240            })
241        }
242    }
243
244    // -----------------------------------------------------------------------
245    // Admin graph registry wiring
246    // -----------------------------------------------------------------------
247
248    /// Build a cached [`HttpGraphProvider`] from `GREENTIC_AW_ADMIN_ENDPOINT` +
249    /// `GREENTIC_AW_ADMIN_TOKEN`. Returns `None` when either is unset/empty,
250    /// so the runtime keeps using the local pack provider alone.
251    ///
252    /// Mirrors [`super::agent_node::registry_from_env`] exactly — same env
253    /// vars, same "both must be present" semantics.
254    fn graph_registry_from_env() -> Option<CachingGraphProvider<HttpGraphProvider>> {
255        let endpoint = std::env::var("GREENTIC_AW_ADMIN_ENDPOINT")
256            .ok()
257            .filter(|s| !s.is_empty())?;
258        let token = std::env::var("GREENTIC_AW_ADMIN_TOKEN")
259            .ok()
260            .filter(|s| !s.is_empty())?;
261        Some(CachingGraphProvider::new(HttpGraphProvider::new(
262            endpoint, token,
263        )))
264    }
265
266    // -----------------------------------------------------------------------
267    // Pack-sidecar graph loader
268    // -----------------------------------------------------------------------
269
270    /// Parse an `agent-graph.json` sidecar (raw bytes from a `.gtpack`) into a
271    /// validated [`GraphConfig`].
272    ///
273    /// Mirrors the lenient posture of
274    /// [`super::super::agent_node::agent_configs_from_manifest`]: every failure
275    /// mode — invalid UTF-8, malformed JSON, schema-version mismatch, or graph
276    /// validation error — is logged via [`tracing::warn!`] (with `pack_id`) and
277    /// yields `None`, so a single bad graph never prevents the rest of the pack
278    /// from loading. The `pack_id` argument is used only in log messages.
279    pub fn graph_config_from_sidecar(pack_id: &str, bytes: &[u8]) -> Option<GraphConfig> {
280        let raw = match std::str::from_utf8(bytes) {
281            Ok(raw) => raw,
282            Err(error) => {
283                tracing::warn!(
284                    pack_id,
285                    error = %error,
286                    "skipping agent-graph sidecar: not valid UTF-8"
287                );
288                return None;
289            }
290        };
291        match GraphConfig::from_json(raw) {
292            Ok(config) => Some(config),
293            Err(error) => {
294                tracing::warn!(
295                    pack_id,
296                    error = %error,
297                    "skipping malformed agent-graph sidecar in pack"
298                );
299                None
300            }
301        }
302    }
303
304    // -----------------------------------------------------------------------
305    // Production graph-handler construction
306    // -----------------------------------------------------------------------
307
308    /// Build the production `DwAgentGraph` handler if the environment is
309    /// configured. Mirrors
310    /// [`super::super::agent_node::build_agent_node_handler`]: it returns `None`
311    /// (so `DwAgentGraph` flow dispatch errors clearly) under any of these
312    /// graceful-degradation conditions:
313    /// - `graphs` is empty (no graphs from any pack sidecar);
314    /// - `GREENTIC_AW_REDIS_URL` is unset/empty;
315    /// - the AW Redis connection fails;
316    /// - the extension runtime fails to initialise.
317    ///
318    /// The shared runtime Arcs (state store, ext runtime, LLM backend,
319    /// telemetry, token meter, ledger) are built exactly as for the single-agent
320    /// path; the durable checkpoint store reuses the same multiplexed Redis
321    /// connection manager.
322    ///
323    /// `tenant`, `secrets` and `unit` are the values the `dw.agent` handler of
324    /// the same `TenantRuntime` receives (`unit` is the deployed unit's
325    /// `bundle_id`, `None` on the legacy tenant-only path). They feed only the
326    /// pack-carried A2A tool source ([`graph_a2a_source`]) and, `tenant` and
327    /// `secrets` only, the Chronicle-index knowledge mount ([`IndexMount`]);
328    /// the rest of this path keeps its env-only secrets, as before.
329    ///
330    /// Bills every turn through `agent_node::resolve_billing_meter(None)` (the
331    /// env-configured sink, or none); see [`build_graph_node_handler_metered`].
332    #[allow(clippy::too_many_arguments)]
333    pub async fn build_graph_node_handler(
334        graphs: HashMap<String, GraphConfig>,
335        audit_sink: Option<AuditSink>,
336        packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
337        merged_agents: HashMap<String, AgentConfig>,
338        tenant: String,
339        secrets: crate::secrets::DynSecretsManager,
340        unit: Option<String>,
341    ) -> Option<Arc<dyn GraphNodeHandler>> {
342        build_graph_node_handler_metered(
343            graphs,
344            audit_sink,
345            packs,
346            merged_agents,
347            tenant,
348            secrets,
349            unit,
350            super::super::agent_node::resolve_billing_meter(None),
351        )
352        .await
353    }
354
355    /// [`build_graph_node_handler`] with the `TenantRuntime`'s already-resolved
356    /// billing sink, shared with its `dw.agent` runtime. Every agent and
357    /// supervisor turn bills through it, attributed to `unit` as `project_id`.
358    #[allow(clippy::too_many_arguments)]
359    pub(crate) async fn build_graph_node_handler_metered(
360        graphs: HashMap<String, GraphConfig>,
361        audit_sink: Option<AuditSink>,
362        packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
363        merged_agents: HashMap<String, AgentConfig>,
364        tenant: String,
365        secrets: crate::secrets::DynSecretsManager,
366        unit: Option<String>,
367        billing_meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
368    ) -> Option<Arc<dyn GraphNodeHandler>> {
369        use crate::runner::aw_backends::{AwBackends, build_aw_backends};
370        use greentic_aw_runtime::OtelTelemetry;
371
372        if graphs.is_empty() {
373            return None; // nothing to serve
374        }
375
376        let AwBackends {
377            state_store,
378            token_meter,
379            tool_ledger: ledger,
380            checkpoint_store: checkpoint,
381        } = build_aw_backends().await?;
382
383        // Process-level graph serve path has no per-tenant secrets context;
384        // tool secrets resolve from the env only. It likewise has no embedding
385        // host, so the ext LLM port falls back to the env-keyed `EnvLlmPort`.
386        let ext_runtime = super::super::agent_node::build_ext_runtime(
387            std::sync::Arc::new(super::super::agent_node::EnvSecretsBackend),
388            None,
389            None,
390            // Process-level path: no embedding host, so no artifact port.
391            None,
392            &packs,
393        )?;
394        let llm = super::super::agent_node::build_llm_backend(&ext_runtime);
395        let telemetry = Arc::new(OtelTelemetry);
396
397        let graph_count = graphs.len();
398        // Build the graph config source: HTTP registry (cached) primary →
399        // InMemoryGraphProvider (local packs) fallback, when the admin env
400        // vars are configured; otherwise local packs only.
401        //
402        // Mirrors the agent-config composition in
403        // `agent_node::build_agent_node_handler`:
404        //   Some(http) → CachingConfigProvider(Layered(http, overlay))
405        //   None       → CachingConfigProvider(overlay)
406        //
407        // The graph path skips the ManifestToolOverlay (no manifest overlay
408        // exists for graphs) and the CachingGraphProvider is already embedded
409        // inside the `CachingGraphProvider<HttpGraphProvider>` returned by
410        // `graph_registry_from_env`. The local InMemoryGraphProvider needs no
411        // separate cache (it is in-memory and O(1)).
412        let local = InMemoryGraphProvider::new(graphs);
413        let provider: Arc<dyn GraphConfigSource> = match graph_registry_from_env() {
414            Some(http) => Arc::new(LayeredGraphProvider::new(http, local)),
415            None => Arc::new(local),
416        };
417
418        let a2a_source = graph_a2a_source(&packs, &tenant, &secrets, unit.as_deref());
419        // Chronicle-index retrieval for `agent_ref` turns. Captured here, with
420        // the runtime's own secrets tenant, so the mount does not depend on the
421        // tenant each turn happens to run under.
422        let index_mount = IndexMount {
423            secrets: Some(super::super::agent_node::mcp_secrets_manager(&secrets)),
424            secret_tenant: Some(tenant.clone()),
425        };
426        let handler = RuntimeGraphNodeHandler::from_parts(
427            provider,
428            checkpoint,
429            state_store,
430            ext_runtime,
431            llm,
432            telemetry,
433            token_meter,
434            ledger,
435            audit_sink,
436            packs,
437            Arc::new(merged_agents),
438            a2a_source,
439            index_mount,
440        )
441        .with_billing(billing_meter, unit);
442
443        tracing::info!(graph_count, "AW graph runtime constructed");
444        Some(Arc::new(handler))
445    }
446
447    /// The pack-carried A2A tool source for a graph handler's agent turns and
448    /// Tool nodes.
449    ///
450    /// Built from exactly the inputs the single-turn `dw.agent` runtime uses —
451    /// the same packs, tenant and deployed unit, and the same remote-tool
452    /// secrets manager (`agent_node::mcp_secrets_manager`, so an explicit
453    /// `SECRETS_BACKEND` wins here too) — through the same helper, so
454    /// `GREENTIC_AW_A2A=0`, first-pack-wins dedup and the credential URI
455    /// (`secrets://default/<tenant>/<auth_team|_>/a2a/<agent_id>[.unit-<seg>]`)
456    /// cannot differ between the two paths.
457    ///
458    /// Built once per handler, not per turn: the handler belongs to one
459    /// `TenantRuntime`, so tenant, unit and packs are fixed for its lifetime,
460    /// and rebuilding per turn would throw away the source's agent-card cache.
461    pub(crate) fn graph_a2a_source(
462        packs: &[Arc<crate::pack::PackRuntime>],
463        tenant: &str,
464        secrets: &crate::secrets::DynSecretsManager,
465        unit: Option<&str>,
466    ) -> Option<Arc<greentic_aw_runtime::A2aToolSource>> {
467        crate::runner::a2a_pack_source::a2a_source_from_packs(
468            packs,
469            tenant,
470            Some(super::super::agent_node::mcp_secrets_manager(secrets)),
471            unit,
472        )
473    }
474
475    // -----------------------------------------------------------------------
476    // RuntimeGraphNodeHandler
477    // -----------------------------------------------------------------------
478
479    /// Supplies the per-visit [`AgentTurnFn`]/[`SupervisorFn`] closures used by
480    /// [`RuntimeGraphNodeHandler::execute`].
481    ///
482    /// `execute` already receives the graph run's real `tenant_id`/`env_id`
483    /// (see its signature), but [`AgentTurnFn`]/[`SupervisorFn`] (from
484    /// `greentic-aw-runtime`, not modifiable here) only pass an
485    /// [`AgentTurnRequest`]/[`SupervisorRequest`] at invocation time — neither
486    /// carries a tenant. So the audit sink + real tenant cannot be baked into
487    /// a closure built once at handler-construction time and reused
488    /// call-after-call; instead `execute` asks this seam for a *fresh*
489    /// closure on every call, passing the sink + the real tenant it just
490    /// resolved from its own parameters (EPIC-B B-3b Task 1 plumbing; Task 2
491    /// makes `run_one_agent_turn`/`run_one_supervisor_turn` actually build an
492    /// `AgentAuditObserver` from them instead of ignoring them).
493    ///
494    /// [`RuntimeTurnSource`] (production) rebuilds via
495    /// [`build_agent_turn`]/[`build_supervisor`] from the shared runtime Arcs
496    /// every call. [`FixedTurnSource`] (test-only, via
497    /// [`RuntimeGraphNodeHandler::with_effects`]) ignores the sink/tenant and
498    /// hands back the same injected closures every time, preserving today's
499    /// deterministic-effect test style untouched.
500    trait TurnEffectSource: Send + Sync {
501        fn agent_turn(
502            &self,
503            audit_sink: Option<AuditSink>,
504            real_tenant: greentic_types::TenantCtx,
505            billing: TurnBilling,
506        ) -> AgentTurnFn;
507        fn supervisor(
508            &self,
509            audit_sink: Option<AuditSink>,
510            real_tenant: greentic_types::TenantCtx,
511            billing: TurnBilling,
512        ) -> SupervisorFn;
513    }
514
515    /// How a graph turn's LLM spend is billed: the `TenantRuntime`'s shared
516    /// billing sink (`agent_node::resolve_billing_meter` — the host-installed
517    /// per-unit meter, else the env-configured one, else none) and the deployed
518    /// unit (`bundle_id`) the spend is attributed to as `project_id`.
519    ///
520    /// Before this existed every graph turn ran on the per-visit runtime's
521    /// default `NoopBillingMeter` under a synthetic `("graph", "run")` tenant,
522    /// so agent-graph workers emitted no usage at all.
523    #[derive(Clone, Default)]
524    pub(crate) struct TurnBilling {
525        pub(crate) meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
526        pub(crate) project_id: Option<String>,
527        /// Per-run scope (`<session>__<graph>`) prefixed onto the per-visit
528        /// agent conversation id. `None` leaves the id unscoped.
529        pub(crate) state_scope: Option<String>,
530    }
531
532    impl TurnBilling {
533        /// The stored-conversation id for a per-visit agent, scoped to this run.
534        fn scoped_session(&self, base: &str) -> String {
535            match &self.state_scope {
536                Some(scope) => format!("{scope}__{base}"),
537                None => base.to_string(),
538            }
539        }
540
541        /// The [`TenantContext`] a graph turn runs (and bills) under: the REAL
542        /// tenant/env the flow node was dispatched with, plus the unit.
543        fn turn_tenant(&self, real_tenant: &greentic_types::TenantCtx) -> TenantContext {
544            TenantContext::new(real_tenant.tenant_id.as_str(), real_tenant.env.as_str())
545                .with_project_id(self.project_id.clone())
546        }
547
548        /// Install the shared sink on a per-visit runtime; no sink leaves the
549        /// runtime's `NoopBillingMeter` in place.
550        fn install(&self, runtime: AgentRuntime) -> AgentRuntime {
551            match &self.meter {
552                Some(meter) => runtime.with_billing_meter(Arc::clone(meter)),
553                None => runtime,
554            }
555        }
556    }
557
558    /// Production [`TurnEffectSource`]: holds the constituent runtime Arcs
559    /// (extension runtime, LLM backend, telemetry, token meter, ledger; the
560    /// state store lives directly on [`RuntimeGraphNodeHandler`]) so it can
561    /// build a lightweight [`AgentRuntime`] *per agent visit* with a fresh
562    /// single-entry [`InMemoryConfigProvider`] — mirroring the
563    /// greentic-designer spike's per-visit runtime construction.
564    struct RuntimeTurnSource {
565        state_store: Arc<dyn AgentStateStore>,
566        ext_runtime: Arc<ExtensionRuntime>,
567        llm: Arc<dyn LlmBackend>,
568        telemetry: Arc<dyn Telemetry>,
569        token_meter: Arc<dyn TokenMeter>,
570        ledger: Arc<dyn ToolLedger>,
571        /// MCP tool source, built ONCE (mirrors the other Arcs) so its 5-min
572        /// TTL catalog cache + warmed HTTP client are reused across every
573        /// graph-agent visit rather than rebuilt (empty-cache) per turn.
574        mcp_source: Option<Arc<greentic_aw_runtime::McpToolSource>>,
575        /// Pack-carried A2A tool source ([`graph_a2a_source`]), built once for
576        /// the same reason as `mcp_source`: its agent-card cache is reused
577        /// across every graph-agent visit. The supervisor stays tool-free.
578        a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
579        /// The tenant's loaded packs, used to build a fresh, tenant-scoped
580        /// [`greentic_aw_runtime::ComponentToolSource`] on EVERY turn (unlike
581        /// `mcp_source`, this is NOT built once — the component source is
582        /// tenant-pinned, and building it per turn from the in-memory pack
583        /// list is cheap; see [`run_one_agent_turn`]).
584        packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
585        /// Process-level merged agent configs (pack + operator-overridden),
586        /// threaded into [`run_one_agent_turn`] so a graph node's `agent_ref`
587        /// resolves to that agent's full [`AgentConfig`] at turn time.
588        merged_agents: Arc<HashMap<String, AgentConfig>>,
589        /// Chronicle-index knowledge mount for `agent_ref` turns, carrying the
590        /// real tenant's secrets (see [`build_graph_node_handler`]).
591        index_mount: IndexMount,
592    }
593
594    impl TurnEffectSource for RuntimeTurnSource {
595        fn agent_turn(
596            &self,
597            audit_sink: Option<AuditSink>,
598            real_tenant: greentic_types::TenantCtx,
599            billing: TurnBilling,
600        ) -> AgentTurnFn {
601            build_agent_turn(
602                self.state_store.clone(),
603                self.ext_runtime.clone(),
604                self.llm.clone(),
605                self.telemetry.clone(),
606                self.token_meter.clone(),
607                self.ledger.clone(),
608                self.mcp_source.clone(),
609                self.a2a_source.clone(),
610                self.packs.clone(),
611                self.merged_agents.clone(),
612                self.index_mount.clone(),
613                audit_sink,
614                real_tenant,
615                billing,
616            )
617        }
618
619        fn supervisor(
620            &self,
621            audit_sink: Option<AuditSink>,
622            real_tenant: greentic_types::TenantCtx,
623            billing: TurnBilling,
624        ) -> SupervisorFn {
625            build_supervisor(
626                self.state_store.clone(),
627                self.ext_runtime.clone(),
628                self.llm.clone(),
629                self.telemetry.clone(),
630                self.token_meter.clone(),
631                self.ledger.clone(),
632                self.merged_agents.clone(),
633                audit_sink,
634                real_tenant,
635                billing,
636            )
637        }
638    }
639
640    /// **Test-only** [`TurnEffectSource`] that always returns the same
641    /// injected closures, ignoring the audit sink/tenant. Lets
642    /// [`RuntimeGraphNodeHandler::with_effects`] keep injecting deterministic
643    /// effects without needing real `AgentRuntime` Arcs.
644    #[cfg(test)]
645    struct FixedTurnSource {
646        agent_turn: AgentTurnFn,
647        supervisor: SupervisorFn,
648    }
649
650    #[cfg(test)]
651    impl TurnEffectSource for FixedTurnSource {
652        fn agent_turn(
653            &self,
654            _audit_sink: Option<AuditSink>,
655            _real_tenant: greentic_types::TenantCtx,
656            _billing: TurnBilling,
657        ) -> AgentTurnFn {
658            self.agent_turn.clone()
659        }
660
661        fn supervisor(
662            &self,
663            _audit_sink: Option<AuditSink>,
664            _real_tenant: greentic_types::TenantCtx,
665            _billing: TurnBilling,
666        ) -> SupervisorFn {
667            self.supervisor.clone()
668        }
669    }
670
671    /// Production [`GraphNodeHandler`] wrapping the durable graph executor.
672    ///
673    /// Tool dispatch goes through the shared [`ExtensionRuntime`] via
674    /// [`dispatch_tool_call`], with `a2a:` refs routed to the handler's
675    /// pack-carried A2A catalog.
676    pub struct RuntimeGraphNodeHandler {
677        graphs: Arc<dyn GraphConfigSource>,
678        checkpoint: Arc<dyn CheckpointStore>,
679        state_store: Arc<dyn AgentStateStore>,
680        turn_source: Arc<dyn TurnEffectSource>,
681        tool: ToolFn,
682        approval: ApprovalFn,
683        /// Best-effort agent-step audit sink (EPIC-B B-3b), threaded from
684        /// [`build_graph_node_handler`]. `None` when no NATS audit client is
685        /// configured (`GREENTIC_EVENTS_NATS_URL` unset/unreachable) — the
686        /// `run_agent_step` seam then stays on the plain `.step()` path,
687        /// byte-identical regardless of this field's value.
688        audit_sink: Option<AuditSink>,
689        /// Billing sink + unit for every agent and supervisor turn (see
690        /// [`TurnBilling`]). Default: no sink, no unit — set by
691        /// [`RuntimeGraphNodeHandler::with_billing`].
692        billing: TurnBilling,
693    }
694
695    impl RuntimeGraphNodeHandler {
696        /// Bill every agent and supervisor turn through `meter`, attributed to
697        /// the deployed unit `project_id` (the revision's `bundle_id`). `None`
698        /// keeps the per-visit runtimes on `NoopBillingMeter`.
699        #[must_use]
700        pub fn with_billing(
701            mut self,
702            meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
703            project_id: Option<String>,
704        ) -> Self {
705            self.billing = TurnBilling {
706                meter,
707                project_id,
708                state_scope: None,
709            };
710            self
711        }
712
713        /// Build a handler from the runtime's constituent parts.
714        ///
715        /// **Deviation from the Task-7 `from_runtime(runtime: Arc<AgentRuntime>, …)`
716        /// signature:** `AgentRuntime`'s inner Arcs (`ext_runtime`, `llm`,
717        /// `telemetry`, `token_meter`, `ledger`) are `pub(crate)` and cannot be
718        /// extracted from an `Arc<AgentRuntime>` outside the `greentic-aw-runtime`
719        /// crate, so a per-visit runtime cannot be reconstructed from a shared
720        /// `AgentRuntime`. The task explicitly allows this: "an acceptable
721        /// alternative is a `from_parts(...)` constructor taking those Arcs
722        /// directly." The pack loader (Task 8) already holds these Arcs when it
723        /// would otherwise build an `AgentRuntime`, so it wires them here instead.
724        #[allow(clippy::too_many_arguments)]
725        pub fn from_parts(
726            graphs: Arc<dyn GraphConfigSource>,
727            checkpoint: Arc<dyn CheckpointStore>,
728            state_store: Arc<dyn AgentStateStore>,
729            ext_runtime: Arc<ExtensionRuntime>,
730            llm: Arc<dyn LlmBackend>,
731            telemetry: Arc<dyn Telemetry>,
732            token_meter: Arc<dyn TokenMeter>,
733            ledger: Arc<dyn ToolLedger>,
734            audit_sink: Option<AuditSink>,
735            packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
736            merged_agents: Arc<HashMap<String, AgentConfig>>,
737            a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
738            index_mount: IndexMount,
739        ) -> Self {
740            // The Tool node and the agent turns share one A2A source, so an
741            // `a2a:` ref resolves identically whichever of the two dispatches it.
742            let tool = build_tool(ext_runtime.clone(), a2a_source.clone());
743            // Built once here (like the other Arcs) so the MCP catalog cache +
744            // HTTP client are reused across every graph-agent turn.
745            // No per-tenant secrets manager reachable in this constructor
746            // (out of scope for this task — see `agent_node::mcp_source_from_env`'s
747            // doc comment); matches this path's pre-existing behavior.
748            let mcp_source = super::super::agent_node::mcp_source_from_env(None);
749            let turn_source: Arc<dyn TurnEffectSource> = Arc::new(RuntimeTurnSource {
750                state_store: state_store.clone(),
751                ext_runtime,
752                llm,
753                telemetry,
754                token_meter,
755                ledger,
756                mcp_source,
757                a2a_source,
758                packs,
759                merged_agents,
760                index_mount,
761            });
762            // NOTE: the real `ApprovalFn` is designer-provided (it wires the
763            // `greentic.approval.request.v1` / `.response.v1` NATS round trip
764            // so a human decision can arrive asynchronously). This in-process
765            // runner-host path does not yet have that transport wired up, so
766            // it always parks (`Awaiting`) — safe (a graph run simply stays
767            // `AwaitingInput`, and `derive_run_id` resumes rather than forks
768            // it on every later call for the same session) but not yet
769            // resolvable from here. A future designer-side approval bridge
770            // (subscriber + node) replaces this with a real consumer.
771            let approval = default_approval_awaiting();
772            Self {
773                graphs,
774                checkpoint,
775                state_store,
776                turn_source,
777                tool,
778                approval,
779                audit_sink,
780                billing: TurnBilling::default(),
781            }
782        }
783
784        /// **Test-only** constructor that injects effect closures directly,
785        /// bypassing per-visit [`AgentRuntime`] construction. Not available
786        /// outside `#[cfg(test)]`; production code must use [`from_parts`].
787        ///
788        /// [`from_parts`]: RuntimeGraphNodeHandler::from_parts
789        #[cfg(test)]
790        #[allow(clippy::too_many_arguments)]
791        pub(crate) fn with_effects(
792            graphs: Arc<dyn GraphConfigSource>,
793            checkpoint: Arc<dyn CheckpointStore>,
794            state_store: Arc<dyn AgentStateStore>,
795            agent_turn: AgentTurnFn,
796            tool: ToolFn,
797            supervisor: SupervisorFn,
798            approval: ApprovalFn,
799        ) -> Self {
800            Self {
801                graphs,
802                checkpoint,
803                state_store,
804                turn_source: Arc::new(FixedTurnSource {
805                    agent_turn,
806                    supervisor,
807                }),
808                tool,
809                approval,
810                audit_sink: None,
811                billing: TurnBilling::default(),
812            }
813        }
814
815        /// Resolve the run id to drive for this `(session, graph)` and whether
816        /// the existing record (if any) is mid-flight.
817        ///
818        /// Base run id is `"{safe_session}__{graph_id}"` where `safe_session` is
819        /// the incoming `session_id` with every `':'` replaced by `'_'`.
820        ///
821        /// **Why sanitize `':'`?**  Flow session ids frequently embed channel
822        /// correlation ids that contain colons (e.g. MS Teams thread ids such as
823        /// `msteams:thread:19xyz`). The checkpoint store key contract forbids
824        /// `':'`, so using the raw session id causes every such graph run to fail
825        /// at save-time. The replacement is stable: the same incoming
826        /// `session_id` always maps to the same `safe_session`, so checkpoint
827        /// resume works correctly across calls.
828        ///
829        /// When the base slot is already terminal (`Succeeded`/`Failed`), retry
830        /// `"{safe_session}__{graph_id}__{n}"` for `n = 2..` until a slot is
831        /// absent (→ start fresh) or non-terminal — `Running` or `AwaitingInput`
832        /// (→ resume). Bounded at
833        /// [`MAX_RUN_ID_SUFFIX`]. Exhausting all suffixes returns
834        /// [`RunIdError::SuffixExhausted`] (distinct from
835        /// [`GraphExecError::IterationCap`] so the caller can surface a
836        /// targeted reply).
837        async fn derive_run_id(
838            &self,
839            tenant: &TenantContext,
840            graph_id: &str,
841            session_id: &str,
842        ) -> Result<RunSlot, RunIdError> {
843            // Sanitize colons: flow session ids (e.g. Teams thread correlation
844            // ids) may contain ':' which the checkpoint key contract forbids.
845            let safe_session = session_id.replace(':', "_");
846            let base = format!("{safe_session}__{graph_id}");
847            match self.checkpoint.load(tenant, &base).await? {
848                None => return Ok(RunSlot::start(base)),
849                // `AwaitingInput` is a parked, non-terminal state (the run is
850                // paused at an approval node, not done) — same resume
851                // treatment as `Running`. Without this arm, every call after
852                // a park would fall through to the terminal branch below and
853                // mint a fresh `__n` run id, orphaning the parked run forever
854                // (it can never be decided because nothing ever resumes it)
855                // and silently forking the conversation.
856                Some(rec)
857                    if matches!(rec.status, RunStatus::Running | RunStatus::AwaitingInput) =>
858                {
859                    return Ok(RunSlot::resume(base));
860                }
861                Some(_) => {}
862            }
863            for n in 2..=MAX_RUN_ID_SUFFIX {
864                let candidate = format!("{safe_session}__{graph_id}__{n}");
865                match self.checkpoint.load(tenant, &candidate).await? {
866                    None => return Ok(RunSlot::start(candidate)),
867                    Some(rec)
868                        if matches!(rec.status, RunStatus::Running | RunStatus::AwaitingInput) =>
869                    {
870                        return Ok(RunSlot::resume(candidate));
871                    }
872                    Some(_) => continue,
873                }
874            }
875            // All suffix slots are occupied (terminal). This is a distinct
876            // error from the graph's own IterationCap: it means the session has
877            // exhausted the run-id namespace, not that any single run looped.
878            Err(RunIdError::SuffixExhausted { base_run_id: base })
879        }
880    }
881
882    /// Outcome of [`RuntimeGraphNodeHandler::derive_run_id`]: which run id to
883    /// drive and whether to start it fresh or resume an in-flight record.
884    struct RunSlot {
885        run_id: String,
886        resume: bool,
887    }
888
889    impl RunSlot {
890        fn start(run_id: String) -> Self {
891            Self {
892                run_id,
893                resume: false,
894            }
895        }
896        fn resume(run_id: String) -> Self {
897            Self {
898                run_id,
899                resume: true,
900            }
901        }
902    }
903
904    #[async_trait::async_trait]
905    impl GraphNodeHandler for RuntimeGraphNodeHandler {
906        async fn execute(
907            &self,
908            tenant_id: &str,
909            env_id: &str,
910            graph_id: &str,
911            session_id: &str,
912            flow_input: &Value,
913        ) -> Result<Value> {
914            // Contract mirror of agent_node.rs: a missing/empty `user_text`
915            // resolves to an empty string and the run proceeds (it never returns
916            // Err for this case).
917            let user_text = flow_input
918                .get("user_text")
919                .and_then(Value::as_str)
920                .unwrap_or("")
921                .to_string();
922            // A graph turn cannot open files: say so with the fixed notices
923            // (counts and codes only, no name) instead of dropping them
924            // silently. Parsed exactly like the `dw.agent` path: a file the
925            // host could not store (or a bad / duplicate / over-limit
926            // reference) gets its own skip notice, and only the files the
927            // runner would actually read are counted as "not available".
928            let parsed = crate::runner::agent_node::attachments_from_flow_input(flow_input);
929            let mut user_text = crate::runner::agent_node::text_with_skipped_notices(
930                user_text,
931                &parsed.skipped_codes,
932            );
933            if !parsed.refs.is_empty() {
934                user_text.push_str(
935                    &greentic_aw_runtime::attachments_materialize::unreadable_note(
936                        parsed.refs.len(),
937                    ),
938                );
939            }
940
941            let tenant = TenantContext::new(tenant_id, env_id);
942
943            // Resolve the graph. A missing graph is a user-facing "unavailable"
944            // outcome, never an Err.
945            let cfg = match self.graphs.graph_config(&tenant, graph_id).await {
946                Ok(cfg) => cfg,
947                Err(error) => {
948                    tracing::warn!(error = %error, graph_id, "graph config not found");
949                    return Ok(error_envelope(GRAPH_UNAVAILABLE_REPLY));
950                }
951            };
952
953            // Acquire the session lock before driving (mirrors the single-agent
954            // loop's default 5s wait). Held across the drive via the guard.
955            let _lock = match self
956                .state_store
957                .acquire_lock(&tenant, session_id, Duration::from_secs(5))
958                .await
959            {
960                Ok(guard) => guard,
961                Err(error) => {
962                    tracing::warn!(error = %error, graph_id, session_id, "session lock failed");
963                    return Ok(error_envelope(SANITISED_ERROR_REPLY));
964                }
965            };
966
967            let slot = match self.derive_run_id(&tenant, graph_id, session_id).await {
968                Ok(slot) => slot,
969                Err(RunIdError::SuffixExhausted { .. }) => {
970                    tracing::warn!(
971                        graph_id,
972                        session_id,
973                        "all run-id slots exhausted for session"
974                    );
975                    return Ok(error_envelope(
976                        "Too many runs for this session. Please start a new conversation.",
977                    ));
978                }
979                Err(RunIdError::Checkpoint(error)) => {
980                    tracing::warn!(error = %error, graph_id, session_id, "run-id derivation failed");
981                    return Ok(error_envelope(SANITISED_ERROR_REPLY));
982                }
983            };
984
985            // The real tenant/env `execute` already received — the same one
986            // driving executor/checkpoint/run-id above. (The turn functions
987            // build their per-visit `TenantContext` from it plus the unit —
988            // see `TurnBilling::turn_tenant`.) Rebuilt fresh on
989            // every call — see `TurnEffectSource` — so the sink + real tenant
990            // reach `run_one_agent_turn`/`run_one_supervisor_turn`, which feed
991            // them into the shared `run_agent_step` seam that builds the
992            // `AgentAuditObserver` (EPIC-B B-3b Task 2).
993            let real_tenant = tenant_ctx_for_audit(tenant_id, env_id)
994                .map_err(crate::runner::engine::pre_effect)?;
995            // Per-run conversation scope: the per-visit agent state is stored
996            // under this tenant, so two sessions (or graphs) running the same
997            // node must not address the same stored conversation.
998            let billing = TurnBilling {
999                state_scope: Some(format!("{session_id}__{graph_id}")),
1000                ..self.billing.clone()
1001            };
1002            let agent_turn = self.turn_source.agent_turn(
1003                self.audit_sink.clone(),
1004                real_tenant.clone(),
1005                billing.clone(),
1006            );
1007            let supervisor =
1008                self.turn_source
1009                    .supervisor(self.audit_sink.clone(), real_tenant, billing);
1010
1011            let executor = GraphExecutor::new(
1012                self.checkpoint.clone(),
1013                agent_turn,
1014                self.tool.clone(),
1015                supervisor,
1016                self.approval.clone(),
1017            );
1018
1019            let result = if slot.resume {
1020                executor.resume(&tenant, &slot.run_id).await
1021            } else {
1022                executor
1023                    .start(&tenant, &slot.run_id, &cfg, &user_text)
1024                    .await
1025            };
1026
1027            match result {
1028                // `AwaitingInput` means the run parked at an approval node
1029                // (see `default_approval_awaiting` below): it is neither a
1030                // completed respond nor a failure, so it must not be
1031                // reported as `terminated_by: "respond"` (a caller branching
1032                // on that value would wrongly treat the pause as done) nor
1033                // surfaced as an error. This runner-host path has no
1034                // approval-transport integration yet (that lands with the
1035                // designer NATS bridge), so a parked run has no other
1036                // observable signal beyond this envelope + the warning
1037                // below — the run itself remains durably `AwaitingInput` in
1038                // the checkpoint store and `derive_run_id` resumes it (not
1039                // forks a new run) on every subsequent call for the same
1040                // session until a decision arrives.
1041                Ok(outcome) if outcome.status == RunStatus::AwaitingInput => {
1042                    tracing::warn!(
1043                        graph_id,
1044                        session_id,
1045                        run_id = %slot.run_id,
1046                        "graph run parked awaiting human approval; no approval \
1047                         transport is wired on this in-process runner-host path, \
1048                         so the run stays AwaitingInput until an external decision \
1049                         resolves it"
1050                    );
1051                    Ok(json!({
1052                        "reply": outcome.reply,
1053                        "trail": outcome.trail,
1054                        "terminated_by": "awaiting_approval",
1055                    }))
1056                }
1057                Ok(outcome) => Ok(json!({
1058                    "reply": outcome.reply,
1059                    "trail": outcome.trail,
1060                    "terminated_by": "respond",
1061                })),
1062                Err(error) => {
1063                    tracing::warn!(error = %error, graph_id, session_id, "graph run failed");
1064                    // The DwAgent envelope only carries "respond" / "error".
1065                    // IterationCap (graph's own node-visit limit) gets a distinct,
1066                    // still user-safe reply; every other runtime failure falls back
1067                    // to the generic sanitised message.
1068                    let reply = match error {
1069                        GraphExecError::IterationCap { .. } => {
1070                            "This is taking longer than expected. Please try again."
1071                        }
1072                        _ => SANITISED_ERROR_REPLY,
1073                    };
1074                    Ok(error_envelope(reply))
1075                }
1076            }
1077        }
1078    }
1079
1080    /// Build the `{"reply", "trail", "terminated_by": "error"}` envelope. The
1081    /// trail is empty: a failed/unavailable run surfaces no completed-node trail
1082    /// to the flow output (the detail is logged instead).
1083    fn error_envelope(reply: &str) -> Value {
1084        json!({
1085            "reply": reply,
1086            "trail": Vec::<Value>::new(),
1087            "terminated_by": "error",
1088        })
1089    }
1090
1091    /// Seed a fresh [`ConversationState`] from the graph run's message log so the
1092    /// per-visit agent has full context (including after a checkpoint resume).
1093    ///
1094    /// Tool-role graph messages are folded in as a plain user-context line
1095    /// rather than a `ChatMessage::Tool` (which needs a `call_id` paired to an
1096    /// assistant `tool_calls[]` entry the graph state does not track) — matching
1097    /// the designer spike.
1098    fn seed_state_from_graph(
1099        tenant: &TenantContext,
1100        session_id: &str,
1101        state: &GraphRunState,
1102    ) -> ConversationState {
1103        let mut seeded = ConversationState::empty(tenant, session_id);
1104        for m in &state.messages {
1105            match m.role {
1106                GraphRole::User => seeded.messages.push(ChatMessage::User {
1107                    content: m.content.clone(),
1108                    attachments: Vec::new(),
1109                }),
1110                GraphRole::Assistant => seeded.messages.push(ChatMessage::Assistant {
1111                    content: m.content.clone(),
1112                    tool_calls: vec![],
1113                }),
1114                GraphRole::Tool => seeded.messages.push(ChatMessage::User {
1115                    content: format!("Tool result: {}", m.content),
1116                    attachments: Vec::new(),
1117                }),
1118            }
1119        }
1120        seeded
1121    }
1122
1123    /// Build the [`AgentTurnFn`] effect closure.
1124    ///
1125    /// Each invocation constructs a lightweight [`AgentRuntime`] with a fresh
1126    /// single-entry [`InMemoryConfigProvider`] (agent id `"{graph_id}.{node_id}"`,
1127    /// the node's system prompt, no tools — the graph owns tool dispatch via the
1128    /// explicit Tool node) reusing the shared runtime Arcs. Conversation context
1129    /// is re-seeded from the durable [`GraphRunState`] on every visit; the
1130    /// per-visit session id is `"{session_id}__{graph_id}__{node_id}"`.
1131    #[allow(clippy::too_many_arguments)]
1132    fn build_agent_turn(
1133        state_store: Arc<dyn AgentStateStore>,
1134        ext_runtime: Arc<ExtensionRuntime>,
1135        llm: Arc<dyn LlmBackend>,
1136        telemetry: Arc<dyn Telemetry>,
1137        token_meter: Arc<dyn TokenMeter>,
1138        ledger: Arc<dyn ToolLedger>,
1139        mcp_source: Option<Arc<greentic_aw_runtime::McpToolSource>>,
1140        a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
1141        packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
1142        merged_agents: Arc<HashMap<String, AgentConfig>>,
1143        index_mount: IndexMount,
1144        audit_sink: Option<AuditSink>,
1145        real_tenant: greentic_types::TenantCtx,
1146        billing: TurnBilling,
1147    ) -> AgentTurnFn {
1148        Arc::new(move |req: AgentTurnRequest| {
1149            let state_store = state_store.clone();
1150            let ext_runtime = ext_runtime.clone();
1151            let llm = llm.clone();
1152            let telemetry = telemetry.clone();
1153            let token_meter = token_meter.clone();
1154            let ledger = ledger.clone();
1155            let mcp_source = mcp_source.clone();
1156            let a2a_source = a2a_source.clone();
1157            let packs = packs.clone();
1158            let merged_agents = merged_agents.clone();
1159            let audit_sink = audit_sink.clone();
1160            let real_tenant = real_tenant.clone();
1161            let index_mount = index_mount.clone();
1162            let billing = billing.clone();
1163            Box::pin(async move {
1164                run_one_agent_turn(
1165                    req,
1166                    state_store,
1167                    ext_runtime,
1168                    llm,
1169                    telemetry,
1170                    token_meter,
1171                    ledger,
1172                    mcp_source,
1173                    a2a_source,
1174                    packs,
1175                    merged_agents,
1176                    audit_sink.as_ref(),
1177                    &real_tenant,
1178                    &index_mount,
1179                    &billing,
1180                )
1181                .await
1182            }) as BoxFut<'static, Result<AgentTurnResult, GraphExecError>>
1183        })
1184    }
1185
1186    /// Drive one graph-node agent step: [`AgentRuntime::step`] when no audit
1187    /// sink is configured, or [`AgentRuntime::step_with_observer`] with an
1188    /// [`AgentAuditObserver`] when one is (EPIC-B B-3b Task 2). Shared by
1189    /// [`run_one_agent_turn`] and [`run_one_supervisor_turn`] so the
1190    /// audit-injection seam is defined exactly once.
1191    ///
1192    /// `tenant`/`session_id`/`agent_id` are the per-visit state identifiers
1193    /// (`TurnBilling::turn_tenant` — the real tenant/env plus the unit — and
1194    /// the derived session/agent ids); `tenant` is also what the billing sink
1195    /// attributes the turn to. `real_tenant` is used ONLY to build the audit
1196    /// observer's `TenantCtx`, unchanged by the billing wiring.
1197    ///
1198    /// Off by default: when `audit_sink` is `None` (no NATS audit client
1199    /// configured), this is exactly `runtime.step(...)` — byte-identical to
1200    /// the call before this observer existed.
1201    async fn run_agent_step(
1202        runtime: &AgentRuntime,
1203        tenant: TenantContext,
1204        session_id: &str,
1205        agent_id: &str,
1206        input: AgentInput,
1207        audit_sink: Option<&AuditSink>,
1208        real_tenant: &greentic_types::TenantCtx,
1209    ) -> std::result::Result<AgentOutput, AgentError> {
1210        match audit_sink {
1211            Some(sink) => {
1212                let observer: Arc<dyn StepObserver> = Arc::new(AgentAuditObserver::new(
1213                    sink.clone(),
1214                    real_tenant.clone(),
1215                    agent_id.to_string(),
1216                    session_id.to_string(),
1217                ));
1218                runtime
1219                    .step_with_observer(tenant, session_id, agent_id, input, observer)
1220                    .await
1221            }
1222            None => runtime.step(tenant, session_id, agent_id, input).await,
1223        }
1224    }
1225
1226    /// Parse a graph node's declared tool reference string into a [`ToolRef`].
1227    ///
1228    /// Format convention: `"<extension_id>/<tool_name>"`, split on the LAST
1229    /// `/` (so an `extension_id` that itself contains `/`, e.g.
1230    /// `"component:owner/repo"`, is preserved intact). Returns `None` — with a
1231    /// `tracing::warn!` naming the skipped string — when there is no `/`, or
1232    /// when either side of the split is empty. Never panics: this runs against
1233    /// node-authored config, not host-controlled input.
1234    fn parse_tool_ref(s: &str) -> Option<ToolRef> {
1235        match s.rsplit_once('/') {
1236            Some((extension_id, tool_name))
1237                if !extension_id.is_empty() && !tool_name.is_empty() =>
1238            {
1239                Some(ToolRef {
1240                    extension_id: extension_id.to_string(),
1241                    tool_name: tool_name.to_string(),
1242                    description: None,
1243                    input_schema: None,
1244                    usage_note: None,
1245                })
1246            }
1247            _ => {
1248                tracing::warn!(tool_ref = %s, "skipping malformed graph-node tool ref (expected \"<extension_id>/<tool_name>\")");
1249                None
1250            }
1251        }
1252    }
1253
1254    /// Map a graph node's declared `tools: Vec<String>` (see
1255    /// [`AgentTurnRequest::tools`]) to the `Vec<ToolRef>` the ephemeral
1256    /// per-visit [`AgentConfig`] expects. Malformed entries are dropped by
1257    /// [`parse_tool_ref`] (warned, never fatal) rather than failing the turn.
1258    fn map_tool_refs(tools: &[String]) -> Vec<ToolRef> {
1259        tools.iter().filter_map(|t| parse_tool_ref(t)).collect()
1260    }
1261
1262    /// The [`AgentConfig`] a graph agent-turn runs.
1263    ///
1264    /// `req.agent_ref` present (`Some(id)`) → the full published config
1265    /// resolved from `merged` (memory/knowledge/guardrails intact, exactly as
1266    /// stored) — errors when `id` is not in the map. `req.agent_ref` absent
1267    /// (`None`) → the stripped ephemeral config fabricated from the node's
1268    /// own inline fields (today's unchanged one-shot behaviour: no
1269    /// guardrails, no memory, no knowledge).
1270    fn resolve_turn_config(
1271        req: &AgentTurnRequest,
1272        merged: &HashMap<String, AgentConfig>,
1273        agent_id: &str,
1274    ) -> Result<AgentConfig, GraphExecError> {
1275        if let Some(id) = req.agent_ref.as_deref() {
1276            return merged.get(id).cloned().ok_or_else(|| {
1277                GraphExecError::AgentTurn(format!("referenced agent '{id}' not found"))
1278            });
1279        }
1280        // `inherit_from` is the specialist case: keep this node's own prompt and
1281        // model — that is what makes a specialist a specialist — but adopt the
1282        // referenced worker's capability surface. Using `agent_ref` here instead
1283        // would overwrite the prompt and collapse every specialist in a
1284        // generated graph into an identical copy of its parent.
1285        //
1286        // Like the supervisor path, an id that does not resolve FAILS rather
1287        // than running stripped: a specialist believed to be guarded and
1288        // tool-equipped but running bare is worse than one that never claimed
1289        // to be.
1290        if let Some(id) = req.inherit_from.as_deref() {
1291            let parent = merged.get(id).ok_or_else(|| {
1292                GraphExecError::AgentTurn(format!(
1293                    "node '{}': inherit_from '{}' not found in merged agents; \
1294                     refusing to run without its tools and guardrails",
1295                    req.node_id, id
1296                ))
1297            })?;
1298            return Ok(AgentConfig {
1299                agent_id: agent_id.to_string(),
1300                system_prompt: req.system_prompt.clone(),
1301                llm: LlmProviderRef {
1302                    provider: req.provider.clone().unwrap_or_else(|| "openai".into()),
1303                    model: req.model.clone(),
1304                    credential_ref: None,
1305                },
1306                // Inherited capability surface.
1307                tools: parent.tools.clone(),
1308                guardrails: parent.guardrails.clone(),
1309                memory: parent.memory.clone(),
1310                knowledge: parent.knowledge.clone(),
1311                limits: parent.limits.clone(),
1312                conversational: false,
1313                opening_message: None,
1314                on_text_while_parked: Default::default(),
1315            });
1316        }
1317        Ok(AgentConfig {
1318            agent_id: agent_id.to_string(),
1319            system_prompt: req.system_prompt.clone(),
1320            tools: map_tool_refs(&req.tools),
1321            guardrails: vec![],
1322            llm: LlmProviderRef {
1323                provider: req.provider.clone().unwrap_or_else(|| "openai".into()),
1324                model: req.model.clone(),
1325                credential_ref: None,
1326            },
1327            limits: AgentLimits::default(),
1328            memory: None,
1329            knowledge: None,
1330            conversational: false,
1331            opening_message: None,
1332            on_text_while_parked: Default::default(),
1333        })
1334    }
1335
1336    /// Drive one [`AgentRuntime::step`] for an agent-node visit. Derives the
1337    /// agent/session ids, seeds conversation context, runs the step, and maps the
1338    /// reply's resolution sentinel.
1339    ///
1340    /// `audit_sink`/`real_tenant` are forwarded to [`run_agent_step`], which
1341    /// injects an [`AgentAuditObserver`] built from `real_tenant` when a sink
1342    /// is configured (EPIC-B B-3b Task 2).
1343    ///
1344    /// When `req.agent_ref` is `Some`, [`resolve_turn_config`] resolves the
1345    /// full published `AgentConfig` from `merged_agents` and the runtime is
1346    /// built with the same fidelity as `agent_node::build_agent_runtime`
1347    /// (guardrails + short-term memory + feature-gated long-term/knowledge).
1348    /// `agent_ref: None` stays byte-unchanged: the stripped ephemeral config,
1349    /// no guardrails/memory/knowledge attached.
1350    #[allow(clippy::too_many_arguments)]
1351    async fn run_one_agent_turn(
1352        req: AgentTurnRequest,
1353        state_store: Arc<dyn AgentStateStore>,
1354        ext_runtime: Arc<ExtensionRuntime>,
1355        llm: Arc<dyn LlmBackend>,
1356        telemetry: Arc<dyn Telemetry>,
1357        token_meter: Arc<dyn TokenMeter>,
1358        ledger: Arc<dyn ToolLedger>,
1359        mcp_source: Option<Arc<greentic_aw_runtime::McpToolSource>>,
1360        a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
1361        packs: Arc<Vec<Arc<crate::pack::PackRuntime>>>,
1362        merged_agents: Arc<HashMap<String, AgentConfig>>,
1363        audit_sink: Option<&AuditSink>,
1364        real_tenant: &greentic_types::TenantCtx,
1365        index_mount: &IndexMount,
1366        billing: &TurnBilling,
1367    ) -> Result<AgentTurnResult, GraphExecError> {
1368        // The request carries no tenant/graph/session — they live on the
1369        // GraphRunState's seeded session. The executor seeds the run state with
1370        // the tenant-scoped messages, so we reconstruct a turn-scoped session
1371        // purely for the per-visit runtime. Conversation durability is owned by
1372        // the graph checkpoint, not this ephemeral store.
1373        //
1374        // The tenant is the REAL one the node was dispatched with (plus the
1375        // deployed unit), not a synthetic `("graph", "run")`: it is also the
1376        // tenant the billing sink attributes this turn's LLM spend to.
1377        let tenant = billing.turn_tenant(real_tenant);
1378        let session_id = billing.scoped_session(&format!("graph__{}", req.node_id));
1379        let agent_id = format!("graph.{}", req.node_id);
1380
1381        let seeded = seed_state_from_graph(&tenant, &session_id, &req.state);
1382        if let Err(error) = state_store.save(&tenant, &session_id, &seeded).await {
1383            return Err(GraphExecError::AgentTurn(format!(
1384                "seeding conversation state: {error}"
1385            )));
1386        }
1387
1388        let cfg = resolve_turn_config(&req, &merged_agents, &agent_id)?;
1389        // Key the config provider — and the `.step()` call — by the id the
1390        // runtime will actually resolve config under: the referenced agent's
1391        // own id when `agent_ref` is set (so guardrail/memory/knowledge
1392        // bindings on that published agent are addressed correctly), else the
1393        // synthetic per-node id used today.
1394        let step_agent_id = req.agent_ref.clone().unwrap_or_else(|| agent_id.clone());
1395        let mut provider = InMemoryConfigProvider::new();
1396        provider.insert(&tenant, &step_agent_id, cfg.clone());
1397
1398        // Guardrails are attached to every graph turn below; memory/knowledge
1399        // fidelity is only for a referenced agent (agent_ref: Some).
1400        // MCP tool source: mirror the `dw.agent` path so a graph agent declaring an
1401        // `mcp:<server>/<tool>` ref resolves it against the tenant's registered MCP
1402        // servers (same double-authorization: tenant registers the server + the node's
1403        // tool allowlist must reference it). `None` unless the admin creds are set.
1404        //
1405        // Component tool source: unlike `mcp_source` (built once, reused across
1406        // every graph-agent visit), the component source is tenant-pinned, so it
1407        // is rebuilt PER TURN from the in-memory `packs` list — cheap, and keeps
1408        // a `component:<ref>` tool ref scoped to the real tenant.
1409        let component_source = super::super::agent_node::component_source_from_packs(
1410            &packs,
1411            real_tenant.tenant_id.as_str(),
1412        );
1413        let mut runtime = AgentRuntime::new(
1414            Arc::new(provider),
1415            state_store,
1416            ext_runtime.clone(),
1417            llm,
1418            telemetry,
1419            token_meter,
1420            ledger,
1421            mcp_source,
1422        )
1423        .with_component_source(component_source)
1424        // A2A: the handler's pack-carried source (see `graph_a2a_source`),
1425        // for inline, inheriting and referenced agents alike — exactly what
1426        // the single-turn `dw.agent` runtime attaches.
1427        .with_a2a_source(a2a_source);
1428        runtime = billing.install(runtime);
1429        // Guardrails for EVERY graph agent turn (inline ones included), through
1430        // the builder the serve path and in-process `dw.agent` share, so a graph
1431        // can never run an agent with fewer guardrails than a flow node would.
1432        //
1433        // The fallback policy is EMPTY on purpose: `cfg.guardrails` already
1434        // rides in the agent config the loop evaluates as agent-level
1435        // guardrails, and naming them here too made them the mandatory
1436        // fallback as well, so `assemble_chain` ran every one of them twice
1437        // per turn (double cost, double verdicts).
1438        runtime =
1439            super::super::agent_node::attach_guardrails(runtime, ext_runtime.clone(), Vec::new());
1440
1441        // Full fidelity ONLY for a referenced agent — mirrors
1442        // `agent_node::build_agent_runtime`'s guardrail/short-term-memory/
1443        // long-term/knowledge attachment sequence exactly. The `agent_ref:
1444        // None` inline path stays byte-unchanged (no guardrails/memory/
1445        // knowledge), preserving today's one-shot graph-node behaviour.
1446        if req.agent_ref.is_some() {
1447            runtime = runtime.with_short_term_memory(Arc::new(
1448                greentic_aw_runtime::memory::InMemoryMemoryProvider::new(),
1449            ));
1450            // Long-term memory and corpus knowledge from every registered
1451            // agent-runtime extension (see `runtime_ext`).
1452            runtime = crate::runner::runtime_ext::attach_all(runtime).await;
1453            // Knowledge delegated to a design-extension tool. Not feature-gated
1454            // (see `knowledge_ext`); it wraps whatever corpus backend an
1455            // extension above left in place. Inside the `agent_ref.is_some()` arm with the rest
1456            // of the full-fidelity attachment sequence, so the `agent_ref: None`
1457            // inline path stays byte-unchanged.
1458            // Chronicle-index retrieval beneath it, reading its credentials
1459            // under the secrets tenant the mount captured at construction.
1460            runtime = index_mount.attach(runtime);
1461            runtime = crate::runner::knowledge_ext::attach(runtime, ext_runtime.clone());
1462        }
1463
1464        // The latest user turn is the most recent user message in the seeded log
1465        // (the executor pushes the initial user message and re-seeds it here);
1466        // pass an empty input so we do not duplicate it — the step appends the
1467        // input as a fresh user turn, so an empty string keeps the history intact.
1468        let input = AgentInput {
1469            text: String::new(),
1470            ..Default::default()
1471        };
1472
1473        let out = run_agent_step(
1474            &runtime,
1475            tenant.clone(),
1476            &session_id,
1477            &step_agent_id,
1478            input,
1479            audit_sink,
1480            real_tenant,
1481        )
1482        .await
1483        .map_err(|e| GraphExecError::AgentTurn(format!("agent step failed: {e}")))?;
1484
1485        Ok(AgentTurnResult {
1486            resolved: detect_resolved(&out.reply),
1487            reply: strip_sentinel(&out.reply),
1488        })
1489    }
1490
1491    /// Routing sentinel that the supervisor LLM must include in its reply to
1492    /// select a branch. Parsed case-insensitively.
1493    const ROUTE_SENTINEL_PREFIX: &str = "[[ROUTE:";
1494    const ROUTE_SENTINEL_SUFFIX: &str = "]]";
1495
1496    /// Build the [`SupervisorFn`] effect closure.
1497    ///
1498    /// Each invocation constructs a lightweight [`AgentRuntime`] (same pattern
1499    /// as [`build_agent_turn`]) with a system prompt that appends a route menu
1500    /// to the node's own `systemPrompt`. The reply is scanned for
1501    /// `[[ROUTE:<branch>]]`; if the sentinel is absent or the branch is unknown
1502    /// the executor falls back to the FIRST route with a `tracing::warn!`.
1503    #[allow(clippy::too_many_arguments)]
1504    fn build_supervisor(
1505        state_store: Arc<dyn AgentStateStore>,
1506        ext_runtime: Arc<ExtensionRuntime>,
1507        llm: Arc<dyn LlmBackend>,
1508        telemetry: Arc<dyn Telemetry>,
1509        token_meter: Arc<dyn TokenMeter>,
1510        ledger: Arc<dyn ToolLedger>,
1511        merged_agents: Arc<HashMap<String, AgentConfig>>,
1512        audit_sink: Option<AuditSink>,
1513        real_tenant: greentic_types::TenantCtx,
1514        billing: TurnBilling,
1515    ) -> SupervisorFn {
1516        Arc::new(move |req: SupervisorRequest| {
1517            let merged_agents = merged_agents.clone();
1518            let state_store = state_store.clone();
1519            let ext_runtime = ext_runtime.clone();
1520            let llm = llm.clone();
1521            let telemetry = telemetry.clone();
1522            let token_meter = token_meter.clone();
1523            let ledger = ledger.clone();
1524            let audit_sink = audit_sink.clone();
1525            let real_tenant = real_tenant.clone();
1526            let billing = billing.clone();
1527            Box::pin(async move {
1528                run_one_supervisor_turn(
1529                    req,
1530                    state_store,
1531                    ext_runtime,
1532                    llm,
1533                    telemetry,
1534                    token_meter,
1535                    ledger,
1536                    merged_agents,
1537                    audit_sink.as_ref(),
1538                    &real_tenant,
1539                    &billing,
1540                )
1541                .await
1542            }) as BoxFut<'static, Result<SupervisorResult, GraphExecError>>
1543        })
1544    }
1545
1546    /// Resolve the guardrails a supervisor node runs under.
1547    ///
1548    /// A supervisor inherits its worker's GUARDRAILS and nothing else — it
1549    /// routes, it does not work, so tools, memory and knowledge stay unset.
1550    /// Guardrails are the exception because this node sees the operator's raw
1551    /// input first: it is where inbound content-safety has to run.
1552    ///
1553    /// An `agent_ref` that does not resolve FAILS the turn rather than routing
1554    /// unguarded. A supervisor believed to be protected but running bare is the
1555    /// precise failure this inheritance exists to prevent, and a silent
1556    /// downgrade would be indistinguishable from success.
1557    fn resolve_supervisor_guardrails(
1558        agent_ref: Option<&str>,
1559        merged: &HashMap<String, AgentConfig>,
1560        node_id: &str,
1561    ) -> Result<Vec<greentic_aw_runtime::config::GuardrailRef>, GraphExecError> {
1562        let Some(id) = agent_ref else {
1563            return Ok(vec![]);
1564        };
1565        merged
1566            .get(id)
1567            .map(|parent| parent.guardrails.clone())
1568            .ok_or_else(|| {
1569                GraphExecError::Supervisor(format!(
1570                    "node '{node_id}': agent_ref '{id}' not found in merged agents; \
1571                     refusing to route without its guardrails"
1572                ))
1573            })
1574    }
1575
1576    /// Drive one supervisor routing turn via [`AgentRuntime::step`].
1577    ///
1578    /// The routing prompt appends a route menu to the node's `systemPrompt`:
1579    ///
1580    /// ```text
1581    /// <node system_prompt>
1582    ///
1583    /// Available routes:
1584    /// - billing: Billing and payment questions
1585    /// - tech: Technical support issues
1586    ///
1587    /// Reply with [[ROUTE:<branch>]] to select a route.
1588    /// ```
1589    ///
1590    /// The agent reply is scanned for `[[ROUTE:<branch>]]` (case-insensitive).
1591    /// If the sentinel is absent or the branch does not match a declared route,
1592    /// the first route is used as fallback with a `tracing::warn!`.
1593    ///
1594    /// `audit_sink`/`real_tenant` are forwarded to [`run_agent_step`], which
1595    /// injects an [`AgentAuditObserver`] built from `real_tenant` when a sink
1596    /// is configured (EPIC-B B-3b Task 2).
1597    #[allow(clippy::too_many_arguments)]
1598    async fn run_one_supervisor_turn(
1599        req: SupervisorRequest,
1600        state_store: Arc<dyn AgentStateStore>,
1601        ext_runtime: Arc<ExtensionRuntime>,
1602        llm: Arc<dyn LlmBackend>,
1603        telemetry: Arc<dyn Telemetry>,
1604        token_meter: Arc<dyn TokenMeter>,
1605        ledger: Arc<dyn ToolLedger>,
1606        merged_agents: Arc<HashMap<String, AgentConfig>>,
1607        audit_sink: Option<&AuditSink>,
1608        real_tenant: &greentic_types::TenantCtx,
1609        billing: &TurnBilling,
1610    ) -> Result<SupervisorResult, GraphExecError> {
1611        // Real tenant + unit, as for an agent turn: routing is an LLM call too.
1612        let tenant = billing.turn_tenant(real_tenant);
1613        let session_id = billing.scoped_session(&format!("graph__{}_sup", req.node_id));
1614        let agent_id = format!("graph.{}.supervisor", req.node_id);
1615
1616        // Build the route menu suffix.
1617        let mut route_menu = String::from("\n\nAvailable routes:\n");
1618        for r in &req.routes {
1619            route_menu.push_str(&format!("- {}: {}\n", r.branch, r.description));
1620        }
1621        route_menu.push_str("\nReply with [[ROUTE:<branch>]] to select a route.");
1622
1623        let routing_system_prompt = format!("{}{}", req.system_prompt, route_menu);
1624
1625        let seeded = seed_state_from_graph(&tenant, &session_id, &req.state);
1626        if let Err(error) = state_store.save(&tenant, &session_id, &seeded).await {
1627            return Err(GraphExecError::Supervisor(format!(
1628                "seeding conversation state: {error}"
1629            )));
1630        }
1631
1632        let guardrails =
1633            resolve_supervisor_guardrails(req.agent_ref.as_deref(), &merged_agents, &req.node_id)?;
1634
1635        let cfg = AgentConfig {
1636            agent_id: agent_id.clone(),
1637            system_prompt: routing_system_prompt,
1638            tools: vec![],
1639            guardrails,
1640            llm: LlmProviderRef {
1641                provider: req.provider.clone().unwrap_or_else(|| "openai".into()),
1642                model: req.model.clone(),
1643                credential_ref: None,
1644            },
1645            limits: AgentLimits::default(),
1646            memory: None,
1647            knowledge: None,
1648            conversational: false,
1649            opening_message: None,
1650            on_text_while_parked: Default::default(),
1651        };
1652        let mut provider = InMemoryConfigProvider::new();
1653        provider.insert(&tenant, &agent_id, cfg);
1654
1655        let runtime = billing.install(AgentRuntime::new(
1656            Arc::new(provider),
1657            state_store,
1658            ext_runtime.clone(),
1659            llm,
1660            telemetry,
1661            token_meter,
1662            ledger,
1663            // Supervisor routing runs with an empty tool list; MCP tools are
1664            // never offered on this path.
1665            None,
1666        ));
1667        // Routing is an LLM call too: same mandatory-guardrail policy as every
1668        // other agent turn.
1669        let runtime = super::super::agent_node::attach_guardrails(runtime, ext_runtime, Vec::new());
1670
1671        let input = AgentInput {
1672            text: String::new(),
1673            ..Default::default()
1674        };
1675
1676        let out = run_agent_step(
1677            &runtime,
1678            tenant.clone(),
1679            &session_id,
1680            &agent_id,
1681            input,
1682            audit_sink,
1683            real_tenant,
1684        )
1685        .await
1686        .map_err(|e| GraphExecError::Supervisor(format!("supervisor step failed: {e}")))?;
1687
1688        // Parse [[ROUTE:<branch>]] from the reply (case-insensitive).
1689        // Do this BEFORE stripping so we read from the unmodified reply.
1690        let branch = parse_route_branch(&out.reply, &req.routes).unwrap_or_else(|| {
1691            let fallback = req
1692                .routes
1693                .first()
1694                .map(|r| r.branch.clone())
1695                .unwrap_or_default();
1696            tracing::warn!(
1697                node_id = req.node_id,
1698                reply = %out.reply,
1699                fallback = %fallback,
1700                "supervisor reply missing or unknown [[ROUTE:]] sentinel; falling back to first route"
1701            );
1702            fallback
1703        });
1704
1705        // Strip the [[ROUTE:<branch>]] sentinel from the stored assistant message
1706        // so the message log does not expose routing instructions to downstream nodes.
1707        let raw_reply = strip_route_sentinel(&out.reply);
1708
1709        Ok(SupervisorResult { branch, raw_reply })
1710    }
1711
1712    /// Parse `[[ROUTE:<branch>]]` from the reply and return the branch label if
1713    /// it matches one of the declared routes. Returns `None` if the sentinel is
1714    /// absent or the extracted branch is not in the route list.
1715    fn parse_route_branch(
1716        reply: &str,
1717        routes: &[greentic_aw_runtime::graph::SupervisorRoute],
1718    ) -> Option<String> {
1719        let lower = reply.to_ascii_lowercase();
1720        let prefix_lower = ROUTE_SENTINEL_PREFIX.to_ascii_lowercase();
1721        let suffix_lower = ROUTE_SENTINEL_SUFFIX.to_ascii_lowercase();
1722        let start = lower.find(&prefix_lower)?;
1723        let after_prefix = start + prefix_lower.len();
1724        let end = lower[after_prefix..].find(&suffix_lower)?;
1725        let branch = reply[after_prefix..after_prefix + end].trim().to_string();
1726        // Validate against declared routes (case-sensitive match, per spec).
1727        if routes.iter().any(|r| r.branch == branch) {
1728            Some(branch)
1729        } else {
1730            None
1731        }
1732    }
1733
1734    /// Strip the `[[ROUTE:<branch>]]` sentinel (case-insensitive, first occurrence)
1735    /// from a supervisor reply, trimming surrounding whitespace.
1736    ///
1737    /// If no sentinel is present the reply is returned trimmed. Used to clean
1738    /// up the text before it is pushed into the message log as an assistant
1739    /// message.
1740    fn strip_route_sentinel(reply: &str) -> String {
1741        let lower = reply.to_ascii_lowercase();
1742        let prefix_lower = ROUTE_SENTINEL_PREFIX.to_ascii_lowercase();
1743        let suffix_lower = ROUTE_SENTINEL_SUFFIX.to_ascii_lowercase();
1744        if let Some(start) = lower.find(&prefix_lower) {
1745            let after_prefix = start + prefix_lower.len();
1746            if let Some(end) = lower[after_prefix..].find(&suffix_lower) {
1747                let sentinel_end = after_prefix + end + suffix_lower.len();
1748                let mut out = reply.to_string();
1749                out.replace_range(start..sentinel_end, "");
1750                return out.trim().to_string();
1751            }
1752        }
1753        reply.trim().to_string()
1754    }
1755
1756    /// Build the [`ToolFn`] effect closure.
1757    ///
1758    /// `tool_name` is parsed as `"extension_id/tool_name"` (split on the FIRST
1759    /// `'/'`). Anything without a `'/'`, or an empty side, is a
1760    /// [`GraphExecError::Tool`]. Dispatch goes through the shared
1761    /// [`ExtensionRuntime`] via [`dispatch_tool_call`], which wraps the blocking
1762    /// `invoke_tool` in `spawn_blocking`.
1763    fn build_tool(
1764        ext_runtime: Arc<ExtensionRuntime>,
1765        a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
1766    ) -> ToolFn {
1767        Arc::new(move |req: ToolCallRequest| {
1768            let ext_runtime = ext_runtime.clone();
1769            let a2a_source = a2a_source.clone();
1770            Box::pin(async move { run_one_tool(req, ext_runtime, a2a_source).await })
1771                as BoxFut<'static, Result<Value, GraphExecError>>
1772        })
1773    }
1774
1775    /// Default [`ApprovalFn`] for the in-process runner-host path: always
1776    /// reports `Awaiting`.
1777    ///
1778    /// The real `ApprovalFn` is designer-provided and wires the
1779    /// `greentic.approval.request.v1` / `.response.v1` round trip so a human
1780    /// decision can arrive asynchronously and unpark the run. This in-process
1781    /// default has no such transport, so it parks the run safely
1782    /// (`RunStatus::AwaitingInput`) but never resolves it. `derive_run_id`
1783    /// resumes (not forks) the parked run on every subsequent call for the
1784    /// same session, so it stays resolvable once a real `ApprovalFn` is
1785    /// wired in. See the `from_parts` doc comment; the designer-side
1786    /// approval bridge (subscriber + node, cross-repo Phase 2) supplies the
1787    /// real consumer.
1788    fn default_approval_awaiting() -> ApprovalFn {
1789        Arc::new(|_req: ApprovalRequest| Box::pin(async move { Ok(ApprovalOutcome::Awaiting) }))
1790    }
1791
1792    /// Parse + dispatch a single Tool-node call. See [`build_tool`].
1793    async fn run_one_tool(
1794        req: ToolCallRequest,
1795        ext_runtime: Arc<ExtensionRuntime>,
1796        a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
1797    ) -> Result<Value, GraphExecError> {
1798        let (extension_id, tool_name) = req.tool_name.split_once('/').ok_or_else(|| {
1799            GraphExecError::Tool(format!(
1800                "tool name '{}' must be 'extension_id/tool_name'",
1801                req.tool_name
1802            ))
1803        })?;
1804        if extension_id.is_empty() || tool_name.is_empty() {
1805            return Err(GraphExecError::Tool(format!(
1806                "tool name '{}' must be 'extension_id/tool_name' (non-empty parts)",
1807                req.tool_name
1808            )));
1809        }
1810
1811        // The graph Tool node carries no arguments today: dispatch with an empty
1812        // object. A future schema can thread structured args from node config.
1813        let call = greentic_aw_runtime::state::ToolCallRecord {
1814            call_id: format!("{}__{}", req.node_id, tool_name),
1815            extension_id: extension_id.to_string(),
1816            tool_name: tool_name.to_string(),
1817            args: json!({}),
1818        };
1819
1820        // A Tool node names 'extension_id/tool'. An `a2a:<agent_id>/ask` ref
1821        // dispatches through the handler's pack-carried A2A catalog (the same
1822        // source the agent turns use; see `graph_a2a_source`), which reads its
1823        // credential with the tenant and unit it captured at build time, so
1824        // the placeholder `TenantContext` below does not reach it. mcp:,
1825        // component:, flow: and sorla: refs are still not wired here — the
1826        // agent-graph Tool node has no catalog for them, and such a ref
1827        // returns the dispatcher's "no catalog wired" error value.
1828        // No per-request TenantContext is available at the graph-node layer;
1829        // use a no-op placeholder so the extension's host-LLM port receives an
1830        // empty context (equivalent to the previous `invoke_tool` default).
1831        let a2a = match a2a_source.as_ref() {
1832            Some(source) => Some(source.catalog().await),
1833            None => None,
1834        };
1835        let tenant = TenantContext::new("", "");
1836        // `dispatch_tool_call`, not its `_in_conversation` sibling: a graph
1837        // node holds no `ConversationState`, so there is nowhere to keep a
1838        // remote A2A `contextId` between calls. An `a2a:` tool reached from
1839        // here therefore opens a fresh remote task each time and cannot
1840        // answer an `input-required`. Closing that needs the graph executor's
1841        // own checkpoint to carry the continuations, which is a separate
1842        // change to a different state machine.
1843        dispatch_tool_call(ext_runtime, None, None, None, None, a2a, call, &tenant)
1844            .await
1845            .map_err(|e| GraphExecError::Tool(format!("dispatch '{}': {e}", req.tool_name)))
1846    }
1847
1848    #[cfg(all(test, feature = "agentic-worker"))]
1849    mod tests {
1850        use std::collections::HashMap;
1851        use std::sync::Arc;
1852        use std::sync::atomic::{AtomicU32, Ordering};
1853
1854        use greentic_aw_runtime::graph::model::SupervisorRoute;
1855        use greentic_aw_runtime::graph::{
1856            AgentTurnFn, AgentTurnRequest, AgentTurnResult, ApprovalFn, ApprovalOutcome,
1857            ApprovalRequest, GraphConfig, InMemoryCheckpointStore, SupervisorFn, SupervisorRequest,
1858            SupervisorResult, ToolCallRequest, ToolFn,
1859        };
1860        use greentic_aw_runtime::mock::MockAgentStateStore;
1861        use serde_json::json;
1862
1863        use super::*;
1864
1865        // -------------------------------------------------------------------
1866        // Fixtures
1867        // -------------------------------------------------------------------
1868
1869        /// Minimal triage-style graph: agent → lookup tool → router → respond,
1870        /// router maxIterations=3. Mirrors the aw-runtime test fixture (which is
1871        /// `pub(crate)` to that crate and thus not importable here).
1872        fn triage_graph_json(max_iterations: u32) -> String {
1873            json!({
1874                "schemaVersion": 1,
1875                "entry": "agent",
1876                "nodes": [
1877                    {"id": "agent", "kind": "agent", "systemPrompt": "You triage.", "model": "gpt-4o-mini", "tools": []},
1878                    {"id": "lookup", "kind": "tool", "toolName": "kb/search"},
1879                    {"id": "router", "kind": "router", "maxIterations": max_iterations},
1880                    {"id": "respond", "kind": "respond"}
1881                ],
1882                "edges": [
1883                    {"from": "agent", "to": "lookup"},
1884                    {"from": "lookup", "to": "router"},
1885                    {"from": "router", "to": "agent", "branch": "loop"},
1886                    {"from": "router", "to": "respond", "branch": "resolved"}
1887                ]
1888            })
1889            .to_string()
1890        }
1891
1892        fn triage_cfg(max_iterations: u32) -> GraphConfig {
1893            GraphConfig::from_json(&triage_graph_json(max_iterations)).expect("fixture valid")
1894        }
1895
1896        /// Graph with a human-in-the-loop approval gate: `start` (agent) ->
1897        /// `approval` -> `respond` (branch `"approved"`). Mirrors the
1898        /// aw-runtime executor test fixture (`approval_json` in
1899        /// `graph/executor.rs`), which is `pub(crate)` there and thus not
1900        /// importable here.
1901        fn approval_graph_json() -> String {
1902            json!({
1903                "schemaVersion": 2,
1904                "entry": "start",
1905                "nodes": [
1906                    {"id": "start", "kind": "agent", "systemPrompt": "greet the user", "model": "gpt-4o-mini", "tools": []},
1907                    {"id": "approval", "kind": "approval", "title": "Approve refund?", "mode": "always"},
1908                    {"id": "respond", "kind": "respond"}
1909                ],
1910                "edges": [
1911                    {"from": "start", "to": "approval"},
1912                    {"from": "approval", "to": "respond", "branch": "approved"}
1913                ]
1914            })
1915            .to_string()
1916        }
1917
1918        fn approval_cfg() -> GraphConfig {
1919            GraphConfig::from_json(&approval_graph_json()).expect("approval fixture valid")
1920        }
1921
1922        /// An [`ApprovalFn`] whose decision flips based on a shared flag:
1923        /// `Awaiting` while `false`, `Decided { branch: "approved" }` once
1924        /// `true`. Lets a single handler drive both the initial park and a
1925        /// later resume-with-decision within one test.
1926        fn approval_fn_toggle(decide: Arc<std::sync::atomic::AtomicBool>) -> ApprovalFn {
1927            Arc::new(move |_req: ApprovalRequest| {
1928                let decide = decide.clone();
1929                Box::pin(async move {
1930                    if decide.load(Ordering::SeqCst) {
1931                        Ok(ApprovalOutcome::Decided {
1932                            branch: "approved".to_string(),
1933                        })
1934                    } else {
1935                        Ok(ApprovalOutcome::Awaiting)
1936                    }
1937                })
1938            })
1939        }
1940
1941        fn provider_with(graph_id: &str, cfg: GraphConfig) -> Arc<InMemoryGraphProvider> {
1942            let mut graphs = HashMap::new();
1943            graphs.insert(graph_id.to_string(), cfg);
1944            Arc::new(InMemoryGraphProvider::new(graphs))
1945        }
1946
1947        /// Agent closure that resolves on the n-th (non-replayed) call.
1948        fn agent_fn_resolves_on(counter: Arc<AtomicU32>, resolve_on_call: u32) -> AgentTurnFn {
1949            Arc::new(move |req: AgentTurnRequest| {
1950                let n = counter.fetch_add(1, Ordering::SeqCst) + 1;
1951                let resolved = n >= resolve_on_call;
1952                let reply = format!("reply-{n} from {}", req.node_id);
1953                Box::pin(async move { Ok(AgentTurnResult { reply, resolved }) })
1954            })
1955        }
1956
1957        fn tool_fn_ok() -> ToolFn {
1958            Arc::new(move |_req: ToolCallRequest| {
1959                Box::pin(async move { Ok(json!({"found": true})) })
1960            })
1961        }
1962
1963        /// A no-op supervisor fn for tests that do not exercise supervisor nodes.
1964        fn supervisor_fn_noop() -> SupervisorFn {
1965            Arc::new(|_req: SupervisorRequest| {
1966                Box::pin(async move {
1967                    Err(greentic_aw_runtime::graph::GraphExecError::Supervisor(
1968                        "supervisor fn should not be called in this test".into(),
1969                    ))
1970                })
1971            })
1972        }
1973
1974        /// A trivial approval fn that always reports `Awaiting` — none of
1975        /// these fixtures contain an approval node, so this is never invoked.
1976        fn approval_fn_awaiting() -> ApprovalFn {
1977            Arc::new(|_req: ApprovalRequest| Box::pin(async move { Ok(ApprovalOutcome::Awaiting) }))
1978        }
1979
1980        fn handler_with(
1981            graphs: Arc<dyn GraphConfigSource>,
1982            agent_turn: AgentTurnFn,
1983            tool: ToolFn,
1984        ) -> RuntimeGraphNodeHandler {
1985            RuntimeGraphNodeHandler::with_effects(
1986                graphs,
1987                Arc::new(InMemoryCheckpointStore::default()),
1988                Arc::new(MockAgentStateStore::new()),
1989                agent_turn,
1990                tool,
1991                supervisor_fn_noop(),
1992                approval_fn_awaiting(),
1993            )
1994        }
1995
1996        // -------------------------------------------------------------------
1997        // parse_tool_ref / map_tool_refs tests
1998        // -------------------------------------------------------------------
1999
2000        #[test]
2001        fn parse_tool_ref_splits_on_last_slash() {
2002            assert_eq!(
2003                super::parse_tool_ref("myext/dothing"),
2004                Some(ToolRef {
2005                    extension_id: "myext".into(),
2006                    tool_name: "dothing".into(),
2007                    description: None,
2008                    input_schema: None,
2009                    usage_note: None,
2010                })
2011            );
2012            assert_eq!(
2013                super::parse_tool_ref("component:owner/repo/list"),
2014                Some(ToolRef {
2015                    extension_id: "component:owner/repo".into(),
2016                    tool_name: "list".into(),
2017                    description: None,
2018                    input_schema: None,
2019                    usage_note: None,
2020                })
2021            );
2022            assert_eq!(super::parse_tool_ref("noslash"), None);
2023            assert_eq!(super::parse_tool_ref("trailing/"), None);
2024        }
2025
2026        #[test]
2027        fn parse_tool_ref_rejects_leading_slash() {
2028            // Empty extension_id half — also malformed, never panics.
2029            assert_eq!(super::parse_tool_ref("/dothing"), None);
2030        }
2031
2032        #[test]
2033        fn map_tool_refs_drops_malformed_entries_and_keeps_valid_ones() {
2034            let tools = vec![
2035                "myext/dothing".to_string(),
2036                "noslash".to_string(),
2037                "other/thing".to_string(),
2038            ];
2039            let refs = super::map_tool_refs(&tools);
2040            assert_eq!(
2041                refs,
2042                vec![
2043                    ToolRef {
2044                        extension_id: "myext".into(),
2045                        tool_name: "dothing".into(),
2046                        description: None,
2047                        input_schema: None,
2048                        usage_note: None,
2049                    },
2050                    ToolRef {
2051                        extension_id: "other".into(),
2052                        tool_name: "thing".into(),
2053                        description: None,
2054                        input_schema: None,
2055                        usage_note: None,
2056                    },
2057                ]
2058            );
2059        }
2060
2061        // -------------------------------------------------------------------
2062        // graph_config_from_sidecar tests
2063        // -------------------------------------------------------------------
2064
2065        #[test]
2066        fn sidecar_valid_triage_parses() {
2067            let bytes = triage_graph_json(3).into_bytes();
2068            let cfg = super::graph_config_from_sidecar("test-pack", &bytes);
2069            assert!(cfg.is_some(), "valid triage sidecar must parse");
2070        }
2071
2072        #[test]
2073        fn sidecar_malformed_json_returns_none() {
2074            let bytes = b"{ this is not valid json";
2075            // Must not panic; a malformed sidecar is skipped (None).
2076            let cfg = super::graph_config_from_sidecar("test-pack", bytes);
2077            assert!(cfg.is_none(), "malformed JSON sidecar must yield None");
2078        }
2079
2080        #[test]
2081        fn sidecar_unsupported_schema_version_returns_none() {
2082            let bytes = json!({
2083                "schemaVersion": 99,
2084                "entry": "agent",
2085                "nodes": [
2086                    {"id": "agent", "kind": "agent", "systemPrompt": "x", "model": "gpt-4o-mini", "tools": []},
2087                    {"id": "respond", "kind": "respond"}
2088                ],
2089                "edges": [{"from": "agent", "to": "respond"}]
2090            })
2091            .to_string()
2092            .into_bytes();
2093            let cfg = super::graph_config_from_sidecar("test-pack", &bytes);
2094            assert!(
2095                cfg.is_none(),
2096                "unsupported schemaVersion must be rejected (None)"
2097            );
2098        }
2099
2100        // -------------------------------------------------------------------
2101        // Tests
2102        // -------------------------------------------------------------------
2103
2104        #[tokio::test]
2105        async fn executes_graph_and_returns_dw_agent_envelope() {
2106            let handler = handler_with(
2107                provider_with("triage", triage_cfg(3)),
2108                agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
2109                tool_fn_ok(),
2110            );
2111
2112            let out = handler
2113                .execute("t", "e", "triage", "sess-1", &json!({"user_text": "help"}))
2114                .await
2115                .expect("execute should succeed");
2116
2117            assert_eq!(out["terminated_by"].as_str(), Some("respond"));
2118            assert!(
2119                out["reply"].as_str().unwrap_or("").contains("reply-1"),
2120                "reply should carry agent output: {:?}",
2121                out["reply"]
2122            );
2123            assert!(
2124                out["trail"]
2125                    .as_array()
2126                    .map(|a| !a.is_empty())
2127                    .unwrap_or(false),
2128                "trail should be a non-empty array: {:?}",
2129                out["trail"]
2130            );
2131        }
2132
2133        /// A graph turn cannot open files: attachments on the flow node are
2134        /// announced to the graph's agents with the fixed notice, never
2135        /// dropped silently, and no name reaches them.
2136        #[tokio::test]
2137        async fn attachments_on_a_graph_turn_are_announced_with_the_fixed_notice() {
2138            let seen = Arc::new(std::sync::Mutex::new(Vec::<String>::new()));
2139            let seen_by_agent = seen.clone();
2140            let agent: AgentTurnFn = Arc::new(move |req: AgentTurnRequest| {
2141                seen_by_agent.lock().unwrap().extend(
2142                    req.state
2143                        .messages
2144                        .iter()
2145                        .map(|m| m.content.clone())
2146                        .collect::<Vec<_>>(),
2147                );
2148                Box::pin(async move {
2149                    Ok(AgentTurnResult {
2150                        reply: "done".into(),
2151                        resolved: true,
2152                    })
2153                })
2154            });
2155            let handler = handler_with(provider_with("triage", triage_cfg(3)), agent, tool_fn_ok());
2156            handler
2157                .execute(
2158                    "t",
2159                    "e",
2160                    "triage",
2161                    "sess-1",
2162                    &json!({
2163                        "user_text": "look",
2164                        "attachments": [
2165                            {"mime_type": "image/png", "url": format!("artifact://{}", "a".repeat(64)), "name": "secret.png"},
2166                            {"mime_type": "application/pdf", "url": null, "name": "b.pdf"}
2167                        ]
2168                    }),
2169                )
2170                .await
2171                .expect("execute should succeed");
2172            let seen = seen.lock().unwrap().join("\n");
2173            // Counted like the `dw.agent` path: only the file the runner would
2174            // read is "not available"; the one the host could not store gets
2175            // its own fixed notice, and is not counted twice.
2176            let note = greentic_aw_runtime::attachments_materialize::unreadable_note(1);
2177            assert!(
2178                seen.contains(&format!(
2179                    "look\n[attachment not used: a file was not stored for the agent]{note}"
2180                )),
2181                "{seen}"
2182            );
2183            assert!(!seen.contains("secret.png"), "{seen}");
2184            assert!(!seen.contains("b.pdf"), "{seen}");
2185        }
2186
2187        #[tokio::test]
2188        async fn same_session_resumes_completed_run_with_fresh_run() {
2189            // Shared checkpoint + state stores so the second call sees the first
2190            // run's terminal record and mints a fresh `__2` run id.
2191            let graphs = provider_with("triage", triage_cfg(3));
2192            let checkpoint = Arc::new(InMemoryCheckpointStore::default());
2193            let state_store = Arc::new(MockAgentStateStore::new());
2194            let counter = Arc::new(AtomicU32::new(0));
2195
2196            let handler = RuntimeGraphNodeHandler::with_effects(
2197                graphs,
2198                checkpoint.clone(),
2199                state_store,
2200                agent_fn_resolves_on(counter, 1),
2201                tool_fn_ok(),
2202                supervisor_fn_noop(),
2203                approval_fn_awaiting(),
2204            );
2205
2206            let first = handler
2207                .execute("t", "e", "triage", "sess-1", &json!({"user_text": "one"}))
2208                .await
2209                .expect("first call succeeds");
2210            assert_eq!(first["terminated_by"].as_str(), Some("respond"));
2211
2212            let second = handler
2213                .execute("t", "e", "triage", "sess-1", &json!({"user_text": "two"}))
2214                .await
2215                .expect("second call succeeds with fresh run id");
2216            assert_eq!(second["terminated_by"].as_str(), Some("respond"));
2217
2218            // The fresh run id (`__2`) must exist in the checkpoint store.
2219            let tenant = TenantContext::new("t", "e");
2220            let fresh = checkpoint
2221                .load(&tenant, "sess-1__triage__2")
2222                .await
2223                .expect("store ok");
2224            assert!(fresh.is_some(), "fresh __2 run id should be recorded");
2225        }
2226
2227        /// Task C3: a graph run parked at an approval node (`RunStatus::
2228        /// AwaitingInput`) must be surfaced as neither a completed respond
2229        /// nor a failure, and — unlike a terminal (`Succeeded`/`Failed`) run
2230        /// — the SAME run id must be resumed on every later call for the
2231        /// same session, not forked into a fresh `__n` slot (which would
2232        /// orphan the parked run: it could never be decided because nothing
2233        /// would ever resume it again).
2234        #[tokio::test]
2235        async fn awaiting_input_parks_without_orphaning_and_resumes_on_decision() {
2236            let graphs = provider_with("approval-graph", approval_cfg());
2237            let checkpoint = Arc::new(InMemoryCheckpointStore::default());
2238            let state_store = Arc::new(MockAgentStateStore::new());
2239            let decide = Arc::new(std::sync::atomic::AtomicBool::new(false));
2240
2241            let handler = RuntimeGraphNodeHandler::with_effects(
2242                graphs,
2243                checkpoint.clone(),
2244                state_store,
2245                agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
2246                tool_fn_ok(),
2247                supervisor_fn_noop(),
2248                approval_fn_toggle(decide.clone()),
2249            );
2250            let tenant = TenantContext::new("t", "e");
2251
2252            // Call 1: the run drives to the approval node and parks.
2253            let first = handler
2254                .execute(
2255                    "t",
2256                    "e",
2257                    "approval-graph",
2258                    "sess-approve",
2259                    &json!({"user_text": "please refund"}),
2260                )
2261                .await
2262                .expect("a parked run must be Ok, not an Err");
2263            assert_ne!(
2264                first["terminated_by"].as_str(),
2265                Some("respond"),
2266                "a parked run must not be reported as a completed respond: {first:?}"
2267            );
2268            assert_ne!(
2269                first["terminated_by"].as_str(),
2270                Some("error"),
2271                "a parked run must not be reported as an error: {first:?}"
2272            );
2273
2274            let rec = checkpoint
2275                .load(&tenant, "sess-approve__approval-graph")
2276                .await
2277                .expect("store accessible")
2278                .expect("base run id must be recorded");
2279            assert_eq!(
2280                rec.status,
2281                RunStatus::AwaitingInput,
2282                "persisted record must reflect the park"
2283            );
2284
2285            // Call 2 (still undecided): must RESUME the base run id in
2286            // place, not fork "__2" (the bug this test guards against).
2287            let second = handler
2288                .execute(
2289                    "t",
2290                    "e",
2291                    "approval-graph",
2292                    "sess-approve",
2293                    &json!({"user_text": "still waiting"}),
2294                )
2295                .await
2296                .expect("a re-parked run must be Ok, not an Err");
2297            assert_ne!(second["terminated_by"].as_str(), Some("respond"));
2298
2299            let forked = checkpoint
2300                .load(&tenant, "sess-approve__approval-graph__2")
2301                .await
2302                .expect("store accessible");
2303            assert!(
2304                forked.is_none(),
2305                "an AwaitingInput run must resume in place, not fork a fresh run id"
2306            );
2307
2308            // Call 3: the decision has arrived — the SAME base run id
2309            // resolves via `executor.resume()`, not a fresh run.
2310            decide.store(true, Ordering::SeqCst);
2311            let third = handler
2312                .execute(
2313                    "t",
2314                    "e",
2315                    "approval-graph",
2316                    "sess-approve",
2317                    &json!({"user_text": "resolve"}),
2318                )
2319                .await
2320                .expect("execute should succeed once decided");
2321            assert_eq!(third["terminated_by"].as_str(), Some("respond"));
2322
2323            let rec = checkpoint
2324                .load(&tenant, "sess-approve__approval-graph")
2325                .await
2326                .expect("store accessible")
2327                .expect("base run id must still be recorded");
2328            assert_eq!(
2329                rec.status,
2330                RunStatus::Succeeded,
2331                "the base run id must resolve once decided, not a forked one"
2332            );
2333        }
2334
2335        #[tokio::test]
2336        async fn missing_graph_returns_structured_error_reply() {
2337            let handler = handler_with(
2338                provider_with("triage", triage_cfg(3)),
2339                agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
2340                tool_fn_ok(),
2341            );
2342
2343            let out = handler
2344                .execute("t", "e", "unknown", "sess-1", &json!({"user_text": "hi"}))
2345                .await
2346                .expect("missing graph must NOT return Err");
2347
2348            assert_eq!(out["terminated_by"].as_str(), Some("error"));
2349            assert!(
2350                out["reply"]
2351                    .as_str()
2352                    .unwrap_or("")
2353                    .to_ascii_lowercase()
2354                    .contains("available"),
2355                "reply should mention availability: {:?}",
2356                out["reply"]
2357            );
2358        }
2359
2360        #[tokio::test]
2361        async fn missing_user_text_matches_agent_node_contract() {
2362            // agent_node.rs treats missing `user_text` as an empty string and
2363            // proceeds (never Err). Assert the same contract here.
2364            let handler = handler_with(
2365                provider_with("triage", triage_cfg(3)),
2366                agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
2367                tool_fn_ok(),
2368            );
2369
2370            let out = handler
2371                .execute("t", "e", "triage", "sess-1", &json!({}))
2372                .await
2373                .expect("missing user_text must NOT return Err (matches agent_node)");
2374
2375            assert_eq!(out["terminated_by"].as_str(), Some("respond"));
2376        }
2377
2378        #[tokio::test]
2379        async fn iteration_cap_maps_to_error_envelope() {
2380            // maxIterations=1000 on the router → the executor's global
2381            // MAX_NODE_VISITS cap (64) trips first → IterationCap → "error".
2382            let handler = handler_with(
2383                provider_with("triage", triage_cfg(1000)),
2384                // never resolves → loops until the global visit cap
2385                agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), u32::MAX),
2386                tool_fn_ok(),
2387            );
2388
2389            let out = handler
2390                .execute("t", "e", "triage", "sess-1", &json!({"user_text": "loop"}))
2391                .await
2392                .expect("iteration cap must NOT return Err");
2393
2394            assert_eq!(out["terminated_by"].as_str(), Some("error"));
2395            assert_ne!(
2396                out["reply"].as_str(),
2397                Some(SANITISED_ERROR_REPLY),
2398                "iteration cap should use a distinct reply"
2399            );
2400        }
2401
2402        /// Regression test: flow session ids can contain `':'` (e.g. MS Teams
2403        /// channel correlation ids like `"msteams:thread:19xyz"`). The checkpoint
2404        /// store rejects keys that contain `':'`, so without sanitization every
2405        /// such graph run fails at save-time. [`derive_run_id`] must replace every
2406        /// `':'` with `'_'` before composing the checkpoint key.
2407        #[tokio::test]
2408        async fn colon_bearing_session_id_executes_successfully() {
2409            let handler = handler_with(
2410                provider_with("triage", triage_cfg(3)),
2411                agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
2412                tool_fn_ok(),
2413            );
2414
2415            // Session id with multiple colons — typical of Teams thread ids.
2416            let out = handler
2417                .execute(
2418                    "t",
2419                    "e",
2420                    "triage",
2421                    "msteams:thread:19xyz",
2422                    &json!({"user_text": "hello"}),
2423                )
2424                .await
2425                .expect("colon-bearing session id must NOT return Err");
2426
2427            assert_eq!(
2428                out["terminated_by"].as_str(),
2429                Some("respond"),
2430                "colon-bearing session id should complete successfully: {:?}",
2431                out
2432            );
2433        }
2434
2435        // -------------------------------------------------------------------
2436        // LayeredGraphProvider tests
2437        // -------------------------------------------------------------------
2438
2439        /// Provider that always returns the given error.
2440        struct ErrGraphProvider(fn() -> ConfigError);
2441
2442        impl GraphConfigSource for ErrGraphProvider {
2443            fn graph_config<'a>(
2444                &'a self,
2445                _tenant: &'a TenantContext,
2446                _graph_id: &'a str,
2447            ) -> BoxFut<'a, Result<GraphConfig, ConfigError>> {
2448                let e = (self.0)();
2449                Box::pin(async move { Err(e) })
2450            }
2451        }
2452
2453        /// Fallback that panics if consulted — proves primary short-circuits.
2454        struct PanicGraphProvider;
2455
2456        impl GraphConfigSource for PanicGraphProvider {
2457            fn graph_config<'a>(
2458                &'a self,
2459                _tenant: &'a TenantContext,
2460                _graph_id: &'a str,
2461            ) -> BoxFut<'a, Result<GraphConfig, ConfigError>> {
2462                Box::pin(
2463                    async move { panic!("fallback must not be consulted when primary returns Ok") },
2464                )
2465            }
2466        }
2467
2468        #[tokio::test]
2469        async fn layered_primary_ok_short_circuits_fallback() {
2470            let mut graphs = HashMap::new();
2471            graphs.insert("g".to_string(), triage_cfg(3));
2472            let primary = InMemoryGraphProvider::new(graphs);
2473            let layered = LayeredGraphProvider::new(primary, PanicGraphProvider);
2474            let tc = TenantContext::new("t", "e");
2475            // If fallback were consulted, PanicGraphProvider panics and fails this.
2476            let cfg = layered.graph_config(&tc, "g").await.unwrap();
2477            assert_eq!(cfg.graph.entry, "agent");
2478        }
2479
2480        #[tokio::test]
2481        async fn layered_falls_back_on_not_found() {
2482            let mut graphs = HashMap::new();
2483            graphs.insert("g".to_string(), triage_cfg(3));
2484            let fb = InMemoryGraphProvider::new(graphs);
2485            let layered = LayeredGraphProvider::new(
2486                ErrGraphProvider(|| ConfigError::AgentNotFound("g".into())),
2487                fb,
2488            );
2489            let tc = TenantContext::new("t", "e");
2490            let cfg = layered.graph_config(&tc, "g").await.unwrap();
2491            assert_eq!(cfg.graph.entry, "agent");
2492        }
2493
2494        #[tokio::test]
2495        async fn layered_falls_back_on_internal() {
2496            let mut graphs = HashMap::new();
2497            graphs.insert("g".to_string(), triage_cfg(3));
2498            let fb = InMemoryGraphProvider::new(graphs);
2499            let layered = LayeredGraphProvider::new(
2500                ErrGraphProvider(|| ConfigError::Internal("down".into())),
2501                fb,
2502            );
2503            let tc = TenantContext::new("t", "e");
2504            let cfg = layered.graph_config(&tc, "g").await.unwrap();
2505            assert_eq!(cfg.graph.entry, "agent");
2506        }
2507
2508        #[tokio::test]
2509        async fn layered_propagates_misconfigured_without_fallback() {
2510            let fb = InMemoryGraphProvider::new(HashMap::new());
2511            let layered = LayeredGraphProvider::new(
2512                ErrGraphProvider(|| ConfigError::Misconfigured("bad schema".into())),
2513                fb,
2514            );
2515            let tc = TenantContext::new("t", "e");
2516            let result = layered.graph_config(&tc, "g").await;
2517            assert!(
2518                matches!(result, Err(ConfigError::Misconfigured(_))),
2519                "Misconfigured must NOT fall back: {result:?}"
2520            );
2521        }
2522
2523        // -------------------------------------------------------------------
2524        // graph_registry_from_env tests
2525        // -------------------------------------------------------------------
2526
2527        #[test]
2528        #[serial_test::serial]
2529        #[allow(unsafe_code)]
2530        fn graph_registry_from_env_requires_both_vars() {
2531            // SAFETY: #[serial] serializes env-mutating tests; vars cleaned up.
2532            unsafe {
2533                std::env::remove_var("GREENTIC_AW_ADMIN_ENDPOINT");
2534                std::env::remove_var("GREENTIC_AW_ADMIN_TOKEN");
2535            }
2536            assert!(super::graph_registry_from_env().is_none());
2537
2538            unsafe {
2539                std::env::set_var("GREENTIC_AW_ADMIN_ENDPOINT", "http://localhost:9999");
2540            }
2541            assert!(
2542                super::graph_registry_from_env().is_none(),
2543                "endpoint alone is not enough"
2544            );
2545
2546            unsafe {
2547                std::env::set_var("GREENTIC_AW_ADMIN_TOKEN", "gtc_live_x");
2548            }
2549            assert!(super::graph_registry_from_env().is_some());
2550
2551            // Token-alone (no endpoint) must also be None.
2552            unsafe {
2553                std::env::remove_var("GREENTIC_AW_ADMIN_ENDPOINT");
2554            }
2555            assert!(
2556                super::graph_registry_from_env().is_none(),
2557                "token alone is not enough"
2558            );
2559
2560            unsafe {
2561                std::env::remove_var("GREENTIC_AW_ADMIN_TOKEN");
2562            }
2563        }
2564
2565        // -------------------------------------------------------------------
2566        // Supervisor fixture
2567        // -------------------------------------------------------------------
2568
2569        /// Supervisor graph (schemaVersion 2): sup → agent_billing / agent_tech →
2570        /// router → respond. Mirrors the aw-runtime `supervisor_json()` fixture
2571        /// (which is `pub(crate)` to that crate and cannot be imported here).
2572        ///
2573        /// Topology:
2574        ///   sup (supervisor: routes=[billing, tech])
2575        ///    ├─[billing]─► agent_billing ─► router_billing ─┬─[loop]──► sup
2576        ///    │                                               └─[resolved]─► respond
2577        ///    └─[tech]────► agent_tech ───► router_tech    ─┬─[loop]──► sup
2578        ///                                                   └─[resolved]─► respond
2579        fn supervisor_graph_json() -> String {
2580            json!({
2581                "schemaVersion": 2,
2582                "entry": "sup",
2583                "nodes": [
2584                    {
2585                        "id": "sup",
2586                        "kind": "supervisor",
2587                        "systemPrompt": "Route the request to the correct specialist.",
2588                        "model": "gpt-4o-mini",
2589                        "routes": [
2590                            {"branch": "billing", "description": "Billing and payment questions"},
2591                            {"branch": "tech",    "description": "Technical support issues"}
2592                        ]
2593                    },
2594                    {"id": "agent_billing", "kind": "agent", "systemPrompt": "Billing.", "model": "gpt-4o-mini", "tools": []},
2595                    {"id": "router_billing", "kind": "router", "maxIterations": 2},
2596                    {"id": "agent_tech",    "kind": "agent", "systemPrompt": "Tech.",    "model": "gpt-4o-mini", "tools": []},
2597                    {"id": "router_tech",   "kind": "router", "maxIterations": 2},
2598                    {"id": "respond",       "kind": "respond"}
2599                ],
2600                "edges": [
2601                    {"from": "sup",           "to": "agent_billing",  "branch": "billing"},
2602                    {"from": "sup",           "to": "agent_tech",     "branch": "tech"},
2603                    {"from": "agent_billing", "to": "router_billing"},
2604                    {"from": "router_billing","to": "agent_billing",  "branch": "loop"},
2605                    {"from": "router_billing","to": "respond",        "branch": "resolved"},
2606                    {"from": "agent_tech",    "to": "router_tech"},
2607                    {"from": "router_tech",   "to": "agent_tech",     "branch": "loop"},
2608                    {"from": "router_tech",   "to": "respond",        "branch": "resolved"}
2609                ]
2610            })
2611            .to_string()
2612        }
2613
2614        fn supervisor_cfg() -> GraphConfig {
2615            GraphConfig::from_json(&supervisor_graph_json()).expect("supervisor fixture valid")
2616        }
2617
2618        /// Helpers for building [`SupervisorRoute`] values inline.
2619        fn route(branch: &str, description: &str) -> SupervisorRoute {
2620            SupervisorRoute {
2621                branch: branch.to_string(),
2622                description: description.to_string(),
2623            }
2624        }
2625
2626        /// Build a supervisor fn that always routes to `fixed_branch`.
2627        fn supervisor_fn_routes_to(fixed_branch: &str) -> SupervisorFn {
2628            let branch = fixed_branch.to_string();
2629            Arc::new(move |_req: SupervisorRequest| {
2630                let branch = branch.clone();
2631                Box::pin(async move {
2632                    Ok(SupervisorResult {
2633                        branch: branch.clone(),
2634                        raw_reply: format!("I'll route this. [[ROUTE:{branch}]] Done."),
2635                    })
2636                })
2637            })
2638        }
2639
2640        // Build a handler wired with the given supervisor fn (and a no-op agent
2641        // that always resolves immediately).
2642        fn supervisor_handler(
2643            graphs: Arc<dyn GraphConfigSource>,
2644            supervisor: SupervisorFn,
2645        ) -> RuntimeGraphNodeHandler {
2646            let agent: AgentTurnFn = agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1);
2647            RuntimeGraphNodeHandler::with_effects(
2648                graphs,
2649                Arc::new(InMemoryCheckpointStore::default()),
2650                Arc::new(MockAgentStateStore::new()),
2651                agent,
2652                tool_fn_ok(),
2653                supervisor,
2654                approval_fn_awaiting(),
2655            )
2656        }
2657
2658        // -------------------------------------------------------------------
2659        // parse_route_branch unit tests
2660        // -------------------------------------------------------------------
2661
2662        /// Two routes for the parse tests.
2663        fn billing_tech_routes() -> Vec<SupervisorRoute> {
2664            vec![
2665                route("billing", "Billing and payment questions"),
2666                route("tech", "Technical support issues"),
2667            ]
2668        }
2669
2670        #[test]
2671        fn parse_route_extracts_billing_from_reply() {
2672            // Standard case: sentinel embedded in a longer reply.
2673            let reply = "I analysed the message. [[ROUTE:billing]] Go ahead.";
2674            let result = parse_route_branch(reply, &billing_tech_routes());
2675            assert_eq!(result, Some("billing".to_string()));
2676        }
2677
2678        #[test]
2679        fn parse_route_case_insensitive_prefix() {
2680            // The prefix [[ROUTE: is matched case-insensitively; the extracted
2681            // branch label must still match the declared route exactly
2682            // (case-sensitive per spec).
2683            let reply = "[[route:tech]] is the answer";
2684            let result = parse_route_branch(reply, &billing_tech_routes());
2685            assert_eq!(result, Some("tech".to_string()));
2686        }
2687
2688        #[test]
2689        fn parse_route_missing_sentinel_returns_none() {
2690            // No sentinel at all → None (caller's unwrap_or_else picks first route).
2691            let reply = "I think billing would be best here.";
2692            let result = parse_route_branch(reply, &billing_tech_routes());
2693            assert_eq!(result, None);
2694        }
2695
2696        #[test]
2697        fn parse_route_unknown_branch_returns_none() {
2698            // Sentinel present but branch label does not match any declared route.
2699            let reply = "[[ROUTE:unknown_branch]] routing";
2700            let result = parse_route_branch(reply, &billing_tech_routes());
2701            assert_eq!(result, None);
2702        }
2703
2704        #[test]
2705        fn parse_route_multiple_sentinels_uses_first() {
2706            // When multiple sentinels are present the function uses the FIRST one
2707            // (find on the lowercased string returns the first occurrence).
2708            let reply = "[[ROUTE:billing]] or [[ROUTE:tech]]";
2709            let result = parse_route_branch(reply, &billing_tech_routes());
2710            assert_eq!(
2711                result,
2712                Some("billing".to_string()),
2713                "multiple sentinels: first occurrence wins"
2714            );
2715        }
2716
2717        #[test]
2718        fn parse_route_branch_label_whitespace_trimmed() {
2719            // Whitespace around the branch label inside the sentinel is trimmed.
2720            let reply = "[[ROUTE:  billing  ]]";
2721            let result = parse_route_branch(reply, &billing_tech_routes());
2722            assert_eq!(result, Some("billing".to_string()));
2723        }
2724
2725        // -------------------------------------------------------------------
2726        // strip_route_sentinel unit tests
2727        // -------------------------------------------------------------------
2728
2729        #[test]
2730        fn strip_sentinel_removes_token_leaves_rest() {
2731            let reply = "I'll route this. [[ROUTE:billing]] Proceeding.";
2732            let stripped = strip_route_sentinel(reply);
2733            assert!(
2734                !stripped.contains("[[ROUTE:billing]]"),
2735                "sentinel must be removed: {stripped:?}"
2736            );
2737            assert!(
2738                stripped.contains("Proceeding"),
2739                "text after sentinel must survive: {stripped:?}"
2740            );
2741        }
2742
2743        #[test]
2744        fn strip_sentinel_no_sentinel_returns_trimmed() {
2745            let reply = "  No routing needed here.  ";
2746            let stripped = strip_route_sentinel(reply);
2747            assert_eq!(stripped, "No routing needed here.");
2748        }
2749
2750        #[test]
2751        fn strip_sentinel_case_insensitive_removal() {
2752            let reply = "Decision: [[route:tech]] done.";
2753            let stripped = strip_route_sentinel(reply);
2754            assert!(
2755                !stripped.to_ascii_lowercase().contains("[[route:"),
2756                "sentinel must be stripped case-insensitively: {stripped:?}"
2757            );
2758        }
2759
2760        #[test]
2761        fn strip_sentinel_only_first_occurrence_removed() {
2762            // If two sentinels appear, only the first is stripped.
2763            let reply = "[[ROUTE:billing]] first [[ROUTE:tech]] second";
2764            let stripped = strip_route_sentinel(reply);
2765            assert!(
2766                !stripped.contains("[[ROUTE:billing]]"),
2767                "first sentinel must be gone: {stripped:?}"
2768            );
2769            // The second sentinel remains (we only strip the first occurrence).
2770            assert!(
2771                stripped.contains("[[ROUTE:tech]]"),
2772                "second sentinel must remain: {stripped:?}"
2773            );
2774        }
2775
2776        // -------------------------------------------------------------------
2777        // Fallback: parse_route_branch None → first-route fallback
2778        // -------------------------------------------------------------------
2779
2780        #[test]
2781        fn parse_route_none_documents_fallback_to_first_route() {
2782            // This is a pure-fn test of the fallback path used in
2783            // `run_one_supervisor_turn` via `unwrap_or_else(|| first_route)`.
2784            // When parse_route_branch returns None, the build_supervisor closure
2785            // picks req.routes.first().branch as the fallback.
2786            let routes = billing_tech_routes();
2787            let garbage = "absolutely no routing sentinel here";
2788            let parsed = parse_route_branch(garbage, &routes);
2789            assert_eq!(parsed, None, "no sentinel → None from parser");
2790
2791            // Simulate the fallback: first route is "billing".
2792            let fallback = parsed
2793                .unwrap_or_else(|| routes.first().map(|r| r.branch.clone()).unwrap_or_default());
2794            assert_eq!(
2795                fallback, "billing",
2796                "None → first route 'billing' as fallback"
2797            );
2798        }
2799
2800        // -------------------------------------------------------------------
2801        // Handler-level supervisor routing tests
2802        // -------------------------------------------------------------------
2803
2804        #[tokio::test]
2805        async fn supervisor_routes_to_billing_returns_respond_envelope() {
2806            // The mock supervisor always picks "billing". The billing agent
2807            // resolves immediately. Expect terminated_by="respond" and a
2808            // non-empty reply.
2809            let handler = supervisor_handler(
2810                provider_with("sup_graph", supervisor_cfg()),
2811                supervisor_fn_routes_to("billing"),
2812            );
2813
2814            let out = handler
2815                .execute(
2816                    "t",
2817                    "e",
2818                    "sup_graph",
2819                    "sess-sup-1",
2820                    &json!({"user_text": "I need billing help"}),
2821                )
2822                .await
2823                .expect("supervisor execute must not Err");
2824
2825            assert_eq!(
2826                out["terminated_by"].as_str(),
2827                Some("respond"),
2828                "billing path must terminate at respond: {out:?}"
2829            );
2830            assert!(
2831                out["reply"].as_str().is_some_and(|r| !r.is_empty()),
2832                "reply must be non-empty: {out:?}"
2833            );
2834            assert!(
2835                out["trail"].as_array().is_some_and(|t| !t.is_empty()),
2836                "trail must be non-empty: {out:?}"
2837            );
2838        }
2839
2840        #[tokio::test]
2841        async fn supervisor_routes_to_tech_returns_respond_envelope() {
2842            // Same topology, supervisor picks "tech" branch instead.
2843            let handler = supervisor_handler(
2844                provider_with("sup_graph", supervisor_cfg()),
2845                supervisor_fn_routes_to("tech"),
2846            );
2847
2848            let out = handler
2849                .execute(
2850                    "t",
2851                    "e",
2852                    "sup_graph",
2853                    "sess-sup-2",
2854                    &json!({"user_text": "my device is broken"}),
2855                )
2856                .await
2857                .expect("supervisor tech-route execute must not Err");
2858
2859            assert_eq!(
2860                out["terminated_by"].as_str(),
2861                Some("respond"),
2862                "tech path must terminate at respond: {out:?}"
2863            );
2864        }
2865
2866        #[tokio::test]
2867        async fn supervisor_fallback_on_missing_sentinel_still_completes() {
2868            // A supervisor fn that returns a raw_reply with NO [[ROUTE:]] sentinel.
2869            // The build_supervisor closure maps None→first-route ("billing").
2870            // The handler-level execute() must still complete (not Err).
2871            //
2872            // Because with_effects injects the supervisor fn directly (bypassing
2873            // build_supervisor's parse), we simulate the fallback by having the
2874            // fn return the first route explicitly — matching what build_supervisor
2875            // does in production via parse_route_branch(...)
2876            //   .unwrap_or_else(|| routes.first().branch).
2877            // The pure-fn fallback path is fully covered by
2878            // `parse_route_none_documents_fallback_to_first_route`.
2879            let supervisor: SupervisorFn = Arc::new(|_req: SupervisorRequest| {
2880                // No sentinel in raw_reply; we return first-route directly as
2881                // the mock of the fallback behaviour.
2882                Box::pin(async move {
2883                    Ok(SupervisorResult {
2884                        branch: "billing".to_string(),
2885                        raw_reply: "I think billing is right.".to_string(),
2886                    })
2887                })
2888            });
2889
2890            let handler =
2891                supervisor_handler(provider_with("sup_graph", supervisor_cfg()), supervisor);
2892
2893            let out = handler
2894                .execute(
2895                    "t",
2896                    "e",
2897                    "sup_graph",
2898                    "sess-sup-3",
2899                    &json!({"user_text": "help me"}),
2900                )
2901                .await
2902                .expect("fallback supervisor must not Err");
2903
2904            assert_eq!(
2905                out["terminated_by"].as_str(),
2906                Some("respond"),
2907                "fallback path must still reach respond: {out:?}"
2908            );
2909        }
2910
2911        // -------------------------------------------------------------------
2912        // EPIC-B B-3b Task 2: `AgentAuditObserver` injection at the graph
2913        // turn `.step` seam (`run_agent_step`, shared by `run_one_agent_turn`
2914        // and `run_one_supervisor_turn`).
2915        // -------------------------------------------------------------------
2916
2917        fn real_tenant_ctx(tenant: &str, env: &str) -> greentic_types::TenantCtx {
2918            greentic_types::TenantCtx::new(
2919                greentic_types::EnvId::try_from(env).expect("valid env id"),
2920                greentic_types::TenantId::try_from(tenant).expect("valid tenant id"),
2921            )
2922        }
2923
2924        /// Build an [`AgentRuntime`] scripted to make one `remember` (host
2925        /// built-in short-term-memory) tool call before replying "done".
2926        /// Mirrors `agent_node`'s `runtime_with_scripted_remember_call`
2927        /// fixture — the host built-in path fires
2928        /// `StepObserver::on_tool_call`/`on_tool_result` without needing a
2929        /// real WASM extension dispatch, so it is the cheapest way to drive a
2930        /// genuine tool call through the seam.
2931        ///
2932        /// `run_one_agent_turn`/`run_one_supervisor_turn` hardcode
2933        /// `tools: vec![]` + `memory: None` on their ephemeral per-visit
2934        /// `AgentConfig` (graph-node agents have no tool/memory access in v1
2935        /// scope — see the `TODO(guardrail)` comment at each call site), so
2936        /// no tool call can ever reach the observer through those two
2937        /// functions today. This fixture instead drives the shared
2938        /// `run_agent_step` seam directly with its own memory-enabled
2939        /// config — the exact same `match audit_sink { .. }` code both turn
2940        /// functions delegate to — so the real-tenant wiring is verified
2941        /// against genuine tool-call traffic rather than asserted in the
2942        /// abstract.
2943        fn agent_runtime_with_scripted_remember_call(
2944            tenant: &TenantContext,
2945            agent_id: &str,
2946        ) -> AgentRuntime {
2947            use greentic_aw_runtime::cost::MockTokenMeter;
2948            use greentic_aw_runtime::llm::LlmResponse;
2949            use greentic_aw_runtime::mock::{MockLlmBackend, MockTelemetry, NoopToolLedger};
2950            use greentic_aw_runtime::state::ToolCallRecord;
2951            use greentic_aw_runtime::{InMemoryMemoryProvider, MemoryProviderRef, MemorySettings};
2952
2953            let llm = Arc::new(MockLlmBackend::new(vec![
2954                Ok(LlmResponse {
2955                    content: None,
2956                    tool_calls: vec![ToolCallRecord {
2957                        call_id: "c1".into(),
2958                        extension_id: "host".into(),
2959                        tool_name: "remember".into(),
2960                        args: json!({"key": "k", "value": "v"}),
2961                    }],
2962                    tokens_in: 1,
2963                    tokens_out: 1,
2964                }),
2965                Ok(LlmResponse {
2966                    content: Some("done".into()),
2967                    tool_calls: vec![],
2968                    tokens_in: 1,
2969                    tokens_out: 1,
2970                }),
2971            ]));
2972
2973            let cfg = AgentConfig {
2974                agent_id: agent_id.to_string(),
2975                system_prompt: "test".into(),
2976                tools: vec![],
2977                guardrails: vec![],
2978                llm: LlmProviderRef {
2979                    provider: "openai".into(),
2980                    model: "gpt-4o-mini".into(),
2981                    credential_ref: None,
2982                },
2983                limits: AgentLimits::default(),
2984                memory: Some(MemorySettings {
2985                    short_term: Some(MemoryProviderRef {
2986                        provider: "inmemory".into(),
2987                        capability: "cap://memory/short-term".into(),
2988                        params: Default::default(),
2989                        credential_ref: None,
2990                    }),
2991                    long_term: None,
2992                }),
2993                knowledge: None,
2994                conversational: false,
2995                opening_message: None,
2996                on_text_while_parked: Default::default(),
2997            };
2998            let mut provider = InMemoryConfigProvider::new();
2999            provider.insert(tenant, agent_id, cfg);
3000
3001            AgentRuntime::new(
3002                Arc::new(provider),
3003                Arc::new(MockAgentStateStore::new()),
3004                Arc::new(ExtensionRuntime::for_test().unwrap()),
3005                llm,
3006                Arc::new(MockTelemetry::new()),
3007                Arc::new(MockTokenMeter::new(0)),
3008                Arc::new(NoopToolLedger),
3009                None,
3010            )
3011            .with_short_term_memory(Arc::new(InMemoryMemoryProvider::new()))
3012        }
3013
3014        #[tokio::test]
3015        async fn run_agent_step_with_audit_sink_enqueues_events_under_real_tenant_not_state_tenant()
3016        {
3017            // The SYNTHETIC state tenant every graph-node turn uses today —
3018            // must NOT leak into the audit subject.
3019            let state_tenant = TenantContext::new("graph", "run");
3020            let agent_id = "graph.agent-1";
3021            let session_id = "graph__agent-1";
3022            let runtime = agent_runtime_with_scripted_remember_call(&state_tenant, agent_id);
3023
3024            let (tx, mut rx) = tokio::sync::mpsc::channel(16);
3025            let sink = AuditSink::from_sender(tx);
3026            let real_tenant = real_tenant_ctx("acme", "prod");
3027
3028            let input = AgentInput {
3029                text: String::new(),
3030                ..Default::default()
3031            };
3032            let out = run_agent_step(
3033                &runtime,
3034                state_tenant.clone(),
3035                session_id,
3036                agent_id,
3037                input,
3038                Some(&sink),
3039                &real_tenant,
3040            )
3041            .await
3042            .expect("step should succeed");
3043            assert_eq!(out.reply, "done");
3044
3045            let (subject, bytes) = rx.try_recv().expect("tool_call audit event enqueued");
3046            assert_eq!(
3047                subject, "audit.acme.agent.tool_call",
3048                "audit subject must carry the REAL tenant (\"acme\"), not the synthetic state tenant (\"graph\")"
3049            );
3050            let value: Value = serde_json::from_slice(&bytes).expect("valid JSON");
3051            assert_eq!(value["payload"]["tool"], json!("remember"));
3052            assert_eq!(value["payload"]["agent_id"], json!(agent_id));
3053
3054            let (subject, bytes) = rx.try_recv().expect("tool_result audit event enqueued");
3055            assert_eq!(subject, "audit.acme.agent.tool_result");
3056            let value: Value = serde_json::from_slice(&bytes).expect("valid JSON");
3057            assert_eq!(value["payload"]["tool"], json!("remember"));
3058
3059            assert!(
3060                rx.try_recv().is_err(),
3061                "exactly two audit events enqueued (one tool_call, one tool_result)"
3062            );
3063        }
3064
3065        #[tokio::test]
3066        async fn run_agent_step_without_audit_sink_uses_plain_step_path_unchanged() {
3067            // Same scripted tool call as the audited test above, but no audit
3068            // sink at all — proves the "off" branch (runtime.step, no
3069            // observer constructed) still dispatches the tool call and
3070            // returns the same reply, exactly as it did before
3071            // AgentAuditObserver existed.
3072            let state_tenant = TenantContext::new("graph", "run");
3073            let agent_id = "graph.agent-1";
3074            let session_id = "graph__agent-1";
3075            let runtime = agent_runtime_with_scripted_remember_call(&state_tenant, agent_id);
3076            let real_tenant = real_tenant_ctx("acme", "prod");
3077
3078            let input = AgentInput {
3079                text: String::new(),
3080                ..Default::default()
3081            };
3082            let out = run_agent_step(
3083                &runtime,
3084                state_tenant.clone(),
3085                session_id,
3086                agent_id,
3087                input,
3088                None,
3089                &real_tenant,
3090            )
3091            .await
3092            .expect("step should succeed");
3093
3094            assert_eq!(out.reply, "done");
3095        }
3096
3097        /// Minimal [`MockLlmBackend`] that always replies with `reply` and no
3098        /// tool calls — enough to drive `run_one_agent_turn`/
3099        /// `run_one_supervisor_turn` end to end without needing tool access
3100        /// (which their hardcoded ephemeral `AgentConfig` does not grant).
3101        fn plain_reply_llm(reply: &str) -> Arc<dyn LlmBackend> {
3102            use greentic_aw_runtime::llm::LlmResponse;
3103            use greentic_aw_runtime::mock::MockLlmBackend;
3104
3105            Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
3106                content: Some(reply.to_string()),
3107                tool_calls: vec![],
3108                tokens_in: 1,
3109                tokens_out: 1,
3110            })]))
3111        }
3112
3113        fn agent_turn_request(node_id: &str, system_prompt: &str) -> AgentTurnRequest {
3114            AgentTurnRequest {
3115                node_id: node_id.to_string(),
3116                system_prompt: system_prompt.to_string(),
3117                model: "gpt-4o-mini".to_string(),
3118                state: GraphRunState::default(),
3119                provider: None,
3120                tools: vec![],
3121                agent_ref: None,
3122                inherit_from: None,
3123            }
3124        }
3125
3126        /// Shared effect Arcs for `run_one_agent_turn`/`run_one_supervisor_turn`
3127        /// test calls: state store, ext runtime, telemetry, token meter, ledger.
3128        type AgentTurnEffects = (
3129            Arc<dyn AgentStateStore>,
3130            Arc<ExtensionRuntime>,
3131            Arc<dyn Telemetry>,
3132            Arc<dyn TokenMeter>,
3133            Arc<dyn ToolLedger>,
3134        );
3135
3136        fn agent_turn_effects() -> AgentTurnEffects {
3137            use greentic_aw_runtime::cost::MockTokenMeter;
3138            use greentic_aw_runtime::mock::{MockTelemetry, NoopToolLedger};
3139
3140            (
3141                Arc::new(MockAgentStateStore::new()),
3142                Arc::new(ExtensionRuntime::for_test().unwrap()),
3143                Arc::new(MockTelemetry::new()),
3144                Arc::new(MockTokenMeter::new(0)),
3145                Arc::new(NoopToolLedger),
3146            )
3147        }
3148
3149        #[tokio::test]
3150        async fn run_one_agent_turn_without_audit_sink_completes_unchanged() {
3151            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3152            let real_tenant = real_tenant_ctx("acme", "prod");
3153
3154            let result = run_one_agent_turn(
3155                agent_turn_request("agent", "You triage."),
3156                state_store,
3157                ext_runtime,
3158                plain_reply_llm("all good [[RESOLVED]]"),
3159                telemetry,
3160                token_meter,
3161                ledger,
3162                None,
3163                None,
3164                Arc::new(vec![]),
3165                Arc::new(HashMap::new()),
3166                None,
3167                &real_tenant,
3168                &crate::runner::knowledge_index::IndexMount::default(),
3169                &TurnBilling::default(),
3170            )
3171            .await
3172            .expect("turn should succeed");
3173
3174            assert!(result.resolved);
3175            assert_eq!(result.reply, "all good");
3176        }
3177
3178        #[tokio::test]
3179        async fn run_one_agent_turn_with_audit_sink_completes_same_reply_as_without() {
3180            // `agent_turn_request` declares no tools, and the mock LLM never
3181            // emits tool calls, so no audit event is expected here either —
3182            // this test guards that routing through `step_with_observer` does
3183            // not change the turn's outcome. Genuine tool-call
3184            // audit-under-real-tenant coverage lives in
3185            // `run_agent_step_with_audit_sink_enqueues_events_under_real_tenant_not_state_tenant`.
3186            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3187            let (tx, mut rx) = tokio::sync::mpsc::channel(16);
3188            let sink = AuditSink::from_sender(tx);
3189            let real_tenant = real_tenant_ctx("acme", "prod");
3190
3191            let result = run_one_agent_turn(
3192                agent_turn_request("agent", "You triage."),
3193                state_store,
3194                ext_runtime,
3195                plain_reply_llm("all good [[RESOLVED]]"),
3196                telemetry,
3197                token_meter,
3198                ledger,
3199                None,
3200                None,
3201                Arc::new(vec![]),
3202                Arc::new(HashMap::new()),
3203                Some(&sink),
3204                &real_tenant,
3205                &crate::runner::knowledge_index::IndexMount::default(),
3206                &TurnBilling::default(),
3207            )
3208            .await
3209            .expect("turn should succeed");
3210
3211            assert!(result.resolved);
3212            assert_eq!(result.reply, "all good");
3213            assert!(
3214                rx.try_recv().is_err(),
3215                "no tool call happens on this path, so no audit event is expected"
3216            );
3217        }
3218
3219        /// Wiring assertion (Task 2): a request whose `tools` field declares a
3220        /// well-formed ref reaches the ephemeral per-visit `AgentConfig`
3221        /// unharmed — the turn still completes (the runtime only warns, never
3222        /// fails, on tools that don't resolve against the test `ExtensionRuntime`
3223        /// — see `preflight_warn_tools`/`missing_tools` in `greentic-aw-runtime`).
3224        /// `map_tool_refs`/`parse_tool_ref` above cover the mapping itself;
3225        /// this proves `run_one_agent_turn` actually calls it instead of the
3226        /// old hardcoded `tools: vec![]`.
3227        #[tokio::test]
3228        async fn run_one_agent_turn_with_declared_tools_still_completes() {
3229            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3230            let real_tenant = real_tenant_ctx("acme", "prod");
3231
3232            let mut req = agent_turn_request("agent", "You triage.");
3233            req.tools = vec!["myext/dothing".to_string()];
3234
3235            let result = run_one_agent_turn(
3236                req,
3237                state_store,
3238                ext_runtime,
3239                plain_reply_llm("all good [[RESOLVED]]"),
3240                telemetry,
3241                token_meter,
3242                ledger,
3243                None,
3244                None,
3245                Arc::new(vec![]),
3246                Arc::new(HashMap::new()),
3247                None,
3248                &real_tenant,
3249                &crate::runner::knowledge_index::IndexMount::default(),
3250                &TurnBilling::default(),
3251            )
3252            .await
3253            .expect("turn should succeed even with a declared-but-unregistered tool");
3254
3255            assert!(result.resolved);
3256            assert_eq!(result.reply, "all good");
3257        }
3258
3259        // -------------------------------------------------------------------
3260        // SP1 Task 3: `agent_ref` resolution
3261        // -------------------------------------------------------------------
3262
3263        /// A published-agent config with a distinctive `system_prompt` marker
3264        /// ("FAQ-BOT") plus non-empty `memory`/`knowledge` bindings, standing
3265        /// in for a real `merged_agents` entry resolved by `agent_ref`.
3266        fn faq_bot_agent_config() -> AgentConfig {
3267            use greentic_aw_runtime::config::KnowledgeSettings;
3268            use greentic_aw_runtime::{MemoryProviderRef, MemorySettings};
3269
3270            AgentConfig {
3271                agent_id: "faq".to_string(),
3272                system_prompt: "You are FAQ-BOT. Answer only from the knowledge base.".to_string(),
3273                tools: vec![],
3274                guardrails: vec![],
3275                llm: LlmProviderRef {
3276                    provider: "openai".to_string(),
3277                    model: "gpt-4o-mini".to_string(),
3278                    credential_ref: None,
3279                },
3280                limits: AgentLimits::default(),
3281                memory: Some(MemorySettings {
3282                    short_term: Some(MemoryProviderRef {
3283                        provider: "inmemory".to_string(),
3284                        capability: "cap://memory/short-term".to_string(),
3285                        params: Default::default(),
3286                        credential_ref: None,
3287                    }),
3288                    long_term: None,
3289                }),
3290                knowledge: Some(KnowledgeSettings {
3291                    knowledge: Some(MemoryProviderRef {
3292                        provider: "chronicle".to_string(),
3293                        capability: "cap://dw.knowledge".to_string(),
3294                        params: Default::default(),
3295                        credential_ref: None,
3296                    }),
3297                    embedding: None,
3298                    top_k: 5,
3299                }),
3300                conversational: false,
3301                opening_message: None,
3302                on_text_while_parked: Default::default(),
3303            }
3304        }
3305
3306        /// Like [`plain_reply_llm`] but returns the concrete
3307        /// [`greentic_aw_runtime::mock::MockLlmBackend`] (not erased to
3308        /// `Arc<dyn LlmBackend>`) so the test can inspect `seen_system_prompts`
3309        /// after the turn completes.
3310        fn recording_llm(reply: &str) -> Arc<greentic_aw_runtime::mock::MockLlmBackend> {
3311            use greentic_aw_runtime::llm::LlmResponse;
3312            use greentic_aw_runtime::mock::MockLlmBackend;
3313
3314            Arc::new(MockLlmBackend::new(vec![Ok(LlmResponse {
3315                content: Some(reply.to_string()),
3316                tool_calls: vec![],
3317                tokens_in: 1,
3318                tokens_out: 1,
3319            })]))
3320        }
3321
3322        #[test]
3323        fn resolve_turn_config_agent_ref_present_returns_full_config_from_map() {
3324            let mut merged = HashMap::new();
3325            merged.insert("faq".to_string(), faq_bot_agent_config());
3326
3327            let mut req = agent_turn_request("s", "inline prompt, should be ignored");
3328            req.agent_ref = Some("faq".to_string());
3329
3330            let cfg = resolve_turn_config(&req, &merged, "graph.s").expect("resolves");
3331
3332            assert!(cfg.system_prompt.contains("FAQ-BOT"));
3333            assert!(cfg.memory.is_some(), "memory carried through unstripped");
3334            assert!(
3335                cfg.knowledge.is_some(),
3336                "knowledge carried through unstripped"
3337            );
3338        }
3339
3340        #[test]
3341        fn resolve_turn_config_agent_ref_none_returns_stripped_inline_config() {
3342            let merged = HashMap::new();
3343            let req = agent_turn_request("s", "You triage.");
3344
3345            let cfg = resolve_turn_config(&req, &merged, "graph.s").expect("resolves");
3346
3347            assert_eq!(cfg.system_prompt, "You triage.");
3348            assert_eq!(cfg.agent_id, "graph.s");
3349            assert!(cfg.memory.is_none());
3350            assert!(cfg.knowledge.is_none());
3351            assert!(cfg.guardrails.is_empty());
3352        }
3353
3354        #[test]
3355        fn resolve_turn_config_agent_ref_missing_returns_err() {
3356            let merged = HashMap::new();
3357            let mut req = agent_turn_request("s", "inline prompt");
3358            req.agent_ref = Some("missing".to_string());
3359
3360            let err = resolve_turn_config(&req, &merged, "graph.s").expect_err("must error");
3361
3362            assert!(
3363                err.to_string()
3364                    .contains("referenced agent 'missing' not found"),
3365                "unexpected error message: {err}"
3366            );
3367        }
3368
3369        #[tokio::test]
3370        async fn run_one_agent_turn_with_agent_ref_uses_referenced_config_system_prompt() {
3371            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3372            let real_tenant = real_tenant_ctx("acme", "prod");
3373
3374            let mut merged = HashMap::new();
3375            merged.insert("faq".to_string(), faq_bot_agent_config());
3376
3377            let mut req = agent_turn_request("s", "inline prompt, should NOT be used");
3378            req.agent_ref = Some("faq".to_string());
3379
3380            let llm = recording_llm("all good [[RESOLVED]]");
3381
3382            let result = run_one_agent_turn(
3383                req,
3384                state_store,
3385                ext_runtime,
3386                llm.clone(),
3387                telemetry,
3388                token_meter,
3389                ledger,
3390                None,
3391                None,
3392                Arc::new(vec![]),
3393                Arc::new(merged),
3394                None,
3395                &real_tenant,
3396                &crate::runner::knowledge_index::IndexMount::default(),
3397                &TurnBilling::default(),
3398            )
3399            .await
3400            .expect("turn should succeed");
3401
3402            assert!(result.resolved);
3403            assert_eq!(result.reply, "all good");
3404
3405            let seen = llm.seen_system_prompts.lock().expect("lock poisoned");
3406            assert_eq!(seen.len(), 1);
3407            assert!(
3408                seen[0].contains("FAQ-BOT"),
3409                "expected the referenced agent's system prompt, got: {}",
3410                seen[0]
3411            );
3412            assert!(
3413                !seen[0].contains("should NOT be used"),
3414                "the node's inline system prompt must not be used when agent_ref is set"
3415            );
3416        }
3417
3418        #[tokio::test]
3419        async fn run_one_agent_turn_without_agent_ref_uses_inline_system_prompt() {
3420            // Regression: agent_ref = None stays byte-unchanged — the node's
3421            // own inline system_prompt is what the LLM sees, not any entry
3422            // from `merged_agents` (even when one happens to exist).
3423            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3424            let real_tenant = real_tenant_ctx("acme", "prod");
3425
3426            let mut merged = HashMap::new();
3427            merged.insert("faq".to_string(), faq_bot_agent_config());
3428
3429            let req = agent_turn_request("s", "You triage inline.");
3430            let llm = recording_llm("all good [[RESOLVED]]");
3431
3432            let result = run_one_agent_turn(
3433                req,
3434                state_store,
3435                ext_runtime,
3436                llm.clone(),
3437                telemetry,
3438                token_meter,
3439                ledger,
3440                None,
3441                None,
3442                Arc::new(vec![]),
3443                Arc::new(merged),
3444                None,
3445                &real_tenant,
3446                &crate::runner::knowledge_index::IndexMount::default(),
3447                &TurnBilling::default(),
3448            )
3449            .await
3450            .expect("turn should succeed");
3451
3452            assert!(result.resolved);
3453
3454            let seen = llm.seen_system_prompts.lock().expect("lock poisoned");
3455            assert_eq!(seen.len(), 1);
3456            assert!(seen[0].contains("You triage inline."));
3457            assert!(!seen[0].contains("FAQ-BOT"));
3458        }
3459
3460        #[tokio::test]
3461        async fn run_one_agent_turn_with_missing_agent_ref_errors() {
3462            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3463            let real_tenant = real_tenant_ctx("acme", "prod");
3464
3465            let mut req = agent_turn_request("s", "inline prompt");
3466            req.agent_ref = Some("missing".to_string());
3467
3468            let err = run_one_agent_turn(
3469                req,
3470                state_store,
3471                ext_runtime,
3472                plain_reply_llm("unused"),
3473                telemetry,
3474                token_meter,
3475                ledger,
3476                None,
3477                None,
3478                Arc::new(vec![]),
3479                Arc::new(HashMap::new()),
3480                None,
3481                &real_tenant,
3482                &crate::runner::knowledge_index::IndexMount::default(),
3483                &TurnBilling::default(),
3484            )
3485            .await
3486            .expect_err("must error when agent_ref doesn't resolve");
3487
3488            assert!(
3489                err.to_string()
3490                    .contains("referenced agent 'missing' not found"),
3491                "unexpected error message: {err}"
3492            );
3493        }
3494
3495        /// The specialist case: `inherit_from` adopts the worker's capability
3496        /// surface WITHOUT overwriting the node's own prompt. If this ever
3497        /// regressed to `agent_ref` semantics, every specialist in a generated
3498        /// graph would collapse into an identical copy of its parent.
3499        #[test]
3500        fn inherit_from_keeps_the_node_prompt_and_adopts_the_capability_surface() {
3501            use greentic_aw_runtime::config::GuardrailRef;
3502
3503            let mut parent = faq_bot_agent_config();
3504            parent.guardrails = vec![GuardrailRef {
3505                cap_id: "greentic:guardrail/pii".to_string(),
3506                offer_id: None,
3507                config: serde_json::json!({}),
3508                mode: Default::default(),
3509            }];
3510            let mut merged = HashMap::new();
3511            merged.insert("faq".to_string(), parent);
3512
3513            let mut req = agent_turn_request("spec-billing", "You handle billing only.");
3514            req.inherit_from = Some("faq".to_string());
3515
3516            let cfg = resolve_turn_config(&req, &merged, "graph.spec-billing")
3517                .expect("a resolvable inherit_from must succeed");
3518
3519            assert_eq!(
3520                cfg.system_prompt, "You handle billing only.",
3521                "the specialist keeps its OWN prompt — this is the whole point"
3522            );
3523            assert_eq!(cfg.guardrails.len(), 1, "guardrails are inherited");
3524            assert!(cfg.memory.is_some(), "memory is inherited");
3525            assert!(cfg.knowledge.is_some(), "knowledge is inherited");
3526        }
3527
3528        /// An unresolvable `inherit_from` fails rather than running stripped.
3529        #[test]
3530        fn inherit_from_unresolvable_fails_rather_than_running_stripped() {
3531            let merged = HashMap::new();
3532            let mut req = agent_turn_request("spec", "Specialist prompt.");
3533            req.inherit_from = Some("ghost".to_string());
3534
3535            let err = resolve_turn_config(&req, &merged, "graph.spec")
3536                .expect_err("an unknown inherit_from must not silently succeed");
3537            let msg = err.to_string();
3538            assert!(
3539                msg.contains("ghost") && msg.contains("refusing to run"),
3540                "error should name the id and say it refused: {msg}"
3541            );
3542        }
3543
3544        /// `agent_ref` still wins when both are set — it already takes
3545        /// everything, including the prompt.
3546        #[test]
3547        fn agent_ref_takes_precedence_over_inherit_from() {
3548            let mut merged = HashMap::new();
3549            merged.insert("faq".to_string(), faq_bot_agent_config());
3550
3551            let mut req = agent_turn_request("spec", "Specialist prompt.");
3552            req.agent_ref = Some("faq".to_string());
3553            req.inherit_from = Some("faq".to_string());
3554
3555            let cfg = resolve_turn_config(&req, &merged, "graph.spec").expect("resolvable");
3556            assert_eq!(
3557                cfg.system_prompt, "You are FAQ-BOT. Answer only from the knowledge base.",
3558                "agent_ref adopts the referenced prompt wholesale"
3559            );
3560        }
3561
3562        /// A supervisor with no `agent_ref` keeps today's behaviour: no
3563        /// guardrails, and nothing fails.
3564        #[test]
3565        fn supervisor_without_agent_ref_resolves_no_guardrails() {
3566            let merged = HashMap::new();
3567            let got = resolve_supervisor_guardrails(None, &merged, "router")
3568                .expect("absent agent_ref is not an error");
3569            assert!(got.is_empty());
3570        }
3571
3572        /// The point of the whole change: a supervisor pointed at its worker
3573        /// runs under that worker's guardrails.
3574        #[test]
3575        fn supervisor_with_agent_ref_inherits_the_parent_guardrails() {
3576            use greentic_aw_runtime::config::GuardrailRef;
3577
3578            let mut parent = faq_bot_agent_config();
3579            parent.guardrails = vec![GuardrailRef {
3580                cap_id: "greentic:guardrail/pii".to_string(),
3581                offer_id: None,
3582                config: serde_json::json!({}),
3583                mode: Default::default(),
3584            }];
3585            let mut merged = HashMap::new();
3586            merged.insert("faq".to_string(), parent);
3587
3588            let got = resolve_supervisor_guardrails(Some("faq"), &merged, "router")
3589                .expect("a resolvable agent_ref must succeed");
3590            assert_eq!(got.len(), 1);
3591            assert_eq!(got[0].cap_id, "greentic:guardrail/pii");
3592        }
3593
3594        /// An unresolvable `agent_ref` FAILS rather than routing unguarded — a
3595        /// supervisor believed to be protected but running bare is exactly what
3596        /// this inheritance exists to prevent.
3597        #[test]
3598        fn supervisor_with_unresolvable_agent_ref_fails_rather_than_routing_bare() {
3599            let merged = HashMap::new();
3600            let err = resolve_supervisor_guardrails(Some("ghost"), &merged, "router")
3601                .expect_err("an unknown agent_ref must not silently succeed");
3602            let msg = err.to_string();
3603            assert!(
3604                msg.contains("ghost") && msg.contains("refusing to route"),
3605                "error should name the id and say it refused: {msg}"
3606            );
3607        }
3608
3609        /// A supervisor inherits guardrails ONLY — the referenced worker's
3610        /// memory and knowledge are deliberately left behind. It routes, it
3611        /// does not work.
3612        #[test]
3613        fn supervisor_inherits_guardrails_but_not_memory_or_knowledge() {
3614            use greentic_aw_runtime::config::GuardrailRef;
3615
3616            let mut parent = faq_bot_agent_config();
3617            parent.guardrails = vec![GuardrailRef {
3618                cap_id: "greentic:guardrail/pii".to_string(),
3619                offer_id: None,
3620                config: serde_json::json!({}),
3621                mode: Default::default(),
3622            }];
3623            assert!(parent.memory.is_some(), "fixture should carry memory");
3624            assert!(parent.knowledge.is_some(), "fixture should carry knowledge");
3625
3626            let mut merged = HashMap::new();
3627            merged.insert("faq".to_string(), parent);
3628
3629            let got =
3630                resolve_supervisor_guardrails(Some("faq"), &merged, "router").expect("resolvable");
3631            assert_eq!(got.len(), 1, "guardrails come across");
3632        }
3633
3634        #[tokio::test]
3635        async fn run_one_supervisor_turn_without_audit_sink_completes_unchanged() {
3636            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3637            let real_tenant = real_tenant_ctx("acme", "prod");
3638            let routes = vec![
3639                SupervisorRoute {
3640                    branch: "billing".into(),
3641                    description: "Billing questions".into(),
3642                },
3643                SupervisorRoute {
3644                    branch: "tech".into(),
3645                    description: "Technical support".into(),
3646                },
3647            ];
3648            let req = SupervisorRequest {
3649                node_id: "router".to_string(),
3650                system_prompt: "Route the user.".to_string(),
3651                model: "gpt-4o-mini".to_string(),
3652                routes,
3653                state: GraphRunState::default(),
3654                provider: None,
3655                agent_ref: None,
3656            };
3657
3658            // No [[ROUTE:..]] sentinel in the reply -> falls back to the
3659            // first declared route.
3660            let result = run_one_supervisor_turn(
3661                req,
3662                state_store,
3663                ext_runtime,
3664                plain_reply_llm("I'm not sure, let me think."),
3665                telemetry,
3666                token_meter,
3667                ledger,
3668                Arc::new(HashMap::new()),
3669                None,
3670                &real_tenant,
3671                &TurnBilling::default(),
3672            )
3673            .await
3674            .expect("supervisor turn should succeed");
3675
3676            assert_eq!(result.branch, "billing");
3677        }
3678
3679        #[tokio::test]
3680        async fn run_one_supervisor_turn_with_audit_sink_completes_same_branch_as_without() {
3681            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3682            let (tx, mut rx) = tokio::sync::mpsc::channel(16);
3683            let sink = AuditSink::from_sender(tx);
3684            let real_tenant = real_tenant_ctx("acme", "prod");
3685            let routes = vec![
3686                SupervisorRoute {
3687                    branch: "billing".into(),
3688                    description: "Billing questions".into(),
3689                },
3690                SupervisorRoute {
3691                    branch: "tech".into(),
3692                    description: "Technical support".into(),
3693                },
3694            ];
3695            let req = SupervisorRequest {
3696                node_id: "router".to_string(),
3697                system_prompt: "Route the user.".to_string(),
3698                model: "gpt-4o-mini".to_string(),
3699                routes,
3700                state: GraphRunState::default(),
3701                provider: None,
3702                agent_ref: None,
3703            };
3704
3705            let result = run_one_supervisor_turn(
3706                req,
3707                state_store,
3708                ext_runtime,
3709                plain_reply_llm("I'm not sure, let me think."),
3710                telemetry,
3711                token_meter,
3712                ledger,
3713                Arc::new(HashMap::new()),
3714                Some(&sink),
3715                &real_tenant,
3716                &TurnBilling::default(),
3717            )
3718            .await
3719            .expect("supervisor turn should succeed");
3720
3721            assert_eq!(result.branch, "billing");
3722            assert!(
3723                rx.try_recv().is_err(),
3724                "no tool call happens on this path, so no audit event is expected"
3725            );
3726        }
3727
3728        // -------------------------------------------------------------------
3729        // Billing of graph turns
3730        // -------------------------------------------------------------------
3731
3732        /// (tenant_id, env_id, project_id, agent_id, model) per `emit`.
3733        type GraphEmit = (String, String, Option<String>, String, String);
3734
3735        #[derive(Default)]
3736        struct RecordingGraphMeter {
3737            calls: std::sync::Mutex<Vec<GraphEmit>>,
3738        }
3739
3740        impl greentic_aw_runtime::billing::BillingMeter for RecordingGraphMeter {
3741            fn emit<'a>(
3742                &'a self,
3743                tenant: &'a TenantContext,
3744                _input_tokens: u64,
3745                _output_tokens: u64,
3746                agent_id: &'a str,
3747                model: &'a str,
3748            ) -> std::pin::Pin<
3749                Box<
3750                    dyn std::future::Future<
3751                            Output = Result<(), greentic_aw_runtime::billing::BillingError>,
3752                        > + Send
3753                        + 'a,
3754                >,
3755            > {
3756                self.calls.lock().expect("lock").push((
3757                    tenant.tenant_id.clone(),
3758                    tenant.env_id.clone(),
3759                    tenant.project_id.clone(),
3760                    agent_id.to_string(),
3761                    model.to_string(),
3762                ));
3763                Box::pin(async { Ok(()) })
3764            }
3765
3766            fn over_budget<'a>(
3767                &'a self,
3768                _tenant: &'a TenantContext,
3769            ) -> std::pin::Pin<Box<dyn std::future::Future<Output = bool> + Send + 'a>>
3770            {
3771                Box::pin(std::future::ready(false))
3772            }
3773        }
3774
3775        fn unit_billing(meter: &Arc<RecordingGraphMeter>) -> TurnBilling {
3776            TurnBilling {
3777                meter: Some(
3778                    Arc::clone(meter) as Arc<dyn greentic_aw_runtime::billing::BillingMeter>
3779                ),
3780                project_id: Some("support-bot".to_string()),
3781                state_scope: None,
3782            }
3783        }
3784
3785        /// Per-visit agent conversations are scoped to the session AND graph, so
3786        /// two sessions running the same node never share stored state.
3787        #[test]
3788        fn per_visit_session_ids_are_scoped_to_session_and_graph() {
3789            let scoped = |session: &str, graph: &str| TurnBilling {
3790                state_scope: Some(format!("{session}__{graph}")),
3791                ..TurnBilling::default()
3792            };
3793            let a = scoped("sess-a", "triage").scoped_session("graph__n1");
3794            let b = scoped("sess-b", "triage").scoped_session("graph__n1");
3795            let c = scoped("sess-a", "other").scoped_session("graph__n1");
3796            assert_ne!(a, b);
3797            assert_ne!(a, c);
3798            assert_eq!(a, "sess-a__triage__graph__n1");
3799            assert_eq!(
3800                TurnBilling::default().scoped_session("graph__n1"),
3801                "graph__n1"
3802            );
3803        }
3804
3805        /// An agent-graph turn bills through the unit's installed sink, under
3806        /// the REAL tenant/env the node was dispatched with and the deployed
3807        /// unit — not the synthetic `("graph", "run")` tenant every graph turn
3808        /// used to run under, which also meant no sink at all.
3809        #[tokio::test]
3810        async fn a_graph_agent_turn_bills_the_real_tenant_and_the_unit() {
3811            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3812            let real_tenant = real_tenant_ctx("acme", "prod");
3813            let meter = Arc::new(RecordingGraphMeter::default());
3814
3815            run_one_agent_turn(
3816                agent_turn_request("triage", "You triage."),
3817                state_store,
3818                ext_runtime,
3819                plain_reply_llm("routed [[RESOLVED]]"),
3820                telemetry,
3821                token_meter,
3822                ledger,
3823                None,
3824                None,
3825                Arc::new(vec![]),
3826                Arc::new(HashMap::new()),
3827                None,
3828                &real_tenant,
3829                &crate::runner::knowledge_index::IndexMount::default(),
3830                &unit_billing(&meter),
3831            )
3832            .await
3833            .expect("turn succeeds");
3834
3835            let calls = meter.calls.lock().expect("lock");
3836            assert_eq!(calls.len(), 1, "one LLM iteration → one billing emit");
3837            assert_eq!(
3838                calls[0],
3839                (
3840                    "acme".to_string(),
3841                    "prod".to_string(),
3842                    Some("support-bot".to_string()),
3843                    "graph.triage".to_string(),
3844                    "gpt-4o-mini".to_string(),
3845                )
3846            );
3847        }
3848
3849        /// Supervisor routing is an LLM call too, and bills the same way.
3850        #[tokio::test]
3851        async fn a_supervisor_routing_turn_is_billed() {
3852            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3853            let real_tenant = real_tenant_ctx("acme", "prod");
3854            let meter = Arc::new(RecordingGraphMeter::default());
3855            let req = SupervisorRequest {
3856                node_id: "router".to_string(),
3857                system_prompt: "Route the user.".to_string(),
3858                model: "claude-3-haiku".to_string(),
3859                routes: vec![SupervisorRoute {
3860                    branch: "billing".into(),
3861                    description: "Billing questions".into(),
3862                }],
3863                state: GraphRunState::default(),
3864                provider: None,
3865                agent_ref: None,
3866            };
3867
3868            run_one_supervisor_turn(
3869                req,
3870                state_store,
3871                ext_runtime,
3872                plain_reply_llm("[[ROUTE:billing]]"),
3873                telemetry,
3874                token_meter,
3875                ledger,
3876                Arc::new(HashMap::new()),
3877                None,
3878                &real_tenant,
3879                &unit_billing(&meter),
3880            )
3881            .await
3882            .expect("supervisor turn succeeds");
3883
3884            let calls = meter.calls.lock().expect("lock");
3885            assert_eq!(calls.len(), 1);
3886            assert_eq!(calls[0].0, "acme");
3887            assert_eq!(calls[0].1, "prod");
3888            assert_eq!(calls[0].2.as_deref(), Some("support-bot"));
3889            assert_eq!(calls[0].3, "graph.router.supervisor");
3890            assert_eq!(calls[0].4, "claude-3-haiku");
3891        }
3892
3893        /// No installed sink leaves the turn exactly as unbilled as before —
3894        /// and it still runs.
3895        #[tokio::test]
3896        async fn a_graph_turn_without_a_sink_still_runs() {
3897            let (state_store, ext_runtime, telemetry, token_meter, ledger) = agent_turn_effects();
3898            let real_tenant = real_tenant_ctx("acme", "prod");
3899            let result = run_one_agent_turn(
3900                agent_turn_request("triage", "You triage."),
3901                state_store,
3902                ext_runtime,
3903                plain_reply_llm("hello"),
3904                telemetry,
3905                token_meter,
3906                ledger,
3907                None,
3908                None,
3909                Arc::new(vec![]),
3910                Arc::new(HashMap::new()),
3911                None,
3912                &real_tenant,
3913                &crate::runner::knowledge_index::IndexMount::default(),
3914                &TurnBilling::default(),
3915            )
3916            .await
3917            .expect("turn succeeds with no sink");
3918            assert_eq!(result.reply, "hello");
3919        }
3920
3921        #[test]
3922        fn with_billing_sets_the_sink_and_unit_on_the_handler() {
3923            let handler = handler_with(
3924                Arc::new(InMemoryGraphProvider::new(HashMap::new())),
3925                agent_fn_resolves_on(Arc::new(AtomicU32::new(0)), 1),
3926                tool_fn_ok(),
3927            );
3928            assert!(handler.billing.meter.is_none());
3929            let meter = Arc::new(RecordingGraphMeter::default());
3930            let handler = handler.with_billing(
3931                Some(meter as Arc<dyn greentic_aw_runtime::billing::BillingMeter>),
3932                Some("support-bot".to_string()),
3933            );
3934            assert!(handler.billing.meter.is_some());
3935            assert_eq!(handler.billing.project_id.as_deref(), Some("support-bot"));
3936        }
3937    }
3938
3939    /// Graph turns and graph Tool nodes resolve `a2a:` tools from the same
3940    /// pack-carried source a single-turn `dw.agent` does
3941    /// ([`graph_a2a_source`]). Env-mutating, so every test is `#[serial]`
3942    /// (crate convention, as in `a2a_pack_source`'s tests).
3943    #[cfg(all(test, feature = "agentic-worker"))]
3944    #[allow(clippy::unwrap_used, clippy::expect_used)]
3945    mod a2a_tests {
3946        use std::collections::HashMap;
3947        use std::future::Future;
3948        use std::pin::Pin;
3949        use std::sync::{Arc, Mutex};
3950
3951        use greentic_aw_runtime::cost::MockTokenMeter;
3952        use greentic_aw_runtime::error::LlmError;
3953        use greentic_aw_runtime::graph::{AgentTurnRequest, GraphRunState, ToolCallRequest};
3954        use greentic_aw_runtime::llm::{LlmBackend, LlmRequest, LlmResponse};
3955        use greentic_aw_runtime::mock::{MockAgentStateStore, MockTelemetry, NoopToolLedger};
3956        use greentic_aw_runtime::state::ToolCallRecord;
3957        use greentic_aw_runtime::{AgentConfig, AgentLimits, LlmProviderRef, ToolRef};
3958        use greentic_ext_runtime::ExtensionRuntime;
3959        use serde_json::json;
3960        use wiremock::matchers::{method, path};
3961        use wiremock::{Mock, MockServer, ResponseTemplate};
3962
3963        use super::{RuntimeTurnSource, TurnEffectSource, build_tool, graph_a2a_source};
3964
3965        /// A hyphenated id, as the admin mints them.
3966        const AGENT_ID: &str = "8d2f0c1e-recipe";
3967        const TENANT: &str = "acme";
3968        const UNIT: &str = "unit-1";
3969
3970        async fn serve_agent(server: &MockServer, reply: &str) {
3971            let card = json!({
3972                "name": "Recipe Agent",
3973                "description": "Suggests dishes.",
3974                "version": "1.0.0",
3975                "supportedInterfaces": [{
3976                    "url": format!("{}/a2a", server.uri()),
3977                    "protocolBinding": "JSONRPC",
3978                    "protocolVersion": "1.0"
3979                }],
3980                "capabilities": {"streaming": false, "pushNotifications": false},
3981                "defaultInputModes": ["text/plain"],
3982                "defaultOutputModes": ["text/plain"],
3983                "skills": []
3984            });
3985            Mock::given(method("GET"))
3986                .and(path("/.well-known/agent-card.json"))
3987                .respond_with(ResponseTemplate::new(200).set_body_json(card))
3988                .mount(server)
3989                .await;
3990            Mock::given(method("POST"))
3991                .and(path("/a2a"))
3992                .respond_with(ResponseTemplate::new(200).set_body_json(json!({
3993                    "jsonrpc": "2.0", "id": 1,
3994                    "result": {"message": {"messageId": "m-2", "role": "ROLE_AGENT",
3995                                           "parts": [{"text": reply}]}}
3996                })))
3997                .mount(server)
3998                .await;
3999        }
4000
4001        /// A pack whose `assets/a2a-routes.json` names one team-scoped agent at
4002        /// `server`.
4003        fn pack_for(server: &MockServer) -> (tempfile::TempDir, Arc<crate::pack::PackRuntime>) {
4004            let dir = tempfile::tempdir().unwrap();
4005            std::fs::create_dir_all(dir.path().join("assets")).unwrap();
4006            let sidecar = json!([{
4007                "agent_id": AGENT_ID,
4008                "name": "Recipe agent",
4009                "base_url": server.uri(),
4010                "auth_header_name": null,
4011                "auth_team": "sales",
4012                "requires_auth": true
4013            }]);
4014            std::fs::write(
4015                dir.path().join("assets/a2a-routes.json"),
4016                sidecar.to_string(),
4017            )
4018            .unwrap();
4019            let pack = Arc::new(crate::pack::tests::pack_runtime_for_dir(dir.path()));
4020            (dir, pack)
4021        }
4022
4023        struct MapSecrets(HashMap<String, Vec<u8>>);
4024
4025        #[async_trait::async_trait]
4026        impl greentic_secrets_lib::SecretsManager for MapSecrets {
4027            async fn read(&self, path: &str) -> greentic_secrets_lib::Result<Vec<u8>> {
4028                self.0
4029                    .get(path)
4030                    .cloned()
4031                    .ok_or_else(|| greentic_secrets_lib::SecretError::NotFound(path.to_string()))
4032            }
4033            async fn write(&self, _: &str, _: &[u8]) -> greentic_secrets_lib::Result<()> {
4034                Ok(())
4035            }
4036            async fn delete(&self, _: &str) -> greentic_secrets_lib::Result<()> {
4037                Ok(())
4038            }
4039        }
4040
4041        /// A store holding the token ONLY at the unit-scoped URI, so a call
4042        /// that authenticates proves the tenant, the team and the unit all
4043        /// reached the source.
4044        fn unit_scoped_store() -> crate::secrets::DynSecretsManager {
4045            let uri = greentic_aw_runtime::scoped_secrets::secret_uri_candidates(
4046                "a2a",
4047                TENANT,
4048                Some("sales"),
4049                Some(UNIT),
4050                AGENT_ID,
4051            )
4052            .unwrap()
4053            .remove(0);
4054            assert!(uri.contains(".unit-"), "first candidate is the unit scope");
4055            Arc::new(MapSecrets(HashMap::from([(uri, b"tok-1".to_vec())])))
4056        }
4057
4058        #[allow(unsafe_code)]
4059        fn set_gate(value: Option<&str>) {
4060            // SAFETY: every caller is #[serial] (crate convention).
4061            unsafe {
4062                match value {
4063                    Some(v) => std::env::set_var("GREENTIC_AW_A2A", v),
4064                    None => std::env::remove_var("GREENTIC_AW_A2A"),
4065                }
4066            }
4067        }
4068
4069        /// LLM backend recording the tools offered on each call, then
4070        /// replaying a script.
4071        struct RecordingLlm {
4072            responses: Mutex<Vec<LlmResponse>>,
4073            offered: Mutex<Vec<Vec<(String, String)>>>,
4074        }
4075
4076        impl LlmBackend for RecordingLlm {
4077            fn complete<'a>(
4078                &'a self,
4079                req: LlmRequest,
4080            ) -> Pin<Box<dyn Future<Output = Result<LlmResponse, LlmError>> + Send + 'a>>
4081            {
4082                self.offered.lock().unwrap().push(
4083                    req.tools
4084                        .iter()
4085                        .map(|t| (t.extension_id.clone(), t.tool_name.clone()))
4086                        .collect(),
4087                );
4088                let next = {
4089                    let mut queue = self.responses.lock().unwrap();
4090                    if queue.is_empty() {
4091                        Err(LlmError::Transport("script exhausted".into()))
4092                    } else {
4093                        Ok(queue.remove(0))
4094                    }
4095                };
4096                Box::pin(async move { next })
4097            }
4098        }
4099
4100        fn tool_ref() -> String {
4101            format!("a2a:{AGENT_ID}")
4102        }
4103
4104        /// The worker a specialist inherits from: it binds the `a2a:` tool
4105        /// with the author contract the designer ships.
4106        fn worker_with_a2a_tool() -> AgentConfig {
4107            AgentConfig {
4108                agent_id: "worker".into(),
4109                system_prompt: "sys".into(),
4110                tools: vec![ToolRef {
4111                    extension_id: tool_ref(),
4112                    tool_name: "ask".into(),
4113                    description: Some("Ask the Recipe agent agent.".into()),
4114                    input_schema: Some(json!({
4115                        "type": "object",
4116                        "properties": {"message": {"type": "string"}},
4117                        "required": ["message"]
4118                    })),
4119                    usage_note: None,
4120                }],
4121                llm: LlmProviderRef {
4122                    provider: "mock".into(),
4123                    model: "m".into(),
4124                    credential_ref: None,
4125                },
4126                limits: AgentLimits::default(),
4127                memory: None,
4128                knowledge: None,
4129                guardrails: vec![],
4130                conversational: false,
4131                opening_message: None,
4132                on_text_while_parked: Default::default(),
4133            }
4134        }
4135
4136        /// Drive one graph agent turn through the PRODUCTION turn source (the
4137        /// same `RuntimeTurnSource` `from_parts` builds), for a specialist that
4138        /// inherits the worker's tools. Returns the reply and the tools offered
4139        /// on the first LLM call.
4140        async fn run_specialist_turn(
4141            a2a_source: Option<Arc<greentic_aw_runtime::A2aToolSource>>,
4142            calls_tool: bool,
4143        ) -> (String, Vec<(String, String)>) {
4144            let mut script = Vec::new();
4145            if calls_tool {
4146                script.push(LlmResponse {
4147                    content: None,
4148                    tool_calls: vec![ToolCallRecord {
4149                        call_id: "c1".into(),
4150                        extension_id: tool_ref(),
4151                        tool_name: "ask".into(),
4152                        args: json!({"message": "eggs?"}),
4153                    }],
4154                    tokens_in: 5,
4155                    tokens_out: 5,
4156                });
4157            }
4158            script.push(LlmResponse {
4159                content: Some("Try an omelette. [[RESOLVED]]".into()),
4160                tool_calls: vec![],
4161                tokens_in: 5,
4162                tokens_out: 5,
4163            });
4164            let llm = Arc::new(RecordingLlm {
4165                responses: Mutex::new(script),
4166                offered: Mutex::new(Vec::new()),
4167            });
4168            let source = RuntimeTurnSource {
4169                state_store: Arc::new(MockAgentStateStore::new()),
4170                ext_runtime: Arc::new(ExtensionRuntime::for_test().unwrap()),
4171                llm: llm.clone(),
4172                telemetry: Arc::new(MockTelemetry::new()),
4173                token_meter: Arc::new(MockTokenMeter::new(0)),
4174                ledger: Arc::new(NoopToolLedger),
4175                mcp_source: None,
4176                a2a_source,
4177                packs: Arc::new(vec![]),
4178                merged_agents: Arc::new(HashMap::from([(
4179                    "worker".to_string(),
4180                    worker_with_a2a_tool(),
4181                )])),
4182                index_mount: crate::runner::knowledge_index::IndexMount::default(),
4183            };
4184            let real_tenant = greentic_types::TenantCtx::new(
4185                greentic_types::EnvId::try_from("prod").unwrap(),
4186                greentic_types::TenantId::try_from(TENANT).unwrap(),
4187            );
4188            let turn = source.agent_turn(None, real_tenant, super::TurnBilling::default());
4189            let result = turn(AgentTurnRequest {
4190                node_id: "specialist".into(),
4191                system_prompt: "You suggest recipes.".into(),
4192                model: "m".into(),
4193                state: GraphRunState::default(),
4194                provider: Some("mock".into()),
4195                tools: vec![],
4196                agent_ref: None,
4197                inherit_from: Some("worker".into()),
4198            })
4199            .await
4200            .expect("the turn completes");
4201            let offered = llm
4202                .offered
4203                .lock()
4204                .unwrap()
4205                .first()
4206                .cloned()
4207                .unwrap_or_default();
4208            (result.reply, offered)
4209        }
4210
4211        /// (a) A graph agent turn is offered the `a2a:` tool from a pack
4212        /// carrying `assets/a2a-routes.json`, and calling it reaches the agent
4213        /// with the unit-scoped credential.
4214        #[tokio::test]
4215        #[serial_test::serial]
4216        async fn a_graph_agent_turn_is_offered_and_calls_a_pack_carried_a2a_tool() {
4217            set_gate(None);
4218            let server = MockServer::start().await;
4219            serve_agent(&server, "an omelette").await;
4220            let (_dir, pack) = pack_for(&server);
4221            let source = graph_a2a_source(&[pack], TENANT, &unit_scoped_store(), Some(UNIT));
4222            assert!(source.is_some(), "the sidecar must yield a source");
4223
4224            let (reply, offered) = run_specialist_turn(source, true).await;
4225
4226            assert!(
4227                offered.contains(&(tool_ref(), "ask".to_string())),
4228                "the a2a tool must be offered to a graph agent turn; offered: {offered:?}"
4229            );
4230            assert_eq!(reply, "Try an omelette.");
4231            let requests = server.received_requests().await.unwrap();
4232            let post = requests
4233                .iter()
4234                .find(|r| r.method.as_str() == "POST")
4235                .expect("the agent must have been called");
4236            assert_eq!(
4237                post.headers
4238                    .get("authorization")
4239                    .and_then(|v| v.to_str().ok()),
4240                Some("Bearer tok-1"),
4241                "the credential is read at the unit scope the handler was built for"
4242            );
4243        }
4244
4245        /// (b) `GREENTIC_AW_A2A=0` disables the graph path too: no source is
4246        /// built, so the turn is offered no `a2a:` tool.
4247        #[tokio::test]
4248        #[serial_test::serial]
4249        async fn the_env_gate_disables_a2a_for_graph_turns() {
4250            let server = MockServer::start().await;
4251            serve_agent(&server, "unused").await;
4252            let (_dir, pack) = pack_for(&server);
4253            set_gate(Some("0"));
4254            let gated = graph_a2a_source(
4255                std::slice::from_ref(&pack),
4256                TENANT,
4257                &unit_scoped_store(),
4258                Some(UNIT),
4259            );
4260            set_gate(None);
4261            assert!(gated.is_none(), "the operator's kill switch must hold");
4262
4263            let (_, offered) = run_specialist_turn(gated, false).await;
4264            assert!(
4265                !offered.iter().any(|(ext, _)| ext.starts_with("a2a:")),
4266                "a disabled A2A source must offer no a2a: tool; offered: {offered:?}"
4267            );
4268            assert!(
4269                server.received_requests().await.unwrap().is_empty(),
4270                "a disabled source must never dial the agent"
4271            );
4272            assert!(
4273                graph_a2a_source(&[pack], TENANT, &unit_scoped_store(), Some(UNIT)).is_some(),
4274                "control: the same pack builds a source with the gate unset"
4275            );
4276        }
4277
4278        /// (c) A graph Tool node naming `a2a:<agent_id>/ask` dispatches through
4279        /// the handler's A2A catalog rather than the extension runtime.
4280        #[tokio::test]
4281        #[serial_test::serial]
4282        async fn a_graph_tool_node_dispatches_an_a2a_ref() {
4283            set_gate(None);
4284            let server = MockServer::start().await;
4285            serve_agent(&server, "an omelette").await;
4286            let (_dir, pack) = pack_for(&server);
4287            let source = graph_a2a_source(&[pack], TENANT, &unit_scoped_store(), Some(UNIT));
4288            let tool = build_tool(Arc::new(ExtensionRuntime::for_test().unwrap()), source);
4289
4290            let value = tool(ToolCallRequest {
4291                node_id: "lookup".into(),
4292                tool_name: format!("{}/ask", tool_ref()),
4293                state: GraphRunState::default(),
4294            })
4295            .await
4296            .expect("dispatch succeeds");
4297
4298            assert_eq!(
4299                value,
4300                json!({"status": "completed", "agent": AGENT_ID, "reply": "an omelette"})
4301            );
4302            let requests = server.received_requests().await.unwrap();
4303            let post = requests
4304                .iter()
4305                .find(|r| r.method.as_str() == "POST")
4306                .expect("the agent must have been called");
4307            assert_eq!(
4308                post.headers
4309                    .get("authorization")
4310                    .and_then(|v| v.to_str().ok()),
4311                Some("Bearer tok-1")
4312            );
4313        }
4314    }
4315}
4316
4317#[cfg(feature = "agentic-worker")]
4318pub use aw::{
4319    GraphConfigSource, InMemoryGraphProvider, LayeredGraphProvider, RuntimeGraphNodeHandler,
4320    build_graph_node_handler, graph_config_from_sidecar,
4321};
4322
4323#[cfg(feature = "agentic-worker")]
4324pub(crate) use aw::build_graph_node_handler_metered;