Skip to main content

plexus_core/plexus/
plexus.rs

1//! DynamicHub - the central routing layer for activations
2//!
3//! DynamicHub IS an activation that also serves as the registry for other activations.
4//! It implements the Plexus RPC protocol for routing and introspection.
5//! It uses hub-macro for its methods, with the `call` method using the streaming
6//! pattern to forward responses from routed methods.
7
8use super::{
9    context::PlexusContext,
10    method_enum::MethodEnumSchema,
11    schema::{ChildSummary, MethodSchema, PluginSchema, Schema},
12    streaming::PlexusStream,
13};
14use crate::types::Handle;
15use async_stream::stream;
16use plexus_client::{DenyReason, ParamProblem, RemoteError};
17use async_trait::async_trait;
18use bitflags::bitflags;
19use futures::Stream;
20use futures_core::stream::BoxStream;
21use jsonrpsee::core::server::Methods;
22use jsonrpsee::RpcModule;
23
24/// The JSON-RPC method name used in all plexus subscription notifications.
25///
26/// Every subscription registered by plexus (`.call`, `.hash`, `.schema`, `_info`)
27/// sends notifications with `"method": PLEXUS_NOTIF_METHOD` on the wire.
28/// Clients must match against this value when dispatching raw subscription frames.
29pub const PLEXUS_NOTIF_METHOD: &str = "result";
30use schemars::JsonSchema;
31use serde::{Deserialize, Serialize};
32use serde_json::Value;
33use std::collections::{BTreeMap, HashMap};
34use std::sync::Arc;
35
36// ============================================================================
37// Error Types
38// ============================================================================
39
40/// Why the service could not or would not run a call — the server side of the
41/// wire's [`RemoteError`].
42///
43/// Every variant converts to a `RemoteError` (`From<&PlexusError>`), which
44/// is what crosses the wire: in an error frame
45/// (`PlexusStreamItem::error(metadata, RemoteError::from(&e), recoverable)`)
46/// and in the `data` of a JSON-RPC rejection ([`plexus_error_to_jsonrpc`]).
47#[derive(Debug, Clone)]
48pub enum PlexusError {
49    ActivationNotFound(String),
50    MethodNotFound { activation: String, method: String },
51    /// The call's params did not fit the method (RETURNS-6: structured, was
52    /// `InvalidParams(String)`). `param` names the parameter at fault when
53    /// the failure is about one; `problem` says what is wrong with it.
54    InvalidParams {
55        param: Option<String>,
56        problem: ParamProblem,
57    },
58    ExecutionError(String),
59    HandleNotSupported(String),
60    TransportError(TransportErrorKind),
61    Unauthenticated(String),
62    /// Layer-2+ denial from the layered denial model (AUTHZ-0 §4, R-5):
63    /// the caller is authenticated but the call is not authorized.
64    ///
65    /// Produced by the scope gate ([`super::scope_gate`]) when a required
66    /// scope is unmet. The full wire-side rendering policy is
67    /// AUTHZ-PRIVACY-4's (`plexus_error_to_jsonrpc`); this variant only
68    /// commits to the typed server-side value.
69    Forbidden { reason: AuthzDenyReason },
70}
71
72/// Why a [`PlexusError::Forbidden`] denial fired — the layered denial
73/// model's typed discriminator (AUTHZ-S01-output §1, R-5).
74///
75/// No-enumeration posture per AUTHZ-CORE-1/5: each variant carries at most
76/// the single fact the caller already failed. The registry's role taxonomy
77/// and the method's full requirement set are never rendered.
78#[derive(Debug, Clone, PartialEq, Eq)]
79pub enum AuthzDenyReason {
80    /// Layer 2 (method authorization): the caller's effective scope set
81    /// does not satisfy `scope` — the FIRST unmet required scope.
82    /// Emitted by the scope gate (R-5 / AUTHZ-CORE-5).
83    MissingScope { scope: plexus_auth_core::Scope },
84    /// Layer 4 (data isolation): typed here per AUTHZ-S01-output §1 but
85    /// NOT emitted by the scope gate — the tenant-scoped storage layer
86    /// (AUTHZ-DATA) owns its emission.
87    TenantBoundary,
88    /// Layer 3 (action context): typed here but NOT emitted by the scope
89    /// gate — AUTHLANG-3's action gate owns its emission.
90    NotAccepted,
91    /// AUTH-2: the grant gate's refusal — the caller does not hold `grant`
92    /// on `scope` (within its session's ceiling). Unlike `MissingScope` it
93    /// names what was needed and where the caller does hold it (owner,
94    /// 2026-10-10: "return the grants required to hit an endpoint"); the
95    /// gate gives it only to a signed-in caller — an anonymous one gets
96    /// [`PlexusError::Unauthenticated`].
97    MissingGrant {
98        /// The method's grant, `<activation>.<method>`.
99        grant: plexus_auth_core::grants::Grant,
100        /// Where it was needed: the target's innermost scope, or `*` for a
101        /// method without a target.
102        scope: plexus_auth_core::grants::ScopeRef,
103        /// The roles that list the grant, `admin` last.
104        roles: Vec<plexus_auth_core::RoleName>,
105        /// Where the caller holds it.
106        held_on: Vec<plexus_auth_core::grants::ScopeRef>,
107    },
108    /// NEST-16: a child called its service for `method`, which is neither
109    /// the standard upward interface nor one of the methods it `needs`.
110    NotNeeded {
111        /// The method the child called, by its path from the service.
112        method: String,
113    },
114}
115
116#[derive(Debug, Clone, Serialize, Deserialize)]
117#[serde(tag = "error_kind", rename_all = "snake_case")]
118pub enum TransportErrorKind {
119    ConnectionRefused { host: String, port: u16 },
120    ConnectionTimeout { host: String, port: u16 },
121    ProtocolError { message: String },
122    NetworkError { message: String },
123}
124
125impl std::fmt::Display for TransportErrorKind {
126    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
127        match self {
128            TransportErrorKind::ConnectionRefused { host, port } => {
129                write!(f, "Connection refused to {}:{}", host, port)
130            }
131            TransportErrorKind::ConnectionTimeout { host, port } => {
132                write!(f, "Connection timeout to {}:{}", host, port)
133            }
134            TransportErrorKind::ProtocolError { message } => {
135                write!(f, "Protocol error: {}", message)
136            }
137            TransportErrorKind::NetworkError { message } => {
138                write!(f, "Network error: {}", message)
139            }
140        }
141    }
142}
143
144impl std::fmt::Display for PlexusError {
145    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
146        match self {
147            PlexusError::ActivationNotFound(name) => write!(f, "Activation not found: {}", name),
148            PlexusError::MethodNotFound { activation, method } => {
149                write!(f, "Method not found: {}.{}", activation, method)
150            }
151            // MACRO-15's lines: the parameter's wire name first, so the
152            // message names it (spec/05) — `Invalid params: id: <serde's
153            // message>`, `Invalid params: missing field: id`.
154            PlexusError::InvalidParams { param, problem } => match (param, problem) {
155                (Some(p), ParamProblem::Missing) => {
156                    write!(f, "Invalid params: missing field: {}", p)
157                }
158                (None, ParamProblem::Missing) => {
159                    write!(f, "Invalid params: a required parameter is missing")
160                }
161                (Some(p), ParamProblem::Malformed { detail }) => {
162                    write!(f, "Invalid params: {}: {}", p, detail)
163                }
164                (None, ParamProblem::Malformed { detail }) => {
165                    write!(f, "Invalid params: {}", detail)
166                }
167            },
168            PlexusError::ExecutionError(msg) => write!(f, "Execution error: {}", msg),
169            PlexusError::HandleNotSupported(activation) => {
170                write!(f, "Handle resolution not supported by activation: {}", activation)
171            }
172            PlexusError::TransportError(kind) => match kind {
173                TransportErrorKind::ConnectionRefused { host, port } => {
174                    write!(f, "Connection refused to {}:{}", host, port)
175                }
176                TransportErrorKind::ConnectionTimeout { host, port } => {
177                    write!(f, "Connection timeout to {}:{}", host, port)
178                }
179                TransportErrorKind::ProtocolError { message } => {
180                    write!(f, "Protocol error: {}", message)
181                }
182                TransportErrorKind::NetworkError { message } => {
183                    write!(f, "Network error: {}", message)
184                }
185            }
186            PlexusError::Unauthenticated(msg) => write!(f, "Authentication required: {}", msg),
187            PlexusError::Forbidden { reason } => match reason {
188                // Names ONLY the unmet scope — never the registry's
189                // taxonomy or the method's full requirement set
190                // (no-enumeration posture, AUTHZ-CORE-1/5).
191                AuthzDenyReason::MissingScope { scope } => {
192                    write!(f, "Forbidden: missing required scope '{}'", scope)
193                }
194                AuthzDenyReason::TenantBoundary => write!(f, "Forbidden: tenant boundary"),
195                AuthzDenyReason::NotAccepted => write!(f, "Forbidden: call not accepted"),
196                // AUTH-2: the wire's `message` for a refusal.
197                AuthzDenyReason::MissingGrant { grant, scope, .. } if scope.is_everywhere() => {
198                    write!(f, "needs {}", grant)
199                }
200                AuthzDenyReason::MissingGrant { grant, scope, .. } => {
201                    write!(f, "needs {} on {}", grant, scope)
202                }
203                AuthzDenyReason::NotNeeded { method } => {
204                    write!(f, "`{method}` is not among the methods this child needs (its schema's `needs`)")
205                }
206            },
207        }
208    }
209}
210
211impl std::error::Error for PlexusError {}
212
213impl PlexusError {
214    /// `InvalidParams` naming no one parameter: `detail` says what is wrong
215    /// (`Invalid params: <detail>`).
216    pub fn invalid_params(detail: impl Into<String>) -> Self {
217        PlexusError::InvalidParams { param: None, problem: ParamProblem::Malformed { detail: detail.into() } }
218    }
219
220    /// `InvalidParams` naming the parameter at fault
221    /// (`Invalid params: <param>: <detail>`).
222    pub fn malformed_param(param: impl Into<String>, detail: impl Into<String>) -> Self {
223        PlexusError::InvalidParams {
224            param: Some(param.into()),
225            problem: ParamProblem::Malformed { detail: detail.into() },
226        }
227    }
228}
229
230/// RETURNS-6: the server's failure, as the wire carries it.
231///
232/// | `PlexusError` | `RemoteError` |
233/// |---|---|
234/// | `ActivationNotFound(name)` | `ActivationNotFound { activation: name }` |
235/// | `MethodNotFound { activation, method }` | same |
236/// | `InvalidParams { param, problem }` | same |
237/// | `ExecutionError(msg)` | `Execution { message: msg }` |
238/// | `HandleNotSupported(ns)` | `HandleNotSupported { activation: ns }` |
239/// | `TransportError(kind)` — a service forwarding upstream failed | `Execution { message: kind.to_string() }` |
240/// | `Unauthenticated(_)` | `Unauthenticated` — the server-side reason stays server-side |
241/// | `Forbidden { reason }` | `Forbidden { reason: DenyReason }` |
242///
243/// `Forbidden` renders at most the single fact the caller already failed
244/// (AUTHZ-CORE-1/5): `MissingScope` names the one unmet scope — the fact
245/// the 0.6 wire already carried in its `Display` line — and
246/// `TenantBoundary` / `NotAccepted` carry nothing.
247impl From<&PlexusError> for RemoteError {
248    fn from(e: &PlexusError) -> Self {
249        match e {
250            PlexusError::ActivationNotFound(name) => RemoteError::ActivationNotFound {
251                activation: name.clone(),
252            },
253            PlexusError::MethodNotFound { activation, method } => RemoteError::MethodNotFound {
254                activation: activation.clone(),
255                method: method.clone(),
256            },
257            PlexusError::InvalidParams { param, problem } => RemoteError::InvalidParams {
258                param: param.clone(),
259                problem: problem.clone(),
260            },
261            PlexusError::ExecutionError(message) => RemoteError::Execution {
262                message: message.clone(),
263            },
264            PlexusError::HandleNotSupported(activation) => RemoteError::HandleNotSupported {
265                activation: activation.clone(),
266            },
267            PlexusError::TransportError(kind) => RemoteError::Execution {
268                message: kind.to_string(),
269            },
270            PlexusError::Unauthenticated(_) => RemoteError::Unauthenticated,
271            PlexusError::Forbidden { reason } => RemoteError::Forbidden {
272                reason: match reason {
273                    AuthzDenyReason::MissingScope { scope } => DenyReason::MissingScope {
274                        scope: scope.as_str().to_string(),
275                    },
276                    AuthzDenyReason::TenantBoundary => DenyReason::TenantBoundary,
277                    AuthzDenyReason::NotAccepted => DenyReason::NotAccepted,
278                    AuthzDenyReason::NotNeeded { method } => DenyReason::NotNeeded { method: method.clone() },
279                    // AUTH-2's refusal, whole: what was needed, where, the
280                    // roles listing it and where the caller holds it.
281                    AuthzDenyReason::MissingGrant { grant, scope, roles, held_on } => {
282                        DenyReason::MissingGrant {
283                            grant: grant.as_str().to_string(),
284                            scope: scope.as_str().to_string(),
285                            roles: roles.iter().map(|r| r.as_str().to_string()).collect(),
286                            held_on: held_on.iter().map(|s| s.as_str().to_string()).collect(),
287                        }
288                    }
289                },
290            },
291        }
292    }
293}
294
295/// RETURNS-47: a child's call inside its own context (when the parent's call
296/// had one), its stream carrying it.
297async fn in_child<F>(ctx: Option<crate::call::CallContext>, routed: F) -> Result<PlexusStream, PlexusError>
298where
299    F: std::future::Future<Output = Result<PlexusStream, PlexusError>>,
300{
301    match ctx {
302        Some(ctx) => in_call(ctx, routed).await,
303        None => routed.await,
304    }
305}
306
307/// RETURNS-47: run a call's routing inside its context, and hand back its
308/// stream carrying that context, so the method's stream reads its caller as
309/// its first line does ([`crate::call`]).
310async fn in_call<F>(ctx: crate::call::CallContext, routed: F) -> Result<PlexusStream, PlexusError>
311where
312    F: std::future::Future<Output = Result<PlexusStream, PlexusError>>,
313{
314    let stream = crate::call::scope(ctx.clone(), routed).await?;
315    Ok(Box::pin(crate::call::InCall::new(ctx, stream)))
316}
317
318/// Get the semantic JSON-RPC error code for a PlexusError.
319///
320/// Codes:
321/// - `-32001`: Authentication required (custom app-level error)
322/// - `-32003`: Forbidden — authenticated but not authorized (custom app-level error)
323/// - `-32601`: Method/activation not found (standard JSON-RPC)
324/// - `-32602`: Invalid parameters (standard JSON-RPC)
325/// - `-32000`: Generic server error (execution, transport, handle errors)
326fn plexus_error_code(e: &PlexusError) -> i32 {
327    match e {
328        PlexusError::Unauthenticated(_) => -32001,
329        PlexusError::Forbidden { .. } => -32003,
330        PlexusError::InvalidParams { .. } => -32602,
331        PlexusError::MethodNotFound { .. } | PlexusError::ActivationNotFound(_) => -32601,
332        _ => -32000,
333    }
334}
335
336/// Convert a PlexusError to a JSON-RPC rejection.
337///
338/// JSON-RPC 2.0 requires `code` and `message`, so they stay: `code` is the
339/// semantic code above, `message` the `RemoteError`'s `Display` line. `data`
340/// always carries the typed [`RemoteError`] (RETURNS-6):
341///
342/// ```text
343/// {"code": -32601, "message": "method not found: tickets.frob",
344///  "data": {"kind": "method_not_found", "activation": "tickets", "method": "frob"}}
345/// ```
346pub fn plexus_error_to_jsonrpc(e: &PlexusError) -> jsonrpsee::types::ErrorObjectOwned {
347    let error = RemoteError::from(e);
348    jsonrpsee::types::ErrorObject::owned(plexus_error_code(e), error.to_string(), Some(error))
349}
350
351/// The error stream item a failed dispatch sends: `{"type":"error",
352/// "metadata", "message", "code", "recoverable"}`, plus — for an auth
353/// refusal — AUTH-2's typed fields (`error_kind`, and for a missing grant
354/// `grant`, `scope`, `roles`, `held_on`; see
355/// [`super::types::spec_fields`]), and RETURNS-6's typed `error` beside them.
356pub(crate) fn error_item_raw(ns: &str, e: &PlexusError) -> Option<Box<serde_json::value::RawValue>> {
357    serde_json::value::to_raw_value(&error_item(ns, e)).ok()
358}
359
360/// AUTH-2: the error stream item a failed dispatch of `ns.call` sends for
361/// `e`, as JSON — `{"type":"error","metadata","message","code",
362/// "recoverable"}` plus, for an auth refusal, `error_kind` and (a missing
363/// grant) `grant`, `scope`, `roles`, `held_on`. Public so a transport that
364/// renders dispatch errors itself renders them the same way.
365pub fn error_item(ns: &str, e: &PlexusError) -> serde_json::Value {
366    // POLYGLOT-5: the typed refusal's fields ride in the item itself, and
367    // RETURNS-6's typed `error` beside them.
368    let item = super::types::PlexusStreamItem::from_plexus_error(
369        super::types::StreamMetadata::new(vec![ns.into()], super::context::PlexusContext::hash()),
370        e,
371        false,
372    );
373    serde_json::to_value(&item).unwrap_or(serde_json::Value::Null)
374}
375
376// ============================================================================
377// Schema Types
378// ============================================================================
379
380#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
381pub struct ActivationInfo {
382    pub namespace: String,
383    pub version: String,
384    pub description: String,
385    pub methods: Vec<String>,
386}
387
388// ============================================================================
389// Activation Trait
390// ============================================================================
391
392#[async_trait]
393pub trait Activation: Send + Sync + 'static {
394    type Methods: MethodEnumSchema;
395
396    fn namespace(&self) -> &str;
397    fn version(&self) -> &str;
398    /// Short description (max 15 words)
399    fn description(&self) -> &str { "No description available" }
400    /// Long description (optional, for detailed documentation)
401    fn long_description(&self) -> Option<&str> { None }
402    fn methods(&self) -> Vec<&str>;
403    fn method_help(&self, _method: &str) -> Option<String> { None }
404    /// Stable activation instance ID for handle routing
405    /// By default generates a deterministic UUID from namespace+major_version
406    /// Using major version only ensures handles survive minor/patch upgrades (semver)
407    fn plugin_id(&self) -> uuid::Uuid {
408        let major_version = self.version().split('.').next().unwrap_or("0");
409        uuid::Uuid::new_v5(&uuid::Uuid::NAMESPACE_OID, format!("{}@{}", self.namespace(), major_version).as_bytes())
410    }
411
412    async fn call(
413        &self,
414        method: &str,
415        params: Value,
416        auth: Option<&super::auth::AuthContext>,
417        raw_ctx: Option<&crate::request::RawRequestContext>,
418    ) -> Result<PlexusStream, PlexusError>;
419    async fn resolve_handle(&self, _handle: &Handle) -> Result<PlexusStream, PlexusError> {
420        Err(PlexusError::HandleNotSupported(self.namespace().to_string()))
421    }
422
423    fn into_rpc_methods(self) -> Methods where Self: Sized;
424
425    /// MACRO-20: this activation's static children and theirs, as
426    /// `(path, schema)` — the same list as
427    /// [`ChildRouter::router_static_child_schemas`], reachable from the
428    /// hub's type-erased registry (which holds `Activation`s).
429    ///
430    /// Default empty; `#[plexus_macros::activation]` emits it for an
431    /// activation with static `#[plexus_macros::child]`ren. A
432    /// [`DynamicHub`] indexes each child's methods for its gate
433    /// (`<activation>.<path>.<method>`, the child's own `target`), merges the
434    /// children's `roles(...)` into [`DynamicHub::declared_roles`], and lists
435    /// them in `auth.requires` and the caller's view — every grant qualified
436    /// by the path (see [`super::children`]).
437    fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
438        Vec::new()
439    }
440
441    /// NEST-5: this activation's schema without an instance — what a
442    /// parent's dynamic `#[child]` publishes as its slot's type
443    /// (`MethodRole::DynamicChild { child }`). `None` (the default) for an
444    /// activation the macro did not write; `#[plexus_macros::activation]`
445    /// emits it (its static namespace, version, description, methods and
446    /// roles).
447    fn slot_schema() -> Option<PluginSchema>
448    where
449        Self: Sized,
450    {
451        None
452    }
453
454    /// NEST-16: what this activation calls of the service it is grafted
455    /// onto — its schema's `needs`, answered without building the schema
456    /// (`#[plexus_macros::activation(parent = …)]` emits it). `None`: it
457    /// declares nothing.
458    fn needs(&self) -> Option<Vec<super::schema::Need>> {
459        None
460    }
461
462    /// Return this activation's schema (methods + optional children)
463    fn plugin_schema(&self) -> PluginSchema {
464        // A method of an activation not built with `#[activation]` is known
465        // by its name and help text alone; its hash is that schema's content
466        // hash (RETURNS-10), as a macro-built method's is of its whole schema.
467        let methods: Vec<MethodSchema> = self.methods().iter().map(|name| {
468            let desc = self.method_help(name).unwrap_or_default();
469            MethodSchema::new(name.to_string(), desc, String::new()).with_content_hash()
470        }).collect();
471
472        if let Some(long_desc) = self.long_description() {
473            PluginSchema::leaf_with_long_description(
474                self.namespace(),
475                self.version(),
476                self.description(),
477                long_desc,
478                methods,
479            )
480        } else {
481            PluginSchema::leaf(
482                self.namespace(),
483                self.version(),
484                self.description(),
485                methods,
486            )
487        }
488    }
489}
490
491// ============================================================================
492// Child Routing for Hub Plugins
493// ============================================================================
494
495bitflags! {
496    /// Opt-in capability flags advertising which optional `ChildRouter`
497    /// operations a router supports.
498    ///
499    /// The Plexus RPC network is a *graph*, not a tree: children may be
500    /// remote, infinite, or deliberately private. Listing and searching
501    /// children are therefore opt-in — routers must declare them here
502    /// before callers can rely on them.
503    ///
504    /// # Contract
505    ///
506    /// | Condition | Expected |
507    /// |---|---|
508    /// | `capabilities().contains(LIST)` is `true` | `list_children().await` returns `Some(stream)` |
509    /// | `capabilities().contains(LIST)` is `false` | `list_children().await` returns `None` |
510    /// | `capabilities().contains(SEARCH)` is `true` | `search_children(q).await` returns `Some(stream)` for every `q` |
511    /// | `capabilities().contains(SEARCH)` is `false` | `search_children(q).await` returns `None` for every `q` |
512    ///
513    /// These rules are not runtime-enforced; advertising a capability you
514    /// do not implement is a correctness bug in the router.
515    ///
516    /// # Deprecated (IR-4)
517    ///
518    /// This bitflags type is superseded by the `MethodRole::DynamicChild {
519    /// list_method, search_method }` tag on the corresponding gate method.
520    /// Consumers that want to know whether a child router supports list /
521    /// search operations should inspect the gate method's role instead of
522    /// calling `ChildRouter::capabilities()`. The type stays on the wire for
523    /// the 0.5 transition window and is slated for removal in 0.7.
524    #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)]
525    #[deprecated(
526        since = "0.5",
527        note = "Use MethodRole::DynamicChild { list_method, search_method } instead. Removed in 0.7."
528    )]
529    pub struct ChildCapabilities: u32 {
530        /// The router promises `list_children()` returns `Some(stream)`.
531        const LIST = 0b0000_0001;
532        /// The router promises `search_children(query)` returns
533        /// `Some(stream)` for any query.
534        const SEARCH = 0b0000_0010;
535    }
536}
537
538/// Trait for activations that can route to child activations
539///
540/// Hub activations implement this to support nested method routing.
541/// When a method like "mercury.info" is called on a solar activation,
542/// this trait enables routing to the mercury child.
543///
544/// This trait is separate from Activation to avoid associated type issues
545/// with dynamic dispatch.
546///
547/// # Optional capabilities
548///
549/// In addition to the required `router_namespace` + `get_child` surface,
550/// routers may opt in to advertising enumerable and searchable children
551/// via [`ChildCapabilities`]. When a flag is set, the corresponding
552/// `list_children` / `search_children` method must return `Some(stream)`.
553/// The default implementations report no capabilities and return `None`.
554#[async_trait]
555pub trait ChildRouter: Send + Sync {
556    /// Get the namespace of this router (for error messages)
557    fn router_namespace(&self) -> &str;
558
559    /// Call a method on this router
560    async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError>;
561
562    /// Get a child activation instance by name for nested routing
563    async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>>;
564
565    /// NEST-7: the child or peer named `name`, or why a peer could not be
566    /// returned — what routing asks, so a caller gets a typed error item
567    /// (`not_grafted`, `unavailable`, `shape_mismatch`, …), never "not
568    /// found", for a peer that failed. Default: [`Self::get_child`], which
569    /// cannot fail. `#[plexus_macros::activation]` overrides it for an
570    /// activation with a `#[plexus_macros::peer]` slot.
571    async fn peer_child(&self, name: &str) -> Result<Option<Box<dyn ChildRouter>>, super::peer::PeerError> {
572        Ok(self.get_child(name).await)
573    }
574
575    /// Which optional operations (list / search) this router supports.
576    ///
577    /// Defaults to [`ChildCapabilities::empty()`]: a router that only
578    /// exposes `get_child` for exact-name lookup.
579    #[allow(deprecated)]
580    fn capabilities(&self) -> ChildCapabilities {
581        ChildCapabilities::empty()
582    }
583
584    /// Stream every child name the router is willing to enumerate.
585    ///
586    /// Returns `None` when the router does not support listing — callers
587    /// should check [`ChildRouter::capabilities`] first.
588    ///
589    /// Routers that implement this **must** set
590    /// [`ChildCapabilities::LIST`] in [`ChildRouter::capabilities`].
591    async fn list_children(&self) -> Option<BoxStream<'_, String>> {
592        None
593    }
594
595    /// Stream child names matching the router-defined query semantics.
596    ///
597    /// Returns `None` when the router does not support searching — callers
598    /// should check [`ChildRouter::capabilities`] first.
599    ///
600    /// Routers that implement this **must** set
601    /// [`ChildCapabilities::SEARCH`] in [`ChildRouter::capabilities`].
602    async fn search_children(&self, _query: &str) -> Option<BoxStream<'_, String>> {
603        None
604    }
605
606    // AUTHLANG-3 — three default-implemented methods that the framework's
607    // dispatch path (`route_to_child` below) consults. Existing impls keep
608    // compiling unchanged: they inherit the defaults below. Hub-level impls
609    // (DynamicHub) override them to consult the registry/principal/sink the
610    // hub holds.
611
612    /// Look up the forward policy declared for a callee namespace.
613    ///
614    /// Default: returns `None`, which the framework interprets as
615    /// [`plexus_auth_core::IdentityOnly`] — the safe default per
616    /// `AUTHLANG-S01-output` §5. Macro-emitted impls (AUTHLANG-4) override
617    /// this from the `#[plexus::activation(forward_policy = ...)]`
618    /// attribute; the [`DynamicHub`] override consults its
619    /// [`ForwardPolicyRegistry`](super::forward_registry::ForwardPolicyRegistry).
620    fn forward_policy_for(
621        &self,
622        _callee_ns: &str,
623    ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
624        None
625    }
626
627    /// MACRO-20: this router's own schema, when it has one.
628    ///
629    /// Default `None` (a hand-written router describes nothing). The
630    /// `ChildRouter` impl `#[plexus_macros::activation]` emits answers its
631    /// activation's [`Activation::plugin_schema`], which is how a parent
632    /// describes its static children ([`Self::router_static_child_schemas`]).
633    fn router_schema(&self) -> Option<PluginSchema> {
634        None
635    }
636
637    /// MACRO-20: every static child below this router that describes itself,
638    /// as `(path, schema)` — `path` relative to this router, dotted for a
639    /// grandchild (`"commits"`, `"commits.audit"`), `schema` the child's own
640    /// (its methods' grants and its `roles` relative to it, as its macro
641    /// wrote them).
642    ///
643    /// Default empty. `#[plexus_macros::activation]` emits it for an
644    /// activation with static `#[plexus_macros::child]`ren: each child's
645    /// [`Self::router_schema`], then its own static children under its name.
646    /// A dynamic child (an open name set) is never listed. The hub reads it
647    /// through [`Activation::static_child_schemas`] to gate a child's method
648    /// by its whole path ([`super::children`]).
649    fn router_static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
650        Vec::new()
651    }
652
653    /// Framework-stamped immediate-caller [`plexus_auth_core::Principal`] of
654    /// this router.
655    ///
656    /// Default: [`plexus_auth_core::Principal::Anonymous`]. The dispatch
657    /// path passes this into the [`plexus_auth_core::CallSite`] handed to
658    /// the policy so policies can implement callee-and-caller-aware
659    /// decisions (e.g., "PassThrough only when callee is in `audit.*`").
660    /// Hub-level impls override to return the per-connection stamp.
661    fn framework_stamped_principal(&self) -> plexus_auth_core::Principal {
662        plexus_auth_core::Principal::Anonymous
663    }
664}
665
666/// Route a method call to a child activation
667///
668/// This is called from generated code when a hub activation receives
669/// a method that doesn't match its local methods. If the method
670/// contains a dot (e.g., "mercury.info"), it routes to the child.
671///
672/// # AUTHLANG-3 dispatch sequence
673///
674/// Between callee resolution (`get_child`) and the actual dispatch
675/// (`router_call`), the framework runs the forwarding-policy step pinned
676/// in `plans/AUTHLANG/AUTHLANG-S01-output.md` §3:
677///
678/// 1. Resolve the policy registered for the callee namespace via
679///    [`ChildRouter::forward_policy_for`]; default
680///    [`plexus_auth_core::IdentityOnly`] when none is declared.
681/// 2. Build a [`plexus_auth_core::CallSite`] from the parent router's
682///    framework-stamped principal and the callee's [`MethodPath`].
683/// 3. Invoke [`plexus_auth_core::ForwardPolicy::forward`] to obtain a
684///    [`plexus_auth_core::ForwardDerivation`].
685/// 4. *(deferred — PRIVACY-1)* Emit one `AuditRecord` with
686///    `kind: ForwardPolicyApplied` to the configured `AuditSink`.
687/// 5. Mint the callee `AuthContext` via the framework-only constructor
688///    [`plexus_auth_core::AuthContext::derive_callee_context`].
689/// 6. Dispatch to `child.router_call(...)` with the derived context.
690///
691/// The policy step is invisible to activation authors per AUTHZ-0
692/// principle 1 ("trust is structural, not procedural"). The
693/// [`plexus_auth_core::ForwardPolicy::forward`] surface returns
694/// *parameters*, never a constructed `AuthContext`; the framework is the
695/// only entity that can mint one, per the sealed-type pattern.
696pub async fn route_to_child<T: ChildRouter + ?Sized>(
697    parent: &T,
698    method: &str,
699    params: Value,
700    auth: Option<&super::auth::AuthContext>,
701    raw_ctx: Option<&crate::request::RawRequestContext>,
702) -> Result<PlexusStream, PlexusError> {
703    // Try to split on first dot for nested routing
704    if let Some((child_name, rest)) = method.split_once('.') {
705        // NEST-7: a peer that could not be returned is its typed error item.
706        let found = match parent.peer_child(child_name).await {
707            Ok(found) => found,
708            Err(e) => {
709                return Ok(e.stream(vec![parent.router_namespace().to_string(), child_name.to_string()]));
710            }
711        };
712        if let Some(child) = found {
713            // ── AUTHLANG-3: forwarding-policy dispatch sequence ───────────
714            // Steps 1–3, 5–6 per the pinned spike §3. Step 4 (audit
715            // emission) is deferred until PRIVACY-1 lands `AuditRecord` /
716            // `AuditSink` / `ForwardPolicyApplied`; the TODO below marks
717            // the exact insertion point. See run-notes on the ticket.
718
719            // Step 1: resolve the policy registered for the callee
720            // namespace; default to IdentityOnly per the spike-pinned safe
721            // default (AUTHLANG-S01-output §5).
722            let policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy> = parent
723                .forward_policy_for(child_name)
724                .unwrap_or_else(|| {
725                    std::sync::Arc::new(plexus_auth_core::IdentityOnly)
726                        as std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>
727                });
728
729            // Step 2: build the CallSite. The framework-built path string
730            // is always a valid MethodPath because the caller already
731            // validated the inbound method on its way in; if validation
732            // ever fails here it indicates a framework bug, not a user
733            // input error.
734            let callee_method_str = format!("{}.{}", child_name, rest);
735            let callee_method = plexus_auth_core::MethodPath::try_new(callee_method_str.as_str())
736                .map_err(|e| PlexusError::ExecutionError(format!(
737                    "framework-built MethodPath rejected: {} ({:?})",
738                    callee_method_str, e
739                )))?;
740            let site = plexus_auth_core::CallSite::new(
741                parent.framework_stamped_principal(),
742                callee_method,
743            );
744
745            // Step 3: invoke the policy. When the caller has no
746            // AuthContext (anonymous edge), feed the policy the anonymous
747            // sealed context so the policy contract is honored uniformly.
748            let anonymous_owned;
749            let caller_ctx: &super::auth::AuthContext = match auth {
750                Some(ctx) => ctx,
751                None => {
752                    anonymous_owned = super::auth::AuthContext::anonymous();
753                    &anonymous_owned
754                }
755            };
756            let derivation = policy.forward(caller_ctx, &site);
757
758            // Step 4 (DEFERRED — PRIVACY-1): emit AuditRecord with
759            // kind: ForwardPolicyApplied before dispatch. When PRIVACY-1
760            // lands `AuditRecord`, `AuditSink`, and `ForwardPolicyApplied`
761            // in `plexus_auth_core`, add a `ChildRouter::audit_sink()`
762            // default method (returning a no-op sink) and call:
763            //
764            //     parent.audit_sink().write(
765            //         AuditRecord::for_forward(
766            //             &site.callee_method,
767            //             &site.caller,
768            //             policy.name(),
769            //             derivation,
770            //             auth.and_then(|c| c.verified_user_id()),
771            //         )
772            //     ).await;
773            //
774            // Sink failure must be logged at WARN and NOT propagated
775            // (acceptance-criteria row 4 in AUTHLANG-3 §"Required
776            // behavior"). Until then, log a structured trace event so
777            // operators can confirm the policy step ran:
778            tracing::trace!(
779                target: "plexus::audit",
780                policy = policy.name().as_str(),
781                callee_method = %site.callee_method.as_str(),
782                derivation_keep_verified_user = derivation.keep_verified_user,
783                derivation_keep_roles = derivation.keep_roles,
784                derivation_keep_capabilities = derivation.keep_capabilities,
785                derivation_keep_metadata = derivation.keep_metadata,
786                "forward_policy_applied (audit-record emission stubbed pending PRIVACY-1)"
787            );
788
789            // Step 5+6: framework-blessed derivation of the callee sealed
790            // AuthContext, and dispatch with it. The policy NEVER sees the
791            // constructed value — it returned *parameters*; the framework
792            // consumed them via `with_callee_context`, which scopes the
793            // callee to the dispatch closure (the raw constructor remains
794            // pub(crate) to plexus-auth-core).
795            // RETURNS-47 (owner, 2026-11-04: children receive auth): the
796            // child's call runs in a context of its own, as the policy
797            // derived it — its caller the derived context, its reach the
798            // call's when the policy keeps the caller's identity, nowhere
799            // when not — so `caller()`, `current_reach()` and `required` in a
800            // child answer as the policy says, not as the outer call does.
801            let outer = crate::call::context().ok();
802            let keeps_identity = derivation.keep_verified_user;
803            return match auth {
804                Some(caller_ctx) => {
805                    caller_ctx
806                        .with_callee_context(&derivation, &site.caller, |callee_ctx| async move {
807                            let ctx = outer.map(|o| o.for_child(Some(&callee_ctx), keeps_identity));
808                            in_child(ctx, child.router_call(rest, params, Some(&callee_ctx), raw_ctx)).await
809                        })
810                        .await
811                }
812                None => {
813                    let ctx = outer.map(|o| o.for_child(None, keeps_identity));
814                    in_child(ctx, child.router_call(rest, params, None, raw_ctx)).await
815                }
816            };
817        }
818        return Err(PlexusError::ActivationNotFound(child_name.to_string()));
819    }
820
821    // No dot - method simply not found
822    Err(PlexusError::MethodNotFound {
823        activation: parent.router_namespace().to_string(),
824        method: method.to_string(),
825    })
826}
827
828/// Wrapper to implement ChildRouter for Arc<dyn ChildRouter>
829///
830/// This allows DynamicHub to return its stored Arc<dyn ChildRouter> from get_child()
831struct ArcChildRouter(Arc<dyn ChildRouter>);
832
833#[async_trait]
834impl ChildRouter for ArcChildRouter {
835    fn router_namespace(&self) -> &str {
836        self.0.router_namespace()
837    }
838
839    async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
840        self.0.router_call(method, params, auth, raw_ctx).await
841    }
842
843    async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
844        self.0.get_child(name).await
845    }
846
847    async fn peer_child(&self, name: &str) -> Result<Option<Box<dyn ChildRouter>>, super::peer::PeerError> {
848        self.0.peer_child(name).await
849    }
850
851    #[allow(deprecated)]
852    fn capabilities(&self) -> ChildCapabilities {
853        self.0.capabilities()
854    }
855
856    async fn list_children(&self) -> Option<BoxStream<'_, String>> {
857        self.0.list_children().await
858    }
859
860    async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
861        self.0.search_children(query).await
862    }
863
864    // AUTHLANG-3 — forward the new ChildRouter trait methods through the
865    // Arc wrapper so a `DynamicHub` reached via `get_child` keeps its
866    // overrides (especially `forward_policy_for`).
867    fn forward_policy_for(
868        &self,
869        callee_ns: &str,
870    ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
871        self.0.forward_policy_for(callee_ns)
872    }
873
874    fn framework_stamped_principal(&self) -> plexus_auth_core::Principal {
875        self.0.framework_stamped_principal()
876    }
877
878    fn router_schema(&self) -> Option<PluginSchema> {
879        self.0.router_schema()
880    }
881
882    fn router_static_child_schemas(&self) -> Vec<(String, PluginSchema)> {
883        self.0.router_static_child_schemas()
884    }
885}
886
887// ============================================================================
888// Internal Type-Erased Activation
889// ============================================================================
890
891#[async_trait]
892#[allow(dead_code)] // Methods exist for completeness but some aren't called post-erasure yet
893pub(crate) trait ActivationObject: Send + Sync + 'static {
894    fn namespace(&self) -> &str;
895    fn version(&self) -> &str;
896    fn description(&self) -> &str;
897    fn long_description(&self) -> Option<&str>;
898    fn methods(&self) -> Vec<&str>;
899    fn method_help(&self, method: &str) -> Option<String>;
900    fn plugin_id(&self) -> uuid::Uuid;
901    async fn call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError>;
902    async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError>;
903    fn plugin_schema(&self) -> PluginSchema;
904    fn static_child_schemas(&self) -> Vec<(String, PluginSchema)>;
905    fn schema(&self) -> Schema;
906    /// NEST-16: [`Activation::needs`].
907    fn needs(&self) -> Option<Vec<super::schema::Need>> {
908        None
909    }
910}
911
912struct ActivationWrapper<A: Activation> {
913    inner: A,
914}
915
916#[async_trait]
917impl<A: Activation> ActivationObject for ActivationWrapper<A> {
918    fn namespace(&self) -> &str { self.inner.namespace() }
919    fn version(&self) -> &str { self.inner.version() }
920    fn description(&self) -> &str { self.inner.description() }
921    fn long_description(&self) -> Option<&str> { self.inner.long_description() }
922    fn methods(&self) -> Vec<&str> { self.inner.methods() }
923    fn method_help(&self, method: &str) -> Option<String> { self.inner.method_help(method) }
924    fn plugin_id(&self) -> uuid::Uuid { self.inner.plugin_id() }
925
926    async fn call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
927        self.inner.call(method, params, auth, raw_ctx).await
928    }
929
930    async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
931        self.inner.resolve_handle(handle).await
932    }
933
934    fn plugin_schema(&self) -> PluginSchema { self.inner.plugin_schema() }
935
936    fn static_child_schemas(&self) -> Vec<(String, PluginSchema)> { self.inner.static_child_schemas() }
937
938    fn needs(&self) -> Option<Vec<super::schema::Need>> { self.inner.needs() }
939
940    fn schema(&self) -> Schema {
941        let schema = schemars::schema_for!(A::Methods);
942        serde_json::from_value(serde_json::to_value(schema).expect("serialize"))
943            .expect("parse schema")
944    }
945}
946
947// ============================================================================
948// Plexus Event Types
949// ============================================================================
950
951#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
952#[serde(tag = "event", rename_all = "snake_case")]
953pub enum HashEvent {
954    Hash { value: String },
955}
956
957/// Event for schema() RPC method - returns plugin schema
958#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
959#[serde(tag = "event", rename_all = "snake_case")]
960pub enum SchemaEvent {
961    /// This plugin's schema
962    Schema(PluginSchema),
963}
964
965/// Lightweight hash information for cache validation
966#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
967pub struct PluginHashes {
968    pub namespace: String,
969    pub self_hash: String,
970    #[serde(skip_serializing_if = "Option::is_none")]
971    pub children_hash: Option<String>,
972    pub hash: String,
973    /// Child plugin hashes (for recursive checking)
974    #[serde(skip_serializing_if = "Option::is_none")]
975    pub children: Option<Vec<ChildHashes>>,
976}
977
978/// Hash information for a child plugin
979#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
980pub struct ChildHashes {
981    pub namespace: String,
982    pub hash: String,
983}
984
985
986// ============================================================================
987// Activation Registry
988// ============================================================================
989
990/// Entry in the activation registry
991#[derive(Debug, Clone)]
992pub struct PluginEntry {
993    /// Stable activation instance ID
994    pub id: uuid::Uuid,
995    /// Current path/namespace for this activation
996    pub path: String,
997    /// Activation type (e.g., "cone", "bash", "arbor")
998    pub plugin_type: String,
999}
1000
1001/// Registry mapping activation UUIDs to their current paths
1002///
1003/// This enables handle routing without path dependency - handles reference
1004/// activations by their stable UUID, and the registry maps to the current path.
1005#[derive(Default)]
1006pub struct PluginRegistry {
1007    /// Lookup by plugin UUID
1008    by_id: HashMap<uuid::Uuid, PluginEntry>,
1009    /// Lookup by current path (for reverse lookup)
1010    by_path: HashMap<String, uuid::Uuid>,
1011}
1012
1013/// Read-only snapshot of the activation registry
1014///
1015/// Safe to use outside of DynamicHub locks.
1016#[derive(Clone)]
1017pub struct PluginRegistrySnapshot {
1018    by_id: HashMap<uuid::Uuid, PluginEntry>,
1019    by_path: HashMap<String, uuid::Uuid>,
1020}
1021
1022impl PluginRegistrySnapshot {
1023    /// Look up an activation's path by its UUID
1024    pub fn lookup(&self, id: uuid::Uuid) -> Option<&str> {
1025        self.by_id.get(&id).map(|e| e.path.as_str())
1026    }
1027
1028    /// Look up an activation's UUID by its path
1029    pub fn lookup_by_path(&self, path: &str) -> Option<uuid::Uuid> {
1030        self.by_path.get(path).copied()
1031    }
1032
1033    /// Get an activation entry by its UUID
1034    pub fn get(&self, id: uuid::Uuid) -> Option<&PluginEntry> {
1035        self.by_id.get(&id)
1036    }
1037
1038    /// List all registered activations
1039    pub fn list(&self) -> impl Iterator<Item = &PluginEntry> {
1040        self.by_id.values()
1041    }
1042
1043    /// Get the number of registered plugins
1044    pub fn len(&self) -> usize {
1045        self.by_id.len()
1046    }
1047
1048    /// Check if the registry is empty
1049    pub fn is_empty(&self) -> bool {
1050        self.by_id.is_empty()
1051    }
1052}
1053
1054impl PluginRegistry {
1055    /// Create a new empty registry
1056    pub fn new() -> Self {
1057        Self::default()
1058    }
1059
1060    /// Look up an activation's path by its UUID
1061    pub fn lookup(&self, id: uuid::Uuid) -> Option<&str> {
1062        self.by_id.get(&id).map(|e| e.path.as_str())
1063    }
1064
1065    /// Look up an activation's UUID by its path
1066    pub fn lookup_by_path(&self, path: &str) -> Option<uuid::Uuid> {
1067        self.by_path.get(path).copied()
1068    }
1069
1070    /// Get an activation entry by its UUID
1071    pub fn get(&self, id: uuid::Uuid) -> Option<&PluginEntry> {
1072        self.by_id.get(&id)
1073    }
1074
1075    /// Register an activation
1076    pub fn register(&mut self, id: uuid::Uuid, path: String, plugin_type: String) {
1077        let entry = PluginEntry { id, path: path.clone(), plugin_type };
1078        self.by_id.insert(id, entry);
1079        self.by_path.insert(path, id);
1080    }
1081
1082    /// NEST-15: forget the activation `id` (an entry the service no longer
1083    /// serves).
1084    pub(crate) fn remove(&mut self, id: uuid::Uuid) {
1085        if let Some(entry) = self.by_id.remove(&id) {
1086            if self.by_path.get(&entry.path) == Some(&id) {
1087                self.by_path.remove(&entry.path);
1088            }
1089        }
1090    }
1091
1092    /// List all registered activations
1093    pub fn list(&self) -> impl Iterator<Item = &PluginEntry> {
1094        self.by_id.values()
1095    }
1096
1097    /// Get the number of registered plugins
1098    pub fn len(&self) -> usize {
1099        self.by_id.len()
1100    }
1101
1102    /// Check if the registry is empty
1103    pub fn is_empty(&self) -> bool {
1104        self.by_id.is_empty()
1105    }
1106}
1107
1108// ============================================================================
1109// DynamicHub (formerly Plexus)
1110// ============================================================================
1111
1112/// Build the JSON payload for the `_info` well-known endpoint.
1113///
1114/// The shape is `{"backend": "<ns>", "auth_capabilities": {…}}` per
1115/// AUTHZ-S01-output §2 / AUTHZ-CORE-3. When the backend has not declared its
1116/// capabilities via [`DynamicHub::with_auth_capabilities`], the field falls
1117/// back to [`plexus_auth_core::BackendAuthCapabilities::anonymous_default`]
1118/// (a single `Anonymous` mechanism). The `_info` endpoint itself remains
1119/// public — no authentication is required to read it.
1120fn build_info_payload(
1121    namespace: &str,
1122    caps: Option<&plexus_auth_core::BackendAuthCapabilities>,
1123) -> serde_json::Value {
1124    let advertised = match caps {
1125        Some(c) => c.clone(),
1126        None => plexus_auth_core::BackendAuthCapabilities::anonymous_default(),
1127    };
1128    serde_json::json!({
1129        "backend": namespace,
1130        "auth_capabilities": advertised,
1131    })
1132}
1133
1134/// CA-1 (trak facet `ccc924ad-0e78-4d4b-b71f-0018d249d0bf`): map a schema
1135/// response stream so every `requires_credential` lacking a `site_hint`
1136/// gets the hub-derived attach site.
1137///
1138/// Only `Data` items whose `content_type` is a schema payload
1139/// (`*.schema` / `*.method_schema`) are touched; their `content` is decoded
1140/// as a [`super::SchemaResult`], hint-filled, and re-encoded. Items that do
1141/// not decode (defensive: a custom activation emitting a non-standard
1142/// payload under a schema content type) pass through unchanged, as do all
1143/// non-`Data` items.
1144fn fill_site_hints_in_schema_stream(
1145    stream: PlexusStream,
1146    site: plexus_auth_core::AttachmentSite,
1147) -> PlexusStream {
1148    use futures::StreamExt;
1149    Box::pin(stream.map(move |item| match item {
1150        super::types::PlexusStreamItem::Data {
1151            metadata,
1152            content_type,
1153            content,
1154        } if content_type.ends_with(".schema") || content_type.ends_with(".method_schema") => {
1155            // PERF-7: an encoded content is decoded straight from its bytes.
1156            let content = match content.decode::<super::SchemaResult>() {
1157                Ok(mut result) => {
1158                    result.fill_site_hints(&site);
1159                    match serde_json::to_value(&result) {
1160                        Ok(v) => v.into(),
1161                        Err(_) => content,
1162                    }
1163                }
1164                Err(_) => content,
1165            };
1166            super::types::PlexusStreamItem::Data {
1167                metadata,
1168                content_type,
1169                content,
1170            }
1171        }
1172        other => other,
1173    }))
1174}
1175
1176pub(crate) struct DynamicHubInner {
1177    /// Custom namespace for this hub instance (defaults to "plexus")
1178    namespace: String,
1179    /// NEST-15: the service root — its table of peers, by name: each
1180    /// registered activation, each mounted child, each peer served while the
1181    /// service serves ([`DynamicHub::root`]). Read as a snapshot (an `Arc`),
1182    /// changed by swapping one in. PERF-21: ordered, so every list of them —
1183    /// the service schema's `children` ([`DynamicHub::plugin_children`]),
1184    /// what the self-description cache keeps, the static children, the
1185    /// declared roles — is in name order: a function of what the service
1186    /// serves, the same at every start.
1187    root: std::sync::RwLock<Arc<super::service_root::Table>>,
1188    /// NEST-15: told the service's hash each time the root's table changes.
1189    root_watch: tokio::sync::watch::Sender<String>,
1190    /// Activation registry mapping UUIDs to paths
1191    registry: std::sync::RwLock<PluginRegistry>,
1192    pending_rpc: std::sync::Mutex<Vec<Box<dyn FnOnce() -> Methods + Send>>>,
1193    /// What this backend advertises at `_info`'s `auth_capabilities` field.
1194    ///
1195    /// `None` means the backend has not called
1196    /// [`DynamicHub::with_auth_capabilities`]; `_info` falls back to
1197    /// [`plexus_auth_core::BackendAuthCapabilities::anonymous_default`]
1198    /// (a single `Anonymous` mechanism, no default). This preserves today's
1199    /// no-auth substrate behavior while signaling "no auth wired" to
1200    /// capability-aware clients.
1201    ///
1202    /// Per AUTHZ-CORE-3 and AUTHZ-S01-output §2.
1203    auth_capabilities: Option<plexus_auth_core::BackendAuthCapabilities>,
1204    /// AUTHLANG-3 — per-hub mapping from callee namespace to the
1205    /// [`plexus_auth_core::ForwardPolicy`] consulted at every
1206    /// cross-boundary call routed through this hub. Populated declaratively
1207    /// (by the AUTHLANG-4 macro emission) or imperatively (via
1208    /// [`DynamicHub::with_forward_policy`]). When the registry has no entry
1209    /// for a callee namespace, the framework falls back to
1210    /// [`plexus_auth_core::IdentityOnly`] per the spike-pinned safe
1211    /// default. See `plans/AUTHLANG/AUTHLANG-S01-output.md` §3.
1212    forward_policies: super::forward_registry::ForwardPolicyRegistry,
1213    /// R-5 (AUTHZ-CORE-4 acceptance 8) — the deployment's role→scope
1214    /// taxonomy, consulted by the scope gate at every dispatch through
1215    /// [`DynamicHub::route_with_ctx`]. `None` means no registry is
1216    /// configured: with `default_deny` also off (the default), dispatch
1217    /// behaves byte-for-byte as before the gate existed.
1218    scope_registry: Option<Arc<plexus_auth_core::ScopeRegistry>>,
1219    /// R-5 (AUTHZ-CORE-1) — the default-deny posture. **Ships OFF.**
1220    ///
1221    /// Whether / when each backend flips this ON is an open human decision
1222    /// (R-S01 open question 4); see [`super::scope_gate`] module docs for
1223    /// the full decision table and the deviation note (runtime builder
1224    /// option here vs CORE-1's Cargo feature flag).
1225    default_deny: bool,
1226    /// Where the scope gate writes its `ScopeCheck` [`AuditRecord`]s
1227    /// (AUTHZ-CORE-5). Defaults to [`plexus_auth_core::TracingAuditSink`];
1228    /// override via [`DynamicHub::with_audit_sink`].
1229    ///
1230    /// [`AuditRecord`]: plexus_auth_core::AuditRecord
1231    audit_sink: Arc<dyn plexus_auth_core::AuditSink>,
1232    /// BIDIR-6: see [`DynamicHub::duplex_gate`].
1233    duplex_gate: std::sync::OnceLock<super::duplex_gate::DuplexGate>,
1234    /// Lazily-built index from full dotted method path
1235    /// (`<activation>.<method>`, hub-own methods under
1236    /// `<hub-ns>.<method>`) to the gate-relevant schema facts. Built on the
1237    /// first gated dispatch so the gate never re-walks plugin schemas on the
1238    /// hot path, and NEST-15: dropped when the root's table changes (an
1239    /// entry added or removed while the service serves), built again at the
1240    /// next dispatch.
1241    /// NEST-5: and the service's slots, so a literal path through a
1242    /// dynamic child (`solar.earth.info`) finds its slot's entry
1243    /// (`solar.{planet}.info`).
1244    gate_index: std::sync::RwLock<Option<Arc<GateIndex>>>,
1245    /// BIDIR-6: every method path the service knows, and whether it takes an
1246    /// `Input` (see [`DynamicHub::may_take_input`]). Built once, on the first
1247    /// call (NEST-15: and again after the root's table changes).
1248    input_index: std::sync::RwLock<Option<Arc<HashMap<String, bool>>>>,
1249    /// AUTH-2 — the grant gate: when set, every call is decided by it
1250    /// before routing (default deny). `None` (the default): dispatch exactly
1251    /// as before it existed. See [`super::grant_gate`].
1252    gate: Option<Arc<plexus_auth_core::grants::Gate>>,
1253    /// AUTH-4/AUTH-5: grants every signed-in caller reaches whatever its
1254    /// roles or ceiling (the auth activation's `whoami`, `logout`,
1255    /// `requires`). Empty unless [`DynamicHub::with_auth`] mounted it.
1256    signed_in_grants: std::collections::BTreeSet<String>,
1257    /// AUTH-4: the RFC 9728 metadata URL an anonymous `_info` names
1258    /// (`auth.resource_metadata`). See [`DynamicHub::with_resource_metadata`].
1259    resource_metadata: Option<String>,
1260    /// AUTH-5: what each method requires — grant, target, public — kept
1261    /// for `auth.requires`; present only when the auth activation is
1262    /// mounted, and fed by every [`DynamicHub::register`].
1263    auth_catalog: Option<super::auth_activation::Catalog>,
1264    /// PERF-15: the self-description cache — what the service's schemas
1265    /// show, and each caller's view of them — that `_info`, `hash`, `hashes`
1266    /// and every `<ns>.schema` answer from. See [`super::view`].
1267    describe: super::view::Cache,
1268    /// RETURNS-40: the `ir` answers kept, by the hash the caller sees and
1269    /// the namespaces asked. See [`DynamicHub::service_ir`].
1270    ir_cache: super::ir::IrCache,
1271    /// NEST-16: what children said through `host.notify`, to whoever in the
1272    /// service listens ([`DynamicHub::notices`]).
1273    notices: tokio::sync::broadcast::Sender<super::parent::Notice>,
1274    /// NEST-21: the service's configuration, made at its first use.
1275    config: std::sync::OnceLock<super::config::Config>,
1276}
1277
1278/// NEST-5: the gate's index — every method path to its gate facts, and the
1279/// service's slots, through which a literal path finds its slot's entry.
1280#[derive(Debug, Default)]
1281pub(crate) struct GateIndex {
1282    methods: HashMap<String, super::scope_gate::MethodGateInfo>,
1283    slots: super::slots::Slots,
1284}
1285
1286impl GateIndex {
1287    /// NEST-5: the gate's facts for `method` — its own entry, else its
1288    /// slot's (`solar.earth.info` → `solar.{planet}.info`).
1289    fn info(&self, method: &str) -> Option<&super::scope_gate::MethodGateInfo> {
1290        self.methods.get(method).or_else(|| self.slots.resolve(method).and_then(|k| self.methods.get(&k)))
1291    }
1292}
1293
1294
1295/// DynamicHub - an activation that routes to dynamically registered child activations
1296///
1297/// Unlike hub activations with hardcoded children (like Solar),
1298/// DynamicHub allows registering activations at runtime via `.register()`.
1299///
1300/// # Direct Hosting
1301///
1302/// For a single activation, host it directly:
1303/// ```ignore
1304/// let solar = Arc::new(Solar::new());
1305/// TransportServer::builder(solar, converter).serve().await?;
1306/// ```
1307///
1308/// # Composition
1309///
1310/// For multiple top-level activations, use DynamicHub:
1311/// ```ignore
1312/// let hub = DynamicHub::with_namespace("myapp")
1313///     .register(Solar::new())
1314///     .register(EchoActivation::new());
1315/// ```
1316#[derive(Clone)]
1317pub struct DynamicHub {
1318    inner: Arc<DynamicHubInner>,
1319}
1320
1321/// RETURNS-40: one snapshot of what a caller is shown, an IR is built from.
1322struct IrView {
1323    base: Arc<super::view::Described>,
1324    /// The caller's view under the grant gate; `None`: the whole service.
1325    shaped: Option<Arc<super::view::Shaped>>,
1326    /// The view's hash (the service's own without a gate).
1327    hash: String,
1328}
1329
1330impl IrView {
1331    fn root(&self) -> PluginSchema {
1332        match &self.shaped {
1333            Some(v) => v.service.clone(),
1334            None => self.base.service.clone(),
1335        }
1336    }
1337
1338    fn top(&self, ns: &str) -> Option<PluginSchema> {
1339        match &self.shaped {
1340            Some(v) => v.schema_of(&self.base, ns).filter(|_| ns != v.service.namespace),
1341            None => self.base.activations.iter().find(|a| a.namespace == ns).cloned(),
1342        }
1343    }
1344
1345    fn shows(&self, ns: &str) -> bool {
1346        match &self.shaped {
1347            Some(v) => v.shows(ns),
1348            None => self.base.activations.iter().any(|a| a.namespace == ns),
1349        }
1350    }
1351
1352    /// Every namespace the snapshot shows, dotted (`""`: the service's own):
1353    /// the root, each activation shown, and each static child below one —
1354    /// in a gated view, when the entry that reaches it is shown.
1355    fn names(&self, service: &str) -> Vec<String> {
1356        let mut out = vec![String::new()];
1357        out.extend(self.base.activations.iter().map(|a| a.namespace.clone()).filter(|ns| ns != service && self.shows(ns)));
1358        for path in self.base.nested() {
1359            let mut segs = path.split('.');
1360            let (Some(top), Some(entry)) = (segs.next(), segs.next()) else { continue };
1361            let reached = self.shows(top)
1362                && match &self.shaped {
1363                    Some(v) => v.method_of(&self.base, top, entry).is_some(),
1364                    None => true,
1365                };
1366            if reached {
1367                out.push(path.to_string());
1368            }
1369        }
1370        out
1371    }
1372}
1373
1374// ============================================================================
1375// DynamicHub Infrastructure (non-RPC methods)
1376// ============================================================================
1377
1378impl DynamicHub {
1379    /// NEST-11: the service a [`super::service_scope::WeakService`] upgrades to.
1380    pub(crate) fn from_inner(inner: Arc<DynamicHubInner>) -> Self {
1381        Self { inner }
1382    }
1383
1384    /// Create a new DynamicHub with explicit namespace
1385    ///
1386    /// Unlike single activations which have fixed namespaces, DynamicHub is a
1387    /// composition tool that can be named based on your application. Common choices:
1388    /// - "hub" - generic default
1389    /// - "substrate" - for substrate server
1390    /// - "myapp" - for your application name
1391    ///
1392    /// The namespace appears in method calls: `{namespace}.call`, `{namespace}.schema`
1393    ///
1394    /// # The root name is a routing namespace, not a label
1395    ///
1396    /// Routing resolves the hub root namespace **before** registered
1397    /// activations, so the root name must differ from the namespace of every
1398    /// activation you later [`register`](Self::register). A hub root that
1399    /// shares its name with a child (`DynamicHub::new("echo").register(Echo)`
1400    /// where `Echo`'s namespace is also `"echo"`) makes every method on that
1401    /// child unreachable: `echo.<method>` resolves to the hub root and fails
1402    /// with `Command not found`, and navigators resolve the like-named child
1403    /// back to the root schema. This is silent at construction and fatal at
1404    /// call time, so [`register`](Self::register) rejects the collision with
1405    /// a panic. Pick a distinct root name (e.g. `"echo_hub"`).
1406    ///
1407    /// Z2H-8 / HOSTLESS-3 — register-time detection of the root/activation
1408    /// namespace shadow.
1409    pub fn new(namespace: impl Into<String>) -> Self {
1410        Self {
1411            inner: Arc::new(DynamicHubInner {
1412                namespace: namespace.into(),
1413                root: Default::default(),
1414                root_watch: tokio::sync::watch::Sender::new(String::new()),
1415                registry: std::sync::RwLock::new(PluginRegistry::new()),
1416                pending_rpc: std::sync::Mutex::new(Vec::new()),
1417                auth_capabilities: None,
1418                forward_policies: super::forward_registry::ForwardPolicyRegistry::new(),
1419                scope_registry: None,
1420                default_deny: false,
1421                audit_sink: Arc::new(plexus_auth_core::TracingAuditSink),
1422                duplex_gate: std::sync::OnceLock::new(),
1423                gate_index: Default::default(),
1424                input_index: Default::default(),
1425                gate: None,
1426                signed_in_grants: std::collections::BTreeSet::new(),
1427                resource_metadata: None,
1428                auth_catalog: None,
1429                describe: Default::default(),
1430                ir_cache: Default::default(),
1431                notices: tokio::sync::broadcast::Sender::new(64),
1432                config: std::sync::OnceLock::new(),
1433            }),
1434        }
1435    }
1436
1437    /// The service's state while it is built — every builder's way in;
1438    /// panics with `refused` once the service is shared. PERF-15: a change
1439    /// made here may change what the service describes, so the
1440    /// self-description cache starts over.
1441    fn inner_mut(&mut self, refused: &str) -> &mut DynamicHubInner {
1442        let inner = Arc::get_mut(&mut self.inner).expect(refused);
1443        inner.describe.reset();
1444        *inner.gate_index.get_mut().unwrap_or_else(|p| p.into_inner()) = None;
1445        *inner.input_index.get_mut().unwrap_or_else(|p| p.into_inner()) = None;
1446        inner
1447    }
1448
1449
1450    /// Configure the deployment's [`ScopeRegistry`] — the scope gate's
1451    /// source of truth for role→scope expansion, public-method
1452    /// declarations, and per-method scope overlays (R-5 / AUTHZ-CORE-4
1453    /// acceptance 8).
1454    ///
1455    /// Once a registry is configured, every dispatch through this hub
1456    /// consults the gate: methods whose [`MethodSchema`] carries
1457    /// `requires_credential` scopes (or that have a registry overlay) are
1458    /// enforced; `public` methods bypass; methods with no declared
1459    /// requirement pass through unchanged unless
1460    /// [`DynamicHub::with_default_deny`] is also set.
1461    ///
1462    /// A hub that never calls this (and never sets `default_deny`)
1463    /// dispatches byte-for-byte as before the gate existed.
1464    ///
1465    /// See [`super::scope_gate`] for the full decision table.
1466    ///
1467    /// [`ScopeRegistry`]: plexus_auth_core::ScopeRegistry
1468    /// [`MethodSchema`]: super::schema::MethodSchema
1469    pub fn with_scope_registry(mut self, registry: plexus_auth_core::ScopeRegistry) -> Self {
1470        let inner = self.inner_mut("Cannot set scope_registry: DynamicHub has multiple references");
1471        inner.scope_registry = Some(Arc::new(registry));
1472        self
1473    }
1474
1475    /// Set the default-deny posture (R-5 / AUTHZ-CORE-1). **Ships OFF.**
1476    ///
1477    /// With it ON, methods with NO declared requirement are enforced
1478    /// against the implicit full-path scope
1479    /// ([`ScopeRegistry::required_scopes_for`]'s implicit rule) — fail
1480    /// closed, including when no registry is configured at all. With it
1481    /// OFF (the default), such methods behave exactly as today.
1482    ///
1483    /// **Open human decision (R-S01 Q4):** whether / when each backend
1484    /// flips this ON (inside the ROLES wave's completion gate vs left to
1485    /// backend epics à la AUTHZ-FLOWS-4) is unresolved. Until that call is
1486    /// made, no backend should enable it in production.
1487    ///
1488    /// Deviation from AUTHZ-CORE-1: this is a runtime builder option, not
1489    /// the Cargo feature flag CORE-1 pinned — see [`super::scope_gate`]
1490    /// module docs for the rationale.
1491    ///
1492    /// [`ScopeRegistry::required_scopes_for`]: plexus_auth_core::ScopeRegistry::required_scopes_for
1493    pub fn with_default_deny(mut self, default_deny: bool) -> Self {
1494        let inner = self.inner_mut("Cannot set default_deny: DynamicHub has multiple references");
1495        inner.default_deny = default_deny;
1496        self
1497    }
1498
1499    /// Override where the scope gate writes its `ScopeCheck`
1500    /// [`AuditRecord`]s (AUTHZ-CORE-5). Default:
1501    /// [`plexus_auth_core::TracingAuditSink`] (`tracing::info!` events on
1502    /// the `plexus::audit` target).
1503    ///
1504    /// The gate awaits the sink's write BEFORE the dispatch responds
1505    /// ("audit before respond", AUTHZ-S01-output §8). Sink implementors
1506    /// are responsible for low-latency writes.
1507    ///
1508    /// [`AuditRecord`]: plexus_auth_core::AuditRecord
1509    pub fn with_audit_sink(mut self, sink: Arc<dyn plexus_auth_core::AuditSink>) -> Self {
1510        let inner = self.inner_mut("Cannot set audit_sink: DynamicHub has multiple references");
1511        inner.audit_sink = sink;
1512        self
1513    }
1514
1515    /// AUTH-2: put every call through `gate` before routing — default deny.
1516    ///
1517    /// With a gate, a call runs only if the caller holds the method's grant
1518    /// (`MethodSchema.grant`, else `<activation>.<method>`) through a role
1519    /// on the scope its target param resolves to — or anywhere, for a method
1520    /// without a target — within the session's ceiling. `public` methods run
1521    /// for anyone; an anonymous caller reaches nothing else
1522    /// ([`PlexusError::Unauthenticated`]); a refusal is
1523    /// [`AuthzDenyReason::MissingGrant`], rendered on the wire as an error
1524    /// item with `error_kind: "forbidden"`, `grant`, `scope`, `roles`,
1525    /// `held_on`. The routed call runs with the gate's [`Reach`] as
1526    /// [`super::grant_gate::current_reach`], which `#[plexus_macros::method]`
1527    /// hands a method declaring `reach: Reach`.
1528    ///
1529    /// A gated hub also stops merging its activations' direct JSON-RPC
1530    /// methods (`<activation>.<method>` registered beside `<hub>.call`):
1531    /// they carry no auth and would pass around the gate. Every call goes
1532    /// through `<hub>.call`.
1533    ///
1534    /// A hub that never calls this dispatches exactly as before. R-5's
1535    /// [`DynamicHub::with_scope_registry`] / [`DynamicHub::with_default_deny`]
1536    /// still apply after it when configured.
1537    ///
1538    /// [`Reach`]: plexus_auth_core::grants::Reach
1539    pub fn with_gate(mut self, gate: Arc<plexus_auth_core::grants::Gate>) -> Self {
1540        let inner = self.inner_mut("Cannot set gate: DynamicHub has multiple references");
1541        inner.gate = Some(gate);
1542        self
1543    }
1544
1545    /// AUTH-2: the configured gate, if any.
1546    pub fn gate(&self) -> Option<&Arc<plexus_auth_core::grants::Gate>> {
1547        self.inner.gate.as_ref()
1548    }
1549
1550    /// AUTH-4: the RFC 9728 protected-resource metadata URL
1551    /// (`…/.well-known/oauth-protected-resource`, AUTH-6) an anonymous
1552    /// caller's `_info` names as `auth.resource_metadata`. Only a gated hub
1553    /// says it; without a gate `_info` is unchanged.
1554    pub fn with_resource_metadata(mut self, url: impl Into<String>) -> Self {
1555        let inner = self.inner_mut("Cannot set resource_metadata: DynamicHub has multiple references");
1556        inner.resource_metadata = Some(url.into());
1557        self
1558    }
1559
1560    /// AUTH-4/AUTH-5: grants every signed-in caller reaches whatever its
1561    /// roles or ceiling — admitted by the gate like a `public` method, but
1562    /// only with a principal, and shown in every caller's view.
1563    /// [`DynamicHub::with_auth`] sets the auth activation's `whoami`,
1564    /// `logout` and `requires`; a hub calls this only for a method of its
1565    /// own of the same kind.
1566    pub fn with_signed_in_grants<I, S>(mut self, grants: I) -> Self
1567    where
1568        I: IntoIterator<Item = S>,
1569        S: Into<String>,
1570    {
1571        let inner = self.inner_mut("Cannot set signed_in grants: DynamicHub has multiple references");
1572        inner.signed_in_grants.extend(grants.into_iter().map(Into::into));
1573        self
1574    }
1575
1576    /// AUTH-5: mount the `auth` activation ([`super::auth_activation::AuthActivation`])
1577    /// and put every call through a gate built from the same stores — the
1578    /// one way a service turns login on. `setup` carries what only the
1579    /// service knows: its [`AuthBackend`] (providers, login flows, sessions,
1580    /// signup's waiting list), its editable [`RoleStore`] and
1581    /// [`MembershipStore`], and its scope [`Resolve`]r.
1582    ///
1583    /// Call it **after** registering the service's own activations or
1584    /// before — either way `auth.requires` knows every method (later
1585    /// registrations are added as they come). It replaces a gate set by
1586    /// [`DynamicHub::with_gate`].
1587    ///
1588    /// [`AuthBackend`]: super::auth_activation::AuthBackend
1589    /// [`RoleStore`]: super::auth_activation::RoleStore
1590    /// [`MembershipStore`]: super::auth_activation::MembershipStore
1591    /// [`Resolve`]: plexus_auth_core::grants::Resolve
1592    pub fn with_auth(mut self, setup: super::auth_activation::AuthSetup) -> Self {
1593        let catalog = super::auth_activation::Catalog::default();
1594        catalog.add(&Activation::plugin_schema(&self));
1595        for e in self.table().entries.values() {
1596            catalog.add(&e.object.plugin_schema());
1597        }
1598        // MACRO-20: a static child's methods, by their whole path; NEST-5:
1599        // a typed slot's, by the slot's (`solar.{planet}.info`), and an
1600        // untyped slot whole (`solar.{planet}`).
1601        for child in self.described_children() {
1602            catalog.add(&child);
1603        }
1604        let (_, untyped) = self.slot_children();
1605        catalog.add_slots(&untyped);
1606        let (auth, gate) = super::auth_activation::AuthActivation::mount(setup, catalog.clone());
1607        {
1608            let inner = self.inner_mut("Cannot mount auth: DynamicHub has multiple references");
1609            inner.auth_catalog = Some(catalog);
1610            inner.gate = Some(Arc::new(gate));
1611        }
1612        self.register(auth)
1613            .with_signed_in_grants(super::auth_activation::SIGNED_IN_GRANTS.iter().copied())
1614    }
1615
1616    /// AUTH-4: the hub as `caller` may see it — what `_info`, the hub's
1617    /// `schema` / `hash` / `hashes` and every `<ns>.schema` answer that
1618    /// caller on a gated hub. Anonymous: the `public` methods only (the
1619    /// auth activation's door). Signed in: each method whose grant a role
1620    /// the caller holds lists (within its ceiling), with `held_on`; the
1621    /// public methods; the signed-in methods (`auth.whoami`, …). Methods
1622    /// the caller cannot use are absent; activations left with none are
1623    /// absent. The hub's own methods are in every view.
1624    ///
1625    /// Without a gate: the whole hub, as every caller sees it today
1626    /// ([`ViewKind::Caller`](super::ViewKind::Caller), the hub's own hash).
1627    /// See [`super::view`].
1628    ///
1629    /// PERF-15: answered from the service's self-description cache — built
1630    /// once per schema generation and, for a gated service, once per view
1631    /// key (the caller's grants' fingerprint, or anonymous) and grants
1632    /// generation.
1633    pub fn view(&self, caller: Option<&super::auth::AuthContext>) -> super::view::View {
1634        match self.inner.gate.as_ref() {
1635            None => self.described().whole(),
1636            Some(_) => {
1637                let (base, view) = self.shaped(caller);
1638                view.view(&base)
1639            }
1640        }
1641    }
1642
1643    /// PERF-15: something this service describes changed after it was built
1644    /// — a child mounted or gone while it serves, an activation whose schema
1645    /// changed: what the self-description cache kept is dropped, and the
1646    /// next `_info`, `hash` or `schema` builds it again. Registering, and
1647    /// every other change while the service is built, does this by itself.
1648    pub fn schema_moved(&self) {
1649        self.inner.describe.schema_moved();
1650    }
1651
1652    /// PERF-15: what the service's schemas show whoever asks — its own,
1653    /// every activation's, every static child's — kept per schema
1654    /// generation.
1655    fn described(&self) -> Arc<super::view::Described> {
1656        let at = self.inner.describe.schema_generation();
1657        match self.inner.describe.base(at) {
1658            Some(cell) => cell.get_or_init(|| Arc::new(self.describe_now())).clone(),
1659            None => Arc::new(self.describe_now()),
1660        }
1661    }
1662
1663    fn describe_now(&self) -> super::view::Described {
1664        let service = Activation::plugin_schema(self);
1665        let activations: Vec<PluginSchema> = self.table().entries.values().map(|e| e.object.plugin_schema()).collect();
1666        // MACRO-20: a static child's entry stays in its parent's view when
1667        // the caller can use something below it.
1668        // NEST-5: and a slot's (`solar.planet`) when something in the slot.
1669        super::view::Described::new(service, activations, self.described_children())
1670    }
1671
1672    /// PERF-15: a gated service's view for `caller`, kept per view key and
1673    /// grants generation, with what it was decided over. The generations
1674    /// are read before anything they cover, so a write that lands while a
1675    /// view is built leaves it under the generation before — dropped at the
1676    /// next ask.
1677    fn shaped(&self, caller: Option<&super::auth::AuthContext>) -> (Arc<super::view::Described>, Arc<super::view::Shaped>) {
1678        let gate = self.inner.gate.as_ref().expect("a view is a gated service's");
1679        let schema_at = self.inner.describe.schema_generation();
1680        let grants_at = gate.generation().current();
1681        // AUTH-11: a sign-in that ended sees the anonymous view — asked on
1682        // every ask, never kept.
1683        let (caller, _) = super::grant_gate::standing(gate, caller);
1684        let who = caller.and_then(|c| gate.fingerprint(c));
1685        let shape = |base: &super::view::Described| {
1686            Arc::new(super::view::shape(gate, &self.inner.signed_in_grants, who.as_ref(), base))
1687        };
1688        match self.inner.describe.view(schema_at, grants_at, &who) {
1689            Some((base, view)) => {
1690                let base = base.get_or_init(|| Arc::new(self.describe_now())).clone();
1691                let view = view.get_or_init(|| shape(&base)).clone();
1692                (base, view)
1693            }
1694            None => {
1695                let base = Arc::new(self.describe_now());
1696                let view = shape(&base);
1697                (base, view)
1698            }
1699        }
1700    }
1701
1702    /// AUTH-4: `_info`'s content for `caller`. Without a gate, exactly
1703    /// today's `{backend, auth_capabilities}` whoever asks. With one, also
1704    /// `view` (`anonymous` | `caller`) and `view_hash`; and, to an
1705    /// anonymous caller, `auth: {methods: [the public methods' grants],
1706    /// resource_metadata?}` — how to sign in.
1707    pub fn info(&self, caller: Option<&super::auth::AuthContext>) -> serde_json::Value {
1708        if self.inner.gate.is_none() {
1709            return build_info_payload(self.runtime_namespace(), self.inner.auth_capabilities.as_ref());
1710        }
1711        // PERF-15: built once per view, kept with it.
1712        let (base, view) = self.shaped(caller);
1713        view.info
1714            .get_or_init(|| {
1715                let mut payload = build_info_payload(self.runtime_namespace(), self.inner.auth_capabilities.as_ref());
1716                if let Some(obj) = payload.as_object_mut() {
1717                    obj.insert("view".into(), view.kind.as_str().into());
1718                    obj.insert("view_hash".into(), view.hash.clone().into());
1719                    if view.kind == super::ViewKind::Anonymous {
1720                        let mut auth = serde_json::Map::new();
1721                        auth.insert("methods".into(), view.public_methods(&base).into());
1722                        if let Some(url) = self.inner.resource_metadata.as_ref() {
1723                            auth.insert("resource_metadata".into(), url.clone().into());
1724                        }
1725                        obj.insert("auth".into(), serde_json::Value::Object(auth));
1726                    }
1727                }
1728                payload
1729            })
1730            .clone()
1731    }
1732
1733    /// AUTH-4: a gated hub's introspection (`<ns>.schema`, the hub's
1734    /// `hash` / `hashes`, `<ns>.<method>.schema`) answered from the
1735    /// caller's view: the stream the hub would send, its content replaced
1736    /// by the view's. `None`: not answered here (a nested child path of a
1737    /// visible activation) — route it as before.
1738    async fn introspect_in_view(
1739        &self,
1740        method: &str,
1741        params: &Value,
1742        auth: Option<&super::auth::AuthContext>,
1743        raw_ctx: Option<&crate::request::RawRequestContext>,
1744    ) -> Option<Result<PlexusStream, PlexusError>> {
1745        let (ns, rest) = method.split_once('.')?;
1746        let hub_ns = self.inner.namespace.as_str();
1747        // PERF-15: the view, and what it was decided over, from the cache.
1748        let (base, view) = self.shaped(auth);
1749        let not_found = || PlexusError::ActivationNotFound(ns.to_string());
1750        let content: serde_json::Value = match rest {
1751            "schema" => {
1752                if !view.shows(ns) {
1753                    return Some(Err(not_found()));
1754                }
1755                let mut result = match params.get("method").and_then(|v| v.as_str()) {
1756                    Some(name) => match view.method_of(&base, ns, name) {
1757                        Some(m) => super::SchemaResult::Method(m),
1758                        None => {
1759                            return Some(Err(PlexusError::MethodNotFound {
1760                                activation: ns.to_string(),
1761                                method: name.to_string(),
1762                            }))
1763                        }
1764                    },
1765                    None => super::SchemaResult::Plugin(view.schema_of(&base, ns)?),
1766                };
1767                if let Some(site) = self.derived_site_hint() {
1768                    result.fill_site_hints(&site);
1769                }
1770                serde_json::to_value(&result).ok()?
1771            }
1772            "hash" if ns == hub_ns => serde_json::to_value(HashEvent::Hash { value: view.hash.clone() }).ok()?,
1773            "hashes" if ns == hub_ns => serde_json::to_value(view.hashes()).ok()?,
1774            r if r.ends_with(".schema") => {
1775                if !view.shows(ns) {
1776                    return Some(Err(not_found()));
1777                }
1778                let name = r.trim_end_matches(".schema");
1779                match view.method_of(&base, ns, name) {
1780                    Some(m) if matches!(m.role, super::MethodRole::Rpc) => {
1781                        serde_json::to_value(super::SchemaResult::Method(m)).ok()?
1782                    }
1783                    // A visible nested child: its own routing answers.
1784                    Some(_) => return None,
1785                    None if name.contains('.') => return None,
1786                    // NEST-6: a name in the activation's dynamic slot
1787                    // (`solar.earth.schema`): the instance's own schema,
1788                    // which its routing answers.
1789                    None if base.activations.iter().any(|a| a.namespace == ns && a.methods.iter().any(|m| m.role.is_slot())) => return None,
1790                    None => {
1791                        return Some(Err(PlexusError::MethodNotFound {
1792                            activation: ns.to_string(),
1793                            method: name.to_string(),
1794                        }))
1795                    }
1796                }
1797            }
1798            _ => return None,
1799        };
1800        // The stream the service sends today, so content types and metadata
1801        // stay what clients know; only the content is the view's.
1802        use futures::StreamExt;
1803        let with = |content: serde_json::Value| {
1804            // PERF-7: an encoded item is a `Data` item: its content is
1805            // replaced whole, whatever it was made as.
1806            move |item: super::types::PlexusStreamItem| match item {
1807                super::types::PlexusStreamItem::Data { metadata, content_type, .. } => {
1808                    super::types::PlexusStreamItem::Data { metadata, content_type, content: content.clone().into() }
1809                }
1810                other => other,
1811            }
1812        };
1813        // R-5's scope gate decides introspection on every call, and audits
1814        // it: routed every time, as before.
1815        if self.inner.scope_registry.is_some() || self.inner.default_deny {
1816            let routed = self.route_ungated(method, params.clone(), auth, raw_ctx).await;
1817            return Some(routed.map(|s| -> PlexusStream { Box::pin(s.map(with(content))) }));
1818        }
1819        // PERF-15: that stream's envelope is learned from the first answer
1820        // routed for this method and params, and kept with what the service
1821        // describes; after it no activation builds its schema to say it.
1822        let key = format!("{method}\n{params}");
1823        if let Some(shell) = base.shell(&key) {
1824            return Some(Ok(Box::pin(futures::stream::iter(shell.answer(content)))));
1825        }
1826        let items: Vec<super::types::PlexusStreamItem> = match self.route_ungated(method, params.clone(), auth, raw_ctx).await {
1827            Ok(s) => s.collect().await,
1828            Err(e) => return Some(Err(e)),
1829        };
1830        if let Some(shell) = super::view::Shell::of(&items) {
1831            base.keep_shell(key, shell);
1832        }
1833        Some(Ok(Box::pin(futures::stream::iter(items.into_iter().map(with(content))))))
1834    }
1835
1836    /// RETURNS-40: the service's IR of the walks from `namespaces` (dotted
1837    /// paths; none: the whole service) as `caller` sees it — what its `ir`
1838    /// method answers. Synapse's walk, made in process over **one snapshot**
1839    /// of what the caller is shown (RETURNS-40 review #2): the service's own
1840    /// schema and each activation's from that one view (a grant that moves
1841    /// while the IR is built moves the next view, not this one), a static
1842    /// child's as its activation answers it, each child summary followed;
1843    /// under the R-5 scope gate only the schemas the caller's own calls are
1844    /// answered (#3). Built off the runtime (`spawn_blocking`), once per key
1845    /// at a time, and kept by the view's hash, the roots and — under the
1846    /// scope gate — what the caller is answered ([`super::ir::IrCache`],
1847    /// #4); a refusal is not kept. The IR is [`super::ir::build`]'s, equal
1848    /// to synapse's `buildIRFromSchemas` over the same schemas.
1849    pub async fn service_ir(
1850        &self,
1851        namespaces: &[String],
1852        caller: Option<&super::auth::AuthContext>,
1853    ) -> Result<super::ir::ServiceIr, super::ir::IrError> {
1854        let roots = super::ir::roots(&self.inner.namespace, namespaces);
1855        let view = self.ir_view(caller);
1856        let permitted = match self.inner.scope_registry.is_some() || self.inner.default_deny {
1857            false => None,
1858            true => {
1859                // re-review #4: decided for the names under the roots asked
1860                // alone, and written to no audit sink — the `ir` call was
1861                // enforced, and audited, once
1862                let mut answered = Vec::new();
1863                for name in view.names(&self.inner.namespace) {
1864                    let under = roots.iter().any(|r| {
1865                        let r = r.join(".");
1866                        r.is_empty() || name == r || name.starts_with(&format!("{r}."))
1867                    });
1868                    if under && self.scope_answers(&self.schema_method(&name), caller).await {
1869                        answered.push(name);
1870                    }
1871                }
1872                Some(answered)
1873            }
1874        };
1875        let key = super::ir::IrKey { view: view.hash.clone(), roots: roots.clone(), permitted: permitted.clone() };
1876        self.inner
1877            .ir_cache
1878            .get_or_build(key, || async {
1879                let mut schemas: BTreeMap<Vec<String>, Value> = BTreeMap::new();
1880                let mut todo: Vec<Vec<String>> = roots.clone();
1881                while let Some(path) = todo.pop() {
1882                    if schemas.contains_key(&path) || permitted.as_ref().is_some_and(|p| !p.contains(&path.join("."))) {
1883                        continue;
1884                    }
1885                    // a schema the caller is not answered is one the walk skips
1886                    let Some(schema) = self.ir_schema(&view, &path, caller).await else { continue };
1887                    for child in schema.get("children").and_then(Value::as_array).into_iter().flatten() {
1888                        if let Some(ns) = child.get("namespace").and_then(Value::as_str) {
1889                            let mut next = path.clone();
1890                            next.push(ns.to_string());
1891                            todo.push(next);
1892                        }
1893                    }
1894                    schemas.insert(path, schema);
1895                }
1896                let service = self.inner.namespace.clone();
1897                crate::rt::spawn_blocking(move || super::ir::answer(&service, &roots, &schemas))
1898                    .await
1899                    .unwrap_or_else(|e| Err(super::ir::IrError::Unreadable { namespace: String::new(), message: format!("the IR's build failed: {e}") }))
1900            })
1901            .await
1902    }
1903
1904    /// How many IR builds this service has run — its `ir` answers built
1905    /// rather than kept.
1906    pub fn ir_builds(&self) -> usize {
1907        self.inner.ir_cache.builds()
1908    }
1909
1910    /// RETURNS-40: one snapshot of what `caller` is shown — the caller's view
1911    /// under the grant gate (one [`DynamicHub::shaped`]), the whole service
1912    /// otherwise.
1913    fn ir_view(&self, caller: Option<&super::auth::AuthContext>) -> IrView {
1914        match self.inner.gate {
1915            Some(_) => {
1916                let (base, shaped) = self.shaped(caller);
1917                IrView { hash: shaped.hash.clone(), base, shaped: Some(shaped) }
1918            }
1919            None => {
1920                let base = self.described();
1921                IrView { hash: base.service.hash.clone(), base, shaped: None }
1922            }
1923        }
1924    }
1925
1926    /// `<path>.schema` (the service's own `<ns>.schema` at `[]`).
1927    fn schema_method(&self, dotted: &str) -> String {
1928        if dotted.is_empty() { format!("{}.schema", self.inner.namespace) } else { format!("{dotted}.schema") }
1929    }
1930
1931    /// Whether the R-5 scope gate answers `caller`'s `method` — the gate the
1932    /// call itself would meet.
1933    async fn scope_answers(&self, method: &str, caller: Option<&super::auth::AuthContext>) -> bool {
1934        let registry = self.inner.scope_registry.as_deref().unwrap_or_else(|| super::scope_gate::empty_registry());
1935        super::scope_gate::answers(registry, self.inner.default_deny, method, self.gate_index().info(method), caller).await
1936    }
1937
1938    /// The schema at `path` as the snapshot answers it — what `<path>.schema`
1939    /// answers the caller: the service's own and each activation's from the
1940    /// view, a static child's (which no view shapes) as its activation
1941    /// answers it, asked of the activation as the route asks it.
1942    async fn ir_schema(&self, view: &IrView, path: &[String], caller: Option<&super::auth::AuthContext>) -> Option<Value> {
1943        use futures::StreamExt;
1944        let shown = match path {
1945            [] => Some(view.root()),
1946            [ns] => view.top(ns),
1947            [top, below @ ..] => {
1948                // asked of its activation as the route asks it past both
1949                // gates — the scope gate decided this name already, silently
1950                let activation = self.table().entries.get(top.as_str())?.object.clone();
1951                let mut stream = activation.call(&format!("{}.schema", below.join(".")), Value::Null, caller, None).await.ok()?;
1952                if let Some(site) = self.derived_site_hint() {
1953                    stream = fill_site_hints_in_schema_stream(stream, site);
1954                }
1955                let items: Vec<super::types::PlexusStreamItem> = stream.collect().await;
1956                return items.into_iter().find_map(|item| match item {
1957                    super::types::PlexusStreamItem::Data { content_type, content, .. } if content_type.ends_with(".schema") => {
1958                        Some(content.into_value())
1959                    }
1960                    _ => None,
1961                });
1962            }
1963        };
1964        let mut schema = shown?;
1965        if let Some(site) = self.derived_site_hint() {
1966            schema.fill_site_hints(&site);
1967        }
1968        serde_json::to_value(super::SchemaResult::Plugin(schema)).ok()
1969    }
1970
1971    /// RETURNS-40 review #1: `ir`'s `namespaces` refused before any work —
1972    /// more names than the caller's view of the service has, or a name it
1973    /// has not (named), is `invalid_params`.
1974    fn check_ir_names(&self, params: &Value, caller: Option<&super::auth::AuthContext>) -> Result<(), PlexusError> {
1975        let asked = match params.get("namespaces") {
1976            None | Some(Value::Null) => return Ok(()),
1977            Some(Value::Array(a)) => a,
1978            Some(_) => return Err(PlexusError::malformed_param("namespaces", "a list of namespaces")),
1979        };
1980        // the cheap bound first, read with no schema built: no view shows
1981        // more than the service has — said without the service's size
1982        // (re-review #3), which the caller's view may not show
1983        let most = {
1984            let table = self.table();
1985            1 + table.entries.len() + table.nested
1986        };
1987        if asked.len() > most {
1988            return Err(PlexusError::malformed_param(
1989                "namespaces",
1990                format!("{} namespaces asked; more than this service shows you", asked.len()),
1991            ));
1992        }
1993        let names: std::collections::HashSet<String> = self.ir_view(caller).names(&self.inner.namespace).into_iter().collect();
1994        if asked.len() > names.len() {
1995            return Err(PlexusError::malformed_param(
1996                "namespaces",
1997                format!("{} namespaces asked; this service shows you {}", asked.len(), names.len()),
1998            ));
1999        }
2000        for n in asked {
2001            let Some(n) = n.as_str() else { return Err(PlexusError::malformed_param("namespaces", "a list of namespaces")) };
2002            let known = n == self.inner.namespace || names.contains(n);
2003            if !known {
2004                return Err(PlexusError::malformed_param("namespaces", format!("no namespace `{n}` in this service")));
2005            }
2006        }
2007        Ok(())
2008    }
2009
2010    /// AUTH-2/AUTH-3: the default roles every registered activation
2011    /// declares (`#[plexus_macros::activation(roles(...))]`), merged by role
2012    /// name — what a service seeds its [`Roles`] with
2013    /// ([`RoleTable::from_lists`]) before an admin's edits.
2014    ///
2015    /// [`Roles`]: plexus_auth_core::grants::Roles
2016    /// [`RoleTable::from_lists`]: plexus_auth_core::grants::RoleTable::from_lists
2017    pub fn declared_roles(&self) -> std::collections::BTreeMap<String, Vec<String>> {
2018        let mut out: std::collections::BTreeMap<String, Vec<String>> = std::collections::BTreeMap::new();
2019        // MACRO-20: and every static child's, its grants qualified by the
2020        // path it is reached through (`commits.link` → `tickets.commits.link`).
2021        // NEST-5: and every typed slot's, by the slot's path.
2022        let schemas = self.table().entries.values().map(|e| e.object.plugin_schema()).chain(self.described_children()).collect::<Vec<_>>();
2023        for schema in schemas {
2024            for (role, grants) in schema.roles {
2025                let entry = out.entry(role).or_default();
2026                for g in grants {
2027                    if !entry.contains(&g) {
2028                        entry.push(g);
2029                    }
2030                }
2031            }
2032        }
2033        out
2034    }
2035
2036    /// MACRO-20: every registered activation's static children (and
2037    /// theirs), each a schema whose namespace is its whole path
2038    /// (`tickets.commits`) and whose grants and roles are qualified by it —
2039    /// see [`super::children`]. Empty for a hub whose activations have no
2040    /// static `#[plexus_macros::child]`.
2041    pub fn static_children(&self) -> Vec<PluginSchema> {
2042        self.table()
2043            .entries
2044            .values()
2045            .flat_map(|e| super::children::qualified(&e.object.plugin_schema().namespace, e.object.static_child_schemas()))
2046            .collect()
2047    }
2048
2049    /// Read-only view of the configured [`ScopeRegistry`], if any.
2050    /// Test-side accessor.
2051    ///
2052    /// [`ScopeRegistry`]: plexus_auth_core::ScopeRegistry
2053    pub fn scope_registry(&self) -> Option<&plexus_auth_core::ScopeRegistry> {
2054        self.inner.scope_registry.as_deref()
2055    }
2056
2057    /// BIDIR-6: what a call with an input half is held to when it is asked
2058    /// again: the grant and targets the gate decided it on. Read only when a
2059    /// method with an `Input` opens, so no other call pays for it.
2060    pub(crate) fn input_terms(&self, method: &str, params: &Value) -> Result<InputTerms, PlexusError> {
2061        if self.inner.gate.is_none() {
2062            return Ok(InputTerms { grant: method.to_string(), targets: Vec::new(), recheck: false });
2063        }
2064        let index = self.gate_index();
2065        let info = index.info(method);
2066        let grant = info.and_then(|i| i.grant.clone()).unwrap_or_else(|| method.to_string());
2067        let open = info.is_some_and(|i| i.public) || self.inner.signed_in_grants.contains(grant.as_str());
2068        let targets = match info.and_then(|i| i.target.as_deref()) {
2069            Some(param) => super::grant_gate::target_values(params, param)?.unwrap_or_default(),
2070            None => Vec::new(),
2071        };
2072        Ok(InputTerms { grant, targets, recheck: !open })
2073    }
2074
2075    /// BIDIR-6: the gate over this service's duplex calls, made when the
2076    /// first one opens (in the runtime, which runs its audit's drain).
2077    pub(crate) fn duplex_gate(&self) -> &super::duplex_gate::DuplexGate {
2078        self.inner.duplex_gate.get_or_init(|| match &self.inner.gate {
2079            Some(gate) => {
2080                let (audit, drain) = plexus_auth_core::audit::AuditQueue::new(1024, self.inner.audit_sink.clone());
2081                crate::rt::spawn(drain);
2082                super::duplex_gate::DuplexGate::new((**gate).clone()).with_audit(audit)
2083            }
2084            None => super::duplex_gate::DuplexGate::ungated(),
2085        })
2086    }
2087
2088    /// BIDIR-6: whether `method` (a `{ns}.call`'s dotted path) may take an
2089    /// `Input`: `false` only for a method this service's schemas show has
2090    /// none — its own, each activation's, each static child's. A path they do
2091    /// not show (a dynamic child's) may.
2092    pub(crate) fn may_take_input(&self, method: &str) -> bool {
2093        let kept = self.inner.input_index.read().unwrap_or_else(|p| p.into_inner()).clone();
2094        let index = match kept {
2095            Some(index) => index,
2096            None => {
2097                let own = Activation::plugin_schema(self).methods.into_iter().map(|m| (format!("{}.{}", self.inner.namespace, m.name), m.input.is_some()));
2098                let schemas: Vec<PluginSchema> = self.table().entries.values().map(|e| e.object.plugin_schema()).chain(self.static_children()).collect();
2099                let theirs = schemas.into_iter().flat_map(|schema| {
2100                    let ns = schema.namespace;
2101                    schema.methods.into_iter().map(move |m| (format!("{ns}.{}", m.name), m.input.is_some()))
2102                });
2103                let index: Arc<HashMap<String, bool>> = Arc::new(own.chain(theirs).collect());
2104                *self.inner.input_index.write().unwrap_or_else(|p| p.into_inner()) = Some(index.clone());
2105                index
2106            }
2107        };
2108        index.get(method).copied().unwrap_or(true)
2109    }
2110
2111    /// NEST-5: every slot of every registered activation and static child
2112    /// (to any depth): each typed slot as a schema at its path
2113    /// (`tickets.{item}`, grants qualified — [`super::slots`]), and each
2114    /// untyped slot's path.
2115    pub fn slot_children(&self) -> (Vec<PluginSchema>, Vec<String>) {
2116        let (mut typed, mut untyped) = (Vec::new(), Vec::new());
2117        let schemas = self.table().entries.values().map(|e| e.object.plugin_schema()).chain(self.static_children()).collect::<Vec<_>>();
2118        for schema in schemas {
2119            super::slots::slot_schemas(&schema, &mut typed, &mut untyped);
2120        }
2121        (typed, untyped)
2122    }
2123
2124    /// MACRO-20 and NEST-5: every static child and every typed slot, each a
2125    /// schema whose namespace is its whole path and whose grants are
2126    /// qualified by it — what the gate, the roles, `auth.requires` and the
2127    /// caller's view read below an activation.
2128    pub fn described_children(&self) -> Vec<PluginSchema> {
2129        let mut out = self.static_children();
2130        out.extend(self.slot_children().0);
2131        out
2132    }
2133
2134    /// The gate's path→schema-facts index; built once on first gated
2135    /// dispatch. See the field docs on `DynamicHubInner::gate_index`.
2136    fn gate_index(&self) -> Arc<GateIndex> {
2137        if let Some(index) = self.inner.gate_index.read().unwrap_or_else(|p| p.into_inner()).as_ref() {
2138            return index.clone();
2139        }
2140        let index = Arc::new(self.build_gate_index());
2141        *self.inner.gate_index.write().unwrap_or_else(|p| p.into_inner()) = Some(index.clone());
2142        index
2143    }
2144
2145    fn build_gate_index(&self) -> GateIndex {
2146        {
2147            let mut index = HashMap::new();
2148            // The hub's own methods, addressable as "<hub-ns>.<method>".
2149            for m in &Activation::plugin_schema(self).methods {
2150                let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
2151                // The hub's own methods are granted under its runtime
2152                // namespace (the macro's static one is "plexus").
2153                info.grant = Some(format!("{}.{}", self.inner.namespace, m.name));
2154                index.insert(format!("{}.{}", self.inner.namespace, m.name), info);
2155            }
2156            // Each registered activation's methods, addressable as
2157            // "<activation-ns>.<method>"; MACRO-20: and each static child's,
2158            // as "<activation-ns>.<path>.<method>", with the child's own
2159            // target and its grant qualified by the path
2160            // (`tickets.commits.link`, see `super::children`). A dynamic
2161            // child (an open name set) has no MethodSchema at this hub's
2162            // level; the gate treats its paths as schema-less (grant = the
2163            // dotted path; registry overlay / default_deny still apply).
2164            // NEST-5: and each typed slot's, as `<parent>.{<slot>}.<method>`
2165            // with its grant qualified by the slot's path; an untyped slot
2166            // is one entry, `<parent>.{<slot>}`, granted whole.
2167            let (typed, untyped) = self.slot_children();
2168            let activations: Vec<PluginSchema> = self.table().entries.values().map(|e| e.object.plugin_schema()).collect();
2169
2170            let statics = self.static_children();
2171            for schema in activations.iter().chain(statics.iter()).chain(typed.iter()) {
2172                for m in &schema.methods {
2173                    let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
2174                    info.grant = Some(m.grant_or(&schema.namespace));
2175                    index.insert(format!("{}.{}", schema.namespace, m.name), info);
2176                }
2177            }
2178            for path in &untyped {
2179                index.insert(
2180                    path.clone(),
2181                    super::scope_gate::MethodGateInfo { grant: Some(path.clone()), ..Default::default() },
2182                );
2183            }
2184            let slots = super::slots::Slots::of(activations.iter().chain(statics.iter()).chain(typed.iter()), &untyped);
2185            GateIndex { methods: index, slots }
2186        }
2187    }
2188
2189    /// Register a [`plexus_auth_core::ForwardPolicy`] for a callee
2190    /// namespace.
2191    ///
2192    /// AUTHLANG-3 — every cross-boundary call through this hub consults
2193    /// the registry at dispatch time. When `callee_ns` has no entry, the
2194    /// framework falls back to [`plexus_auth_core::IdentityOnly`].
2195    ///
2196    /// AUTHLANG-4's `#[plexus::activation(forward_policy = ...)]`
2197    /// attribute is the declarative path; this builder is the imperative
2198    /// escape hatch used by integration tests and hand-rolled wiring.
2199    ///
2200    /// # Example
2201    ///
2202    /// ```ignore
2203    /// use plexus_auth_core::PassThrough;
2204    /// use std::sync::Arc;
2205    ///
2206    /// let hub = DynamicHub::new("my-backend")
2207    ///     .with_forward_policy("solar", Arc::new(PassThrough));
2208    /// ```
2209    pub fn with_forward_policy(
2210        mut self,
2211        callee_ns: impl Into<String>,
2212        policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>,
2213    ) -> Self {
2214        let inner = self.inner_mut("Cannot register forward policy: DynamicHub has multiple references");
2215        inner.forward_policies.register(callee_ns, policy);
2216        self
2217    }
2218
2219    /// Read-only view of the registered forward policies.
2220    ///
2221    /// Test-side accessor; production dispatch consults the registry via
2222    /// the [`ChildRouter::forward_policy_for`] override.
2223    pub fn forward_policies(&self) -> &super::forward_registry::ForwardPolicyRegistry {
2224        &self.inner.forward_policies
2225    }
2226
2227    /// Declare the backend's authentication capabilities, served at `_info`.
2228    ///
2229    /// Backends call this at builder time to advertise which auth mechanisms
2230    /// they support (Bearer, Cookie, OIDC, Anonymous). Generic clients
2231    /// (synapse CLI, gamma, generated SDKs) read the advertisement to decide
2232    /// which authentication flow to drive.
2233    ///
2234    /// Without calling this method, `_info` emits the
2235    /// [`plexus_auth_core::BackendAuthCapabilities::anonymous_default`]
2236    /// fallback: a single `Anonymous` mechanism, no default. This preserves
2237    /// today's no-auth substrate behavior.
2238    ///
2239    /// Per AUTHZ-CORE-3 / AUTHZ-S01-output §2.
2240    ///
2241    /// # Example
2242    ///
2243    /// ```no_run
2244    /// # use plexus_core::DynamicHub;
2245    /// use plexus_auth_core::{
2246    ///     AuthMechanism, BackendAuthCapabilities, CookieName, MethodPath,
2247    /// };
2248    ///
2249    /// let caps = BackendAuthCapabilities::new(
2250    ///     vec![AuthMechanism::Cookie {
2251    ///         cookie: CookieName::try_new("plexus_session").unwrap(),
2252    ///         login: MethodPath::try_new("auth.login").unwrap(),
2253    ///         refresh: None,
2254    ///         logout: None,
2255    ///     }],
2256    ///     Some(0),
2257    /// )
2258    /// .unwrap();
2259    ///
2260    /// let hub = DynamicHub::new("my-backend").with_auth_capabilities(caps);
2261    /// ```
2262    pub fn with_auth_capabilities(
2263        mut self,
2264        caps: plexus_auth_core::BackendAuthCapabilities,
2265    ) -> Self {
2266        let inner = self.inner_mut("Cannot set auth_capabilities: DynamicHub has multiple references");
2267        inner.auth_capabilities = Some(caps);
2268        self
2269    }
2270
2271    /// Returns the configured [`BackendAuthCapabilities`], or `None` if the
2272    /// backend has not called [`Self::with_auth_capabilities`].
2273    ///
2274    /// Test-side accessor; production code reads the advertisement off `_info`.
2275    ///
2276    /// [`BackendAuthCapabilities`]: plexus_auth_core::BackendAuthCapabilities
2277    pub fn auth_capabilities(&self) -> Option<&plexus_auth_core::BackendAuthCapabilities> {
2278        self.inner.auth_capabilities.as_ref()
2279    }
2280
2281    /// Deprecated: Use new() with explicit namespace instead
2282    #[deprecated(since = "0.3.0", note = "Use DynamicHub::new(namespace) instead")]
2283    pub fn with_namespace(namespace: impl Into<String>) -> Self {
2284        Self::new(namespace)
2285    }
2286
2287    /// Get the runtime namespace for this DynamicHub instance
2288    pub fn runtime_namespace(&self) -> &str {
2289        &self.inner.namespace
2290    }
2291
2292    /// Get access to the activation registry
2293    pub fn registry(&self) -> std::sync::RwLockReadGuard<'_, PluginRegistry> {
2294        self.inner.registry.read().unwrap()
2295    }
2296
2297    /// Panic if `child_namespace` shadows the hub root namespace.
2298    ///
2299    /// Z2H-8 / HOSTLESS-3 — routing resolves the hub root before registered
2300    /// activations (see [`Self::route_with_ctx`]), so a child activation whose
2301    /// namespace equals the hub root name is silently unreachable: every
2302    /// `<ns>.<method>` call resolves to the root (which only has
2303    /// call/hash/hashes/schema) and navigators resolve the like-named child
2304    /// back to the root schema. The published echo example shipped exactly
2305    /// this shape and was dead on arrival. A loud, immediate error at
2306    /// registration time beats silent unreachability at call time.
2307    fn assert_no_root_shadow(&self, child_namespace: &str) {
2308        if child_namespace == self.inner.namespace {
2309            panic!(
2310                "DynamicHub namespace shadow: activation namespace '{child}' collides with the hub root namespace '{root}'. \
2311                 The hub root name is a routing namespace, not a label — routing resolves the root first, so a like-named \
2312                 child activation is unreachable (every '{child}.<method>' call resolves to the hub root and fails with \
2313                 'Command not found', and navigation resolves the child back to the root schema). \
2314                 Fix: rename the hub root so it differs from every registered activation's namespace, \
2315                 e.g. DynamicHub::new(\"{root}_hub\").register(...). [Z2H-8 / HOSTLESS-3]",
2316                child = child_namespace,
2317                root = self.inner.namespace,
2318            );
2319        }
2320    }
2321
2322    /// Register an activation
2323    ///
2324    /// # Panics
2325    ///
2326    /// Panics if the activation's namespace equals the hub root namespace —
2327    /// such a child would be unreachable at call time (Z2H-8 / HOSTLESS-3,
2328    /// see [`Self::new`]). Also panics if the hub has already been shared
2329    /// (multiple `Arc` references).
2330    pub fn register<A: Activation + ChildRouter + Clone + 'static>(self, activation: A) -> Self {
2331        self.register_entry(activation)
2332    }
2333
2334    /// Register a hub activation that supports nested routing
2335    ///
2336    /// Hub activations implement `ChildRouter`, enabling direct nested method calls
2337    /// like `hub.solar.mercury.info` at the RPC layer (no hub.call indirection).
2338    ///
2339    /// # Panics
2340    ///
2341    /// Same contract as [`Self::register`]: panics on a root/activation
2342    /// namespace collision (Z2H-8 / HOSTLESS-3).
2343    #[deprecated(since = "0.5.0", note = "Use register() — it now handles both leaf and hub activations")]
2344    pub fn register_hub<A: Activation + ChildRouter + Clone + 'static>(self, activation: A) -> Self {
2345        self.register_entry(activation)
2346    }
2347
2348    /// NEST-15: `activation` as an entry of the root's table.
2349    pub(crate) fn entry_of<A: Activation + ChildRouter + Clone + 'static>(activation: A) -> super::service_root::Entry {
2350        let router = Arc::new(activation.clone());
2351        super::service_root::Entry { object: Arc::new(ActivationWrapper { inner: activation }), router }
2352    }
2353
2354    /// [`register`](Self::register): an entry of the root's table, at build,
2355    /// with its direct RPC methods (a service without a grant gate serves
2356    /// `<ns>.<method>` beside `<ns>.call`).
2357    fn register_entry<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
2358        let namespace = activation.namespace().to_string();
2359        self.assert_no_root_shadow(&namespace);
2360        let activation_for_rpc = activation.clone();
2361        let entry = Self::entry_of(activation);
2362        let inner = self.inner_mut("Cannot register: DynamicHub has multiple references");
2363        Self::index_entry(inner.registry.get_mut().unwrap_or_else(|p| p.into_inner()), inner.auth_catalog.as_ref(), &namespace, &entry);
2364        let table = Arc::make_mut(inner.root.get_mut().unwrap_or_else(|p| p.into_inner()));
2365        if let Some(old) = table.entries.insert(namespace, entry.clone()) {
2366            table.nested -= old.object.static_child_schemas().len();
2367        }
2368        // RETURNS-40: the cheap bound on `ir`'s names, counted here, once
2369        table.nested += entry.object.static_child_schemas().len();
2370        inner.pending_rpc.lock().unwrap()
2371            .push(Box::new(move || activation_for_rpc.into_rpc_methods()));
2372        self
2373    }
2374
2375    /// What every entry is known by besides the table: its id in the
2376    /// activation registry, and — AUTH-5 — its methods in `auth.requires`
2377    /// (registered before the auth activation was mounted or after).
2378    fn index_entry(
2379        registry: &mut PluginRegistry,
2380        catalog: Option<&super::auth_activation::Catalog>,
2381        namespace: &str,
2382        entry: &super::service_root::Entry,
2383    ) {
2384        registry.register(entry.object.plugin_id(), namespace.to_string(), namespace.to_string());
2385        if let Some(catalog) = catalog {
2386            let schema = entry.object.plugin_schema();
2387            // MACRO-20: and its static children's methods, by their whole path.
2388            let statics = super::children::qualified(&schema.namespace, entry.object.static_child_schemas());
2389            // NEST-5: and its slots — a typed slot's methods by the slot's
2390            // path, an untyped slot whole.
2391            let (mut typed, mut untyped) = (Vec::new(), Vec::new());
2392            for s in std::iter::once(&schema).chain(statics.iter()) {
2393                super::slots::slot_schemas(s, &mut typed, &mut untyped);
2394            }
2395            for child in statics.iter().chain(typed.iter()) {
2396                catalog.add(child);
2397            }
2398            catalog.add_slots(&untyped);
2399            catalog.add(&schema);
2400        }
2401    }
2402
2403    /// NEST-15: the service root — its table of peers, read and changed
2404    /// while the service serves.
2405    pub fn root(&self) -> super::service_root::ServiceRoot {
2406        super::service_root::ServiceRoot { hub: self.clone() }
2407    }
2408
2409    /// NEST-15: the root's table now (a snapshot).
2410    pub(crate) fn table(&self) -> Arc<super::service_root::Table> {
2411        self.inner.root.read().unwrap_or_else(|p| p.into_inner()).clone()
2412    }
2413
2414    /// NEST-15: told the service's hash each time the root's table changes.
2415    pub(crate) fn watch_root(&self) -> tokio::sync::watch::Receiver<String> {
2416        self.inner.root_watch.subscribe()
2417    }
2418
2419    /// NEST-15: serve `entry` as `name` while the service serves — refused
2420    /// for the service's own name, a name not one segment, or (unless
2421    /// `replace`) a name taken. Answers whether an entry was replaced.
2422    pub(crate) fn insert_entry(&self, name: String, entry: super::service_root::Entry, replace: bool) -> Result<bool, super::service_root::RootError> {
2423        super::service_root::check_name(&name)?;
2424        if name == self.inner.namespace {
2425            return Err(super::service_root::RootError::Shadows { name });
2426        }
2427        // NEST-16: a graft is checked against the service it joins.
2428        if let Some(needs) = entry.object.needs() {
2429            self.check_needs(&name, &needs).map_err(super::service_root::RootError::Needs)?;
2430        }
2431        let before = self.compute_hash();
2432        let replaced = self.change_table(|table| {
2433            if !replace && table.entries.contains_key(&name) {
2434                return Err(super::service_root::RootError::Taken { name: name.clone() });
2435            }
2436            let nested = entry.object.static_child_schemas().len();
2437            let old = table.entries.insert(name.clone(), entry.clone());
2438            if let Some(old) = old.as_ref() {
2439                table.nested -= old.object.static_child_schemas().len();
2440            }
2441            table.nested += nested;
2442            Ok(old.is_some())
2443        })?;
2444        Self::index_entry(&mut self.inner.registry.write().unwrap_or_else(|p| p.into_inner()), self.inner.auth_catalog.as_ref(), &name, &entry);
2445        self.table_moved(before);
2446        Ok(replaced)
2447    }
2448
2449    /// NEST-21: the service's configuration — a capability handle (every
2450    /// clone the same store), made in memory at its first use unless
2451    /// [`DynamicHub::with_config`] gave one. Hand it to what reads or sets
2452    /// a setting; serve it with [`DynamicHub::with_config_service`].
2453    pub fn config(&self) -> super::config::Config {
2454        self.inner.config.get_or_init(super::config::Config::new).clone()
2455    }
2456
2457    /// NEST-21: keep the configuration in `config` (one with a file, or one
2458    /// a host built before the service). Before the service is shared.
2459    pub fn with_config(mut self, config: super::config::Config) -> Self {
2460        let inner = self.inner_mut("Cannot set config: DynamicHub has multiple references");
2461        inner.config = std::sync::OnceLock::from(config);
2462        self
2463    }
2464
2465    /// NEST-21: serve the service's configuration as the `config`
2466    /// activation ([`super::config::ConfigActivation`]): admin's, each key
2467    /// on its own grant.
2468    pub fn with_config_service(self) -> Self {
2469        let config = self.config();
2470        self.register(super::config::ConfigActivation::new(config))
2471    }
2472
2473    /// NEST-16: what children say through `host.notify` from now on (the
2474    /// last 64 kept for a slow listener; older ones dropped for it).
2475    pub fn notices(&self) -> tokio::sync::broadcast::Receiver<super::parent::Notice> {
2476        self.inner.notices.subscribe()
2477    }
2478
2479    /// NEST-16: say `notice` to whoever listens; answers how many do.
2480    pub fn notify(&self, notice: super::parent::Notice) -> u64 {
2481        self.inner.notices.send(notice).map(|n| n as u64).unwrap_or(0)
2482    }
2483
2484    /// NEST-16: the method this service serves at `path` (`shop.items`,
2485    /// `shop.ui.slots.list`, `<service>.schema`): its shape hash
2486    /// ([`super::peer::Interface::method_hash`]) and its grant. Every
2487    /// registered activation, mounted child, static child and typed slot's
2488    /// method; `None` for anything else.
2489    pub fn method_at(&self, path: &str) -> Option<(String, String)> {
2490        let own = Activation::plugin_schema(self);
2491        if let Some(m) = path.strip_prefix(&format!("{}.", self.inner.namespace)).and_then(|m| own.methods.iter().find(|x| x.name == m)) {
2492            return Some((super::peer::Interface::method_hash(m), path.to_string()));
2493        }
2494        let (at, name) = path.rsplit_once('.')?;
2495        let activations: Vec<PluginSchema> = self.table().entries.values().map(|e| e.object.plugin_schema()).collect();
2496        let statics = self.static_children();
2497        let typed = self.slot_children().0;
2498        activations
2499            .iter()
2500            .chain(statics.iter())
2501            .chain(typed.iter())
2502            .filter(|s| s.namespace == at)
2503            .flat_map(|s| s.methods.iter().map(move |m| (s, m)))
2504            .find(|(_, m)| m.name == name && matches!(m.role, super::schema::MethodRole::Rpc))
2505            .map(|(s, m)| (super::peer::Interface::method_hash(m), m.grant_or(&s.namespace)))
2506    }
2507
2508    /// NEST-16: the grant the gate holds a call to `path` to (its index's,
2509    /// kept until the service changes).
2510    pub(crate) fn grant_at(&self, path: &str) -> Option<String> {
2511        self.gate_index().info(path).and_then(|i| i.grant.clone())
2512    }
2513
2514    /// NEST-16: check a graft's `needs` against what this service serves,
2515    /// each by its shape hash.
2516    pub fn check_needs(&self, child: &str, needs: &[super::schema::Need]) -> Result<(), super::parent::NeedsMiss> {
2517        // A need below an untyped slot (`dyn.peer.w.weather.forecast`) is
2518        // reachable when the slot is; its shape is the peer's, unknown here.
2519        super::parent::check_needs(child, &self.inner.namespace, needs, |p| {
2520            self.method_at(p).map(|(h, _)| h).or_else(|| self.gate_index().slots.resolve(p).map(|_| String::new()))
2521        })
2522    }
2523
2524    /// NEST-16: check every entry that declares `needs` against the rest of
2525    /// the service — what serving a service does first (a static graft whose
2526    /// parent is not there is refused before anything is served).
2527    pub fn check_grafts(&self) -> Result<(), Vec<super::parent::NeedsMiss>> {
2528        let misses: Vec<_> = self
2529            .table()
2530            .entries
2531            .iter()
2532            .filter_map(|(name, e)| e.object.needs().map(|n| (name.clone(), n)))
2533            .filter_map(|(name, needs)| self.check_needs(&name, &needs).err())
2534            .collect();
2535        if misses.is_empty() { Ok(()) } else { Err(misses) }
2536    }
2537
2538    /// NEST-15: stop serving `name`; answers whether it was served.
2539    pub(crate) fn remove_entry(&self, name: &str) -> bool {
2540        let before = self.compute_hash();
2541        let gone = self.change_table(|table| {
2542            let old = table.entries.remove(name);
2543            if let Some(old) = old.as_ref() {
2544                table.nested -= old.object.static_child_schemas().len();
2545            }
2546            old
2547        });
2548        let Some(old) = gone else { return false };
2549        self.inner.registry.write().unwrap_or_else(|p| p.into_inner()).remove(old.object.plugin_id());
2550        if let Some(catalog) = self.inner.auth_catalog.as_ref() {
2551            catalog.remove_under(name);
2552        }
2553        self.table_moved(before);
2554        true
2555    }
2556
2557    /// One change of the root's table, made on a copy and swapped in.
2558    fn change_table<R>(&self, change: impl FnOnce(&mut super::service_root::Table) -> R) -> R {
2559        let mut root = self.inner.root.write().unwrap_or_else(|p| p.into_inner());
2560        let mut table = (**root).clone();
2561        let out = change(&mut table);
2562        *root = Arc::new(table);
2563        out
2564    }
2565
2566    /// NEST-15: the root's table changed while the service serves: what was
2567    /// described and indexed is dropped, the service's hash moves — in the
2568    /// `plexus_hash` items carry when it was this service's — and watchers
2569    /// are told.
2570    fn table_moved(&self, before: String) {
2571        *self.inner.gate_index.write().unwrap_or_else(|p| p.into_inner()) = None;
2572        *self.inner.input_index.write().unwrap_or_else(|p| p.into_inner()) = None;
2573        self.inner.describe.schema_moved();
2574        let after = self.compute_hash();
2575        PlexusContext::moved(&before, &after);
2576        self.inner.root_watch.send_replace(after);
2577    }
2578
2579    /// List all methods across all activations
2580    pub fn list_methods(&self) -> Vec<String> {
2581        let mut methods = Vec::new();
2582
2583        // Include hub's own methods
2584        for m in Activation::methods(self) {
2585            methods.push(format!("{}.{}", self.inner.namespace, m));
2586        }
2587
2588        // Include registered activation methods
2589        for (ns, e) in &self.table().entries {
2590            let act = &e.object;
2591            for m in act.methods() {
2592                methods.push(format!("{}.{}", ns, m));
2593            }
2594        }
2595        methods.sort();
2596        methods
2597    }
2598
2599    /// List all activations (including this hub itself)
2600    pub fn list_activations_info(&self) -> Vec<ActivationInfo> {
2601        let mut activations = Vec::new();
2602
2603        // Include this hub itself
2604        activations.push(ActivationInfo {
2605            namespace: Activation::namespace(self).to_string(),
2606            version: Activation::version(self).to_string(),
2607            description: Activation::description(self).to_string(),
2608            methods: Activation::methods(self).iter().map(|s| s.to_string()).collect(),
2609        });
2610
2611        // Include registered activations
2612        for e in self.table().entries.values() {
2613            let a = &e.object;
2614            activations.push(ActivationInfo {
2615                namespace: a.namespace().to_string(),
2616                version: a.version().to_string(),
2617                description: a.description().to_string(),
2618                methods: a.methods().iter().map(|s| s.to_string()).collect(),
2619            });
2620        }
2621
2622        activations
2623    }
2624
2625    /// Compute hash for cache invalidation
2626    ///
2627    /// Returns the hash from the recursive plugin schema. This hash changes
2628    /// whenever any method definition or child plugin changes — and,
2629    /// PERF-21, only then: the children are listed by namespace, so every
2630    /// start of the same build computes the same hash (the `plexus_hash`
2631    /// every item carries, [`PlexusContext::init`]).
2632    pub fn compute_hash(&self) -> String {
2633        // PERF-15: from what the service describes, kept per schema generation.
2634        self.described().service.hash.clone()
2635    }
2636
2637    /// PERF-15: the service's own `hash` answer for `caller` — the caller's
2638    /// view's on a gated service (AUTH-4), the service's own otherwise —
2639    /// from the cache.
2640    fn own_hash(&self, caller: Option<&super::auth::AuthContext>) -> String {
2641        match self.inner.gate {
2642            Some(_) => self.shaped(caller).1.hash.clone(),
2643            None => self.described().service.hash.clone(),
2644        }
2645    }
2646
2647    /// PERF-15: the service's own schema as `caller` sees it — the
2648    /// `{ns}.schema` answer before its site hints — from the cache.
2649    fn own_schema(&self, caller: Option<&super::auth::AuthContext>) -> PluginSchema {
2650        match self.inner.gate {
2651            Some(_) => self.shaped(caller).1.service.clone(),
2652            None => self.described().service.clone(),
2653        }
2654    }
2655
2656    /// Route a call to the appropriate activation
2657    pub async fn route(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>) -> Result<PlexusStream, PlexusError> {
2658        self.route_with_ctx(method, params, auth, None).await
2659    }
2660
2661    /// Route a call to the appropriate activation, with optional raw HTTP request context.
2662    ///
2663    /// NEST-11: the call is routed knowing its service — the outermost
2664    /// service a call entered — so a child mounted below it
2665    /// ([`RemoteChild`](super::RemoteChild)) can take the calls its far side
2666    /// makes back under a forwarded call through this service's own routing
2667    /// and gate ([`super::service_scope`]).
2668    pub async fn route_with_ctx(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
2669        if super::service_scope::entered() {
2670            return self.route_entered(method, params, auth, raw_ctx).await;
2671        }
2672        super::service_scope::scope(self.downgrade(), self.route_entered(method, params, auth, raw_ctx)).await
2673    }
2674
2675    /// NEST-11: a weak handle to this service — what a child mounted below
2676    /// it keeps, so a child never keeps its service alive.
2677    pub fn downgrade(&self) -> super::service_scope::WeakService {
2678        super::service_scope::WeakService::new(Arc::downgrade(&self.inner))
2679    }
2680
2681    /// NEST-11: a schema the service answers for one of its own children
2682    /// outside any call (a child asking, at its start, for the shape of what
2683    /// it will call): the service's whole description at `method` (a
2684    /// `….schema` path), as the service itself sees it — no caller's view.
2685    pub(crate) async fn schema_for_child(&self, method: &str, params: Value) -> Result<PlexusStream, PlexusError> {
2686        let (_, name) = self.parse_method(method)?;
2687        if !Self::is_schema_query(name) {
2688            return Err(PlexusError::Unauthenticated(format!(
2689                "`{method}` is not a schema: outside a call, a child asks its service only for a schema"
2690            )));
2691        }
2692        let ctx = crate::call::CallContext::admitted(None, plexus_auth_core::grants::Reach::everywhere());
2693        let routed = self.route_ungated(method, params, None, None);
2694        super::service_scope::scope(self.downgrade(), in_call(ctx, routed)).await
2695    }
2696
2697    /// [`DynamicHub::route_with_ctx`], inside its service's scope.
2698    async fn route_entered(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
2699        // AUTH-2 grant gate: only when configured — a hub without one pays
2700        // this one branch and dispatches as before.
2701        if let Some(gate) = self.inner.gate.as_ref() {
2702            // AUTH-11: a sign-in that ended proves no one, on every method.
2703            let (auth, ended) = super::grant_gate::standing(gate, auth);
2704            let decide = |info| super::grant_gate::decide(gate, &self.inner.namespace, method, info, &params, auth, &self.inner.signed_in_grants);
2705            let index = self.gate_index();
2706            let admit = match index.methods.get(method) {
2707                Some(info) => decide(Some(info)),
2708                // NEST-5: a path through a slot is decided on the slot's
2709                // grant; a grant written as its literal path still decides
2710                // first (the slot grant is additive).
2711                None => match index.info(method) {
2712                    Some(slot) => decide(None).or_else(|_| decide(Some(slot))),
2713                    None => decide(None),
2714                },
2715            }
2716            .map_err(|e| super::grant_gate::say_ended(e, ended.as_deref()))?;
2717            return match admit {
2718                // AUTH-4: introspection answers from the caller's view.
2719                // RETURNS-47: in a context too — the caller's reach for the
2720                // path, as the gate gives a public method's — never none.
2721                super::grant_gate::Admit::Open => {
2722                    let grant = plexus_auth_core::grants::Grant::new(method.to_string());
2723                    in_call(crate::call::CallContext::introspection(auth, Arc::clone(gate), grant), async {
2724                        match self.introspect_in_view(method, &params, auth, raw_ctx).await {
2725                            Some(answer) => answer,
2726                            None => self.route_ungated(method, params, auth, raw_ctx).await,
2727                        }
2728                    })
2729                    .await
2730                }
2731                super::grant_gate::Admit::Reach(reach) => {
2732                    in_call(crate::call::CallContext::admitted(auth, reach), self.route_ungated(method, params, auth, raw_ctx)).await
2733                }
2734            };
2735        }
2736        // RETURNS-47: no gate — the call is admitted everywhere, said here
2737        // rather than assumed by `current_reach` (which fails closed). A
2738        // service without a gate reached from inside a call (a nested
2739        // service, a method calling its parent) keeps that call's reach and
2740        // hop, as the task-local reach always carried through, with this
2741        // call's identity.
2742        let ctx = match crate::call::context() {
2743            Ok(outer) => outer.with_auth(auth),
2744            Err(_) => crate::call::CallContext::admitted(auth, plexus_auth_core::grants::Reach::everywhere()),
2745        };
2746        in_call(ctx, self.route_ungated(method, params, auth, raw_ctx)).await
2747    }
2748
2749    /// Everything [`DynamicHub::route_with_ctx`] does after the grant gate.
2750    async fn route_ungated(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
2751        // R-5 scope gate (AUTHZ-CORE-1 + CORE-5). Inactive unless a
2752        // ScopeRegistry is configured or default_deny is set — a hub with
2753        // neither pays exactly this one branch and dispatches as before
2754        // the gate existed (the hard backward-safety constraint).
2755        if self.inner.scope_registry.is_some() || self.inner.default_deny {
2756            let registry = self
2757                .inner
2758                .scope_registry
2759                .as_deref()
2760                .unwrap_or_else(|| super::scope_gate::empty_registry());
2761            super::scope_gate::enforce(
2762                registry,
2763                self.inner.default_deny,
2764                &self.inner.audit_sink,
2765                method,
2766                self.gate_index().info(method),
2767                auth,
2768                raw_ctx.and_then(|ctx| ctx.peer.map(|peer| peer.ip())),
2769            )
2770            .await?;
2771        }
2772
2773        let (namespace, method_name) = self.parse_method(method)?;
2774
2775        // RETURNS-40 review #1: `ir`'s names, before any work
2776        if namespace == self.inner.namespace && method_name == "ir" {
2777            self.check_ir_names(&params, auth)?;
2778        }
2779
2780        // NEST-15: routing is `peer(name)` from the root down — the
2781        // service's own name answers the root itself (its `call`, `hash`,
2782        // `schema`, `ir`), every other name the root's table; the entry
2783        // routes the rest of the path below it.
2784        let stream = if namespace == self.inner.namespace {
2785            Activation::call(self, method_name, params, auth, raw_ctx).await?
2786        } else {
2787            let entry = self.table().entries.get(namespace).map(|e| e.object.clone())
2788                .ok_or_else(|| PlexusError::ActivationNotFound(namespace.to_string()))?;
2789
2790            entry.call(method_name, params, auth, raw_ctx).await?
2791        };
2792
2793        // CA-1 (trak facet ccc924ad): schema responses leaving this hub get
2794        // their `requires_credential.site_hint` filled from the backend's
2795        // advertised auth capabilities. Backends that never call
2796        // `with_auth_capabilities` (or advertise anonymous-only) derive no
2797        // site, and the stream passes through untouched — byte-identical to
2798        // pre-CA-1 emissions.
2799        if Self::is_schema_query(method_name) {
2800            if let Some(site) = self.derived_site_hint() {
2801                return Ok(fill_site_hints_in_schema_stream(stream, site));
2802            }
2803        }
2804        Ok(stream)
2805    }
2806
2807    /// Whether a routed `method_name` (the part after the first dot) is a
2808    /// schema query: `"schema"` (`<ns>.schema`, with or without a `method`
2809    /// param) or a nested `"<child...>.schema"` path routed into a child
2810    /// activation.
2811    fn is_schema_query(method_name: &str) -> bool {
2812        method_name == "schema" || method_name.ends_with(".schema")
2813    }
2814
2815    /// CA-1: the [`AttachmentSite`] implied by this backend's advertised
2816    /// auth capabilities, or `None` when no capabilities are configured or
2817    /// none of the advertised mechanisms implies a site.
2818    ///
2819    /// [`AttachmentSite`]: plexus_auth_core::AttachmentSite
2820    pub fn derived_site_hint(&self) -> Option<plexus_auth_core::AttachmentSite> {
2821        self.inner
2822            .auth_capabilities
2823            .as_ref()
2824            .and_then(|caps| caps.implied_attachment_site())
2825    }
2826
2827    /// Resolve a handle using the activation registry
2828    ///
2829    /// Looks up the activation by its UUID in the registry.
2830    pub async fn do_resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
2831        let path = self.inner.registry.read().unwrap()
2832            .lookup(handle.plugin_id)
2833            .map(|s| s.to_string())
2834            .ok_or_else(|| PlexusError::ActivationNotFound(handle.plugin_id.to_string()))?;
2835
2836        let activation = self.table().entries.get(&path).map(|e| e.object.clone())
2837            .ok_or_else(|| PlexusError::ActivationNotFound(path.clone()))?;
2838        activation.resolve_handle(handle).await
2839    }
2840
2841    /// Get activation schema
2842    pub fn get_activation_schema(&self, namespace: &str) -> Option<Schema> {
2843        self.table().entries.get(namespace).map(|e| e.object.schema())
2844    }
2845
2846    /// Get a snapshot of the activation registry (safe to use outside locks)
2847    pub fn registry_snapshot(&self) -> PluginRegistrySnapshot {
2848        let guard = self.inner.registry.read().unwrap();
2849        PluginRegistrySnapshot {
2850            by_id: guard.by_id.clone(),
2851            by_path: guard.by_path.clone(),
2852        }
2853    }
2854
2855    /// Look up an activation path by its UUID
2856    pub fn lookup_plugin(&self, id: uuid::Uuid) -> Option<String> {
2857        self.inner.registry.read().unwrap().lookup(id).map(|s| s.to_string())
2858    }
2859
2860    /// Look up an activation UUID by its path
2861    pub fn lookup_plugin_by_path(&self, path: &str) -> Option<uuid::Uuid> {
2862        self.inner.registry.read().unwrap().lookup_by_path(path)
2863    }
2864
2865    /// Get activation schemas for all activations (including this hub itself)
2866    pub fn list_plugin_schemas(&self) -> Vec<PluginSchema> {
2867        let mut schemas = Vec::new();
2868
2869        // Include this hub itself
2870        schemas.push(Activation::plugin_schema(self));
2871
2872        // Include registered activations
2873        for e in self.table().entries.values() {
2874            schemas.push(e.object.plugin_schema());
2875        }
2876
2877        schemas
2878    }
2879
2880    /// Deprecated: use list_plugin_schemas instead
2881    #[deprecated(note = "Use list_plugin_schemas instead")]
2882    pub fn list_full_schemas(&self) -> Vec<PluginSchema> {
2883        self.list_plugin_schemas()
2884    }
2885
2886    /// Get help for a method
2887    pub fn get_method_help(&self, method: &str) -> Option<String> {
2888        let (namespace, method_name) = self.parse_method(method).ok()?;
2889        let table = self.table();
2890        table.entries.get(namespace)?.object.method_help(method_name)
2891    }
2892
2893    fn parse_method<'a>(&self, method: &'a str) -> Result<(&'a str, &'a str), PlexusError> {
2894        let parts: Vec<&str> = method.splitn(2, '.').collect();
2895        if parts.len() != 2 {
2896            return Err(PlexusError::InvalidParams {
2897                param: Some("method".into()),
2898                problem: ParamProblem::Malformed {
2899                    detail: format!("expected `namespace.method`, got `{}`", method),
2900                },
2901            });
2902        }
2903        Ok((parts[0], parts[1]))
2904    }
2905
2906    /// Get child activation summaries: one per registered activation, in
2907    /// namespace order (PERF-21) — the service schema's `children`, which
2908    /// its `hash` and every caller's view hash digest in this order.
2909    /// Called by `#[plexus_macros::activation]` when its `hub` flag is set.
2910    pub fn plugin_children(&self) -> Vec<ChildSummary> {
2911        self.table().entries.values()
2912            .map(|e| {
2913                let schema = e.object.plugin_schema();
2914                ChildSummary {
2915                    namespace: schema.namespace,
2916                    description: schema.description,
2917                    hash: schema.hash,
2918                }
2919            })
2920            .collect()
2921    }
2922
2923    /// Convert to RPC module
2924    pub fn into_rpc_module(self) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
2925        let mut module = RpcModule::new(());
2926
2927        // NEST-16: a static graft whose parent's methods are not served
2928        // here, or moved, is refused before anything is served.
2929        if let Err(misses) = self.check_grafts() {
2930            panic!("{}", misses.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "));
2931        }
2932        PlexusContext::init(self.compute_hash());
2933
2934        // Register hub methods with runtime namespace using dot notation (e.g., "plexus.call" or "hub.call")
2935        // Note: we leak these strings to get 'static lifetime required by jsonrpsee
2936        let ns = self.runtime_namespace();
2937        let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
2938        let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
2939        let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2940        let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
2941        let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2942        let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
2943        let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2944        let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2945        let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
2946
2947        // Register {ns}.call subscription
2948        let plexus_for_call = self.clone();
2949        module.register_subscription(
2950            call_method,
2951            PLEXUS_NOTIF_METHOD,
2952            call_unsub,
2953            move |params, pending, _ctx, ext| {
2954                let plexus = plexus_for_call.clone();
2955                // AUTH-4: a gated hub reads the connection's identity (as
2956                // arc_into_rpc_module always has); a hub without a gate
2957                // dispatches anonymously here, as before.
2958                let identified = plexus.inner.gate.is_some();
2959                serve_call(plexus, params, pending, ext, ns_static, identified)
2960            }
2961        )?;
2962
2963        register_input_methods(&mut module, ns_static)?;
2964
2965        // Register {ns}.hash subscription
2966        let plexus_for_hash = self.clone();
2967        module.register_subscription(
2968            hash_method,
2969            PLEXUS_NOTIF_METHOD,
2970            hash_unsub,
2971            move |_params, pending, _ctx, ext| {
2972                let plexus = plexus_for_hash.clone();
2973                Box::pin(async move {
2974                    // AUTH-4: a gated hub's hash is the caller's view's.
2975                    let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2976                    let value = plexus.own_hash(auth);
2977                    let stream = async_stream::stream! {
2978                        yield HashEvent::Hash { value };
2979                    };
2980                    let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
2981                    pipe_stream_to_subscription(pending, wrapped, &ext).await
2982                })
2983            }
2984        )?;
2985
2986        // Register {ns}.schema subscription
2987        let plexus_for_schema = self.clone();
2988        module.register_subscription(
2989            schema_method,
2990            PLEXUS_NOTIF_METHOD,
2991            schema_unsub,
2992            move |params, pending, _ctx, ext| {
2993                let plexus = plexus_for_schema.clone();
2994                Box::pin(async move {
2995                    let p: SchemaParams = params.parse().unwrap_or_default();
2996                    // AUTH-4: a gated hub answers from the caller's view.
2997                    let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2998                    let mut plugin_schema = plexus.own_schema(auth);
2999                    // CA-1: hub-derived site hints on the hub's own schema.
3000                    if let Some(site) = plexus.derived_site_hint() {
3001                        plugin_schema.fill_site_hints(&site);
3002                    }
3003
3004                    let result = if let Some(ref name) = p.method {
3005                        plugin_schema.methods.iter()
3006                            .find(|m| m.name == *name)
3007                            .map(|m| super::SchemaResult::Method(m.clone()))
3008                            .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
3009                                -32602,
3010                                format!("Method '{}' not found", name),
3011                                None::<()>,
3012                            ))?
3013                    } else {
3014                        super::SchemaResult::Plugin(plugin_schema)
3015                    };
3016
3017                    let stream = async_stream::stream! { yield result; };
3018                    let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
3019                    pipe_stream_to_subscription(pending, wrapped, &ext).await
3020                })
3021            }
3022        )?;
3023
3024        // Register _info well-known endpoint (no namespace prefix).
3025        // Returns backend name + auth_capabilities (AUTHZ-CORE-3) as a
3026        // single-item stream with automatic Done event. Backends that have not
3027        // called with_auth_capabilities get the anonymous-default fallback so
3028        // capability-aware clients can still discover the auth surface.
3029        let info_payload = build_info_payload(
3030            self.runtime_namespace(),
3031            self.inner.auth_capabilities.as_ref(),
3032        );
3033        // AUTH-4: a gated hub answers `_info` per caller; without a gate the
3034        // payload is built once, as before.
3035        let plexus_for_info = self.inner.gate.is_some().then(|| self.clone());
3036        module.register_subscription(
3037            "_info",
3038            PLEXUS_NOTIF_METHOD,
3039            "_info_unsub",
3040            move |_params, pending, _ctx, ext| {
3041                let payload = match plexus_for_info.as_ref() {
3042                    Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
3043                    None => info_payload.clone(),
3044                };
3045                Box::pin(async move {
3046                    // Create a single-item stream with the info response
3047                    let info_stream = futures::stream::once(async move { payload });
3048
3049                    // Wrap to auto-append Done event
3050                    let wrapped = super::streaming::wrap_stream(
3051                        info_stream,
3052                        "_info",
3053                        vec![]
3054                    );
3055
3056                    // Pipe to subscription (handles Done automatically)
3057                    pipe_stream_to_subscription(pending, wrapped, &ext).await
3058                })
3059            }
3060        )?;
3061
3062        // Add all registered activation RPC methods — unless a grant gate
3063        // is set (AUTH-2): those direct methods carry no auth and would pass
3064        // around it, so a gated hub is reached only through `<ns>.call`.
3065        let pending = std::mem::take(&mut *self.inner.pending_rpc.lock().unwrap());
3066        if self.inner.gate.is_none() {
3067            for factory in pending {
3068                module.merge(factory())?;
3069            }
3070        }
3071
3072        // CHILD-WIRE: for each registered child router with capability bits set,
3073        // register {ns}.list_children / {ns}.search_children as subscriptions.
3074        // Per-activation namespaced (not top-level _list_children).
3075        for (ns, e) in self.table().entries.iter() {
3076            register_child_capability_methods(&mut module, ns, e.router.clone(), self.inner.gate.clone())?;
3077        }
3078
3079        Ok(module)
3080    }
3081
3082    /// V2-57: serve one `{ns}.call` exactly as this service's own `{ns}.call`
3083    /// does: routed as the connection's caller (the `AuthContext` the upgrade
3084    /// put in `ext`), a method with an `Input` taking its input half from
3085    /// `pending` (BIDIR-6), each item piped, a dispatch error sent as an
3086    /// item. For a host that registers `{ns}.call` itself to check its own
3087    /// limits first (menger's call layer): it removes the module's
3088    /// `{ns}.call`, registers its own, and hands each call it admits here.
3089    /// Routing with [`route`](Self::route) instead runs outside the call's
3090    /// seam, so an `Input` method answers that the transport carries none.
3091    /// `ns` is the service's runtime namespace, the error items' source.
3092    pub fn serve_call(
3093        &self,
3094        params: jsonrpsee::types::Params<'static>,
3095        pending: jsonrpsee::PendingSubscriptionSink,
3096        ext: http::Extensions,
3097        ns: &'static str,
3098    ) -> std::pin::Pin<Box<dyn std::future::Future<Output = jsonrpsee::core::SubscriptionResult> + Send>> {
3099        serve_call(self.clone(), params, pending, ext, ns, true)
3100    }
3101
3102    /// Convert Arc<DynamicHub> to RPC module while keeping the Arc alive
3103    ///
3104    /// Unlike `into_rpc_module`, this keeps the Arc<DynamicHub> reference alive,
3105    /// which is necessary when activations hold Weak<DynamicHub> references that
3106    /// need to remain upgradeable.
3107    pub fn arc_into_rpc_module(hub: Arc<Self>) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
3108        let mut module = RpcModule::new(());
3109
3110        // NEST-16: a static graft whose parent's methods are not served
3111        // here, or moved, is refused before anything is served.
3112        if let Err(misses) = hub.check_grafts() {
3113            panic!("{}", misses.iter().map(ToString::to_string).collect::<Vec<_>>().join("; "));
3114        }
3115        PlexusContext::init(hub.compute_hash());
3116
3117        // Register hub methods with runtime namespace using dot notation (e.g., "plexus.call" or "hub.call")
3118        // Note: we leak these strings to get 'static lifetime required by jsonrpsee
3119        let ns = hub.runtime_namespace();
3120        let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
3121        let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
3122        let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
3123        let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
3124        let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
3125        let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
3126        let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
3127        let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
3128        let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
3129
3130        // Register {ns}.call subscription - clone Arc to keep reference alive
3131        let hub_for_call = hub.clone();
3132        module.register_subscription(
3133            call_method,
3134            call_method,
3135            call_unsub,
3136            move |params, pending, _ctx, ext| {
3137                let hub = hub_for_call.clone();
3138                let hub = (*hub).clone();
3139                serve_call(hub, params, pending, ext, ns_static, true)
3140            }
3141        )?;
3142
3143        register_input_methods(&mut module, ns_static)?;
3144
3145        // Register {ns}.hash subscription
3146        let hub_for_hash = hub.clone();
3147        module.register_subscription(
3148            hash_method,
3149            PLEXUS_NOTIF_METHOD,
3150            hash_unsub,
3151            move |_params, pending, _ctx, ext| {
3152                let hub = hub_for_hash.clone();
3153                Box::pin(async move {
3154                    // AUTH-4: a gated hub's hash is the caller's view's.
3155                    let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
3156                    let value = hub.own_hash(auth);
3157                    let stream = async_stream::stream! {
3158                        yield HashEvent::Hash { value };
3159                    };
3160                    let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
3161                    pipe_stream_to_subscription(pending, wrapped, &ext).await
3162                })
3163            }
3164        )?;
3165
3166        // Register {ns}.schema subscription
3167        let hub_for_schema = hub.clone();
3168        module.register_subscription(
3169            schema_method,
3170            PLEXUS_NOTIF_METHOD,
3171            schema_unsub,
3172            move |params, pending, _ctx, ext| {
3173                let hub = hub_for_schema.clone();
3174                Box::pin(async move {
3175                    let p: SchemaParams = params.parse().unwrap_or_default();
3176                    // AUTH-4: a gated hub answers from the caller's view.
3177                    let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
3178                    let mut plugin_schema = hub.own_schema(auth);
3179                    // CA-1: hub-derived site hints on the hub's own schema.
3180                    if let Some(site) = hub.derived_site_hint() {
3181                        plugin_schema.fill_site_hints(&site);
3182                    }
3183
3184                    let result = if let Some(ref name) = p.method {
3185                        plugin_schema.methods.iter()
3186                            .find(|m| m.name == *name)
3187                            .map(|m| super::SchemaResult::Method(m.clone()))
3188                            .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
3189                                -32602,
3190                                format!("Method '{}' not found", name),
3191                                None::<()>,
3192                            ))?
3193                    } else {
3194                        super::SchemaResult::Plugin(plugin_schema)
3195                    };
3196
3197                    let stream = async_stream::stream! {
3198                        yield result;
3199                    };
3200                    let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
3201                    pipe_stream_to_subscription(pending, wrapped, &ext).await
3202                })
3203            }
3204        )?;
3205
3206        // Register _info well-known endpoint (no namespace prefix).
3207        // Returns backend name + auth_capabilities (AUTHZ-CORE-3) as a
3208        // single-item stream with automatic Done event. Same payload shape as
3209        // the sibling registration in into_rpc_module.
3210        let info_payload = build_info_payload(
3211            hub.runtime_namespace(),
3212            hub.inner.auth_capabilities.as_ref(),
3213        );
3214        // AUTH-4: a gated hub answers `_info` per caller; without a gate the
3215        // payload is built once, as before.
3216        let hub_for_info = hub.inner.gate.is_some().then(|| hub.clone());
3217        module.register_subscription(
3218            "_info",
3219            PLEXUS_NOTIF_METHOD,
3220            "_info_unsub",
3221            move |_params, pending, _ctx, ext| {
3222                let payload = match hub_for_info.as_ref() {
3223                    Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
3224                    None => info_payload.clone(),
3225                };
3226                Box::pin(async move {
3227                    // Create a single-item stream with the info response
3228                    let info_stream = futures::stream::once(async move { payload });
3229
3230                    // Wrap to auto-append Done event
3231                    let wrapped = super::streaming::wrap_stream(
3232                        info_stream,
3233                        "_info",
3234                        vec![]
3235                    );
3236
3237                    // Pipe to subscription (handles Done automatically)
3238                    pipe_stream_to_subscription(pending, wrapped, &ext).await
3239                })
3240            }
3241        )?;
3242
3243        // Register pending RPC methods from activations
3244        // AUTH-2: not under a grant gate — see `into_rpc_module`.
3245        let mut pending = std::mem::take(&mut *hub.inner.pending_rpc.lock().unwrap());
3246        if hub.inner.gate.is_some() {
3247            pending.clear();
3248        }
3249        tracing::trace!(factories = pending.len(), "merging activation RPC factories");
3250        for (idx, factory) in pending.into_iter().enumerate() {
3251            tracing::trace!(factory_idx = idx, "calling factory to get Methods");
3252            let methods = factory();
3253            let method_count = methods.method_names().count();
3254            tracing::trace!(factory_idx = idx, methods = method_count, "factory returned Methods; merging into module");
3255            module.merge(methods)?;
3256            tracing::trace!(factory_idx = idx, "successfully merged factory methods");
3257        }
3258        tracing::trace!("all activations merged successfully");
3259
3260        // CHILD-WIRE: for each registered child router with capability bits set,
3261        // register {ns}.list_children / {ns}.search_children as subscriptions.
3262        for (ns, e) in hub.table().entries.iter() {
3263            register_child_capability_methods(&mut module, ns, e.router.clone(), hub.inner.gate.clone())?;
3264        }
3265
3266        Ok(module)
3267    }
3268}
3269
3270/// CHILD-WIRE: register per-activation namespaced `<ns>.list_children` and
3271/// `<ns>.search_children` as subscription methods when the router advertises
3272/// the corresponding capability bits.
3273///
3274/// Each name returned by `ChildRouter::list_children` / `search_children` is
3275/// emitted as a `data` envelope with `content_type` set to the method name
3276/// (`"list_children"` or `"search_children"`) and `content` carrying the name
3277/// string. Termination is `done`. Mirrors the standard `wrap_stream` shape
3278/// used by every other framework subscription.
3279///
3280/// Activations that advertise neither bit produce no registrations — calling
3281/// the methods returns standard `methodNotFound`. That's the wire-level
3282/// signal that the activation doesn't support enumeration / search.
3283/// RETURNS-47: the context a `{ns}.list_children` / `{ns}.search_children`
3284/// call runs in, so a dynamic child's list or search method reads its caller
3285/// as any method does: everywhere on a service without a gate; on a gated
3286/// one the caller's reach for the method's path, asked of the gate only if
3287/// read (as an introspection call's). These methods are not decided by the
3288/// gate (a gap of their own); the context only says who is asking.
3289fn listing_context(
3290    gate: Option<&Arc<plexus_auth_core::grants::Gate>>,
3291    ext: &jsonrpsee::Extensions,
3292    method: &str,
3293) -> crate::call::CallContext {
3294    let auth = ext.get::<Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
3295    match gate {
3296        None => crate::call::CallContext::admitted(auth, plexus_auth_core::grants::Reach::everywhere()),
3297        Some(gate) => {
3298            let (auth, _) = super::grant_gate::standing(gate, auth);
3299            crate::call::CallContext::introspection(auth, Arc::clone(gate), plexus_auth_core::grants::Grant::new(method.to_string()))
3300        }
3301    }
3302}
3303
3304#[allow(deprecated)] // ChildCapabilities is deprecated by IR-4 but still the wire-level signal
3305fn register_child_capability_methods(
3306    module: &mut RpcModule<()>,
3307    namespace: &str,
3308    router: Arc<dyn ChildRouter>,
3309    gate: Option<Arc<plexus_auth_core::grants::Gate>>,
3310) -> Result<(), jsonrpsee::core::RegisterMethodError> {
3311    let caps = router.capabilities();
3312    if caps.is_empty() {
3313        return Ok(());
3314    }
3315
3316    let ns_static: &'static str = Box::leak(namespace.to_string().into_boxed_str());
3317
3318    if caps.contains(ChildCapabilities::LIST) {
3319        let list_method: &'static str =
3320            Box::leak(format!("{}.list_children", namespace).into_boxed_str());
3321        let list_unsub: &'static str =
3322            Box::leak(format!("{}.list_children_unsub", namespace).into_boxed_str());
3323        let router_for_list = router.clone();
3324        let gate_for_list = gate.clone();
3325        module.register_subscription(
3326            list_method,
3327            PLEXUS_NOTIF_METHOD,
3328            list_unsub,
3329            move |_params, pending, _ctx, ext| {
3330                let router = router_for_list.clone();
3331                let ctx = listing_context(gate_for_list.as_ref(), &ext, list_method);
3332                Box::pin(async move {
3333                    // Collect names eagerly so the BoxStream's borrow on the
3334                    // router doesn't outlive list_children's call. For v1 this
3335                    // matches the typical pattern (small finite child sets like
3336                    // Solar's eight planets). A future variant could keep the
3337                    // Arc-borrow alive across the stream by binding the BoxStream
3338                    // to the Arc directly — out of scope here.
3339                    let collected: Vec<String> = crate::call::scope(ctx, async {
3340                        match router.list_children().await {
3341                            Some(mut s) => {
3342                                use futures::StreamExt;
3343                                let mut acc = Vec::new();
3344                                while let Some(name) = s.next().await {
3345                                    acc.push(name);
3346                                }
3347                                acc
3348                            }
3349                            None => Vec::new(),
3350                        }
3351                    })
3352                    .await;
3353                    let stream = async_stream::stream! {
3354                        for name in collected {
3355                            yield name;
3356                        }
3357                    };
3358                    let wrapped = super::streaming::wrap_stream(
3359                        stream,
3360                        "list_children",
3361                        vec![ns_static.into()],
3362                    );
3363                    pipe_stream_to_subscription(pending, wrapped, &ext).await
3364                })
3365            },
3366        )?;
3367    }
3368
3369    if caps.contains(ChildCapabilities::SEARCH) {
3370        let search_method: &'static str =
3371            Box::leak(format!("{}.search_children", namespace).into_boxed_str());
3372        let search_unsub: &'static str =
3373            Box::leak(format!("{}.search_children_unsub", namespace).into_boxed_str());
3374        let router_for_search = router.clone();
3375        let gate_for_search = gate.clone();
3376        module.register_subscription(
3377            search_method,
3378            PLEXUS_NOTIF_METHOD,
3379            search_unsub,
3380            move |params, pending, _ctx, ext| {
3381                let router = router_for_search.clone();
3382                let ctx = listing_context(gate_for_search.as_ref(), &ext, search_method);
3383                Box::pin(async move {
3384                    let p: SearchChildrenParams = params.parse()?;
3385                    let collected: Vec<String> = crate::call::scope(ctx, async {
3386                        match router.search_children(&p.query).await {
3387                            Some(mut s) => {
3388                                use futures::StreamExt;
3389                                let mut acc = Vec::new();
3390                                while let Some(name) = s.next().await {
3391                                    acc.push(name);
3392                                }
3393                                acc
3394                            }
3395                            None => Vec::new(),
3396                        }
3397                    })
3398                    .await;
3399                    let stream = async_stream::stream! {
3400                        for name in collected {
3401                            yield name;
3402                        }
3403                    };
3404                    let wrapped = super::streaming::wrap_stream(
3405                        stream,
3406                        "search_children",
3407                        vec![ns_static.into()],
3408                    );
3409                    pipe_stream_to_subscription(pending, wrapped, &ext).await
3410                })
3411            },
3412        )?;
3413    }
3414
3415    Ok(())
3416}
3417
3418/// Params for `<ns>.search_children`
3419#[derive(Debug, serde::Deserialize)]
3420struct SearchChildrenParams {
3421    query: String,
3422}
3423
3424/// Params for {ns}.call
3425#[derive(Debug, serde::Deserialize)]
3426pub(crate) struct CallParams {
3427    pub(crate) method: String,
3428    #[serde(default)]
3429    pub(crate) params: Option<Value>,
3430}
3431
3432/// BIDIR-6: [`DynamicHub::input_terms`]' answer.
3433pub(crate) struct InputTerms {
3434    pub(crate) grant: String,
3435    pub(crate) targets: Vec<String>,
3436    pub(crate) recheck: bool,
3437}
3438
3439/// Params for {ns}.schema (SYNAPSE-CC-9: the published type)
3440use super::schema::SchemaParams;
3441
3442/// `{ns}.call`: route the call, then pipe what it answers.
3443///
3444/// The call's future is boxed here, and is its one allocation of that size,
3445/// so it is chosen before it is made: a method the service knows has no
3446/// `Input` is routed and piped as it was before BIDIR-6,
3447/// holding nothing of the input half (the seam inline in one future for both
3448/// was 1,024 bytes more a call, and the params kept beside it 176 more);
3449/// any other ([`DynamicHub::may_take_input`]) is [`serve_seamed`]. A
3450/// dispatch error is sent as a stream item on the
3451/// accepted subscription: this preserves its message and code, where
3452/// returning it from a subscription handler has jsonrpsee wrap it as generic
3453/// -32603.
3454fn serve_call(
3455    service: DynamicHub,
3456    params: jsonrpsee::types::Params<'static>,
3457    pending: jsonrpsee::PendingSubscriptionSink,
3458    ext: http::Extensions,
3459    ns: &'static str,
3460    identified: bool,
3461) -> CallFuture {
3462    // Read here, not in the future: the choice of future is made on it, and
3463    // the plain one then holds neither the params' text nor the method name.
3464    let call: CallParams = match params.parse() {
3465        Ok(call) => call,
3466        Err(e) => return Box::pin(async move { Err(e.into()) }),
3467    };
3468    if service.may_take_input(&call.method) {
3469        return Box::pin(serve_seamed(service, call, params, pending, ext, ns, identified));
3470    }
3471    let CallParams { method, params: args } = call;
3472    Box::pin(async move {
3473        let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().map(|a| a.as_ref()) } else { None };
3474        match service.route(&method, args.unwrap_or_default(), caller).await {
3475            Ok(stream) => pipe_stream_to_subscription(pending, stream, &ext).await,
3476            Err(e) => {
3477                let sink = pending.accept().await?;
3478                if let Some(raw) = error_item_raw(ns, &e) {
3479                    let _ = sink.send(raw).await;
3480                }
3481                Ok(())
3482            }
3483        }
3484    })
3485}
3486
3487/// A `{ns}.call`'s future, boxed: one allocation a call, the size of the
3488/// path it takes.
3489type CallFuture = std::pin::Pin<Box<dyn std::future::Future<Output = jsonrpsee::core::SubscriptionResult> + Send>>;
3490
3491/// [`serve_call`] for a method that may take an `Input`: the route runs
3492/// inside [`super::input::CALL`], holding the unaccepted subscription and the
3493/// extensions, and a method with an `Input` parameter takes them there
3494/// (BIDIR-6); one without leaves them.
3495async fn serve_seamed(
3496    service: DynamicHub,
3497    call: CallParams,
3498    params: jsonrpsee::types::Params<'static>,
3499    pending: jsonrpsee::PendingSubscriptionSink,
3500    ext: http::Extensions,
3501    ns: &'static str,
3502    identified: bool,
3503) -> jsonrpsee::core::SubscriptionResult {
3504    let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().cloned() } else { None };
3505    let seen = service.inner.gate.as_ref().map_or(0, |g| g.generation().current());
3506    let opened = Arc::new(std::sync::Mutex::new(None::<super::input::Opened>));
3507    let take = || opened.lock().unwrap_or_else(|e| e.into_inner()).take();
3508    let mut scoped = std::pin::pin!(super::input::CALL.scope(
3509        std::cell::RefCell::new(super::input::Seam { service: service.clone(), params, pending: Some(pending), ext, seen, opened: opened.clone(), refused: None }),
3510        service.route(&call.method, call.params.unwrap_or_default(), caller.as_deref()),
3511    ));
3512    // The route runs until it answers, or until the method has opened its
3513    // input half: a handler may read its input before it returns its stream,
3514    // so from the open the pipe runs (credit, items, cancel) beside the
3515    // route still resolving.
3516    let answered = std::future::poll_fn(|cx| match std::future::Future::poll(scoped.as_mut(), cx) {
3517        std::task::Poll::Ready(answer) => std::task::Poll::Ready(Some(answer)),
3518        std::task::Poll::Pending if opened.lock().unwrap_or_else(|e| e.into_inner()).is_some() => std::task::Poll::Ready(None),
3519        std::task::Poll::Pending => std::task::Poll::Pending,
3520    })
3521    .await;
3522    let Some(answer) = answered else {
3523        let super::input::Opened { sink, duplex } = take().expect("opened, the route still resolving");
3524        let mut routing = std::pin::pin!(async { scoped.as_mut().await.map_err(|e| error_item(ns, &e)) });
3525        return Box::pin(super::wire::pipe_duplex(sink, super::wire::Output::Routing(routing.as_mut()), duplex)).await;
3526    };
3527    let super::input::Seam { pending, ext, refused, .. } = scoped.as_mut().take_value().expect("the scope ran to its end").into_inner();
3528    match (answer, take()) {
3529        // Boxed: a call with no input half does not carry its room.
3530        (Ok(stream), Some(opened)) => Box::pin(super::wire::pipe_duplex(opened.sink, super::wire::Output::Ready(stream), opened.duplex)).await,
3531        (Ok(stream), None) => {
3532            let pending = pending.expect("only an open takes it, and an open is `opened`");
3533            pipe_stream_to_subscription(pending, stream, &ext).await
3534        }
3535        (Err(e), opened) => {
3536            let sink = match (opened, pending) {
3537                (Some(opened), _) => opened.sink,
3538                (None, Some(pending)) => pending.accept().await?,
3539                (None, None) => return Ok(()),
3540            };
3541            let raw = match refused {
3542                Some(item) => serde_json::value::to_raw_value(&item).ok(),
3543                None => error_item_raw(ns, &e),
3544            };
3545            if let Some(raw) = raw {
3546                let _ = sink.send(raw).await;
3547            }
3548            Ok(())
3549        }
3550    }
3551}
3552
3553/// BIDIR-6: `{ns}.input` and `{ns}.end` in the method table, for a client
3554/// that sends them as requests and wants an answer (`true`: it reached the
3555/// call; `false`: a resend, or the half has closed). The notification, which
3556/// is what a client normally sends, is taken on the socket's reader before
3557/// the table. Sync methods, so a request is run in place, in order.
3558fn register_input_methods(module: &mut RpcModule<()>, ns: &'static str) -> Result<(), jsonrpsee::core::RegisterMethodError> {
3559    use super::input::{Delivered, InputTable};
3560    use jsonrpsee::types::ErrorObjectOwned;
3561
3562    fn answer(delivered: Delivered) -> Result<bool, ErrorObjectOwned> {
3563        match delivered {
3564            Delivered::Taken => Ok(true),
3565            Delivered::Dropped | Delivered::Refused => Ok(false),
3566            Delivered::NotThisCall => Err(ErrorObjectOwned::owned(
3567                -32003,
3568                "not_this_call: input comes from the connection that opened the call",
3569                Some(serde_json::json!({"error_kind": "not_this_call"})),
3570            )),
3571            Delivered::Malformed => Err(ErrorObjectOwned::owned(-32602, "invalid params: subscription, seq and items", None::<()>)),
3572        }
3573    }
3574    fn table(ext: &http::Extensions) -> Result<&Arc<InputTable>, ErrorObjectOwned> {
3575        ext.get::<super::wire::FrameSink>()
3576            .and_then(super::wire::FrameSink::inputs)
3577            .ok_or_else(|| ErrorObjectOwned::owned(-32601, "this transport carries no input half: call over a WebSocket", None::<()>))
3578    }
3579
3580    let input_method: &'static str = Box::leak(format!("{ns}.input").into_boxed_str());
3581    let end_method: &'static str = Box::leak(format!("{ns}.end").into_boxed_str());
3582    module.register_method(input_method, move |params, _ctx, ext| {
3583        let frame = bytes::Bytes::copy_from_slice(params.as_str().unwrap_or("null").as_bytes());
3584        answer(table(ext)?.input(ns, &frame, &frame))
3585    })?;
3586    module.register_method(end_method, move |params, _ctx, ext| answer(table(ext)?.end(ns, params.as_str().unwrap_or("null").as_bytes())))?;
3587    Ok(())
3588}
3589
3590/// Pipe a call's stream to its subscription: accept it, then
3591/// [`super::wire::pipe`] — each item encoded once and written as one frame
3592/// (PERF-7), on the transport's own frames when the call's extensions
3593/// carry them.
3594///
3595/// Notifications are sent with the `notif_method_name` each
3596/// `register_subscription` call set.
3597///
3598/// The pipe watches the sink's close (an unsubscribe, a lost socket),
3599/// dropping the stream at once.
3600async fn pipe_stream_to_subscription(
3601    pending: jsonrpsee::PendingSubscriptionSink,
3602    stream: PlexusStream,
3603    ext: &http::Extensions,
3604) -> jsonrpsee::core::SubscriptionResult {
3605    let sink = pending.accept().await?;
3606    super::wire::pipe(sink, stream, ext).await
3607}
3608
3609// ============================================================================
3610// DynamicHub RPC Methods (via plexus-macros)
3611// ============================================================================
3612
3613#[plexus_macros::activation(
3614    namespace = "plexus",
3615    version = "1.0.0",
3616    description = "Central routing and introspection",
3617    hub,
3618    namespace_fn = "runtime_namespace"
3619)]
3620#[allow(deprecated)]
3621impl DynamicHub {
3622    /// Route a call to a registered activation
3623    #[plexus_macros::method(
3624        description = "Route a call to a registered activation",
3625        params(
3626            method = "The method to call (format: namespace.method)",
3627            params = "Parameters to pass to the method (optional, defaults to {})"
3628        )
3629    )]
3630    async fn call(
3631        &self,
3632        method: String,
3633        params: Option<Value>,
3634    ) -> impl Stream<Item = super::types::PlexusStreamItem> + Send + 'static {
3635        use super::context::PlexusContext;
3636        use super::types::{PlexusStreamItem, StreamMetadata};
3637
3638        let result = self.route(&method, params.unwrap_or_default(), None).await;
3639
3640        match result {
3641            Ok(plexus_stream) => {
3642                // Forward the routed stream directly - it already contains PlexusStreamItems
3643                plexus_stream
3644            }
3645            Err(e) => {
3646                // Return error as a PlexusStreamItem stream
3647                let metadata = StreamMetadata::new(
3648                    vec![self.inner.namespace.clone()],
3649                    PlexusContext::hash(),
3650                );
3651                Box::pin(futures::stream::once(async move {
3652                    PlexusStreamItem::from_plexus_error(metadata, &e, false)
3653                }))
3654            }
3655        }
3656    }
3657
3658    /// Get Plexus RPC server configuration hash (from the recursive schema)
3659    ///
3660    /// This hash changes whenever any method or child activation changes.
3661    /// It's computed from the method hashes rolled up through the schema tree.
3662    #[plexus_macros::method(description = "Get plexus configuration hash (from the recursive schema)\n\n This hash changes whenever any method or child plugin changes.\n It's computed from the method hashes rolled up through the schema tree.")]
3663    async fn hash(&self) -> impl Stream<Item = HashEvent> + Send + 'static {
3664        let schema = Activation::plugin_schema(self);
3665        stream! { yield HashEvent::Hash { value: schema.hash }; }
3666    }
3667
3668    /// Get plugin hashes for cache validation (lightweight alternative to full schema)
3669    #[plexus_macros::method(description = "Get plugin hashes for cache validation")]
3670    #[allow(deprecated)]
3671    async fn hashes(&self) -> impl Stream<Item = PluginHashes> + Send + 'static {
3672        let schema = Activation::plugin_schema(self);
3673
3674        stream! {
3675            yield PluginHashes {
3676                namespace: schema.namespace.clone(),
3677                self_hash: schema.self_hash.clone(),
3678                children_hash: schema.children_hash.clone(),
3679                hash: schema.hash.clone(),
3680                children: schema.children.as_ref().map(|kids| {
3681                    kids.iter()
3682                        .map(|c| ChildHashes {
3683                            namespace: c.namespace.clone(),
3684                            hash: c.hash.clone(),
3685                        })
3686                        .collect()
3687                }),
3688            };
3689        }
3690    }
3691
3692    /// RETURNS-40: the service's IR — IR 3.0, every type once and each
3693    /// method referring to them — of the namespaces asked (none: the whole
3694    /// service), as the caller sees the service. The one way to ask for
3695    /// several schemas; `<ns>.schema` answers one. Equal to what synapse
3696    /// builds from the same raw schemas.
3697    #[plexus_macros::method(
3698        description = "The service's IR (3.0): every type once, each method referring to them — of the namespaces asked, or the whole service",
3699        params(namespaces = "The namespaces (dotted paths) to describe; none: the whole service")
3700    )]
3701    async fn ir(
3702        &self,
3703        auth: Option<&super::auth::AuthContext>,
3704        namespaces: Option<Vec<String>>,
3705    ) -> Result<super::ir::ServiceIr, super::ir::IrError> {
3706        self.service_ir(&namespaces.unwrap_or_default(), auth).await
3707    }
3708
3709    // Note: schema() method is auto-generated by hub-macro for all activations
3710}
3711
3712// ============================================================================
3713// HubContext Implementation for Weak<DynamicHub>
3714// ============================================================================
3715
3716use super::hub_context::HubContext;
3717use std::sync::Weak;
3718
3719/// HubContext implementation for Weak<DynamicHub>
3720///
3721/// This enables activations to receive a weak reference to their parent DynamicHub,
3722/// allowing them to resolve handles and route calls through the hub without
3723/// creating reference cycles.
3724#[async_trait]
3725impl HubContext for Weak<DynamicHub> {
3726    async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
3727        let hub = self.upgrade().ok_or_else(|| {
3728            PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3729        })?;
3730        hub.do_resolve_handle(handle).await
3731    }
3732
3733    async fn call(&self, method: &str, params: serde_json::Value) -> Result<PlexusStream, PlexusError> {
3734        let hub = self.upgrade().ok_or_else(|| {
3735            PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3736        })?;
3737        hub.route(method, params, None).await
3738    }
3739
3740    fn is_valid(&self) -> bool {
3741        self.upgrade().is_some()
3742    }
3743}
3744
3745/// ChildRouter implementation for DynamicHub
3746///
3747/// This enables nested routing through registered activations.
3748/// e.g., hub.call("solar.mercury.info") routes to solar → mercury → info
3749#[async_trait]
3750impl ChildRouter for DynamicHub {
3751    fn router_namespace(&self) -> &str {
3752        &self.inner.namespace
3753    }
3754
3755    async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
3756        // DynamicHub routes via its registered activations
3757        // Method format: "activation.method" or "activation.child.method"
3758        self.route_with_ctx(method, params, auth, raw_ctx).await
3759    }
3760
3761    async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
3762        // Look up registered activations that implement ChildRouter
3763        self.table().entries.get(name).map(|e| e.router.clone())
3764            .map(|router| {
3765
3766                // Clone the Arc and wrap in Box for the trait object
3767                Box::new(ArcChildRouter(router.clone())) as Box<dyn ChildRouter>
3768            })
3769    }
3770
3771    /// AUTHLANG-3 — consult the hub's
3772    /// [`ForwardPolicyRegistry`](super::forward_registry::ForwardPolicyRegistry).
3773    fn forward_policy_for(
3774        &self,
3775        callee_ns: &str,
3776    ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
3777        self.inner.forward_policies.get(callee_ns)
3778    }
3779
3780    // `framework_stamped_principal` retains the trait default
3781    // (`Principal::Anonymous`) for now. AUTHLANG-3 wires the dispatch path
3782    // to read this; populating it with the per-connection stamp lands
3783    // when the principal-minting service (post-AUTHZ-0 / future
3784    // CRED-CORE) is wired into the WS upgrade path. The current
3785    // anonymous return value is correct under today's no-auth substrate.
3786}
3787
3788#[cfg(test)]
3789#[allow(deprecated)]
3790mod tests {
3791    use super::*;
3792
3793    #[test]
3794    fn dynamic_hub_implements_activation() {
3795        fn assert_activation<T: Activation>() {}
3796        assert_activation::<DynamicHub>();
3797    }
3798
3799    #[test]
3800    fn dynamic_hub_methods() {
3801        let hub = DynamicHub::new("test");
3802        let methods = hub.methods();
3803        assert!(methods.contains(&"call"));
3804        assert!(methods.contains(&"hash"));
3805        assert!(methods.contains(&"schema"));
3806        // list_activations was removed - use schema() instead
3807    }
3808
3809    #[test]
3810    fn dynamic_hub_hash_stable() {
3811        let h1 = DynamicHub::new("test");
3812        let h2 = DynamicHub::new("test");
3813        assert_eq!(h1.compute_hash(), h2.compute_hash());
3814    }
3815
3816    #[test]
3817    fn dynamic_hub_is_hub() {
3818        use crate::activations::health::Health;
3819        let hub = DynamicHub::new("test").register(Health::new());
3820        let schema = hub.plugin_schema();
3821
3822        // DynamicHub should be a hub (has children)
3823        assert!(schema.is_hub(), "dynamic hub should be a hub");
3824        assert!(!schema.is_leaf(), "dynamic hub should not be a leaf");
3825
3826        // Should have children (as summaries)
3827        let children = schema.children.expect("dynamic hub should have children");
3828        assert!(!children.is_empty(), "dynamic hub should have at least one child");
3829
3830        // Health should be in the children summaries
3831        let health = children.iter().find(|c| c.namespace == "health").expect("should have health child");
3832        assert!(!health.hash.is_empty(), "health should have a hash");
3833    }
3834
3835    /// Z2H-8 / HOSTLESS-3 — a hub root that shares its name with a registered
3836    /// activation's namespace is rejected loudly at registration time instead
3837    /// of producing a silently unreachable child (the shipped echo example's
3838    /// exact failure shape).
3839    #[test]
3840    #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3841    fn dynamic_hub_rejects_root_namespace_shadow() {
3842        use crate::activations::health::Health;
3843        let _hub = DynamicHub::new("health").register(Health::new());
3844    }
3845
3846    /// Z2H-8 / HOSTLESS-3 — the deprecated register_hub path enforces the
3847    /// same collision contract.
3848    #[test]
3849    #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3850    fn dynamic_hub_register_hub_rejects_root_namespace_shadow() {
3851        use crate::activations::health::Health;
3852        let _hub = DynamicHub::new("health").register_hub(Health::new());
3853    }
3854
3855    /// Z2H-8 — the shadow error names both colliding strings and suggests the
3856    /// fix (rename the hub root), so the failure is actionable without
3857    /// reading plexus-core source.
3858    #[test]
3859    fn dynamic_hub_shadow_error_names_collision_and_fix() {
3860        use crate::activations::health::Health;
3861        let result = std::panic::catch_unwind(|| {
3862            let _hub = DynamicHub::new("health").register(Health::new());
3863        });
3864        let err = result.expect_err("shadow registration must panic");
3865        let msg = err
3866            .downcast_ref::<String>()
3867            .cloned()
3868            .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
3869            .expect("panic payload should be a string");
3870        assert!(msg.contains("'health'"), "must name the colliding namespace: {msg}");
3871        assert!(msg.contains("hub root namespace"), "must name the root side: {msg}");
3872        assert!(msg.contains("rename the hub root"), "must suggest the fix: {msg}");
3873        assert!(msg.contains("Z2H-8"), "must cite the ticket: {msg}");
3874    }
3875
3876    /// Z2H-8 — non-colliding registration is unaffected by shadow detection:
3877    /// the child registers, routes, and appears in the schema.
3878    #[test]
3879    fn dynamic_hub_non_colliding_registration_unaffected() {
3880        use crate::activations::health::Health;
3881        let hub = DynamicHub::new("health_hub").register(Health::new());
3882        assert_eq!(hub.runtime_namespace(), "health_hub");
3883        let schema = hub.plugin_schema();
3884        let children = schema.children.expect("hub should have children");
3885        assert!(
3886            children.iter().any(|c| c.namespace == "health"),
3887            "health child must be registered"
3888        );
3889        assert!(hub.list_methods().iter().any(|m| m.starts_with("health.")));
3890    }
3891
3892    #[test]
3893    fn dynamic_hub_schema_structure() {
3894        use crate::activations::health::Health;
3895        let hub = DynamicHub::new("test").register(Health::new());
3896        let schema = hub.plugin_schema();
3897
3898        // Pretty print the schema
3899        let json = serde_json::to_string_pretty(&schema).unwrap();
3900        println!("DynamicHub schema:\n{}", json);
3901
3902        // Verify structure
3903        assert_eq!(schema.namespace, "test");
3904        assert!(schema.methods.iter().any(|m| m.name == "call"));
3905        assert!(schema.children.is_some());
3906    }
3907
3908    // ========================================================================
3909    // INVARIANT: Handle routing - resolves to correct plugin
3910    // ========================================================================
3911
3912    #[tokio::test]
3913    async fn invariant_resolve_handle_unknown_activation() {
3914        use crate::activations::health::Health;
3915        use crate::types::Handle;
3916        use uuid::Uuid;
3917
3918        let hub = DynamicHub::new("test").register(Health::new());
3919
3920        // Handle for an unregistered activation (random UUID)
3921        let unknown_plugin_id = Uuid::new_v4();
3922        let handle = Handle::new(unknown_plugin_id, "1.0.0", "some_method");
3923
3924        let result = hub.do_resolve_handle(&handle).await;
3925
3926        match result {
3927            Err(PlexusError::ActivationNotFound(_)) => {
3928                // Expected - activation not found
3929            }
3930            Err(other) => panic!("Expected ActivationNotFound, got {:?}", other),
3931            Ok(_) => panic!("Expected error for unknown activation"),
3932        }
3933    }
3934
3935    #[tokio::test]
3936    async fn invariant_resolve_handle_unsupported() {
3937        use crate::activations::health::Health;
3938        use crate::types::Handle;
3939
3940        let hub = DynamicHub::new("test").register(Health::new());
3941
3942        // Handle for health activation (which doesn't support handle resolution)
3943        let handle = Handle::new(Health::PLUGIN_ID, "1.0.0", "check");
3944
3945        let result = hub.do_resolve_handle(&handle).await;
3946
3947        match result {
3948            Err(PlexusError::HandleNotSupported(name)) => {
3949                assert_eq!(name, "health");
3950            }
3951            Err(other) => panic!("Expected HandleNotSupported, got {:?}", other),
3952            Ok(_) => panic!("Expected error for unsupported handle"),
3953        }
3954    }
3955
3956    #[tokio::test]
3957    async fn invariant_resolve_handle_routes_by_plugin_id() {
3958        use crate::activations::health::Health;
3959        use crate::activations::echo::EchoActivation;
3960        use crate::types::Handle;
3961        use uuid::Uuid;
3962
3963        let health = Health::new();
3964        let echo = EchoActivation::new();
3965        let health_plugin_id = health.plugin_id();
3966        let echo_plugin_id = echo.plugin_id();
3967
3968        let hub = DynamicHub::new("test")
3969            .register(health)
3970            .register(echo);
3971
3972        // Health handle → health activation
3973        let health_handle = Handle::new(health_plugin_id, "1.0.0", "check");
3974        match hub.do_resolve_handle(&health_handle).await {
3975            Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "health"),
3976            Err(other) => panic!("health handle should route to health activation, got {:?}", other),
3977            Ok(_) => panic!("health handle should return HandleNotSupported"),
3978        }
3979
3980        // Echo handle → echo activation
3981        let echo_handle = Handle::new(echo_plugin_id, "1.0.0", "echo");
3982        match hub.do_resolve_handle(&echo_handle).await {
3983            Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "echo"),
3984            Err(other) => panic!("echo handle should route to echo activation, got {:?}", other),
3985            Ok(_) => panic!("echo handle should return HandleNotSupported"),
3986        }
3987
3988        // Unknown handle → ActivationNotFound (random UUID not registered)
3989        let unknown_handle = Handle::new(Uuid::new_v4(), "1.0.0", "method");
3990        match hub.do_resolve_handle(&unknown_handle).await {
3991            Err(PlexusError::ActivationNotFound(_)) => { /* expected */ },
3992            Err(other) => panic!("unknown handle should return ActivationNotFound, got {:?}", other),
3993            Ok(_) => panic!("unknown handle should return ActivationNotFound"),
3994        }
3995    }
3996
3997    #[test]
3998    fn invariant_handle_plugin_id_determines_routing() {
3999        use crate::activations::health::Health;
4000        use crate::activations::echo::EchoActivation;
4001        use crate::types::Handle;
4002
4003        let health = Health::new();
4004        let echo = EchoActivation::new();
4005
4006        // Same meta, different activations → different routing targets (by plugin_id)
4007        let health_handle = Handle::new(health.plugin_id(), "1.0.0", "check")
4008            .with_meta(vec!["msg-123".into(), "user".into()]);
4009        let echo_handle = Handle::new(echo.plugin_id(), "1.0.0", "echo")
4010            .with_meta(vec!["msg-123".into(), "user".into()]);
4011
4012        // Different plugin_ids ensure different routing
4013        assert_ne!(health_handle.plugin_id, echo_handle.plugin_id);
4014    }
4015
4016    // ========================================================================
4017    // Plugin Registry Tests
4018    // ========================================================================
4019
4020    #[test]
4021    fn plugin_registry_basic_operations() {
4022        let mut registry = PluginRegistry::new();
4023        let id = uuid::Uuid::new_v4();
4024
4025        // Register an activation
4026        registry.register(id, "test_plugin".to_string(), "test".to_string());
4027
4028        // Lookup by ID
4029        assert_eq!(registry.lookup(id), Some("test_plugin"));
4030
4031        // Lookup by path
4032        assert_eq!(registry.lookup_by_path("test_plugin"), Some(id));
4033
4034        // Get entry
4035        let entry = registry.get(id).expect("should have entry");
4036        assert_eq!(entry.path, "test_plugin");
4037        assert_eq!(entry.plugin_type, "test");
4038    }
4039
4040    #[test]
4041    fn plugin_registry_populated_on_register() {
4042        use crate::activations::health::Health;
4043
4044        let hub = DynamicHub::new("test").register(Health::new());
4045
4046        let registry = hub.registry();
4047        assert!(!registry.is_empty(), "registry should not be empty after registration");
4048
4049        // Health activation should be registered
4050        let health_id = registry.lookup_by_path("health");
4051        assert!(health_id.is_some(), "health should be registered by path");
4052
4053        // Should be able to look up path by ID
4054        let health_uuid = health_id.unwrap();
4055        assert_eq!(registry.lookup(health_uuid), Some("health"));
4056    }
4057
4058    #[test]
4059    fn plugin_registry_deterministic_uuid() {
4060        use crate::activations::health::Health;
4061
4062        // Same activation registered twice should produce same UUID
4063        let health1 = Health::new();
4064        let health2 = Health::new();
4065
4066        assert_eq!(health1.plugin_id(), health2.plugin_id(),
4067            "same activation type should have deterministic UUID");
4068
4069        // UUID should be based on namespace+major_version (semver compatibility)
4070        let expected = uuid::Uuid::new_v5(
4071            &uuid::Uuid::NAMESPACE_OID,
4072            b"health@1"
4073        );
4074        assert_eq!(health1.plugin_id(), expected,
4075            "plugin_id should be deterministic from namespace@major_version");
4076    }
4077
4078    // ========================================================================
4079    // CHILD-2: ChildRouter capabilities + opt-in list/search
4080    // ========================================================================
4081
4082    /// A minimal `ChildRouter` that overrides only the required methods.
4083    /// Exercises default implementations of `capabilities`, `list_children`
4084    /// and `search_children`.
4085    struct MinimalRouter;
4086
4087    #[async_trait]
4088    impl ChildRouter for MinimalRouter {
4089        fn router_namespace(&self) -> &str {
4090            "minimal"
4091        }
4092
4093        async fn router_call(
4094            &self,
4095            _method: &str,
4096            _params: Value,
4097            _auth: Option<&super::super::auth::AuthContext>,
4098            _raw_ctx: Option<&crate::request::RawRequestContext>,
4099        ) -> Result<PlexusStream, PlexusError> {
4100            Err(PlexusError::MethodNotFound {
4101                activation: "minimal".into(),
4102                method: "none".into(),
4103            })
4104        }
4105
4106        async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
4107            None
4108        }
4109    }
4110
4111    #[tokio::test]
4112    async fn child_router_defaults_report_no_capabilities_and_none_streams() {
4113        let router = MinimalRouter;
4114
4115        assert_eq!(
4116            router.capabilities(),
4117            ChildCapabilities::empty(),
4118            "default capabilities should be empty"
4119        );
4120        assert!(
4121            router.list_children().await.is_none(),
4122            "default list_children should be None"
4123        );
4124        assert!(
4125            router.search_children("anything").await.is_none(),
4126            "default search_children should be None"
4127        );
4128    }
4129
4130    /// A `ChildRouter` that opts in to both LIST and SEARCH.
4131    struct ListingRouter {
4132        names: Vec<String>,
4133    }
4134
4135    #[async_trait]
4136    impl ChildRouter for ListingRouter {
4137        fn router_namespace(&self) -> &str {
4138            "listing"
4139        }
4140
4141        async fn router_call(
4142            &self,
4143            _method: &str,
4144            _params: Value,
4145            _auth: Option<&super::super::auth::AuthContext>,
4146            _raw_ctx: Option<&crate::request::RawRequestContext>,
4147        ) -> Result<PlexusStream, PlexusError> {
4148            Err(PlexusError::MethodNotFound {
4149                activation: "listing".into(),
4150                method: "none".into(),
4151            })
4152        }
4153
4154        async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
4155            if self.names.iter().any(|n| n == name) {
4156                // Return the same type to keep the test simple; we only care
4157                // that the override compiles and is reachable.
4158                Some(Box::new(ListingRouter { names: vec![] }))
4159            } else {
4160                None
4161            }
4162        }
4163
4164        fn capabilities(&self) -> ChildCapabilities {
4165            ChildCapabilities::LIST | ChildCapabilities::SEARCH
4166        }
4167
4168        async fn list_children(&self) -> Option<BoxStream<'_, String>> {
4169            let stream = futures::stream::iter(self.names.iter().cloned());
4170            Some(Box::pin(stream))
4171        }
4172
4173        async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
4174            let q = query.to_string();
4175            let stream = futures::stream::iter(
4176                self.names
4177                    .iter()
4178                    .filter(move |n| n.contains(&q))
4179                    .cloned()
4180                    .collect::<Vec<_>>(),
4181            );
4182            Some(Box::pin(stream))
4183        }
4184    }
4185
4186    #[tokio::test]
4187    async fn child_router_overrides_report_capabilities_and_yield_streams() {
4188        use futures::StreamExt;
4189
4190        let router = ListingRouter {
4191            names: vec!["alpha".into(), "beta".into(), "alphabet".into()],
4192        };
4193
4194        // Capabilities
4195        let caps = router.capabilities();
4196        assert!(caps.contains(ChildCapabilities::LIST));
4197        assert!(caps.contains(ChildCapabilities::SEARCH));
4198        assert_eq!(caps, ChildCapabilities::LIST | ChildCapabilities::SEARCH);
4199
4200        // list_children yields the full, non-empty, finite sequence.
4201        let list_stream = router
4202            .list_children()
4203            .await
4204            .expect("LIST capability set — expected Some(stream)");
4205        let listed: Vec<String> = list_stream.collect().await;
4206        assert_eq!(listed, vec!["alpha".to_string(), "beta".into(), "alphabet".into()]);
4207
4208        // search_children filters by the query string.
4209        let search_stream = router
4210            .search_children("alpha")
4211            .await
4212            .expect("SEARCH capability set — expected Some(stream)");
4213        let matched: Vec<String> = search_stream.collect().await;
4214        assert_eq!(matched, vec!["alpha".to_string(), "alphabet".into()]);
4215    }
4216
4217    // ========================================================================
4218    // CHILD-WIRE: per-activation namespaced wire exposure for
4219    // <ns>.list_children / <ns>.search_children
4220    //
4221    // These tests exercise `register_child_capability_methods` directly with
4222    // hand-built fixtures, then drive the resulting RpcModule through the
4223    // in-process subscription path. Mirrors the existing
4224    // `auth_capabilities_info` integration pattern but verifies the
4225    // child-router wire registration instead of the _info payload.
4226    // ========================================================================
4227
4228    /// Like `EnumerableRouter` above but with configurable capability bits +
4229    /// a fixed name set. Used to drive CHILD-WIRE registration through
4230    /// different capability combinations.
4231    struct WireFixture {
4232        names: Vec<String>,
4233        caps: ChildCapabilities,
4234    }
4235
4236    #[async_trait]
4237    impl ChildRouter for WireFixture {
4238        fn router_namespace(&self) -> &str {
4239            "wirefixture"
4240        }
4241        async fn router_call(
4242            &self,
4243            _method: &str,
4244            _params: Value,
4245            _auth: Option<&super::super::auth::AuthContext>,
4246            _raw_ctx: Option<&crate::request::RawRequestContext>,
4247        ) -> Result<PlexusStream, PlexusError> {
4248            Err(PlexusError::MethodNotFound {
4249                activation: "wirefixture".into(),
4250                method: "none".into(),
4251            })
4252        }
4253        async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
4254            None
4255        }
4256        fn capabilities(&self) -> ChildCapabilities {
4257            self.caps
4258        }
4259        async fn list_children(&self) -> Option<futures_core::stream::BoxStream<'_, String>> {
4260            if !self.caps.contains(ChildCapabilities::LIST) {
4261                return None;
4262            }
4263            Some(Box::pin(futures::stream::iter(self.names.clone())))
4264        }
4265        async fn search_children(
4266            &self,
4267            query: &str,
4268        ) -> Option<futures_core::stream::BoxStream<'_, String>> {
4269            if !self.caps.contains(ChildCapabilities::SEARCH) {
4270                return None;
4271            }
4272            let q = query.to_lowercase();
4273            let filtered: Vec<String> = self
4274                .names
4275                .iter()
4276                .filter(|n| n.to_lowercase().contains(&q))
4277                .cloned()
4278                .collect();
4279            Some(Box::pin(futures::stream::iter(filtered)))
4280        }
4281    }
4282
4283    fn build_module_for(router: WireFixture, ns: &str) -> RpcModule<()> {
4284        let mut module = RpcModule::new(());
4285        let arc: Arc<dyn ChildRouter> = Arc::new(router);
4286        register_child_capability_methods(&mut module, ns, arc, None).expect("register");
4287        module
4288    }
4289
4290    #[tokio::test]
4291    async fn child_wire_registers_both_methods_when_both_bits_set() {
4292        let module = build_module_for(
4293            WireFixture {
4294                names: vec!["alpha".into(), "beta".into()],
4295                caps: ChildCapabilities::LIST | ChildCapabilities::SEARCH,
4296            },
4297            "fixture",
4298        );
4299        let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
4300        assert!(
4301            names.contains(&"fixture.list_children".to_string()),
4302            "expected fixture.list_children, got: {:?}",
4303            names
4304        );
4305        assert!(
4306            names.contains(&"fixture.search_children".to_string()),
4307            "expected fixture.search_children, got: {:?}",
4308            names
4309        );
4310    }
4311
4312    #[tokio::test]
4313    async fn child_wire_registers_nothing_when_no_bits_set() {
4314        let module = build_module_for(
4315            WireFixture {
4316                names: vec!["alpha".into()],
4317                caps: ChildCapabilities::empty(),
4318            },
4319            "fixture",
4320        );
4321        let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
4322        assert!(
4323            !names.contains(&"fixture.list_children".to_string()),
4324            "fixture.list_children should NOT be registered when cap absent"
4325        );
4326        assert!(
4327            !names.contains(&"fixture.search_children".to_string()),
4328            "fixture.search_children should NOT be registered when cap absent"
4329        );
4330    }
4331
4332    #[tokio::test]
4333    async fn child_wire_registers_only_list_when_only_list_bit() {
4334        let module = build_module_for(
4335            WireFixture {
4336                names: vec!["alpha".into()],
4337                caps: ChildCapabilities::LIST,
4338            },
4339            "fixture",
4340        );
4341        let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
4342        assert!(names.contains(&"fixture.list_children".to_string()));
4343        assert!(!names.contains(&"fixture.search_children".to_string()));
4344    }
4345
4346    // Live wire-call behavior (subscription stream content, methodNotFound on
4347    // unregistered names, error envelopes) is verified end-to-end against
4348    // running substrate Solar — that's the canonical integration gate per
4349    // the CHILD-WIRE acceptance criteria. The unit-level introspection
4350    // tests above assert the registration shape; the substrate verification
4351    // asserts the live behavior. Splitting it that way avoids forcing the
4352    // unit test to construct a working RpcSubscriptionSink, which is not
4353    // straightforward in the bare jsonrpsee API.
4354}