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