Skip to main content

greentic_runner_host/
runtime.rs

1use std::collections::{BTreeMap, HashMap, HashSet};
2use std::future::Future;
3use std::path::{Path, PathBuf};
4use std::sync::Arc;
5
6use anyhow::{Context, Result, anyhow, bail};
7use arc_swap::ArcSwap;
8use parking_lot::Mutex;
9use reqwest::Client;
10use serde_json::Value;
11use tokio::runtime::{Handle, Runtime};
12use tokio::task::JoinHandle;
13use tokio_util::sync::CancellationToken;
14
15use crate::config::HostConfig;
16use crate::engine::host::{SessionHost, StateHost};
17use crate::engine::runtime::StateMachineRuntime;
18use crate::oauth::{OAuthBrokerConfig, request_resource_token_with_auth};
19use crate::operator_metrics::OperatorMetrics;
20use crate::operator_registry::OperatorRegistry;
21use crate::pack::{ComponentResolution, PackRuntime};
22use crate::runner::adapt_events_email::{
23    EmailExecutionPlan, EmailSendRequest, build_email_execution_plan, execute_email_request,
24};
25use crate::runner::contract_cache::{ContractCache, ContractCacheStats};
26use crate::runner::engine::FlowEngine;
27use crate::runner::mocks::MockLayer;
28use crate::secrets::{DynSecretsManager, canonicalize_secret_key, read_secret_blocking};
29use crate::storage::session::DynSessionStore;
30use crate::storage::state::DynStateStore;
31use crate::telemetry::RolloutIds;
32use crate::trace::PackTraceInfo;
33use crate::wasi::RunnerWasiPolicy;
34use greentic_deploy_spec::ids::{BundleId, DeploymentId, RevisionId};
35use greentic_types::SecretRequirement;
36use runner_core::packs::PackDigest;
37
38const RUNTIME_SECRETS_PACK_ID: &str = "_runner";
39
40/// Key identifying a live runtime in [`ActivePacks`].
41///
42/// Tenant-only entries use [`RuntimeKey::legacy`] (all id fields `None`);
43/// fully-qualified entries use [`RuntimeKey::revision`] (all `Some`). The two
44/// forms never collide, so both can coexist in the same map.
45#[derive(Clone, Debug, PartialEq, Eq, Hash)]
46pub struct RuntimeKey {
47    pub tenant: String,
48    pub deployment_id: Option<DeploymentId>,
49    pub bundle_id: Option<BundleId>,
50    pub revision_id: Option<RevisionId>,
51}
52
53impl RuntimeKey {
54    /// Tenant-only key for the pre-revision-routing path.
55    pub fn legacy(tenant: impl Into<String>) -> Self {
56        Self {
57            tenant: tenant.into(),
58            deployment_id: None,
59            bundle_id: None,
60            revision_id: None,
61        }
62    }
63
64    /// Fully-qualified key for a specific deployment/bundle/revision.
65    pub fn revision(
66        tenant: impl Into<String>,
67        deployment_id: DeploymentId,
68        bundle_id: BundleId,
69        revision_id: RevisionId,
70    ) -> Self {
71        Self {
72            tenant: tenant.into(),
73            deployment_id: Some(deployment_id),
74            bundle_id: Some(bundle_id),
75            revision_id: Some(revision_id),
76        }
77    }
78
79    /// `true` for the tenant-only key produced by [`legacy`](Self::legacy).
80    pub fn is_legacy(&self) -> bool {
81        self.deployment_id.is_none() && self.bundle_id.is_none() && self.revision_id.is_none()
82    }
83}
84
85/// Build the next runtime map for a legacy (tenant-only) reload: install the
86/// freshly-resolved `legacy` entries and carry over every revision-keyed entry
87/// untouched. Revision runtimes are owned by the deployment lifecycle, not the
88/// pack watcher, so a tenant-pack reload must not evict them.
89fn merge_legacy_reload<V: Clone>(
90    prev: &HashMap<RuntimeKey, V>,
91    mut legacy: HashMap<RuntimeKey, V>,
92) -> HashMap<RuntimeKey, V> {
93    for (key, value) in prev {
94        if !key.is_legacy() {
95            legacy.insert(key.clone(), value.clone());
96        }
97    }
98    legacy
99}
100
101/// Pure swap helper for [`ActivePacks::remove_revision`]: clone the prev map
102/// minus `key`, return it alongside the removed value. `None` when the key was
103/// absent so the caller can skip the `ArcSwap` store. Generic over `V` so the
104/// swap logic is testable without standing up a real `TenantRuntime`.
105fn remove_keyed_entry<V: Clone>(
106    prev: &HashMap<RuntimeKey, V>,
107    key: &RuntimeKey,
108) -> Option<(HashMap<RuntimeKey, V>, V)> {
109    let removed = prev.get(key)?.clone();
110    let mut next = prev.clone();
111    next.remove(key);
112    Some((next, removed))
113}
114
115/// Pure swap helper for [`ActivePacks::insert_revision`]: clone the prev map
116/// and insert `value` under `key`, returning the next map. Generic over `V` so
117/// the swap logic is testable without standing up a real `TenantRuntime`.
118fn insert_keyed_entry<V: Clone>(
119    prev: &HashMap<RuntimeKey, V>,
120    key: RuntimeKey,
121    value: V,
122) -> HashMap<RuntimeKey, V> {
123    let mut next = prev.clone();
124    next.insert(key, value);
125    next
126}
127
128/// Atomically swapped view of live tenant runtimes.
129///
130/// Reads are lock-free via `ArcSwap`. Mutations serialize on `write_lock` so a
131/// read-modify-write swap (e.g. a watcher reload preserving revision entries)
132/// cannot interleave with a concurrent insert and clobber the other's update.
133pub struct ActivePacks {
134    inner: ArcSwap<HashMap<RuntimeKey, Arc<TenantRuntime>>>,
135    write_lock: Mutex<()>,
136}
137
138impl ActivePacks {
139    pub fn new() -> Self {
140        Self {
141            inner: ArcSwap::from_pointee(HashMap::new()),
142            write_lock: Mutex::new(()),
143        }
144    }
145
146    /// Look up the tenant-only (legacy) runtime. Compatibility helper for the
147    /// pre-revision-routing path; see [`load_revision`](Self::load_revision).
148    pub fn load_pack(&self, tenant: &str) -> Option<Arc<TenantRuntime>> {
149        self.inner.load().get(&RuntimeKey::legacy(tenant)).cloned()
150    }
151
152    /// Look up the runtime for a specific deployment/bundle/revision.
153    pub fn load_revision(
154        &self,
155        tenant: &str,
156        deployment_id: DeploymentId,
157        bundle_id: BundleId,
158        revision_id: RevisionId,
159    ) -> Option<Arc<TenantRuntime>> {
160        self.inner
161            .load()
162            .get(&RuntimeKey::revision(
163                tenant,
164                deployment_id,
165                bundle_id,
166                revision_id,
167            ))
168            .cloned()
169    }
170
171    pub fn snapshot(&self) -> Arc<HashMap<RuntimeKey, Arc<TenantRuntime>>> {
172        self.inner.load_full()
173    }
174
175    /// Insert (or replace) a single tenant-only runtime, preserving all other
176    /// entries — including revision-keyed ones.
177    ///
178    /// A runtime this replaces has its cron timers stopped
179    /// ([`TenantRuntime::abort_timers`]): it can stay referenced by an embedder
180    /// or in-flight work, and without this its timers kept firing alongside the
181    /// replacement's (a double fire per tick). Re-inserting the SAME runtime is
182    /// not a replacement and cancels nothing.
183    pub fn insert_pack(&self, tenant: &str, runtime: Arc<TenantRuntime>) {
184        let _guard = self.write_lock.lock();
185        let mut next = (*self.inner.load_full()).clone();
186        let replaced = next.insert(RuntimeKey::legacy(tenant), Arc::clone(&runtime));
187        self.inner.store(Arc::new(next));
188        retire_replaced(replaced, &runtime);
189    }
190
191    /// Insert (or replace) a single revision-keyed runtime, preserving every
192    /// other entry — the tenant-only legacy entry and sibling revisions alike.
193    /// This is the producer the deployment warm path calls once a revision's
194    /// packs are loaded; the pack watcher's [`replace_legacy`](Self::replace_legacy)
195    /// then carries the entry across tenant-pack reloads untouched.
196    ///
197    /// Fails closed when the runtime's identity does not match the key it would
198    /// be stored under: a wiring bug that files one tenant's runtime under
199    /// another tenant's revision (breaking isolation) or stores a runtime whose
200    /// telemetry reports a different revision than it routes (breaking rollout
201    /// attribution) is rejected here rather than silently serving traffic under
202    /// the wrong identity. Pairs with [`TenantRuntime::load_revision`], which
203    /// derives the runtime's rollout identity from these same ids.
204    pub fn insert_revision(
205        &self,
206        tenant: &str,
207        deployment_id: DeploymentId,
208        bundle_id: BundleId,
209        revision_id: RevisionId,
210        runtime: Arc<TenantRuntime>,
211    ) -> Result<()> {
212        if runtime.tenant() != tenant {
213            bail!(
214                "revision runtime tenant `{}` does not match key tenant `{tenant}`",
215                runtime.tenant()
216            );
217        }
218        let ids = runtime.engine().rollout_ids();
219        let key_deployment = deployment_id.to_string();
220        let key_bundle = bundle_id.as_str();
221        let key_revision = revision_id.to_string();
222        if ids.deployment_id.as_deref() != Some(key_deployment.as_str())
223            || ids.bundle_id.as_deref() != Some(key_bundle)
224            || ids.revision_id.as_deref() != Some(key_revision.as_str())
225        {
226            bail!(
227                "revision runtime rollout identity (deployment={:?}, bundle={:?}, revision={:?}) \
228                 does not match key (deployment=`{key_deployment}`, bundle=`{key_bundle}`, \
229                 revision=`{key_revision}`)",
230                ids.deployment_id,
231                ids.bundle_id,
232                ids.revision_id
233            );
234        }
235        let _guard = self.write_lock.lock();
236        let key = RuntimeKey::revision(tenant, deployment_id, bundle_id, revision_id);
237        let prev = self.inner.load_full();
238        let replaced = prev.get(&key).cloned();
239        let next = insert_keyed_entry(&prev, key, Arc::clone(&runtime));
240        self.inner.store(Arc::new(next));
241        retire_replaced(replaced, &runtime);
242        Ok(())
243    }
244
245    /// Swap in a freshly-resolved set of tenant-only (legacy) runtimes while
246    /// carrying over every revision-keyed entry. Used by the pack watcher, whose
247    /// index is authoritative for tenant packs but not for deployment revisions.
248    pub fn replace_legacy(&self, legacy: HashMap<RuntimeKey, Arc<TenantRuntime>>) {
249        let _guard = self.write_lock.lock();
250        let prev = self.inner.load_full();
251        let next = merge_legacy_reload(&prev, legacy);
252        self.inner.store(Arc::new(next));
253    }
254
255    /// Remove and return the runtime for a single revision-keyed entry,
256    /// preserving every other entry (legacy and revision alike). Used by the
257    /// drain coordinator (`gtc op revisions drain`) after the drain window
258    /// closes to tear down exactly the one revision being retired. `None` if
259    /// no such entry was present — idempotent for safe re-runs.
260    pub fn remove_revision(
261        &self,
262        tenant: &str,
263        deployment_id: DeploymentId,
264        bundle_id: BundleId,
265        revision_id: RevisionId,
266    ) -> Option<Arc<TenantRuntime>> {
267        let _guard = self.write_lock.lock();
268        let prev = self.inner.load_full();
269        let key = RuntimeKey::revision(tenant, deployment_id, bundle_id, revision_id);
270        let (next, removed) = remove_keyed_entry(&prev, &key)?;
271        self.inner.store(Arc::new(next));
272        // Retired for good: stop its cron timers even though the caller (and
273        // in-flight work) may keep the returned `Arc` alive for a while.
274        removed.abort_timers();
275        Some(removed)
276    }
277
278    /// Replace the entire map, dropping every entry (legacy and revision alike).
279    /// Used for full host stop.
280    pub fn replace(&self, next: HashMap<RuntimeKey, Arc<TenantRuntime>>) {
281        let _guard = self.write_lock.lock();
282        self.inner.store(Arc::new(next));
283    }
284
285    pub fn len(&self) -> usize {
286        self.inner.load().len()
287    }
288
289    pub fn is_empty(&self) -> bool {
290        self.len() == 0
291    }
292}
293
294/// Stop the timers of a runtime that was just replaced by `current`, unless it
295/// IS `current` (re-inserting the same runtime must not cancel its own timers).
296fn retire_replaced(replaced: Option<Arc<TenantRuntime>>, current: &Arc<TenantRuntime>) {
297    if let Some(old) = replaced
298        && !Arc::ptr_eq(&old, current)
299    {
300        old.abort_timers();
301    }
302}
303
304impl Default for ActivePacks {
305    fn default() -> Self {
306        Self::new()
307    }
308}
309
310/// Runtime bundle for a tenant pack.
311pub struct TenantRuntime {
312    tenant: String,
313    config: Arc<HostConfig>,
314    packs: Vec<Arc<PackRuntime>>,
315    digests: Vec<Option<String>>,
316    engine: Arc<FlowEngine>,
317    state_machine: Arc<StateMachineRuntime>,
318    /// The session store this runtime was loaded with. Shared with the inner
319    /// state machine — re-exposed here so callers outside the flow run loop
320    /// (M1.5 welcome-flow first-contact probe) can query the SAME bucket the
321    /// state machine will read/write. For revision mode each revision passes
322    /// its own store into `load_revision`; querying the RunnerHost-level
323    /// store would key the wrong bucket.
324    session_store: DynSessionStore,
325    http_client: Client,
326    mocks: Option<Arc<MockLayer>>,
327    timer_handles: Mutex<Vec<JoinHandle<()>>>,
328    /// Cancelled when this runtime's cron timers must stop. The timer tasks
329    /// only observe it while SLEEPING, so a tick that is already running its
330    /// flow finishes (and saves its snapshot) instead of being torn down.
331    timer_cancel: CancellationToken,
332    /// NATS response listeners and the MCP warm listener this runtime spawned.
333    /// Aborted on drop so a reload (which swaps in a fresh `TenantRuntime`)
334    /// does not leave the old listeners running beside the new ones.
335    background_handles: Mutex<Vec<JoinHandle<()>>>,
336    secrets: DynSecretsManager,
337    operator_registry: OperatorRegistry,
338    operator_metrics: Arc<OperatorMetrics>,
339    contract_cache: ContractCache,
340    /// The HTTP approval inbox, when this runtime serves one. Shut down on
341    /// drop: the poller stops, held decision tokens are forgotten, and a
342    /// superseded revision can never resume into a store it no longer owns.
343    approval_inbox: Option<crate::runner::approval_http::HttpApprovalDispatcher>,
344}
345
346#[derive(Clone)]
347pub struct ResolvedComponent {
348    pub digest: String,
349    pub component_ref: String,
350    pub pack: Arc<PackRuntime>,
351}
352
353/// One pinned pack of a deployment revision: the on-disk path plus the
354/// `algo:value` content digest the deployment staged it under.
355/// [`TenantRuntime::load_revision`] fails closed when the file no longer
356/// matches the digest, defending the stage→warm window against a swapped or
357/// stale cache path.
358#[derive(Clone, Debug)]
359pub struct RevisionPackRef {
360    pub path: PathBuf,
361    pub digest: String,
362}
363
364/// The arguments of [`TenantRuntime::load_revision`], as one struct, for
365/// [`TenantRuntime::load_revision_with`]. Field meanings are exactly
366/// `load_revision`'s parameters of the same names.
367pub struct RevisionLoad<'a> {
368    pub pack_refs: &'a [RevisionPackRef],
369    pub config: Arc<HostConfig>,
370    pub mocks: Option<Arc<MockLayer>>,
371    pub wasi_policy: Arc<RunnerWasiPolicy>,
372    pub session_host: Arc<dyn SessionHost>,
373    pub session_store: DynSessionStore,
374    pub state_store: DynStateStore,
375    pub state_host: Arc<dyn StateHost>,
376    pub secrets_manager: DynSecretsManager,
377    pub deployment_id: DeploymentId,
378    pub bundle_id: BundleId,
379    pub revision_id: RevisionId,
380    pub customer_id: Option<String>,
381    pub runtime_configs_by_pack_id: &'a BTreeMap<String, Arc<BTreeMap<String, Value>>>,
382    pub runtime_refs_by_pack_id: &'a BTreeMap<String, Arc<BTreeMap<String, String>>>,
383    pub runtime_ref_resolver: Option<Arc<dyn crate::runtime_refs::RuntimeRefResolver>>,
384}
385
386/// What the embedding HOST decides for one revision, beyond its pinned packs.
387/// `Default` is exactly [`TenantRuntime::load_revision`]'s behaviour.
388/// Non-exhaustive so a later host seam is an additive field, not a breaking
389/// change: construct with `RevisionHostOptions::default()` plus the `with_*`
390/// setters.
391#[derive(Clone, Default)]
392#[non_exhaustive]
393pub struct RevisionHostOptions {
394    #[cfg(feature = "agentic-worker")]
395    billing_meter: Option<Arc<dyn greentic_aw_runtime::billing::BillingMeter>>,
396    run_outcome_sink: Option<Arc<dyn crate::run_outcome::RunOutcomeSink>>,
397    approval_inbox: Option<crate::runner::approval_http::ApprovalInboxTarget>,
398    #[cfg(feature = "agentic-worker")]
399    user_ledger: Option<greentic_aw_runtime::user_ledger::UserLedgerTarget>,
400    #[cfg(feature = "agentic-worker")]
401    artifact_reader: Option<crate::host::ArtifactReaderPort>,
402    #[cfg(feature = "agentic-worker")]
403    ext_artifact_port: Option<crate::host::ExtArtifactPort>,
404}
405
406impl std::fmt::Debug for RevisionHostOptions {
407    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
408        let mut out = f.debug_struct("RevisionHostOptions");
409        #[cfg(feature = "agentic-worker")]
410        out.field("billing_meter", &self.billing_meter.is_some());
411        out.field("run_outcome_sink", &self.run_outcome_sink.is_some());
412        out.field("approval_inbox", &self.approval_inbox.is_some());
413        #[cfg(feature = "agentic-worker")]
414        out.field("user_ledger", &self.user_ledger.is_some());
415        #[cfg(feature = "agentic-worker")]
416        out.field("artifact_reader", &self.artifact_reader.is_some());
417        #[cfg(feature = "agentic-worker")]
418        out.field("ext_artifact_port", &self.ext_artifact_port.is_some());
419        out.finish()
420    }
421}
422
423impl RevisionHostOptions {
424    /// Record this unit's agentic-worker LLM usage through `meter` as well —
425    /// see [`TenantRuntime::load_revision_with`] for how it combines with the
426    /// env-configured cloud-commerce sink.
427    #[cfg(feature = "agentic-worker")]
428    #[must_use]
429    pub fn with_billing_meter(
430        mut self,
431        meter: Arc<dyn greentic_aw_runtime::billing::BillingMeter>,
432    ) -> Self {
433        self.billing_meter = Some(meter);
434        self
435    }
436
437    /// Report one [`crate::run_outcome::RunOutcome`] per flow turn of this
438    /// unit through `sink` — the deployed run audit. greentic-start installs a
439    /// [`crate::run_outcome::HttpRunOutcomeSink`] built from the same staged
440    /// `metering` block as the billing meter. Without one, flow execution and
441    /// the persisted resume state are unchanged.
442    #[must_use]
443    pub fn with_run_outcome_sink(
444        mut self,
445        sink: Arc<dyn crate::run_outcome::RunOutcomeSink>,
446    ) -> Self {
447        self.run_outcome_sink = Some(sink);
448        self
449    }
450
451    /// File this unit's human approvals with the admin's HTTP approval inbox
452    /// and poll for the decisions, instead of needing a NATS broker — the
453    /// HTTP approval rail (greentic-designer
454    /// `docs/superpowers/specs/2026-09-29-approval-rail-http-design.md`).
455    /// greentic-start builds the target from the same staged `metering`
456    /// block as the run-outcome sink.
457    ///
458    /// Serves ONLY `approval.call`: it goes into the engine's own approval
459    /// slot, so `sorla.call` still fails with `sorla_route_missing` on a lane
460    /// with no broker. When `GREENTIC_EVENTS_NATS_URL` also connects, NATS
461    /// wins and the inbox is not installed. A target that fails validation
462    /// (blank field, cleartext URL off loopback) is logged and skipped; the
463    /// runtime loads either way, and an approval that needs a human then fails
464    /// at the node as it did before. Validate early with
465    /// [`crate::runner::approval_http::HttpApprovalDispatcher::new`].
466    #[must_use]
467    pub fn with_approval_inbox(
468        mut self,
469        target: crate::runner::approval_http::ApprovalInboxTarget,
470    ) -> Self {
471        self.approval_inbox = Some(target);
472        self
473    }
474
475    /// Read and append this unit's user ledger (shared context, Phase C) at
476    /// the admin's ledger door. greentic-start builds the target from the same
477    /// staged `metering` block as the approval inbox: `base_url` is the
478    /// worker-usage endpoint with its last segment swapped for `ledger`,
479    /// `token` the unit's metering token, `tenant_slug` the block's slug. The
480    /// runner never reads that block itself.
481    ///
482    /// Nothing happens unless a pack also names an agent in
483    /// `assets/user-ledger.json`, and only a turn whose caller the provider
484    /// verified, outside any tool call, touches the ledger. That sidecar alone
485    /// decides `read` versus `read_write` for the pack's own agents: there is
486    /// no host-side ceiling on the mode. The gates are the door token's
487    /// `ledger` purpose (the admin refuses a token without it), the
488    /// `GREENTIC_AW_USER_LEDGER` kill switch, the tenant match between the
489    /// runtime and the turn, and a provider-verified subject. A target that
490    /// fails validation (blank field, cleartext URL off loopback, userinfo in
491    /// the URL) is one warning and the runtime loads without the ledger;
492    /// validate early with
493    /// [`greentic_aw_runtime::user_ledger::HttpUserLedger::new`]. The admin
494    /// refuses a token without the `ledger` purpose, and the client then
495    /// stops asking for a while. `GREENTIC_AW_USER_LEDGER=0` turns it off.
496    #[cfg(feature = "agentic-worker")]
497    #[must_use]
498    pub fn with_user_ledger(
499        mut self,
500        target: greentic_aw_runtime::user_ledger::UserLedgerTarget,
501    ) -> Self {
502        self.user_ledger = Some(target);
503        self
504    }
505
506    /// Open this unit's message attachments through `reader` (contract C3 `get`
507    /// on the admin `artifacts` door). greentic-start builds it from the same
508    /// staged `metering` block as the other door targets, with the door base
509    /// `sibling_door(endpoint, "artifacts")` and the unit's metering token: the
510    /// token is this unit's, so the door reads only this unit's tenant.
511    ///
512    /// Per REVISION rather than a `HostBuilder` setting for the same reason as
513    /// the billing meter: one greentic-start process serves every unit, and
514    /// each unit has its own token. Without one the unit has NO reader: the
515    /// `GREENTIC_ARTIFACT_*` env variables are never read on this path, even
516    /// when a `HostBuilder` opted in to the env fallback (they would hand every
517    /// unit of the process one token). Each attachment is
518    /// then a fixed notice to the agent and the turn still runs. Only the
519    /// multi-provider backend (`greentic-llm-backend`) reads attachments.
520    #[cfg(feature = "agentic-worker")]
521    #[must_use]
522    pub fn with_artifact_reader(mut self, reader: crate::host::ArtifactReaderPort) -> Self {
523        self.artifact_reader = Some(reader);
524        self
525    }
526
527    /// Store the files this unit's extensions create (`host.artifact.put`,
528    /// contract C3 `put`) through `port`. greentic-start builds it per unit,
529    /// over that unit's own door and token, like
530    /// [`Self::with_artifact_reader`].
531    ///
532    /// Per REVISION for the same reason: one process serves every unit, each
533    /// with its own token. Without one the unit has NO port: the
534    /// `GREENTIC_ARTIFACT_*` env variables are never read on this path, and an
535    /// extension's `put` answers `unsupported`.
536    #[cfg(feature = "agentic-worker")]
537    #[must_use]
538    pub fn with_ext_artifact_port(mut self, port: crate::host::ExtArtifactPort) -> Self {
539        self.ext_artifact_port = Some(port);
540        self
541    }
542}
543
544/// Block on a future whether or not we're already inside a tokio runtime.
545///
546/// `Handle::block_on` panics when called from async context, so inside a
547/// multi-thread runtime this yields the worker via `block_in_place`, and inside
548/// a current-thread runtime (where `block_in_place` also panics) it drives the
549/// future on a short-lived helper thread with its own runtime.
550///
551/// Infallible by signature; if even the fallback runtime cannot be built it
552/// degrades to a runtime-less executor rather than panicking. Prefer
553/// [`try_block_on`] when the caller can surface the error.
554pub fn block_on<F, R>(future: F) -> R
555where
556    F: Future<Output = R> + Send,
557    R: Send,
558{
559    match Handle::try_current() {
560        Ok(handle) => block_in_context(&handle, future).unwrap_or_else(|(future, err)| {
561            tracing::warn!(error = %err, "falling back to a runtime-less executor");
562            futures::executor::block_on(future)
563        }),
564        Err(_) => match build_scoped_runtime() {
565            Ok(rt) => rt.block_on(future),
566            Err(err) => {
567                tracing::warn!(error = %err, "falling back to a runtime-less executor");
568                futures::executor::block_on(future)
569            }
570        },
571    }
572}
573
574/// [`block_on`], surfacing a failure to build the helper runtime or a panic on
575/// the helper thread as an error.
576pub fn try_block_on<F, R>(future: F) -> Result<R>
577where
578    F: Future<Output = R> + Send,
579    R: Send,
580{
581    match Handle::try_current() {
582        Ok(handle) => block_in_context(&handle, future).map_err(|(_, err)| err),
583        Err(_) => Ok(build_scoped_runtime()?.block_on(future)),
584    }
585}
586
587fn build_scoped_runtime() -> Result<Runtime> {
588    tokio::runtime::Builder::new_current_thread()
589        .enable_all()
590        .build()
591        .context("failed to create tokio runtime")
592}
593
594/// Run `future` to completion from inside a tokio runtime context. On failure
595/// the future is handed back alongside the error when it was never polled.
596fn block_in_context<F, R>(handle: &Handle, future: F) -> std::result::Result<R, (F, anyhow::Error)>
597where
598    F: Future<Output = R> + Send,
599    R: Send,
600{
601    use tokio::runtime::RuntimeFlavor;
602    if matches!(handle.runtime_flavor(), RuntimeFlavor::MultiThread) {
603        return Ok(tokio::task::block_in_place(|| handle.block_on(future)));
604    }
605    let rt = match build_scoped_runtime() {
606        Ok(rt) => rt,
607        Err(err) => return Err((future, err)),
608    };
609    // `std::thread::scope` joins before returning, so `future` may borrow.
610    std::thread::scope(|scope| {
611        match scope.spawn(move || rt.block_on(future)).join() {
612            Ok(value) => Ok(value),
613            // The future panicked: surface that panic to the caller as it
614            // would have been on a direct poll.
615            Err(payload) => std::panic::resume_unwind(payload),
616        }
617    })
618}
619
620impl TenantRuntime {
621    #[allow(clippy::too_many_arguments)]
622    pub async fn load(
623        pack_path: &Path,
624        config: Arc<HostConfig>,
625        mocks: Option<Arc<MockLayer>>,
626        archive_source: Option<&Path>,
627        digest: Option<String>,
628        wasi_policy: Arc<RunnerWasiPolicy>,
629        session_host: Arc<dyn SessionHost>,
630        session_store: DynSessionStore,
631        state_store: DynStateStore,
632        state_host: Arc<dyn StateHost>,
633        secrets_manager: DynSecretsManager,
634        #[cfg(feature = "agentic-worker")] ext_llm_port: Option<crate::host::ExtLlmPort>,
635        #[cfg(feature = "agentic-worker")] mcp_source: Option<crate::host::McpSource>,
636        #[cfg(feature = "agentic-worker")] stream_observers: Option<
637            crate::http::agent_stream::StreamObserverRegistry,
638        >,
639    ) -> Result<Arc<Self>> {
640        Self::load_with_artifact_reader(
641            pack_path,
642            config,
643            mocks,
644            archive_source,
645            digest,
646            wasi_policy,
647            session_host,
648            session_store,
649            state_store,
650            state_host,
651            secrets_manager,
652            #[cfg(feature = "agentic-worker")]
653            ext_llm_port,
654            #[cfg(feature = "agentic-worker")]
655            mcp_source,
656            // No host: no attachment reader and no artifact port.
657            #[cfg(feature = "agentic-worker")]
658            None,
659            #[cfg(feature = "agentic-worker")]
660            None,
661            #[cfg(feature = "agentic-worker")]
662            stream_observers,
663        )
664        .await
665    }
666
667    /// [`load`](Self::load) plus the host's attachment reader
668    /// ([`crate::host::RunnerHost::artifact_reader`], already decided by the
669    /// host, env fallback included).
670    #[allow(clippy::too_many_arguments)]
671    pub(crate) async fn load_with_artifact_reader(
672        pack_path: &Path,
673        config: Arc<HostConfig>,
674        mocks: Option<Arc<MockLayer>>,
675        archive_source: Option<&Path>,
676        digest: Option<String>,
677        wasi_policy: Arc<RunnerWasiPolicy>,
678        session_host: Arc<dyn SessionHost>,
679        session_store: DynSessionStore,
680        state_store: DynStateStore,
681        state_host: Arc<dyn StateHost>,
682        secrets_manager: DynSecretsManager,
683        #[cfg(feature = "agentic-worker")] ext_llm_port: Option<crate::host::ExtLlmPort>,
684        #[cfg(feature = "agentic-worker")] mcp_source: Option<crate::host::McpSource>,
685        #[cfg(feature = "agentic-worker")] artifact_reader: Option<crate::host::ArtifactReaderPort>,
686        #[cfg(feature = "agentic-worker")] ext_artifact_port: Option<crate::host::ExtArtifactPort>,
687        #[cfg(feature = "agentic-worker")] stream_observers: Option<
688            crate::http::agent_stream::StreamObserverRegistry,
689        >,
690    ) -> Result<Arc<Self>> {
691        let pack = Self::load_pack_runtime(
692            pack_path,
693            &config,
694            mocks.clone(),
695            archive_source,
696            &wasi_policy,
697            &session_store,
698            &state_store,
699            &secrets_manager,
700            &BTreeMap::new(),
701            &BTreeMap::new(),
702            None,
703            // Tenant-only path: no deployed unit, so pack secrets resolve the
704            // bare pack scope exactly as before.
705            None,
706        )
707        .await?;
708        Self::from_packs_with_artifact_reader(
709            config,
710            vec![(pack, digest)],
711            mocks,
712            session_host,
713            session_store,
714            state_store,
715            state_host,
716            secrets_manager,
717            #[cfg(feature = "agentic-worker")]
718            ext_llm_port,
719            #[cfg(feature = "agentic-worker")]
720            mcp_source,
721            #[cfg(feature = "agentic-worker")]
722            artifact_reader,
723            #[cfg(feature = "agentic-worker")]
724            ext_artifact_port,
725            #[cfg(feature = "agentic-worker")]
726            stream_observers,
727        )
728        .await
729    }
730
731    /// Build a revision-keyed runtime from its pinned pack list (the resolved
732    /// `pack_list` of a deployment revision). The first entry is the main pack;
733    /// the rest are overlays.
734    ///
735    /// Fails closed if any pack file no longer matches the digest the
736    /// deployment pinned it under — defending the stage→warm window against a
737    /// swapped or stale cache path. The verified digests are threaded into the
738    /// runtime so admin status, traces, and contract hashes report the real
739    /// content (parity with the legacy index path). The rollout telemetry
740    /// identity is **derived from** `deployment_id` / `bundle_id` /
741    /// `revision_id` / `customer_id`, so the engine's attribution cannot drift
742    /// from the key the runtime is later inserted under.
743    ///
744    /// Installs no host billing meter: agentic-worker usage goes to the
745    /// env-configured cloud-commerce sink when `GREENTIC_BILLING_*` is set,
746    /// else nowhere. Graph turns and in-process deep workers are now metered
747    /// and graph turns run under the real tenant; see
748    /// [`load_revision_with`](Self::load_revision_with) for the four
749    /// behaviour changes that brings, and for installing a per-unit meter.
750    #[allow(clippy::too_many_arguments)]
751    pub async fn load_revision(
752        pack_refs: &[RevisionPackRef],
753        config: Arc<HostConfig>,
754        mocks: Option<Arc<MockLayer>>,
755        wasi_policy: Arc<RunnerWasiPolicy>,
756        session_host: Arc<dyn SessionHost>,
757        session_store: DynSessionStore,
758        state_store: DynStateStore,
759        state_host: Arc<dyn StateHost>,
760        secrets_manager: DynSecretsManager,
761        deployment_id: DeploymentId,
762        bundle_id: BundleId,
763        revision_id: RevisionId,
764        customer_id: Option<String>,
765        runtime_configs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, Value>>>,
766        runtime_refs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, String>>>,
767        runtime_ref_resolver: Option<Arc<dyn crate::runtime_refs::RuntimeRefResolver>>,
768    ) -> Result<Arc<Self>> {
769        Self::load_revision_impl(
770            pack_refs,
771            config,
772            mocks,
773            wasi_policy,
774            session_host,
775            session_store,
776            state_store,
777            state_host,
778            secrets_manager,
779            deployment_id,
780            bundle_id,
781            revision_id,
782            customer_id,
783            runtime_configs_by_pack_id,
784            runtime_refs_by_pack_id,
785            runtime_ref_resolver,
786            #[cfg(feature = "agentic-worker")]
787            None,
788            None,
789            None,
790            #[cfg(feature = "agentic-worker")]
791            None,
792            #[cfg(feature = "agentic-worker")]
793            None,
794            #[cfg(feature = "agentic-worker")]
795            None,
796        )
797        .await
798    }
799
800    /// [`load_revision`](Self::load_revision), taking its arguments as one
801    /// struct plus the host-chosen [`RevisionHostOptions`] for this unit.
802    ///
803    /// Two options exist: the run-outcome sink
804    /// ([`RevisionHostOptions::with_run_outcome_sink`], the deployed run audit
805    /// — see `crate::run_outcome`) and the billing sink
806    /// ([`RevisionHostOptions::with_billing_meter`]). For the latter, greentic-start installs a
807    /// [`greentic_aw_runtime::billing::WorkerUsageMeter`] built from the unit's
808    /// staged `metering` block, so the unit's LLM spend is recorded at the
809    /// admin's per-unit ingest door. It is per-REVISION rather than a
810    /// `HostBuilder` setting on purpose: one greentic-start process serves every
811    /// unit of an environment, and each unit has its own worker-usage token.
812    ///
813    /// # Which sink runs (see `agent_node::resolve_billing_meter`)
814    ///
815    /// - An installed meter AND `GREENTIC_BILLING_BASE_URL` +
816    ///   `GREENTIC_BILLING_SERVICE_SECRET` set: every usage event goes to BOTH
817    ///   (a [`greentic_aw_runtime::billing::FanOutBillingMeter`]), and the
818    ///   credit gate (`over_budget`) is the env cloud-commerce sink's. An
819    ///   installed meter never removes the credit gate.
820    /// - An installed meter only: that meter alone (it has no credit gate).
821    /// - No installed meter: exactly [`load_revision`] — the env sink when
822    ///   configured, else none.
823    ///
824    /// # Behaviour that changed with this seam, for BOTH entry points
825    ///
826    /// Recorded because a publish on the dev lane reaches every consumer:
827    ///
828    /// - (a) agent-graph agent and supervisor turns now emit usage and pass
829    ///   the credit gate when `GREENTIC_BILLING_*` is set. Before, they ran on
830    ///   a `NoopBillingMeter` and were never metered or gated;
831    /// - (b) in-process deep workers (`operala.call`) now emit their own
832    ///   reasoning-loop tokens to the chosen sink, cloud-commerce included;
833    /// - (c) graph turns now run under the real tenant/env, so their tokens
834    ///   count against that tenant's `daily_token_cap_per_tenant` bucket,
835    ///   shared with `dw.agent` (before: one global `graph/run` bucket);
836    /// - (d) long-term memory previously written under the synthetic
837    ///   `graph/run` tenant by `agent_ref` graph turns is no longer reachable.
838    ///   That key was shared by every tenant, so losing it is intended.
839    ///   Per-visit conversation state is re-seeded from the graph checkpoint on
840    ///   every visit, so in-flight runs lose nothing.
841    ///
842    /// [`load_revision`]: Self::load_revision
843    pub async fn load_revision_with(
844        args: RevisionLoad<'_>,
845        options: RevisionHostOptions,
846    ) -> Result<Arc<Self>> {
847        Self::load_revision_impl(
848            args.pack_refs,
849            args.config,
850            args.mocks,
851            args.wasi_policy,
852            args.session_host,
853            args.session_store,
854            args.state_store,
855            args.state_host,
856            args.secrets_manager,
857            args.deployment_id,
858            args.bundle_id,
859            args.revision_id,
860            args.customer_id,
861            args.runtime_configs_by_pack_id,
862            args.runtime_refs_by_pack_id,
863            args.runtime_ref_resolver,
864            #[cfg(feature = "agentic-worker")]
865            options.billing_meter,
866            options.run_outcome_sink,
867            options.approval_inbox,
868            #[cfg(feature = "agentic-worker")]
869            options.user_ledger,
870            #[cfg(feature = "agentic-worker")]
871            options.artifact_reader,
872            #[cfg(feature = "agentic-worker")]
873            options.ext_artifact_port,
874        )
875        .await
876    }
877
878    #[allow(clippy::too_many_arguments)]
879    async fn load_revision_impl(
880        pack_refs: &[RevisionPackRef],
881        config: Arc<HostConfig>,
882        mocks: Option<Arc<MockLayer>>,
883        wasi_policy: Arc<RunnerWasiPolicy>,
884        session_host: Arc<dyn SessionHost>,
885        session_store: DynSessionStore,
886        state_store: DynStateStore,
887        state_host: Arc<dyn StateHost>,
888        secrets_manager: DynSecretsManager,
889        deployment_id: DeploymentId,
890        bundle_id: BundleId,
891        revision_id: RevisionId,
892        customer_id: Option<String>,
893        runtime_configs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, Value>>>,
894        runtime_refs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, String>>>,
895        runtime_ref_resolver: Option<Arc<dyn crate::runtime_refs::RuntimeRefResolver>>,
896        #[cfg(feature = "agentic-worker")] billing_meter: Option<
897            Arc<dyn greentic_aw_runtime::billing::BillingMeter>,
898        >,
899        run_outcome_sink: Option<Arc<dyn crate::run_outcome::RunOutcomeSink>>,
900        approval_inbox: Option<crate::runner::approval_http::ApprovalInboxTarget>,
901        #[cfg(feature = "agentic-worker")] user_ledger: Option<
902            greentic_aw_runtime::user_ledger::UserLedgerTarget,
903        >,
904        #[cfg(feature = "agentic-worker")] artifact_reader: Option<crate::host::ArtifactReaderPort>,
905        #[cfg(feature = "agentic-worker")] ext_artifact_port: Option<crate::host::ExtArtifactPort>,
906    ) -> Result<Arc<Self>> {
907        if pack_refs.is_empty() {
908            bail!(
909                "revision runtime for tenant {} requires at least one pack",
910                config.tenant
911            );
912        }
913        let mut packs = Vec::with_capacity(pack_refs.len());
914        let mut seen_pack_ids = HashSet::with_capacity(pack_refs.len());
915        for pack_ref in pack_refs {
916            let expected = PackDigest::parse(&pack_ref.digest).with_context(|| {
917                format!(
918                    "revision pack `{}` has an invalid digest `{}`",
919                    pack_ref.path.display(),
920                    pack_ref.digest
921                )
922            })?;
923            // `matches_file` always hashes with SHA-256, so a digest pinned under
924            // any other algorithm could never match — reject it with a clear
925            // message rather than the misleading "does not match" below.
926            if expected.algorithm() != "sha256" {
927                bail!(
928                    "revision pack `{}` pins unsupported digest algorithm `{}`; only sha256 is supported",
929                    pack_ref.path.display(),
930                    expected.algorithm()
931                );
932            }
933            if !expected.matches_file(&pack_ref.path).with_context(|| {
934                format!(
935                    "hashing revision pack `{}` for digest verification",
936                    pack_ref.path.display()
937                )
938            })? {
939                bail!(
940                    "revision pack `{}` does not match pinned digest `{}`",
941                    pack_ref.path.display(),
942                    pack_ref.digest
943                );
944            }
945            let pack = Self::load_pack_runtime(
946                &pack_ref.path,
947                &config,
948                mocks.clone(),
949                None,
950                &wasi_policy,
951                &session_store,
952                &state_store,
953                &secrets_manager,
954                runtime_configs_by_pack_id,
955                runtime_refs_by_pack_id,
956                runtime_ref_resolver.as_ref(),
957                // The unit every extension credential in this pack is scoped
958                // to. Same value `FlowEngine::mcp_credential_unit` reads off
959                // `rollout_ids.bundle_id` below, so the flow-node MCP lane and
960                // the component lane cannot disagree about which unit is running.
961                Some(bundle_id.as_str()),
962            )
963            .await?;
964            // Reject duplicate pack_id within a single revision — two refs
965            // resolving to the same pack_id would silently share config/routing
966            // entries and produce an ambiguous runtime.
967            let pack_id = pack.metadata().pack_id.clone();
968            if !seen_pack_ids.insert(pack_id.clone()) {
969                bail!(
970                    "revision for tenant {} contains duplicate pack_id `{}` (path `{}`)",
971                    config.tenant,
972                    pack_id,
973                    pack_ref.path.display(),
974                );
975            }
976            packs.push((pack, Some(expected.raw_string())));
977        }
978        let rollout = RolloutIds {
979            customer_id,
980            deployment_id: Some(deployment_id.to_string()),
981            bundle_id: Some(bundle_id.as_str().to_string()),
982            revision_id: Some(revision_id.to_string()),
983        };
984        Self::from_packs_with_rollout(
985            config,
986            packs,
987            mocks,
988            session_host,
989            session_store,
990            state_store,
991            state_host,
992            secrets_manager,
993            // No host-injected ports on the revision-keyed path: it is
994            // constructed from a pinned pack list rather than from a
995            // `RunnerHost`, so there is none to read them from. Matches what
996            // `ext_llm_port` already does here — an engine built this way
997            // falls back to env for both.
998            #[cfg(feature = "agentic-worker")]
999            None,
1000            #[cfg(feature = "agentic-worker")]
1001            None,
1002            // The unit's own attachment reader (the revision's host options).
1003            #[cfg(feature = "agentic-worker")]
1004            artifact_reader,
1005            #[cfg(feature = "agentic-worker")]
1006            ext_artifact_port,
1007            #[cfg(feature = "agentic-worker")]
1008            None,
1009            rollout,
1010            #[cfg(feature = "agentic-worker")]
1011            billing_meter,
1012            run_outcome_sink,
1013            approval_inbox,
1014            #[cfg(feature = "agentic-worker")]
1015            user_ledger,
1016        )
1017        .await
1018    }
1019
1020    /// Load a single [`PackRuntime`] from a path, sharing the tenant's session /
1021    /// state / secrets backends. Shared by [`load`](Self::load) (one pack) and
1022    /// [`load_revision`](Self::load_revision) (the revision's pack list).
1023    ///
1024    /// `runtime_configs_by_pack_id` is consulted AFTER the pack loads (the
1025    /// `pack_id` is only known after the manifest read) and BEFORE the
1026    /// `Arc<PackRuntime>` is created. A matching entry is injected via
1027    /// [`PackRuntime::set_runtime_config_non_secret`] so the C4.3 producer
1028    /// plumbing requires no post-hoc `Arc::get_mut` dance — the single-pack
1029    /// [`load`](Self::load) path just passes an empty map.
1030    ///
1031    /// `runtime_refs_by_pack_id` mirrors the same shape for the C5
1032    /// `pack-config.v1.runtime_refs` channel; a matching entry is injected
1033    /// via [`PackRuntime::set_runtime_refs`] alongside `runtime_ref_resolver`.
1034    ///
1035    /// `unit_id` is the deployed unit this pack belongs to — the revision's
1036    /// `bundle_id` on the [`load_revision`](Self::load_revision) path, `None`
1037    /// on the legacy tenant-only [`load`](Self::load) path. It scopes every
1038    /// extension credential the pack's components read, so two units of the
1039    /// SAME pack in one environment can hold different values. It is taken as
1040    /// a parameter rather than read from a process environment variable
1041    /// because one greentic-start process serves every revision of an
1042    /// environment, so an env var could not differ per unit.
1043    #[allow(clippy::too_many_arguments)]
1044    async fn load_pack_runtime(
1045        pack_path: &Path,
1046        config: &Arc<HostConfig>,
1047        mocks: Option<Arc<MockLayer>>,
1048        archive_source: Option<&Path>,
1049        wasi_policy: &Arc<RunnerWasiPolicy>,
1050        session_store: &DynSessionStore,
1051        state_store: &DynStateStore,
1052        secrets_manager: &DynSecretsManager,
1053        runtime_configs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, Value>>>,
1054        runtime_refs_by_pack_id: &BTreeMap<String, Arc<BTreeMap<String, String>>>,
1055        runtime_ref_resolver: Option<&Arc<dyn crate::runtime_refs::RuntimeRefResolver>>,
1056        unit_id: Option<&str>,
1057    ) -> Result<Arc<PackRuntime>> {
1058        let oauth_config = config.oauth_broker_config();
1059        let mut pack = PackRuntime::load(
1060            pack_path,
1061            Arc::clone(config),
1062            mocks,
1063            archive_source,
1064            Some(Arc::clone(session_store)),
1065            Some(Arc::clone(state_store)),
1066            Arc::clone(wasi_policy),
1067            Arc::clone(secrets_manager),
1068            oauth_config,
1069            true,
1070            ComponentResolution::default(),
1071        )
1072        .await
1073        .with_context(|| {
1074            format!(
1075                "failed to load pack {} for tenant {}",
1076                pack_path.display(),
1077                config.tenant
1078            )
1079        })?;
1080        let pack_id = pack.metadata().pack_id.clone();
1081        if let Some(non_secret) = runtime_configs_by_pack_id.get(pack_id.as_str()) {
1082            pack.set_runtime_config_non_secret(Some(Arc::clone(non_secret)));
1083        }
1084        pack.set_unit_id(unit_id.map(str::to_string));
1085        if let Some(refs) = runtime_refs_by_pack_id.get(pack_id.as_str()) {
1086            let resolver = runtime_ref_resolver.ok_or_else(|| {
1087                anyhow!(
1088                    "pack `{}` has runtime_refs bound but no RuntimeRefResolver was provided",
1089                    pack_id,
1090                )
1091            })?;
1092            pack.set_runtime_refs(Some(crate::runtime_refs::RuntimeRefsInjection {
1093                refs: Arc::clone(refs),
1094                resolver: Arc::clone(resolver),
1095            }));
1096        }
1097        Ok(Arc::new(pack))
1098    }
1099
1100    #[allow(clippy::too_many_arguments)]
1101    pub async fn from_packs(
1102        config: Arc<HostConfig>,
1103        packs: Vec<(Arc<PackRuntime>, Option<String>)>,
1104        mocks: Option<Arc<MockLayer>>,
1105        session_host: Arc<dyn SessionHost>,
1106        session_store: DynSessionStore,
1107        state_store: DynStateStore,
1108        state_host: Arc<dyn StateHost>,
1109        secrets_manager: DynSecretsManager,
1110        #[cfg(feature = "agentic-worker")] ext_llm_port: Option<crate::host::ExtLlmPort>,
1111        #[cfg(feature = "agentic-worker")] mcp_source: Option<crate::host::McpSource>,
1112        #[cfg(feature = "agentic-worker")] stream_observers: Option<
1113            crate::http::agent_stream::StreamObserverRegistry,
1114        >,
1115    ) -> Result<Arc<Self>> {
1116        Self::from_packs_with_artifact_reader(
1117            config,
1118            packs,
1119            mocks,
1120            session_host,
1121            session_store,
1122            state_store,
1123            state_host,
1124            secrets_manager,
1125            #[cfg(feature = "agentic-worker")]
1126            ext_llm_port,
1127            #[cfg(feature = "agentic-worker")]
1128            mcp_source,
1129            // No host: no attachment reader and no artifact port.
1130            #[cfg(feature = "agentic-worker")]
1131            None,
1132            #[cfg(feature = "agentic-worker")]
1133            None,
1134            #[cfg(feature = "agentic-worker")]
1135            stream_observers,
1136        )
1137        .await
1138    }
1139
1140    /// [`from_packs`](Self::from_packs) plus the host's attachment reader.
1141    #[allow(clippy::too_many_arguments)]
1142    pub(crate) async fn from_packs_with_artifact_reader(
1143        config: Arc<HostConfig>,
1144        packs: Vec<(Arc<PackRuntime>, Option<String>)>,
1145        mocks: Option<Arc<MockLayer>>,
1146        session_host: Arc<dyn SessionHost>,
1147        session_store: DynSessionStore,
1148        state_store: DynStateStore,
1149        state_host: Arc<dyn StateHost>,
1150        secrets_manager: DynSecretsManager,
1151        #[cfg(feature = "agentic-worker")] ext_llm_port: Option<crate::host::ExtLlmPort>,
1152        #[cfg(feature = "agentic-worker")] mcp_source: Option<crate::host::McpSource>,
1153        #[cfg(feature = "agentic-worker")] artifact_reader: Option<crate::host::ArtifactReaderPort>,
1154        #[cfg(feature = "agentic-worker")] ext_artifact_port: Option<crate::host::ExtArtifactPort>,
1155        #[cfg(feature = "agentic-worker")] stream_observers: Option<
1156            crate::http::agent_stream::StreamObserverRegistry,
1157        >,
1158    ) -> Result<Arc<Self>> {
1159        Self::from_packs_with_rollout(
1160            config,
1161            packs,
1162            mocks,
1163            session_host,
1164            session_store,
1165            state_store,
1166            state_host,
1167            secrets_manager,
1168            #[cfg(feature = "agentic-worker")]
1169            ext_llm_port,
1170            #[cfg(feature = "agentic-worker")]
1171            mcp_source,
1172            #[cfg(feature = "agentic-worker")]
1173            artifact_reader,
1174            #[cfg(feature = "agentic-worker")]
1175            ext_artifact_port,
1176            #[cfg(feature = "agentic-worker")]
1177            stream_observers,
1178            RolloutIds::default(),
1179            // The tenant-only path has no unit, so no host-chosen meter and
1180            // no run-outcome sink.
1181            #[cfg(feature = "agentic-worker")]
1182            None,
1183            None,
1184            None,
1185            // ... and no host-provided user ledger target.
1186            #[cfg(feature = "agentic-worker")]
1187            None,
1188        )
1189        .await
1190    }
1191
1192    /// Like [`from_packs`](Self::from_packs) but stamps `rollout` onto the flow
1193    /// engine so every span this runtime emits carries the deployment / bundle /
1194    /// revision / customer identity. [`from_packs`](Self::from_packs) is the
1195    /// legacy (tenant-only) path and passes [`RolloutIds::default`].
1196    #[allow(clippy::too_many_arguments)]
1197    pub(crate) async fn from_packs_with_rollout(
1198        config: Arc<HostConfig>,
1199        packs: Vec<(Arc<PackRuntime>, Option<String>)>,
1200        mocks: Option<Arc<MockLayer>>,
1201        session_host: Arc<dyn SessionHost>,
1202        session_store: DynSessionStore,
1203        _state_store: DynStateStore,
1204        state_host: Arc<dyn StateHost>,
1205        secrets_manager: DynSecretsManager,
1206        #[cfg(feature = "agentic-worker")] ext_llm_port: Option<crate::host::ExtLlmPort>,
1207        #[cfg(feature = "agentic-worker")] mcp_source: Option<crate::host::McpSource>,
1208        #[cfg(feature = "agentic-worker")] artifact_reader: Option<crate::host::ArtifactReaderPort>,
1209        #[cfg(feature = "agentic-worker")] ext_artifact_port: Option<crate::host::ExtArtifactPort>,
1210        #[cfg(feature = "agentic-worker")] stream_observers: Option<
1211            crate::http::agent_stream::StreamObserverRegistry,
1212        >,
1213        rollout: RolloutIds,
1214        #[cfg(feature = "agentic-worker")] installed_billing_meter: Option<
1215            Arc<dyn greentic_aw_runtime::billing::BillingMeter>,
1216        >,
1217        run_outcome_sink: Option<Arc<dyn crate::run_outcome::RunOutcomeSink>>,
1218        approval_inbox: Option<crate::runner::approval_http::ApprovalInboxTarget>,
1219        #[cfg(feature = "agentic-worker")] user_ledger: Option<
1220            greentic_aw_runtime::user_ledger::UserLedgerTarget,
1221        >,
1222    ) -> Result<Arc<Self>> {
1223        let operator_registry = OperatorRegistry::build(&packs)?;
1224        let operator_metrics = Arc::new(OperatorMetrics::default());
1225        let pack_runtimes = packs
1226            .iter()
1227            .map(|(pack, _)| Arc::clone(pack))
1228            .collect::<Vec<_>>();
1229        let digests = packs
1230            .iter()
1231            .map(|(_, digest)| digest.clone())
1232            .collect::<Vec<_>>();
1233        let mut pack_trace = HashMap::new();
1234        for (pack, digest) in &packs {
1235            let pack_id = pack.metadata().pack_id.clone();
1236            let pack_ref = config
1237                .pack_bindings
1238                .iter()
1239                .find(|binding| binding.pack_id == pack_id)
1240                .map(|binding| binding.pack_ref.clone())
1241                .unwrap_or_else(|| pack_id.clone());
1242            pack_trace.insert(
1243                pack_id,
1244                PackTraceInfo {
1245                    pack_ref,
1246                    resolved_digest: digest.clone(),
1247                },
1248            );
1249        }
1250        // The deployed unit's identity, used as the `project_id` billing
1251        // dimension for this runtime's agentic-worker spend. It is exactly what
1252        // greentic-designer records as `pack_name`, so authoring-time and
1253        // runtime spend join on it. Captured BEFORE `rollout` moves into the
1254        // engine; `None` on the legacy tenant-only path (no bundle is pinned
1255        // there), which makes billing omit the dimension rather than fall back
1256        // to a non-unique in-pack agent id.
1257        #[cfg(feature = "agentic-worker")]
1258        let agent_project_id = rollout.bundle_id.clone();
1259        let engine = FlowEngine::new(pack_runtimes.clone(), Arc::clone(&config))
1260            .await
1261            .context("failed to prime flow engine")?
1262            .with_rollout_ids(rollout);
1263        // A host-injected MCP source replaces the one `FlowEngine::new` derives
1264        // from env; `None` leaves that env-derived source alone, so a
1265        // standalone runner is unaffected.
1266        #[cfg(feature = "agentic-worker")]
1267        let engine = engine.with_mcp_source(mcp_source);
1268        // An `mcp` flow node resolves its credential through the manager this
1269        // runtime already holds — dev-store in a Cloud Run or Kubernetes
1270        // deployment, which is the only backend there that can read a
1271        // `secrets://` URI. Without this the node built its own manager from
1272        // `SECRETS_BACKEND`, which no remote deployment sets, and every lookup
1273        // missed. An explicit `SECRETS_BACKEND` still wins; see
1274        // `mcp_node::aw::choose_mcp_secrets`.
1275        #[cfg(feature = "agentic-worker")]
1276        let engine = engine.with_mcp_secrets(Some(Arc::clone(&secrets_manager)));
1277        #[cfg_attr(not(feature = "agentic-worker"), allow(unused_mut))]
1278        let mut engine = engine;
1279
1280        // Wire Sorla remote-dispatch (NATS) into the flow engine BEFORE it is
1281        // moved behind an `Arc`. `set_remote_dispatch_handler` takes `&mut self`,
1282        // so the dispatcher must be attached while `engine` is still owned and
1283        // mutable. The response listener (which needs the post-build ingress
1284        // handle) is spawned further below, after the runtime is constructed.
1285        //
1286        // Gated on `GREENTIC_EVENTS_NATS_URL`: when unset, `sorla.call` stays
1287        // disabled and existing behaviour is unchanged. When set but NATS cannot
1288        // be reached we log a warning and continue (the engine simply has no
1289        // dispatch handler, so `sorla.call` nodes fail fast at execution time).
1290        //
1291        // Connected here (BEFORE the agentic-worker block below) rather than
1292        // its original post-block position so the agent-node handler
1293        // construction below can also thread the (possibly connected) client
1294        // into an `AuditSink` for `dw.agent` step audit events (EPIC-B B-3);
1295        // pure reordering, no behaviour change to the dispatch wiring itself.
1296        let dispatch_nats_client = match std::env::var("GREENTIC_EVENTS_NATS_URL") {
1297            Ok(nats_url) => match async_nats::connect(&nats_url).await {
1298                Ok(client) => {
1299                    engine.set_remote_dispatch_handler(Arc::new(
1300                        crate::runner::remote_dispatch::NatsDispatcher::new(client.clone()),
1301                    ));
1302                    Some(client)
1303                }
1304                Err(error) => {
1305                    tracing::warn!(
1306                        %error,
1307                        "GREENTIC_EVENTS_NATS_URL set but NATS connect failed; sorla.call disabled"
1308                    );
1309                    None
1310                }
1311            },
1312            Err(_) => None,
1313        };
1314
1315        // The HTTP approval rail (greentic-designer approval-rail-http design
1316        // §4.6): into the engine's OWN approval slot, never the shared one, so
1317        // `sorla.call` keeps failing with `sorla_route_missing` here. NATS
1318        // stays authoritative where it connected.
1319        if approval_inbox.is_some() && dispatch_nats_client.is_some() {
1320            tracing::info!(
1321                "GREENTIC_EVENTS_NATS_URL connected; approvals go over NATS and the HTTP approval inbox is not installed"
1322            );
1323        }
1324        let approval_inbox = crate::runner::approval_http::inbox_to_install(
1325            dispatch_nats_client.is_some(),
1326            approval_inbox,
1327        )
1328        .and_then(
1329            |target| match crate::runner::approval_http::HttpApprovalDispatcher::new(target) {
1330                Ok(inbox) => {
1331                    engine.set_approval_dispatch_handler(Arc::new(inbox.clone()));
1332                    tracing::info!("HTTP approval inbox wired into runtime: approval.call");
1333                    Some(inbox)
1334                }
1335                Err(error) => {
1336                    tracing::warn!(
1337                        %error,
1338                        "HTTP approval inbox not installed; approval.call needing a human will fail"
1339                    );
1340                    None
1341                }
1342            },
1343        );
1344
1345        // Clone the (possibly connected) client for the audit sink (EPIC-B
1346        // B-2/B-3): threaded into `StateMachineRuntime::from_flow_engine` so
1347        // `TraceRecorder` can publish best-effort audit events over NATS, and
1348        // (as an `AuditSink`) into the `dw.agent` node handler below so agent
1349        // tool-call/tool-result steps are audited too. Cloned BEFORE the
1350        // response-listener loop further below moves `dispatch_nats_client`.
1351        // `None` when NATS is unset/unreachable, which keeps both audit paths
1352        // off by default (zero behaviour change).
1353        let audit_nats_client = dispatch_nats_client.clone();
1354
1355        // The dw.agent handler, kept so flow-tool engines can borrow it
1356        // (`runner::nested_flow`) once the dispatch mode is known below.
1357        #[cfg(feature = "agentic-worker")]
1358        let mut nested_agent_handler: Option<
1359            Arc<dyn crate::runner::agent_node::AgentNodeHandler>,
1360        > = None;
1361
1362        #[cfg(feature = "agentic-worker")]
1363        {
1364            use crate::runner::agent_node::{
1365                agent_configs_from_manifest, merge_agent_sources, merge_sidecar_into,
1366            };
1367            use std::collections::HashMap;
1368
1369            // Collect agent configs from all New-manifest packs. When the same
1370            // agent_id appears in multiple packs the last pack wins (packs are
1371            // ordered: first = primary, rest = overlays). Collisions are logged
1372            // so operators can audit cross-pack conflicts.
1373            let mut pack_agents: HashMap<String, greentic_aw_runtime::AgentConfig> = HashMap::new();
1374            for pack in &pack_runtimes {
1375                let mut blobs = pack.manifest_agent_blobs();
1376                // Bridge: designer-built packs cannot populate `manifest.agents`
1377                // (old greentic-pack); they embed a `dw-agents.json` sidecar.
1378                // Fill any agent_id the manifest lacked (manifest stays authoritative).
1379                merge_sidecar_into(&mut blobs, pack.dw_agents_sidecar_blobs());
1380                if blobs.is_empty() {
1381                    continue;
1382                }
1383                let pack_id = pack.metadata().pack_id.clone();
1384                let configs = agent_configs_from_manifest(&pack_id, &blobs);
1385                for (agent_id, agent_config) in configs {
1386                    if let Some(existing) = pack_agents.get(&agent_id) {
1387                        tracing::warn!(
1388                            agent_id,
1389                            prior_pack = existing.agent_id.as_str(),
1390                            new_pack = pack_id.as_str(),
1391                            "agent_id collision across packs; last pack wins"
1392                        );
1393                    }
1394                    pack_agents.insert(agent_id, agent_config);
1395                }
1396            }
1397
1398            // Operator config overrides pack-provided agents on collision.
1399            let merged_agents = merge_agent_sources(pack_agents, config.agents.clone());
1400
1401            // `media.create` flow nodes store through the SAME artifact port the
1402            // agent runtime hands extensions as `host.artifact.put`.
1403            engine.set_ext_artifact_port(ext_artifact_port.clone());
1404
1405            // First-boot ingest of any pack-baked knowledge corpus (W4 4c), handed
1406            // to every registered agent-runtime extension. Runs BEFORE the agent
1407            // runtime mounts its serving knowledge connection: embedded SurrealDB
1408            // allows one handle per store directory, so the temporary ingest
1409            // connection must open and drop before the serving mount (inside
1410            // build_agent_node_handler) opens its own. No-op when no extension is
1411            // registered or no pack carries a corpus. `runtime_ext`'s
1412            // `boot_ingests_before_any_runtime_is_built` pins this order.
1413            crate::runner::runtime_ext::ingest_all_corpora(&pack_runtimes, &config.tenant_ctx())
1414                .await;
1415
1416            // DwAgent state-store selection. With GREENTIC_AW_REDIS_URL set, use the
1417            // Redis-backed stores. Without it, a `desktop-agent-ephemeral` build
1418            // uses its own process-global in-memory stores; every OTHER build
1419            // (greentic-start, the distroless image) goes through
1420            // `build_aw_backends`, which with no Redis URL auto-selects the
1421            // shared in-memory KV (or redb under GREENTIC_AW_STATE_BACKEND=disk).
1422            // So a missing Redis URL does NOT disable dw.agent in any build. The
1423            // runtime is absent only when there are no agents, when
1424            // GREENTIC_AW_STATE_BACKEND=redis names no URL, when Redis is
1425            // unreachable, or when the extension runtime fails to initialise.
1426            let redis_set = std::env::var("GREENTIC_AW_REDIS_URL")
1427                .map(|v| !v.is_empty())
1428                .unwrap_or(false);
1429            // Best-effort agent-step audit sink (EPIC-B B-3), built from the
1430            // same (possibly connected) NATS client the flow-level audit sink
1431            // (B-2) uses. `None` when NATS is unset/unreachable, which keeps
1432            // `dw.agent` execution on the plain `AgentRuntime::step` path
1433            // (zero behaviour change).
1434            let agent_audit_sink = audit_nats_client
1435                .clone()
1436                .map(crate::trace::audit_sink::AuditSink::new);
1437            // `merged_agents` is MOVED into `build_agent_node_handler` below
1438            // (redis/ephemeral branches); clone for the graph handler first so
1439            // it can resolve a graph node's `agent_ref` (SP1) against the same
1440            // process-level merged config map.
1441            let graph_agents = merged_agents.clone();
1442            // Also needed after `merged_agents` is moved into
1443            // `build_agent_node_handler`/`_ephemeral` below, to resolve the
1444            // in-process operala.call LLM key the same way (see the
1445            // `operala-in-process` block after the DwAgent wiring).
1446            #[cfg(feature = "operala-in-process")]
1447            let operala_agents = merged_agents.clone();
1448            // ONE billing sink for this unit, shared by dw.agent, agent-graph
1449            // turns and in-process deep workers: the meter the embedding host
1450            // installed (a deployed unit's `WorkerUsageMeter`), else the
1451            // env-configured cloud-commerce sink, else none.
1452            let billing_meter =
1453                crate::runner::agent_node::resolve_billing_meter(installed_billing_meter);
1454            let agent_handler = if redis_set {
1455                crate::runner::agent_node::build_agent_node_wiring_metered(
1456                    merged_agents,
1457                    config.tenant.clone(),
1458                    Arc::clone(&secrets_manager),
1459                    ext_llm_port.clone(),
1460                    pack_runtimes.clone(),
1461                    agent_audit_sink.clone(),
1462                    stream_observers.clone(),
1463                    agent_project_id.clone(),
1464                    billing_meter.clone(),
1465                    user_ledger.clone(),
1466                    artifact_reader.clone(),
1467                    ext_artifact_port.clone(),
1468                )
1469                .await
1470            } else {
1471                #[cfg(feature = "desktop-agent-ephemeral")]
1472                {
1473                    crate::runner::agent_node::build_agent_node_wiring_ephemeral_metered(
1474                        merged_agents,
1475                        config.tenant.clone(),
1476                        Arc::clone(&secrets_manager),
1477                        ext_llm_port.clone(),
1478                        pack_runtimes.clone(),
1479                        agent_audit_sink.clone(),
1480                        stream_observers.clone(),
1481                        agent_project_id.clone(),
1482                        billing_meter.clone(),
1483                        user_ledger.clone(),
1484                        artifact_reader.clone(),
1485                        ext_artifact_port.clone(),
1486                    )
1487                    .await
1488                }
1489                #[cfg(not(feature = "desktop-agent-ephemeral"))]
1490                {
1491                    crate::runner::agent_node::build_agent_node_wiring_metered(
1492                        merged_agents,
1493                        config.tenant.clone(),
1494                        Arc::clone(&secrets_manager),
1495                        ext_llm_port.clone(),
1496                        pack_runtimes.clone(),
1497                        agent_audit_sink.clone(),
1498                        stream_observers.clone(),
1499                        agent_project_id.clone(),
1500                        billing_meter.clone(),
1501                        user_ledger.clone(),
1502                        artifact_reader.clone(),
1503                        ext_artifact_port.clone(),
1504                    )
1505                    .await
1506                }
1507            };
1508            // The AgentRuntime behind dw.agent is also the tool surface of
1509            // in-process deep workers (operala.call, below).
1510            #[cfg(feature = "operala-in-process")]
1511            let operala_agent_runtime = agent_handler
1512                .as_ref()
1513                .map(|wiring| Arc::clone(&wiring.runtime));
1514            if let Some(wiring) = agent_handler {
1515                nested_agent_handler = Some(Arc::clone(&wiring.handler));
1516                engine.set_agent_node_handler(wiring.handler);
1517                tracing::info!("DwAgent runtime wired into FlowEngine");
1518            }
1519
1520            // In-process deep-worker runtime for `operala.call` nodes
1521            // (`operala-in-process`; `desktop-agent-ephemeral` implies it, so
1522            // the designer's offline Test-chat sidecar keeps it). Reuses the
1523            // exact key-resolution policy the
1524            // in-process dw.agent LLM backend uses (env key wins; otherwise
1525            // the first agent's `llm.credential_ref` resolved from the
1526            // per-tenant secrets store), then builds a
1527            // `greentic_llm::RigBackend` — the same OpenAI-compatible,
1528            // multi-provider client `GreenticLlmBackend` uses for dw.agent —
1529            // and wraps it in `DeepWorkerInvoker`. No handler is wired (and
1530            // `operala.call` falls back to the NATS `RemoteDispatchHandler`,
1531            // failing without it) when no LLM key resolves or the provider
1532            // fails to build.
1533            #[cfg(feature = "operala-in-process")]
1534            {
1535                use crate::runner::operala_node::{
1536                    OPERALA_DISPATCH_ENV, OperalaSelection, select_operala_handler_metered,
1537                };
1538                use crate::runner::operala_tools::OperalaToolContext;
1539
1540                // Deep workers call their agent's bound tools through the SAME
1541                // AgentRuntime dw.agent uses, so the two share one prerequisite.
1542                // A missing Redis URL is NOT one (see the state-store selection
1543                // above). Without a runtime — an explicit redis backend with no
1544                // URL, an unreachable Redis, or a failed extension runtime, all of
1545                // which also leave dw.agent unwired — deep workers run tool-less,
1546                // which an operator must be able to see.
1547                let operala_tools = match operala_agent_runtime {
1548                    Some(runtime) => Some(Arc::new(OperalaToolContext::new(
1549                        runtime,
1550                        &operala_agents,
1551                        agent_project_id.clone(),
1552                    ))),
1553                    None => {
1554                        if operala_agents.values().any(|agent| !agent.tools.is_empty()) {
1555                            tracing::warn!(
1556                                tenant = %config.tenant,
1557                                "no agent runtime was built for this tenant (dw.agent is \
1558                                 unwired too: GREENTIC_AW_STATE_BACKEND=redis without \
1559                                 GREENTIC_AW_REDIS_URL, Redis unreachable, or the extension \
1560                                 runtime failed; see the earlier log lines); operala.call deep \
1561                                 workers will run WITHOUT the tools their agents declare"
1562                            );
1563                        }
1564                        None
1565                    }
1566                };
1567
1568                // Provider/model are resolved PER WORKER from each
1569                // `operala.call` node's `input.llm` binding (stamped by
1570                // greentic-dw-authoring for authored deep-worker packs); the
1571                // handler builds the LLM per dispatch. For a node that carries
1572                // NO `input.llm` — e.g. an operala.call synthesized at runtime
1573                // for a dw.agent's chronicle knowledge/memory retrieval — fall
1574                // back to the agent's OWN configured provider/model (the same
1575                // `operala_agents` the api_key is resolved from). The
1576                // process-level env still OVERRIDES both. Only when neither the
1577                // node, the agent config, nor the env carries a provider/model
1578                // does the dispatch error explicitly.
1579                let agent_llm = operala_agents
1580                    .values()
1581                    .map(|agent| &agent.llm)
1582                    .find(|llm| !llm.provider.trim().is_empty() && !llm.model.trim().is_empty());
1583                let fallback_provider = std::env::var("GREENTIC_LLM_PROVIDER")
1584                    .ok()
1585                    .filter(|value| !value.trim().is_empty())
1586                    .or_else(|| agent_llm.map(|llm| llm.provider.clone()));
1587                let fallback_model = std::env::var("GREENTIC_LLM_MODEL")
1588                    .ok()
1589                    .filter(|value| !value.trim().is_empty())
1590                    .or_else(|| agent_llm.map(|llm| llm.model.clone()));
1591                let base_url = std::env::var("GREENTIC_LLM_BASE_URL")
1592                    .ok()
1593                    .filter(|value| !value.trim().is_empty());
1594
1595                // Same key policy the in-process dw.agent backend uses: env key
1596                // wins; otherwise the first agent's `llm.credential_ref` from the
1597                // per-tenant secrets store.
1598                let key_secrets = &secrets_manager;
1599                let key_tenant = config.tenant.as_str();
1600                let key_agents = &operala_agents;
1601                let resolve_key = move || async move {
1602                    let env_key = std::env::var("GREENTIC_LLM_API_KEY")
1603                        .ok()
1604                        .filter(|value| !value.trim().is_empty())
1605                        .or_else(|| {
1606                            std::env::var("OPENAI_API_KEY")
1607                                .ok()
1608                                .filter(|value| !value.trim().is_empty())
1609                        });
1610                    match env_key {
1611                        Some(key) => Some(key),
1612                        None => {
1613                            crate::runner::agent_node::resolve_in_process_llm_key(
1614                                key_secrets,
1615                                key_tenant,
1616                                key_agents,
1617                            )
1618                            .await
1619                        }
1620                    }
1621                };
1622
1623                let dispatch_env = std::env::var(OPERALA_DISPATCH_ENV).ok();
1624                match select_operala_handler_metered(
1625                    dispatch_env.as_deref(),
1626                    resolve_key,
1627                    base_url,
1628                    fallback_provider,
1629                    fallback_model,
1630                    operala_tools,
1631                    // The deep worker's OWN loop bills through the same sink
1632                    // as dw.agent, attributed to the same unit.
1633                    billing_meter.clone(),
1634                    agent_project_id.clone(),
1635                )
1636                .await
1637                {
1638                    OperalaSelection::InProcess(handler) => {
1639                        engine.set_operala_node_handler(handler);
1640                        tracing::info!(
1641                            dispatch = "in-process",
1642                            "operala.call in-process deep-worker runtime wired into FlowEngine \
1643                             (provider/model resolved per-worker from node input.llm)"
1644                        );
1645                    }
1646                    OperalaSelection::Nats => {
1647                        tracing::info!(
1648                            dispatch = "nats",
1649                            "GREENTIC_OPERALA_DISPATCH=nats: operala.call dispatches over NATS; \
1650                             in-process deep-worker handler not wired"
1651                        );
1652                        if std::env::var("GREENTIC_EVENTS_NATS_URL")
1653                            .ok()
1654                            .filter(|value| !value.trim().is_empty())
1655                            .is_none()
1656                        {
1657                            tracing::warn!(
1658                                "GREENTIC_OPERALA_DISPATCH=nats but GREENTIC_EVENTS_NATS_URL is \
1659                                 unset; operala.call nodes will fail (no remote dispatch \
1660                                 handler). Set the NATS URL or unset the flag."
1661                            );
1662                        }
1663                    }
1664                    OperalaSelection::NoKey => {
1665                        tracing::warn!(
1666                            dispatch = "nats",
1667                            "no LLM API key resolved (env or store) for operala.call \
1668                             in-process wiring; operala.call nodes will fall back to NATS \
1669                             (and fail without it)"
1670                        );
1671                    }
1672                }
1673            }
1674
1675            // Collect agent-graph sidecars from each pack. Unlike agents (a
1676            // manifest.cbor map), graphs arrive as a pack FILE (`agent-graph.json`)
1677            // — one sidecar per pack — so the graph is keyed by `pack_id`. A
1678            // sidecar that fails UTF-8 / JSON / schema validation is logged and
1679            // skipped (lenient, mirroring `agent_configs_from_manifest`) so a bad
1680            // graph never blocks the rest of pack loading. When the same pack_id
1681            // appears twice (overlay), the last pack wins.
1682            let mut graphs: HashMap<String, greentic_aw_runtime::graph::GraphConfig> =
1683                HashMap::new();
1684            for pack in &pack_runtimes {
1685                let Some(bytes) = pack.read_agent_graph_sidecar() else {
1686                    continue;
1687                };
1688                let pack_id = pack.metadata().pack_id.clone();
1689                if let Some(config) =
1690                    crate::runner::graph_node::graph_config_from_sidecar(&pack_id, &bytes)
1691                    && graphs.insert(pack_id.clone(), config).is_some()
1692                {
1693                    tracing::warn!(
1694                        pack_id = pack_id.as_str(),
1695                        "agent-graph sidecar for pack_id seen twice; last pack wins"
1696                    );
1697                }
1698            }
1699
1700            // Producer/operator-declared graphs (HostConfig.graphs) override
1701            // pack-sidecar graphs on `graph_id` collision — mirroring the
1702            // operator-wins merge for agents.
1703            for (graph_id, graph_config) in config.graphs.clone() {
1704                graphs.insert(graph_id, graph_config);
1705            }
1706
1707            // Tenant, secrets manager and deployed unit are the same three
1708            // values the `dw.agent` handler above receives, so a graph turn's
1709            // `a2a:` tools resolve the same credentials a single-turn worker's
1710            // would.
1711            if let Some(handler) = crate::runner::graph_node::build_graph_node_handler_metered(
1712                graphs,
1713                agent_audit_sink.clone(),
1714                Arc::new(pack_runtimes.clone()),
1715                graph_agents,
1716                config.tenant.clone(),
1717                Arc::clone(&secrets_manager),
1718                agent_project_id.clone(),
1719                billing_meter.clone(),
1720            )
1721            .await
1722            {
1723                engine.set_graph_node_handler(handler);
1724                tracing::info!("DwAgentGraph runtime wired into FlowEngine");
1725            }
1726        }
1727
1728        // Resolve how `dw.agent` nodes dispatch. When `GREENTIC_AW_DISPATCH=nats`
1729        // is set, the node is rerouted over the durable agentic NATS path instead
1730        // of the in-process handler. Must be wired while `engine` is still owned.
1731        #[cfg(feature = "agentic-worker")]
1732        {
1733            let dw_dispatch =
1734                crate::runner::agent_node::dw_agent_dispatch_mode(|k| std::env::var(k).ok());
1735            engine.set_dw_agent_dispatch(dw_dispatch);
1736            // Lend the handler to flow-tool engines, on the SAME
1737            // `Arc<PackRuntime>`s the agent runtime's flow invoker holds (the
1738            // slot lives on the instance). Only for in-process dispatch: over
1739            // NATS a nested engine has no remote handler and must keep
1740            // failing loudly. `GREENTIC_AW_NESTED_FLOW_AGENTS=0` opts out.
1741            // The opt-out is reported only when it changed something: with
1742            // nothing to lend (NATS, no handler) there is nothing opted out of.
1743            if let Some(handlers) =
1744                crate::runner::nested_flow::for_dispatch(dw_dispatch, nested_agent_handler.as_ref())
1745            {
1746                if crate::runner::nested_flow::nested_flow_agents_enabled() {
1747                    for pack in &pack_runtimes {
1748                        pack.set_nested_flow_handlers(handlers.clone());
1749                    }
1750                    tracing::info!("dw.agent handler lent to flow-tool engines");
1751                } else {
1752                    tracing::info!(
1753                        env = crate::runner::nested_flow::NESTED_FLOW_AGENTS_ENV,
1754                        "dw.agent handler not lent to flow-tool engines (opted out)"
1755                    );
1756                }
1757            }
1758            if matches!(
1759                dw_dispatch,
1760                crate::runner::agent_node::DwAgentDispatch::Nats
1761            ) && std::env::var("GREENTIC_EVENTS_NATS_URL")
1762                .ok()
1763                .filter(|s| !s.is_empty())
1764                .is_none()
1765            {
1766                tracing::warn!(
1767                    "GREENTIC_AW_DISPATCH=nats but GREENTIC_EVENTS_NATS_URL is unset; \
1768                     dw.agent nodes will fail (no remote dispatch handler). \
1769                     Set the NATS URL or unset the flag."
1770                );
1771            }
1772        }
1773
1774        let engine = Arc::new(engine);
1775        let state_machine = Arc::new(
1776            StateMachineRuntime::from_flow_engine_with_run_outcome_sink(
1777                Arc::clone(&config),
1778                Arc::clone(&engine),
1779                pack_trace,
1780                session_host,
1781                Arc::clone(&session_store),
1782                state_host,
1783                Arc::clone(&secrets_manager),
1784                mocks.clone(),
1785                audit_nats_client,
1786                run_outcome_sink,
1787            )
1788            .context("failed to initialise state machine runtime")?,
1789        );
1790
1791        // The inbox resumes through a STRICT resumer: a decision for a gate
1792        // that is no longer parked under exactly its nonced id is dropped and
1793        // never starts a fresh run.
1794        if let Some(inbox) = &approval_inbox {
1795            inbox.attach_resumer(Arc::new(
1796                crate::runner::runtime_session_resumer::RuntimeSessionResumer::strict(Arc::clone(
1797                    &state_machine,
1798                )),
1799            ));
1800        }
1801
1802        // Built BEFORE any listener task is spawned: a fallible step after the
1803        // spawns would drop their JoinHandles, which detaches (not aborts) them.
1804        // Guarded like the pack's blocking client: this client carries the
1805        // email/OAuth broker traffic, so it must not reach link-local or
1806        // cloud-metadata addresses (SSRF), including via redirects. The DNS half
1807        // of the guard does NOT apply behind an `HTTP(S)_PROXY` (the proxy
1808        // resolves the name; an IP literal is never resolved): this client keeps
1809        // the environment proxy on purpose, because it talks to operator-set
1810        // broker/OAuth/mail URLs that some deployments reach only via a proxy.
1811        let http_guard = crate::http_guard::HttpGuard::from_env();
1812        let http_client = Client::builder()
1813            .dns_resolver(Arc::new(crate::http_guard::GuardedResolver {
1814                guard: http_guard,
1815            }))
1816            .redirect(crate::http_guard::redirect_policy(http_guard))
1817            .build()?;
1818
1819        // Spawn the response listeners now that the ingress handle
1820        // (`state_machine`) exists. Each listener resumes paused flows by feeding
1821        // a synthesized ingress envelope through `StateMachineRuntime::handle`
1822        // (see `RuntimeSessionResumer`). The resumer is runtime-agnostic (it
1823        // resumes by correlation id), so one shared resumer serves all runtimes;
1824        // we run one listener per runtime so every `*.call` node's responses
1825        // (`greentic.<runtime>.response.v1`) are consumed. Only started when the
1826        // dispatcher above connected successfully.
1827        let mut background_handles: Vec<JoinHandle<()>> = Vec::new();
1828        if let Some(client) = dispatch_nats_client {
1829            let resumer = Arc::new(
1830                crate::runner::runtime_session_resumer::RuntimeSessionResumer::new(Arc::clone(
1831                    &state_machine,
1832                ))
1833                .with_watchdog_notifier(
1834                    crate::runner::dispatch_listener::nats_watchdog_notifier(
1835                        client.clone(),
1836                        config.tenant.clone(),
1837                    ),
1838                ),
1839            );
1840            background_handles.push(spawn_listener_logged(
1841                "watchdog-cancel",
1842                crate::runner::dispatch_listener::run_watchdog_cancel_listener(
1843                    client.clone(),
1844                    config.tenant.clone(),
1845                    crate::runner::dispatch_listener::process_cancel_origin().to_string(),
1846                ),
1847            ));
1848            for runtime_name in ["sorla", "operala", "agentic", "telco-x", "approval"] {
1849                // Per-tenant queue group + tenant filter: replicas and reloaded
1850                // runtimes of one tenant share a delivery, and one tenant's
1851                // runtime never resumes another tenant's response.
1852                let scope = crate::runner::dispatch_listener::ListenerScope {
1853                    queue_group: Some(format!("runner-{}-{runtime_name}", config.tenant)),
1854                    tenant: Some(config.tenant.clone()),
1855                };
1856                background_handles.push(spawn_listener_logged(
1857                    runtime_name,
1858                    crate::runner::dispatch_listener::run_response_listener_scoped(
1859                        client.clone(),
1860                        runtime_name.to_string(),
1861                        Arc::clone(&resumer)
1862                            as Arc<dyn crate::runner::dispatch_listener::SessionResumer>,
1863                        scope,
1864                    ),
1865                ));
1866            }
1867            // Eagerly pre-cache local-wasm MCP components when the admin publishes
1868            // a warm event. Feature-gated behind `agentic-worker` because
1869            // `mcp_store_pull` lives in `greentic-aw-runtime` which is only
1870            // present when that feature is enabled.
1871            #[cfg(feature = "agentic-worker")]
1872            background_handles.push(spawn_listener_logged(
1873                "mcp-warm",
1874                crate::runner::mcp_warm_listener::run_mcp_warm_listener(client.clone()),
1875            ));
1876            tracing::info!(
1877                "Remote-dispatch (NATS) wired into runtime: sorla.call / operala.call / agentic.call / telco-x.call"
1878            );
1879        }
1880        Ok(Arc::new(Self {
1881            tenant: config.tenant.clone(),
1882            config,
1883            packs: pack_runtimes,
1884            digests,
1885            engine,
1886            state_machine,
1887            session_store,
1888            http_client,
1889            mocks,
1890            timer_handles: Mutex::new(Vec::new()),
1891            timer_cancel: CancellationToken::new(),
1892            background_handles: Mutex::new(background_handles),
1893            secrets: secrets_manager,
1894            operator_registry,
1895            operator_metrics,
1896            contract_cache: ContractCache::from_env(),
1897            approval_inbox,
1898        }))
1899    }
1900
1901    pub fn tenant(&self) -> &str {
1902        &self.tenant
1903    }
1904
1905    pub fn config(&self) -> &Arc<HostConfig> {
1906        &self.config
1907    }
1908
1909    pub fn operator_registry(&self) -> &OperatorRegistry {
1910        &self.operator_registry
1911    }
1912
1913    pub fn operator_metrics(&self) -> &OperatorMetrics {
1914        &self.operator_metrics
1915    }
1916
1917    pub fn contract_cache(&self) -> &ContractCache {
1918        &self.contract_cache
1919    }
1920
1921    pub fn contract_cache_stats(&self) -> ContractCacheStats {
1922        self.contract_cache.stats()
1923    }
1924
1925    pub fn main_pack(&self) -> &Arc<PackRuntime> {
1926        self.packs
1927            .first()
1928            .expect("tenant runtime must contain at least one pack")
1929    }
1930
1931    pub fn pack(&self) -> Arc<PackRuntime> {
1932        Arc::clone(self.main_pack())
1933    }
1934
1935    pub fn overlays(&self) -> Vec<Arc<PackRuntime>> {
1936        self.packs.iter().skip(1).cloned().collect()
1937    }
1938
1939    /// All packs in declaration order: main pack at index 0, overlays after.
1940    /// Borrowed slice — no `Arc` clones, no allocation. Use this when you only
1941    /// need to iterate the full pack list; prefer [`pack`]/[`overlays`] when
1942    /// you need to hand out owned `Arc`s downstream.
1943    ///
1944    /// [`pack`]: TenantRuntime::pack
1945    /// [`overlays`]: TenantRuntime::overlays
1946    pub fn all_packs(&self) -> &[Arc<PackRuntime>] {
1947        &self.packs
1948    }
1949
1950    /// Resolved content digest of each loaded pack, index-aligned with the pack
1951    /// list. `Some` for revision runtimes (verified at load) and the legacy
1952    /// index path; `None` only when a digest was unavailable.
1953    pub fn pack_digests(&self) -> &[Option<String>] {
1954        &self.digests
1955    }
1956
1957    pub fn engine(&self) -> &Arc<FlowEngine> {
1958        &self.engine
1959    }
1960
1961    pub fn state_machine(&self) -> &Arc<StateMachineRuntime> {
1962        &self.state_machine
1963    }
1964
1965    /// Shared session store. M1.5: lets `apply_welcome_flow_override`
1966    /// build a `FlowResumeStore` against the SAME bucket the state machine
1967    /// will read/write — important under revision mode where each revision
1968    /// is given its own store via `load_revision`.
1969    pub fn session_store(&self) -> &DynSessionStore {
1970        &self.session_store
1971    }
1972
1973    pub fn http_client(&self) -> &Client {
1974        &self.http_client
1975    }
1976
1977    pub fn oauth_config(&self) -> Option<OAuthBrokerConfig> {
1978        self.config.oauth_broker_config()
1979    }
1980
1981    pub fn digest(&self) -> Option<&str> {
1982        self.digests.first().and_then(|d| d.as_deref())
1983    }
1984
1985    pub fn overlay_digests(&self) -> Vec<Option<String>> {
1986        self.digests.iter().skip(1).cloned().collect()
1987    }
1988
1989    pub fn required_secrets(&self) -> Vec<SecretRequirement> {
1990        self.packs
1991            .iter()
1992            .flat_map(|pack| pack.required_secrets().iter().cloned())
1993            .collect()
1994    }
1995
1996    pub fn missing_secrets(&self) -> Vec<SecretRequirement> {
1997        self.packs
1998            .iter()
1999            .flat_map(|pack| pack.missing_secrets(&self.config.tenant_ctx()))
2000            .collect()
2001    }
2002
2003    pub fn mocks(&self) -> Option<&Arc<MockLayer>> {
2004        self.mocks.as_ref()
2005    }
2006
2007    pub fn register_timers(&self, handles: Vec<JoinHandle<()>>) {
2008        self.timer_handles.lock().extend(handles);
2009    }
2010
2011    /// Token the cron timer tasks select on while sleeping.
2012    pub(crate) fn timer_cancel_token(&self) -> CancellationToken {
2013        self.timer_cancel.clone()
2014    }
2015
2016    /// Stop this runtime's cron timers now. Used when a reload supersedes the
2017    /// runtime: it may stay referenced by in-flight work for a while, and its
2018    /// timers must not fire alongside the replacement's.
2019    ///
2020    /// Cooperative, not `JoinHandle::abort`: a timer sleeping stops before its
2021    /// NEXT tick, but a tick already inside `state_machine().handle(..)` runs
2022    /// to completion, so its effects are never left without the snapshot/state
2023    /// save that follows them. The handles are detached; each task exits on
2024    /// its own.
2025    pub fn abort_timers(&self) {
2026        self.timer_cancel.cancel();
2027        self.timer_handles.lock().clear();
2028    }
2029
2030    #[cfg(test)]
2031    pub(crate) fn timer_count(&self) -> usize {
2032        self.timer_handles.lock().len()
2033    }
2034
2035    /// Read a RUNTIME-level secret, at the `_runner` pseudo-pack segment.
2036    ///
2037    /// **Deliberately NOT unit-scoped**, unlike every pack secret a component
2038    /// reads (see [`crate::secrets::unit_pack_segment`]). Its only caller is
2039    /// the operator HTTP attachments path (`runner::operator::resolve_attachments`),
2040    /// and `_runner` is not a deployed pack: nothing stages a per-unit value
2041    /// there, in any lane. Scoping it per unit would move an address no writer
2042    /// produces, so every currently-working `_runner` secret would resolve only
2043    /// through the compatibility fallback — a strictly worse address for no
2044    /// isolation gained. Revisit only if a per-unit writer for `_runner`
2045    /// appears.
2046    pub fn get_secret(&self, key: &str) -> Result<String> {
2047        if crate::provider_core_only::is_enabled() {
2048            bail!(crate::provider_core_only::blocked_message("secrets"))
2049        }
2050        if !self.config.secrets_policy.is_allowed(key) {
2051            bail!("secret {key} is not permitted by bindings policy");
2052        }
2053        let ctx = self.config.tenant_ctx();
2054        let canonical_key = canonicalize_secret_key(key);
2055        let bytes =
2056            read_secret_blocking(&self.secrets, &ctx, RUNTIME_SECRETS_PACK_ID, &canonical_key)
2057                .context("failed to read secret from manager")?;
2058        let value = String::from_utf8(bytes).context("secret value is not valid UTF-8")?;
2059        Ok(value)
2060    }
2061
2062    pub fn build_events_email_execution_plan(
2063        &self,
2064        tenant: &greentic_types::TenantCtx,
2065        request: &EmailSendRequest,
2066    ) -> Result<EmailExecutionPlan> {
2067        let oauth = self
2068            .oauth_config()
2069            .ok_or_else(|| anyhow!("oauth broker config is not configured for tenant runtime"))?;
2070        build_email_execution_plan(&oauth, tenant, request)
2071    }
2072
2073    pub async fn execute_events_email_request(
2074        &self,
2075        access_token: &str,
2076        request: &EmailSendRequest,
2077    ) -> Result<()> {
2078        execute_email_request(self.http_client(), access_token, request).await
2079    }
2080
2081    pub async fn execute_events_email_with_oauth(
2082        &self,
2083        tenant: &greentic_types::TenantCtx,
2084        request: &EmailSendRequest,
2085    ) -> Result<()> {
2086        let plan = self.build_events_email_execution_plan(tenant, request)?;
2087        // The broker authenticates the runner with its shared secret; the
2088        // un-authenticated variant would be rejected by a secured broker.
2089        let shared_secret = self.oauth_config().and_then(|c| c.shared_secret);
2090        let token = request_resource_token_with_auth(
2091            self.http_client(),
2092            &plan.token_request,
2093            shared_secret.as_deref(),
2094        )
2095        .await?;
2096        self.execute_events_email_request(&token.access_token, request)
2097            .await
2098    }
2099
2100    pub fn pack_for_component(&self, component_ref: &str) -> Option<Arc<PackRuntime>> {
2101        self.packs
2102            .iter()
2103            .find(|pack| pack.contains_component(component_ref))
2104            .cloned()
2105    }
2106
2107    pub fn pack_for_component_with_digest(
2108        &self,
2109        component_ref: &str,
2110    ) -> Option<(Arc<PackRuntime>, Option<String>)> {
2111        self.packs
2112            .iter()
2113            .zip(self.digests.iter())
2114            .find(|(pack, _)| pack.contains_component(component_ref))
2115            .map(|(pack, digest)| (Arc::clone(pack), digest.clone()))
2116    }
2117
2118    pub fn resolve_component(&self, component_ref: &str) -> Option<ResolvedComponent> {
2119        self.pack_for_component_with_digest(component_ref)
2120            .map(|(pack, digest)| ResolvedComponent {
2121                digest: digest
2122                    .or_else(|| self.digest().map(ToString::to_string))
2123                    .unwrap_or_else(|| "unknown".to_string()),
2124                component_ref: component_ref.to_string(),
2125                pack,
2126            })
2127    }
2128}
2129
2130/// Spawn a long-running listener future, logging (rather than discarding) the
2131/// error if it ends. Returns the task handle so the owner can abort it:
2132/// aborting drops the inner future, which closes its subscription.
2133fn spawn_listener_logged<F>(name: &'static str, listener: F) -> JoinHandle<()>
2134where
2135    F: Future<Output = Result<()>> + Send + 'static,
2136{
2137    tokio::spawn(async move {
2138        if let Err(error) = listener.await {
2139            tracing::warn!(listener = name, %error, "background listener stopped");
2140        }
2141    })
2142}
2143
2144impl Drop for TenantRuntime {
2145    fn drop(&mut self) {
2146        // Cooperative (see `abort_timers`): a task mid-tick holds a strong
2147        // `Arc` to this runtime, so Drop can only race a sleeping timer.
2148        self.timer_cancel.cancel();
2149        self.timer_handles.lock().clear();
2150        for handle in self.background_handles.lock().drain(..) {
2151            handle.abort();
2152        }
2153        if let Some(inbox) = &self.approval_inbox {
2154            inbox.shutdown();
2155        }
2156    }
2157}
2158
2159#[cfg(test)]
2160mod timer_retirement_tests {
2161    use super::*;
2162
2163    const CRON: &str = r#"[{ flow_id: "flow.main", cron: "0 0 1 1 *" }]"#;
2164
2165    async fn runtime_with_timers() -> (impl Sized, Arc<TenantRuntime>) {
2166        let (workspace, runtime) = crate::test_support::build_test_runtime_with_timers(CRON)
2167            .await
2168            .expect("runtime");
2169        let timers = crate::runner::adapt_timer::spawn_timers(Arc::clone(&runtime)).expect("spawn");
2170        runtime.register_timers(timers);
2171        (workspace, runtime)
2172    }
2173
2174    #[tokio::test]
2175    async fn insert_pack_stops_the_timers_of_the_runtime_it_replaces() {
2176        let (_w1, old) = runtime_with_timers().await;
2177        let (_w2, new) = runtime_with_timers().await;
2178        let active = ActivePacks::new();
2179        active.insert_pack("demo", Arc::clone(&old));
2180        assert!(!old.timer_cancel_token().is_cancelled());
2181
2182        active.insert_pack("demo", Arc::clone(&new));
2183        assert!(
2184            old.timer_cancel_token().is_cancelled(),
2185            "the replaced runtime must stop firing"
2186        );
2187        assert!(
2188            !new.timer_cancel_token().is_cancelled(),
2189            "the replacement keeps its timers"
2190        );
2191    }
2192
2193    #[tokio::test]
2194    async fn re_inserting_the_same_runtime_keeps_its_timers() {
2195        let (_w, runtime) = runtime_with_timers().await;
2196        let active = ActivePacks::new();
2197        active.insert_pack("demo", Arc::clone(&runtime));
2198        active.insert_pack("demo", Arc::clone(&runtime));
2199        assert!(!runtime.timer_cancel_token().is_cancelled());
2200    }
2201
2202    #[tokio::test]
2203    async fn remove_revision_stops_the_timers_of_the_removed_runtime() {
2204        let (_w, runtime) = runtime_with_timers().await;
2205        let (deployment, bundle, revision) = (
2206            DeploymentId::new(),
2207            BundleId::from("bundle-a"),
2208            RevisionId::new(),
2209        );
2210        let active = ActivePacks::new();
2211        // Install under a revision key directly: building a runtime whose
2212        // rollout identity matches is covered by `insert_revision`'s own tests.
2213        let mut map = HashMap::new();
2214        map.insert(
2215            RuntimeKey::revision("demo", deployment, bundle.clone(), revision),
2216            Arc::clone(&runtime),
2217        );
2218        active.replace(map);
2219        let removed = active.remove_revision("demo", deployment, bundle, revision);
2220        assert!(removed.is_some());
2221        assert!(runtime.timer_cancel_token().is_cancelled());
2222    }
2223}
2224
2225#[cfg(test)]
2226mod block_on_tests {
2227    use super::*;
2228
2229    #[test]
2230    fn works_without_a_runtime() {
2231        assert_eq!(block_on(async { 7 }), 7);
2232    }
2233
2234    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
2235    async fn does_not_panic_inside_a_multi_thread_runtime() {
2236        assert_eq!(block_on(async { 8 }), 8);
2237        assert_eq!(try_block_on(async { 9 }).ok(), Some(9));
2238    }
2239
2240    #[tokio::test(flavor = "current_thread")]
2241    async fn does_not_panic_inside_a_current_thread_runtime() {
2242        assert_eq!(block_on(async { 10 }), 10);
2243        assert_eq!(try_block_on(async { 11 }).ok(), Some(11));
2244    }
2245}
2246
2247#[cfg(test)]
2248mod runtime_key_tests {
2249    use super::*;
2250
2251    #[test]
2252    fn legacy_keys_match_only_on_tenant() {
2253        assert_eq!(RuntimeKey::legacy("acme"), RuntimeKey::legacy("acme"));
2254        assert_ne!(RuntimeKey::legacy("acme"), RuntimeKey::legacy("other"));
2255    }
2256
2257    #[test]
2258    fn legacy_and_revision_keys_never_collide() {
2259        let key = RuntimeKey::revision(
2260            "acme",
2261            DeploymentId::new(),
2262            BundleId::from("bundle-a"),
2263            RevisionId::new(),
2264        );
2265        assert_ne!(RuntimeKey::legacy("acme"), key);
2266    }
2267
2268    #[test]
2269    fn revision_keys_distinguish_revision_id() {
2270        let deployment = DeploymentId::new();
2271        let bundle = BundleId::from("bundle-a");
2272        let rev_a = RevisionId::new();
2273        let rev_b = RevisionId::new();
2274        let key_a = RuntimeKey::revision("acme", deployment, bundle.clone(), rev_a);
2275        let key_b = RuntimeKey::revision("acme", deployment, bundle.clone(), rev_b);
2276        let same = RuntimeKey::revision("acme", deployment, bundle, rev_a);
2277        assert_ne!(key_a, key_b);
2278        assert_eq!(key_a, same);
2279    }
2280
2281    #[test]
2282    fn legacy_reload_preserves_revision_entries() {
2283        let revision_key = RuntimeKey::revision(
2284            "acme",
2285            DeploymentId::new(),
2286            BundleId::from("bundle-a"),
2287            RevisionId::new(),
2288        );
2289        let mut prev: HashMap<RuntimeKey, u32> = HashMap::new();
2290        prev.insert(RuntimeKey::legacy("acme"), 1); // stale legacy, refreshed below
2291        prev.insert(RuntimeKey::legacy("retired"), 2); // dropped: not in new index
2292        prev.insert(revision_key.clone(), 99); // revision runtime: must survive
2293
2294        let mut legacy: HashMap<RuntimeKey, u32> = HashMap::new();
2295        legacy.insert(RuntimeKey::legacy("acme"), 10);
2296        legacy.insert(RuntimeKey::legacy("newcomer"), 20);
2297
2298        let next = merge_legacy_reload(&prev, legacy);
2299
2300        assert_eq!(next.get(&RuntimeKey::legacy("acme")), Some(&10));
2301        assert_eq!(next.get(&RuntimeKey::legacy("newcomer")), Some(&20));
2302        assert_eq!(next.get(&RuntimeKey::legacy("retired")), None);
2303        assert_eq!(next.get(&revision_key), Some(&99));
2304    }
2305
2306    #[test]
2307    fn remove_keyed_entry_pops_only_the_targeted_key() {
2308        let deployment = DeploymentId::new();
2309        let bundle = BundleId::from("bundle-a");
2310        let rev_a = RevisionId::new();
2311        let rev_b = RevisionId::new();
2312        let key_a = RuntimeKey::revision("acme", deployment, bundle.clone(), rev_a);
2313        let key_b = RuntimeKey::revision("acme", deployment, bundle, rev_b);
2314
2315        let mut prev: HashMap<RuntimeKey, u32> = HashMap::new();
2316        prev.insert(RuntimeKey::legacy("acme"), 1);
2317        prev.insert(key_a.clone(), 10);
2318        prev.insert(key_b.clone(), 20);
2319
2320        let (next, removed) = remove_keyed_entry(&prev, &key_a).expect("present");
2321        assert_eq!(removed, 10);
2322        assert_eq!(next.get(&key_a), None);
2323        assert_eq!(next.get(&key_b), Some(&20));
2324        assert_eq!(next.get(&RuntimeKey::legacy("acme")), Some(&1));
2325    }
2326
2327    #[test]
2328    fn remove_keyed_entry_returns_none_for_missing_key() {
2329        let prev: HashMap<RuntimeKey, u32> = HashMap::new();
2330        let ghost = RuntimeKey::revision(
2331            "acme",
2332            DeploymentId::new(),
2333            BundleId::from("bundle-a"),
2334            RevisionId::new(),
2335        );
2336        assert!(remove_keyed_entry(&prev, &ghost).is_none());
2337    }
2338
2339    #[test]
2340    fn remove_keyed_entry_leaves_other_deployments_alone() {
2341        let bundle = BundleId::from("bundle-a");
2342        let dep_a = DeploymentId::new();
2343        let dep_b = DeploymentId::new();
2344        let rev = RevisionId::new();
2345        let key_a = RuntimeKey::revision("acme", dep_a, bundle.clone(), rev);
2346        let key_b = RuntimeKey::revision("acme", dep_b, bundle, rev);
2347
2348        let mut prev: HashMap<RuntimeKey, u32> = HashMap::new();
2349        prev.insert(key_a.clone(), 100);
2350        prev.insert(key_b.clone(), 200);
2351
2352        let (next, removed) = remove_keyed_entry(&prev, &key_a).expect("present");
2353        assert_eq!(removed, 100);
2354        assert_eq!(next.get(&key_b), Some(&200));
2355        assert_eq!(next.len(), 1);
2356    }
2357
2358    #[test]
2359    fn map_lookup_separates_legacy_from_revision() {
2360        let deployment = DeploymentId::new();
2361        let bundle = BundleId::from("bundle-a");
2362        let revision = RevisionId::new();
2363
2364        let mut map: HashMap<RuntimeKey, u32> = HashMap::new();
2365        map.insert(RuntimeKey::legacy("acme"), 1);
2366        map.insert(
2367            RuntimeKey::revision("acme", deployment, bundle.clone(), revision),
2368            2,
2369        );
2370
2371        assert_eq!(map.get(&RuntimeKey::legacy("acme")), Some(&1));
2372        assert_eq!(
2373            map.get(&RuntimeKey::revision("acme", deployment, bundle, revision)),
2374            Some(&2)
2375        );
2376        assert_eq!(map.get(&RuntimeKey::legacy("ghost")), None);
2377    }
2378
2379    #[test]
2380    fn insert_keyed_entry_adds_revision_preserving_legacy_and_siblings() {
2381        let deployment = DeploymentId::new();
2382        let bundle = BundleId::from("bundle-a");
2383        let rev_a = RevisionId::new();
2384        let rev_b = RevisionId::new();
2385        let key_a = RuntimeKey::revision("acme", deployment, bundle.clone(), rev_a);
2386        let key_b = RuntimeKey::revision("acme", deployment, bundle, rev_b);
2387
2388        let mut prev: HashMap<RuntimeKey, u32> = HashMap::new();
2389        prev.insert(RuntimeKey::legacy("acme"), 1);
2390        prev.insert(key_a.clone(), 10);
2391
2392        let next = insert_keyed_entry(&prev, key_b.clone(), 20);
2393
2394        // New revision lands; legacy entry and the sibling revision survive.
2395        assert_eq!(next.get(&key_b), Some(&20));
2396        assert_eq!(next.get(&key_a), Some(&10));
2397        assert_eq!(next.get(&RuntimeKey::legacy("acme")), Some(&1));
2398        assert_eq!(next.len(), 3);
2399    }
2400
2401    #[test]
2402    fn insert_keyed_entry_replaces_existing_revision() {
2403        let key = RuntimeKey::revision(
2404            "acme",
2405            DeploymentId::new(),
2406            BundleId::from("bundle-a"),
2407            RevisionId::new(),
2408        );
2409        let mut prev: HashMap<RuntimeKey, u32> = HashMap::new();
2410        prev.insert(key.clone(), 10);
2411
2412        let next = insert_keyed_entry(&prev, key.clone(), 99);
2413
2414        assert_eq!(next.get(&key), Some(&99));
2415        assert_eq!(next.len(), 1);
2416    }
2417}
2418
2419#[cfg(all(test, feature = "agentic-worker"))]
2420#[path = "runtime_billing_ratchet_tests.rs"]
2421mod runtime_billing_ratchet_tests;