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