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        let info = self.gate_index().get(method);
1928        let grant = info.and_then(|i| i.grant.clone()).unwrap_or_else(|| method.to_string());
1929        let open = info.is_some_and(|i| i.public) || self.inner.signed_in_grants.contains(grant.as_str());
1930        let targets = match info.and_then(|i| i.target.as_deref()) {
1931            Some(param) => super::grant_gate::target_values(params, param)?.unwrap_or_default(),
1932            None => Vec::new(),
1933        };
1934        Ok(InputTerms { grant, targets, recheck: !open })
1935    }
1936
1937    /// BIDIR-6: the gate over this service's duplex calls, made when the
1938    /// first one opens (in the runtime, which runs its audit's drain).
1939    pub(crate) fn duplex_gate(&self) -> &super::duplex_gate::DuplexGate {
1940        self.inner.duplex_gate.get_or_init(|| match &self.inner.gate {
1941            Some(gate) => {
1942                let (audit, drain) = plexus_auth_core::audit::AuditQueue::new(1024, self.inner.audit_sink.clone());
1943                tokio::spawn(drain);
1944                super::duplex_gate::DuplexGate::new((**gate).clone()).with_audit(audit)
1945            }
1946            None => super::duplex_gate::DuplexGate::ungated(),
1947        })
1948    }
1949
1950    /// BIDIR-6: whether `method` (a `{ns}.call`'s dotted path) may take an
1951    /// `Input`: `false` only for a method this service's schemas show has
1952    /// none — its own, each activation's, each static child's. A path they do
1953    /// not show (a dynamic child's) may.
1954    pub(crate) fn may_take_input(&self, method: &str) -> bool {
1955        let index = self.inner.input_index.get_or_init(|| {
1956            let own = Activation::plugin_schema(self).methods.into_iter().map(|m| (format!("{}.{}", self.inner.namespace, m.name), m.input.is_some()));
1957            let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.static_children());
1958            let theirs = schemas.flat_map(|schema| {
1959                let ns = schema.namespace;
1960                schema.methods.into_iter().map(move |m| (format!("{ns}.{}", m.name), m.input.is_some()))
1961            });
1962            own.chain(theirs).collect()
1963        });
1964        index.get(method).copied().unwrap_or(true)
1965    }
1966
1967    /// The gate's path→schema-facts index; built once on first gated
1968    /// dispatch. See the field docs on `DynamicHubInner::gate_index`.
1969    fn gate_index(&self) -> &HashMap<String, super::scope_gate::MethodGateInfo> {
1970        self.inner.gate_index.get_or_init(|| {
1971            let mut index = HashMap::new();
1972            // The hub's own methods, addressable as "<hub-ns>.<method>".
1973            for m in &Activation::plugin_schema(self).methods {
1974                let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
1975                // The hub's own methods are granted under its runtime
1976                // namespace (the macro's static one is "plexus").
1977                info.grant = Some(format!("{}.{}", self.inner.namespace, m.name));
1978                index.insert(format!("{}.{}", self.inner.namespace, m.name), info);
1979            }
1980            // Each registered activation's methods, addressable as
1981            // "<activation-ns>.<method>"; MACRO-20: and each static child's,
1982            // as "<activation-ns>.<path>.<method>", with the child's own
1983            // target and its grant qualified by the path
1984            // (`tickets.commits.link`, see `super::children`). A dynamic
1985            // child (an open name set) has no MethodSchema at this hub's
1986            // level; the gate treats its paths as schema-less (grant = the
1987            // dotted path; registry overlay / default_deny still apply).
1988            let schemas = self.inner.activations.values().map(|a| a.plugin_schema()).chain(self.static_children());
1989            for schema in schemas {
1990                for m in &schema.methods {
1991                    let mut info = super::scope_gate::MethodGateInfo::from_schema(m);
1992                    info.grant = Some(m.grant_or(&schema.namespace));
1993                    index.insert(format!("{}.{}", schema.namespace, m.name), info);
1994                }
1995            }
1996            index
1997        })
1998    }
1999
2000    /// Register a [`plexus_auth_core::ForwardPolicy`] for a callee
2001    /// namespace.
2002    ///
2003    /// AUTHLANG-3 — every cross-boundary call through this hub consults
2004    /// the registry at dispatch time. When `callee_ns` has no entry, the
2005    /// framework falls back to [`plexus_auth_core::IdentityOnly`].
2006    ///
2007    /// AUTHLANG-4's `#[plexus::activation(forward_policy = ...)]`
2008    /// attribute is the declarative path; this builder is the imperative
2009    /// escape hatch used by integration tests and hand-rolled wiring.
2010    ///
2011    /// # Example
2012    ///
2013    /// ```ignore
2014    /// use plexus_auth_core::PassThrough;
2015    /// use std::sync::Arc;
2016    ///
2017    /// let hub = DynamicHub::new("my-backend")
2018    ///     .with_forward_policy("solar", Arc::new(PassThrough));
2019    /// ```
2020    pub fn with_forward_policy(
2021        mut self,
2022        callee_ns: impl Into<String>,
2023        policy: std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>,
2024    ) -> Self {
2025        let inner = self.inner_mut("Cannot register forward policy: DynamicHub has multiple references");
2026        inner.forward_policies.register(callee_ns, policy);
2027        self
2028    }
2029
2030    /// Read-only view of the registered forward policies.
2031    ///
2032    /// Test-side accessor; production dispatch consults the registry via
2033    /// the [`ChildRouter::forward_policy_for`] override.
2034    pub fn forward_policies(&self) -> &super::forward_registry::ForwardPolicyRegistry {
2035        &self.inner.forward_policies
2036    }
2037
2038    /// Declare the backend's authentication capabilities, served at `_info`.
2039    ///
2040    /// Backends call this at builder time to advertise which auth mechanisms
2041    /// they support (Bearer, Cookie, OIDC, Anonymous). Generic clients
2042    /// (synapse CLI, gamma, generated SDKs) read the advertisement to decide
2043    /// which authentication flow to drive.
2044    ///
2045    /// Without calling this method, `_info` emits the
2046    /// [`plexus_auth_core::BackendAuthCapabilities::anonymous_default`]
2047    /// fallback: a single `Anonymous` mechanism, no default. This preserves
2048    /// today's no-auth substrate behavior.
2049    ///
2050    /// Per AUTHZ-CORE-3 / AUTHZ-S01-output §2.
2051    ///
2052    /// # Example
2053    ///
2054    /// ```no_run
2055    /// # use plexus_core::DynamicHub;
2056    /// use plexus_auth_core::{
2057    ///     AuthMechanism, BackendAuthCapabilities, CookieName, MethodPath,
2058    /// };
2059    ///
2060    /// let caps = BackendAuthCapabilities::new(
2061    ///     vec![AuthMechanism::Cookie {
2062    ///         cookie: CookieName::try_new("plexus_session").unwrap(),
2063    ///         login: MethodPath::try_new("auth.login").unwrap(),
2064    ///         refresh: None,
2065    ///         logout: None,
2066    ///     }],
2067    ///     Some(0),
2068    /// )
2069    /// .unwrap();
2070    ///
2071    /// let hub = DynamicHub::new("my-backend").with_auth_capabilities(caps);
2072    /// ```
2073    pub fn with_auth_capabilities(
2074        mut self,
2075        caps: plexus_auth_core::BackendAuthCapabilities,
2076    ) -> Self {
2077        let inner = self.inner_mut("Cannot set auth_capabilities: DynamicHub has multiple references");
2078        inner.auth_capabilities = Some(caps);
2079        self
2080    }
2081
2082    /// Returns the configured [`BackendAuthCapabilities`], or `None` if the
2083    /// backend has not called [`Self::with_auth_capabilities`].
2084    ///
2085    /// Test-side accessor; production code reads the advertisement off `_info`.
2086    ///
2087    /// [`BackendAuthCapabilities`]: plexus_auth_core::BackendAuthCapabilities
2088    pub fn auth_capabilities(&self) -> Option<&plexus_auth_core::BackendAuthCapabilities> {
2089        self.inner.auth_capabilities.as_ref()
2090    }
2091
2092    /// Deprecated: Use new() with explicit namespace instead
2093    #[deprecated(since = "0.3.0", note = "Use DynamicHub::new(namespace) instead")]
2094    pub fn with_namespace(namespace: impl Into<String>) -> Self {
2095        Self::new(namespace)
2096    }
2097
2098    /// Get the runtime namespace for this DynamicHub instance
2099    pub fn runtime_namespace(&self) -> &str {
2100        &self.inner.namespace
2101    }
2102
2103    /// Get access to the activation registry
2104    pub fn registry(&self) -> std::sync::RwLockReadGuard<'_, PluginRegistry> {
2105        self.inner.registry.read().unwrap()
2106    }
2107
2108    /// Panic if `child_namespace` shadows the hub root namespace.
2109    ///
2110    /// Z2H-8 / HOSTLESS-3 — routing resolves the hub root before registered
2111    /// activations (see [`Self::route_with_ctx`]), so a child activation whose
2112    /// namespace equals the hub root name is silently unreachable: every
2113    /// `<ns>.<method>` call resolves to the root (which only has
2114    /// call/hash/hashes/schema) and navigators resolve the like-named child
2115    /// back to the root schema. The published echo example shipped exactly
2116    /// this shape and was dead on arrival. A loud, immediate error at
2117    /// registration time beats silent unreachability at call time.
2118    fn assert_no_root_shadow(&self, child_namespace: &str) {
2119        if child_namespace == self.inner.namespace {
2120            panic!(
2121                "DynamicHub namespace shadow: activation namespace '{child}' collides with the hub root namespace '{root}'. \
2122                 The hub root name is a routing namespace, not a label — routing resolves the root first, so a like-named \
2123                 child activation is unreachable (every '{child}.<method>' call resolves to the hub root and fails with \
2124                 'Command not found', and navigation resolves the child back to the root schema). \
2125                 Fix: rename the hub root so it differs from every registered activation's namespace, \
2126                 e.g. DynamicHub::new(\"{root}_hub\").register(...). [Z2H-8 / HOSTLESS-3]",
2127                child = child_namespace,
2128                root = self.inner.namespace,
2129            );
2130        }
2131    }
2132
2133    /// Register an activation
2134    ///
2135    /// # Panics
2136    ///
2137    /// Panics if the activation's namespace equals the hub root namespace —
2138    /// such a child would be unreachable at call time (Z2H-8 / HOSTLESS-3,
2139    /// see [`Self::new`]). Also panics if the hub has already been shared
2140    /// (multiple `Arc` references).
2141    pub fn register<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
2142        let namespace = activation.namespace().to_string();
2143        self.assert_no_root_shadow(&namespace);
2144        let plugin_id = activation.plugin_id();
2145        let activation_for_rpc = activation.clone();
2146        let activation_for_router = activation.clone();
2147
2148        let inner = self.inner_mut("Cannot register: DynamicHub has multiple references");
2149
2150        // Register in the activation registry
2151        inner.registry.write().unwrap().register(
2152            plugin_id,
2153            namespace.clone(),
2154            namespace.clone(), // Use namespace as plugin_type for now
2155        );
2156
2157        // AUTH-5: `auth.requires` knows every method, registered before
2158        // the auth activation was mounted or after.
2159        if let Some(catalog) = inner.auth_catalog.as_ref() {
2160            let schema = activation.plugin_schema();
2161            // MACRO-20: and its static children's methods, by their whole path.
2162            for child in super::children::qualified(&schema.namespace, Activation::static_child_schemas(&activation)) {
2163                catalog.add(&child);
2164            }
2165            catalog.add(&schema);
2166        }
2167        // RETURNS-40: the cheap bound on `ir`'s names, counted here, once
2168        inner.nested_count += Activation::static_child_schemas(&activation).len();
2169        inner.activations.insert(namespace.clone(), Arc::new(ActivationWrapper { inner: activation }));
2170        inner.child_routers.insert(namespace.clone(), Arc::new(activation_for_router));
2171        inner.pending_rpc.lock().unwrap()
2172            .push(Box::new(move || activation_for_rpc.into_rpc_methods()));
2173        self
2174    }
2175
2176    /// Register a hub activation that supports nested routing
2177    ///
2178    /// Hub activations implement `ChildRouter`, enabling direct nested method calls
2179    /// like `hub.solar.mercury.info` at the RPC layer (no hub.call indirection).
2180    ///
2181    /// # Panics
2182    ///
2183    /// Same contract as [`Self::register`]: panics on a root/activation
2184    /// namespace collision (Z2H-8 / HOSTLESS-3).
2185    #[deprecated(since = "0.5.0", note = "Use register() — it now handles both leaf and hub activations")]
2186    pub fn register_hub<A: Activation + ChildRouter + Clone + 'static>(mut self, activation: A) -> Self {
2187        let namespace = activation.namespace().to_string();
2188        self.assert_no_root_shadow(&namespace);
2189        let plugin_id = activation.plugin_id();
2190        let activation_for_rpc = activation.clone();
2191        let activation_for_router = activation.clone();
2192
2193        let inner = self.inner_mut("Cannot register: DynamicHub has multiple references");
2194
2195        // Register in the activation registry
2196        inner.registry.write().unwrap().register(
2197            plugin_id,
2198            namespace.clone(),
2199            namespace.clone(), // Use namespace as plugin_type for now
2200        );
2201
2202        if let Some(catalog) = inner.auth_catalog.as_ref() {
2203            let schema = activation.plugin_schema();
2204            // MACRO-20: and its static children's methods, by their whole path.
2205            for child in super::children::qualified(&schema.namespace, Activation::static_child_schemas(&activation)) {
2206                catalog.add(&child);
2207            }
2208            catalog.add(&schema);
2209        }
2210        // RETURNS-40: the cheap bound on `ir`'s names, counted here, once
2211        inner.nested_count += Activation::static_child_schemas(&activation).len();
2212        inner.activations.insert(namespace.clone(), Arc::new(ActivationWrapper { inner: activation }));
2213        inner.child_routers.insert(namespace, Arc::new(activation_for_router));
2214        inner.pending_rpc.lock().unwrap()
2215            .push(Box::new(move || activation_for_rpc.into_rpc_methods()));
2216        self
2217    }
2218
2219    /// List all methods across all activations
2220    pub fn list_methods(&self) -> Vec<String> {
2221        let mut methods = Vec::new();
2222
2223        // Include hub's own methods
2224        for m in Activation::methods(self) {
2225            methods.push(format!("{}.{}", self.inner.namespace, m));
2226        }
2227
2228        // Include registered activation methods
2229        for (ns, act) in &self.inner.activations {
2230            for m in act.methods() {
2231                methods.push(format!("{}.{}", ns, m));
2232            }
2233        }
2234        methods.sort();
2235        methods
2236    }
2237
2238    /// List all activations (including this hub itself)
2239    pub fn list_activations_info(&self) -> Vec<ActivationInfo> {
2240        let mut activations = Vec::new();
2241
2242        // Include this hub itself
2243        activations.push(ActivationInfo {
2244            namespace: Activation::namespace(self).to_string(),
2245            version: Activation::version(self).to_string(),
2246            description: Activation::description(self).to_string(),
2247            methods: Activation::methods(self).iter().map(|s| s.to_string()).collect(),
2248        });
2249
2250        // Include registered activations
2251        for a in self.inner.activations.values() {
2252            activations.push(ActivationInfo {
2253                namespace: a.namespace().to_string(),
2254                version: a.version().to_string(),
2255                description: a.description().to_string(),
2256                methods: a.methods().iter().map(|s| s.to_string()).collect(),
2257            });
2258        }
2259
2260        activations
2261    }
2262
2263    /// Compute hash for cache invalidation
2264    ///
2265    /// Returns the hash from the recursive plugin schema. This hash changes
2266    /// whenever any method definition or child plugin changes — and,
2267    /// PERF-21, only then: the children are listed by namespace, so every
2268    /// start of the same build computes the same hash (the `plexus_hash`
2269    /// every item carries, [`PlexusContext::init`]).
2270    pub fn compute_hash(&self) -> String {
2271        // PERF-15: from what the service describes, kept per schema generation.
2272        self.described().service.hash.clone()
2273    }
2274
2275    /// PERF-15: the service's own `hash` answer for `caller` — the caller's
2276    /// view's on a gated service (AUTH-4), the service's own otherwise —
2277    /// from the cache.
2278    fn own_hash(&self, caller: Option<&super::auth::AuthContext>) -> String {
2279        match self.inner.gate {
2280            Some(_) => self.shaped(caller).1.hash.clone(),
2281            None => self.described().service.hash.clone(),
2282        }
2283    }
2284
2285    /// PERF-15: the service's own schema as `caller` sees it — the
2286    /// `{ns}.schema` answer before its site hints — from the cache.
2287    fn own_schema(&self, caller: Option<&super::auth::AuthContext>) -> PluginSchema {
2288        match self.inner.gate {
2289            Some(_) => self.shaped(caller).1.service.clone(),
2290            None => self.described().service.clone(),
2291        }
2292    }
2293
2294    /// Route a call to the appropriate activation
2295    pub async fn route(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>) -> Result<PlexusStream, PlexusError> {
2296        self.route_with_ctx(method, params, auth, None).await
2297    }
2298
2299    /// Route a call to the appropriate activation, with optional raw HTTP request context.
2300    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> {
2301        // AUTH-2 grant gate: only when configured — a hub without one pays
2302        // this one branch and dispatches as before.
2303        if let Some(gate) = self.inner.gate.as_ref() {
2304            // AUTH-11: a sign-in that ended proves no one, on every method.
2305            let (auth, ended) = super::grant_gate::standing(gate, auth);
2306            let admit = super::grant_gate::decide(
2307                gate,
2308                &self.inner.namespace,
2309                method,
2310                self.gate_index().get(method),
2311                &params,
2312                auth,
2313                &self.inner.signed_in_grants,
2314            )
2315            .map_err(|e| super::grant_gate::say_ended(e, ended.as_deref()))?;
2316            return match admit {
2317                // AUTH-4: introspection answers from the caller's view.
2318                super::grant_gate::Admit::Open => match self.introspect_in_view(method, &params, auth, raw_ctx).await {
2319                    Some(answer) => answer,
2320                    None => self.route_ungated(method, params, auth, raw_ctx).await,
2321                },
2322                super::grant_gate::Admit::Reach(reach) => {
2323                    super::grant_gate::with_reach(reach, self.route_ungated(method, params, auth, raw_ctx)).await
2324                }
2325            };
2326        }
2327        self.route_ungated(method, params, auth, raw_ctx).await
2328    }
2329
2330    /// Everything [`DynamicHub::route_with_ctx`] does after the grant gate.
2331    async fn route_ungated(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
2332        // R-5 scope gate (AUTHZ-CORE-1 + CORE-5). Inactive unless a
2333        // ScopeRegistry is configured or default_deny is set — a hub with
2334        // neither pays exactly this one branch and dispatches as before
2335        // the gate existed (the hard backward-safety constraint).
2336        if self.inner.scope_registry.is_some() || self.inner.default_deny {
2337            let registry = self
2338                .inner
2339                .scope_registry
2340                .as_deref()
2341                .unwrap_or_else(|| super::scope_gate::empty_registry());
2342            super::scope_gate::enforce(
2343                registry,
2344                self.inner.default_deny,
2345                &self.inner.audit_sink,
2346                method,
2347                self.gate_index().get(method),
2348                auth,
2349                raw_ctx.and_then(|ctx| ctx.peer.map(|peer| peer.ip())),
2350            )
2351            .await?;
2352        }
2353
2354        let (namespace, method_name) = self.parse_method(method)?;
2355
2356        // RETURNS-40 review #1: `ir`'s names, before any work
2357        if namespace == self.inner.namespace && method_name == "ir" {
2358            self.check_ir_names(&params, auth)?;
2359        }
2360
2361        // Handle plexus's own methods
2362        let stream = if namespace == self.inner.namespace {
2363            Activation::call(self, method_name, params, auth, raw_ctx).await?
2364        } else {
2365            let activation = self.inner.activations.get(namespace)
2366                .ok_or_else(|| PlexusError::ActivationNotFound(namespace.to_string()))?;
2367
2368            activation.call(method_name, params, auth, raw_ctx).await?
2369        };
2370
2371        // CA-1 (trak facet ccc924ad): schema responses leaving this hub get
2372        // their `requires_credential.site_hint` filled from the backend's
2373        // advertised auth capabilities. Backends that never call
2374        // `with_auth_capabilities` (or advertise anonymous-only) derive no
2375        // site, and the stream passes through untouched — byte-identical to
2376        // pre-CA-1 emissions.
2377        if Self::is_schema_query(method_name) {
2378            if let Some(site) = self.derived_site_hint() {
2379                return Ok(fill_site_hints_in_schema_stream(stream, site));
2380            }
2381        }
2382        Ok(stream)
2383    }
2384
2385    /// Whether a routed `method_name` (the part after the first dot) is a
2386    /// schema query: `"schema"` (`<ns>.schema`, with or without a `method`
2387    /// param) or a nested `"<child...>.schema"` path routed into a child
2388    /// activation.
2389    fn is_schema_query(method_name: &str) -> bool {
2390        method_name == "schema" || method_name.ends_with(".schema")
2391    }
2392
2393    /// CA-1: the [`AttachmentSite`] implied by this backend's advertised
2394    /// auth capabilities, or `None` when no capabilities are configured or
2395    /// none of the advertised mechanisms implies a site.
2396    ///
2397    /// [`AttachmentSite`]: plexus_auth_core::AttachmentSite
2398    pub fn derived_site_hint(&self) -> Option<plexus_auth_core::AttachmentSite> {
2399        self.inner
2400            .auth_capabilities
2401            .as_ref()
2402            .and_then(|caps| caps.implied_attachment_site())
2403    }
2404
2405    /// Resolve a handle using the activation registry
2406    ///
2407    /// Looks up the activation by its UUID in the registry.
2408    pub async fn do_resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
2409        let path = self.inner.registry.read().unwrap()
2410            .lookup(handle.plugin_id)
2411            .map(|s| s.to_string())
2412            .ok_or_else(|| PlexusError::ActivationNotFound(handle.plugin_id.to_string()))?;
2413
2414        let activation = self.inner.activations.get(&path)
2415            .ok_or_else(|| PlexusError::ActivationNotFound(path.clone()))?;
2416        activation.resolve_handle(handle).await
2417    }
2418
2419    /// Get activation schema
2420    pub fn get_activation_schema(&self, namespace: &str) -> Option<Schema> {
2421        self.inner.activations.get(namespace).map(|a| a.schema())
2422    }
2423
2424    /// Get a snapshot of the activation registry (safe to use outside locks)
2425    pub fn registry_snapshot(&self) -> PluginRegistrySnapshot {
2426        let guard = self.inner.registry.read().unwrap();
2427        PluginRegistrySnapshot {
2428            by_id: guard.by_id.clone(),
2429            by_path: guard.by_path.clone(),
2430        }
2431    }
2432
2433    /// Look up an activation path by its UUID
2434    pub fn lookup_plugin(&self, id: uuid::Uuid) -> Option<String> {
2435        self.inner.registry.read().unwrap().lookup(id).map(|s| s.to_string())
2436    }
2437
2438    /// Look up an activation UUID by its path
2439    pub fn lookup_plugin_by_path(&self, path: &str) -> Option<uuid::Uuid> {
2440        self.inner.registry.read().unwrap().lookup_by_path(path)
2441    }
2442
2443    /// Get activation schemas for all activations (including this hub itself)
2444    pub fn list_plugin_schemas(&self) -> Vec<PluginSchema> {
2445        let mut schemas = Vec::new();
2446
2447        // Include this hub itself
2448        schemas.push(Activation::plugin_schema(self));
2449
2450        // Include registered activations
2451        for a in self.inner.activations.values() {
2452            schemas.push(a.plugin_schema());
2453        }
2454
2455        schemas
2456    }
2457
2458    /// Deprecated: use list_plugin_schemas instead
2459    #[deprecated(note = "Use list_plugin_schemas instead")]
2460    pub fn list_full_schemas(&self) -> Vec<PluginSchema> {
2461        self.list_plugin_schemas()
2462    }
2463
2464    /// Get help for a method
2465    pub fn get_method_help(&self, method: &str) -> Option<String> {
2466        let (namespace, method_name) = self.parse_method(method).ok()?;
2467        let activation = self.inner.activations.get(namespace)?;
2468        activation.method_help(method_name)
2469    }
2470
2471    fn parse_method<'a>(&self, method: &'a str) -> Result<(&'a str, &'a str), PlexusError> {
2472        let parts: Vec<&str> = method.splitn(2, '.').collect();
2473        if parts.len() != 2 {
2474            return Err(PlexusError::InvalidParams {
2475                param: Some("method".into()),
2476                problem: ParamProblem::Malformed {
2477                    detail: format!("expected `namespace.method`, got `{}`", method),
2478                },
2479            });
2480        }
2481        Ok((parts[0], parts[1]))
2482    }
2483
2484    /// Get child activation summaries: one per registered activation, in
2485    /// namespace order (PERF-21) — the service schema's `children`, which
2486    /// its `hash` and every caller's view hash digest in this order.
2487    /// Called by `#[plexus_macros::activation]` when its `hub` flag is set.
2488    pub fn plugin_children(&self) -> Vec<ChildSummary> {
2489        self.inner.activations.values()
2490            .map(|a| {
2491                let schema = a.plugin_schema();
2492                ChildSummary {
2493                    namespace: schema.namespace,
2494                    description: schema.description,
2495                    hash: schema.hash,
2496                }
2497            })
2498            .collect()
2499    }
2500
2501    /// Convert to RPC module
2502    pub fn into_rpc_module(self) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
2503        let mut module = RpcModule::new(());
2504
2505        PlexusContext::init(self.compute_hash());
2506
2507        // Register hub methods with runtime namespace using dot notation (e.g., "plexus.call" or "hub.call")
2508        // Note: we leak these strings to get 'static lifetime required by jsonrpsee
2509        let ns = self.runtime_namespace();
2510        let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
2511        let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
2512        let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2513        let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
2514        let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2515        let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
2516        let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2517        let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2518        let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
2519
2520        // Register {ns}.call subscription
2521        let plexus_for_call = self.clone();
2522        module.register_subscription(
2523            call_method,
2524            PLEXUS_NOTIF_METHOD,
2525            call_unsub,
2526            move |params, pending, _ctx, ext| {
2527                let plexus = plexus_for_call.clone();
2528                // AUTH-4: a gated hub reads the connection's identity (as
2529                // arc_into_rpc_module always has); a hub without a gate
2530                // dispatches anonymously here, as before.
2531                let identified = plexus.inner.gate.is_some();
2532                serve_call(plexus, params, pending, ext, ns_static, identified)
2533            }
2534        )?;
2535
2536        register_input_methods(&mut module, ns_static)?;
2537
2538        // Register {ns}.hash subscription
2539        let plexus_for_hash = self.clone();
2540        module.register_subscription(
2541            hash_method,
2542            PLEXUS_NOTIF_METHOD,
2543            hash_unsub,
2544            move |_params, pending, _ctx, ext| {
2545                let plexus = plexus_for_hash.clone();
2546                Box::pin(async move {
2547                    // AUTH-4: a gated hub's hash is the caller's view's.
2548                    let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2549                    let value = plexus.own_hash(auth);
2550                    let stream = async_stream::stream! {
2551                        yield HashEvent::Hash { value };
2552                    };
2553                    let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
2554                    pipe_stream_to_subscription(pending, wrapped, &ext).await
2555                })
2556            }
2557        )?;
2558
2559        // Register {ns}.schema subscription
2560        let plexus_for_schema = self.clone();
2561        module.register_subscription(
2562            schema_method,
2563            PLEXUS_NOTIF_METHOD,
2564            schema_unsub,
2565            move |params, pending, _ctx, ext| {
2566                let plexus = plexus_for_schema.clone();
2567                Box::pin(async move {
2568                    let p: SchemaParams = params.parse().unwrap_or_default();
2569                    // AUTH-4: a gated hub answers from the caller's view.
2570                    let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2571                    let mut plugin_schema = plexus.own_schema(auth);
2572                    // CA-1: hub-derived site hints on the hub's own schema.
2573                    if let Some(site) = plexus.derived_site_hint() {
2574                        plugin_schema.fill_site_hints(&site);
2575                    }
2576
2577                    let result = if let Some(ref name) = p.method {
2578                        plugin_schema.methods.iter()
2579                            .find(|m| m.name == *name)
2580                            .map(|m| super::SchemaResult::Method(m.clone()))
2581                            .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
2582                                -32602,
2583                                format!("Method '{}' not found", name),
2584                                None::<()>,
2585                            ))?
2586                    } else {
2587                        super::SchemaResult::Plugin(plugin_schema)
2588                    };
2589
2590                    let stream = async_stream::stream! { yield result; };
2591                    let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
2592                    pipe_stream_to_subscription(pending, wrapped, &ext).await
2593                })
2594            }
2595        )?;
2596
2597        // Register _info well-known endpoint (no namespace prefix).
2598        // Returns backend name + auth_capabilities (AUTHZ-CORE-3) as a
2599        // single-item stream with automatic Done event. Backends that have not
2600        // called with_auth_capabilities get the anonymous-default fallback so
2601        // capability-aware clients can still discover the auth surface.
2602        let info_payload = build_info_payload(
2603            self.runtime_namespace(),
2604            self.inner.auth_capabilities.as_ref(),
2605        );
2606        // AUTH-4: a gated hub answers `_info` per caller; without a gate the
2607        // payload is built once, as before.
2608        let plexus_for_info = self.inner.gate.is_some().then(|| self.clone());
2609        module.register_subscription(
2610            "_info",
2611            PLEXUS_NOTIF_METHOD,
2612            "_info_unsub",
2613            move |_params, pending, _ctx, ext| {
2614                let payload = match plexus_for_info.as_ref() {
2615                    Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
2616                    None => info_payload.clone(),
2617                };
2618                Box::pin(async move {
2619                    // Create a single-item stream with the info response
2620                    let info_stream = futures::stream::once(async move { payload });
2621
2622                    // Wrap to auto-append Done event
2623                    let wrapped = super::streaming::wrap_stream(
2624                        info_stream,
2625                        "_info",
2626                        vec![]
2627                    );
2628
2629                    // Pipe to subscription (handles Done automatically)
2630                    pipe_stream_to_subscription(pending, wrapped, &ext).await
2631                })
2632            }
2633        )?;
2634
2635        // Add all registered activation RPC methods — unless a grant gate
2636        // is set (AUTH-2): those direct methods carry no auth and would pass
2637        // around it, so a gated hub is reached only through `<ns>.call`.
2638        let pending = std::mem::take(&mut *self.inner.pending_rpc.lock().unwrap());
2639        if self.inner.gate.is_none() {
2640            for factory in pending {
2641                module.merge(factory())?;
2642            }
2643        }
2644
2645        // CHILD-WIRE: for each registered child router with capability bits set,
2646        // register {ns}.list_children / {ns}.search_children as subscriptions.
2647        // Per-activation namespaced (not top-level _list_children).
2648        for (ns, router) in self.inner.child_routers.iter() {
2649            register_child_capability_methods(&mut module, ns, router.clone())?;
2650        }
2651
2652        Ok(module)
2653    }
2654
2655    /// Convert Arc<DynamicHub> to RPC module while keeping the Arc alive
2656    ///
2657    /// Unlike `into_rpc_module`, this keeps the Arc<DynamicHub> reference alive,
2658    /// which is necessary when activations hold Weak<DynamicHub> references that
2659    /// need to remain upgradeable.
2660    pub fn arc_into_rpc_module(hub: Arc<Self>) -> Result<RpcModule<()>, jsonrpsee::core::RegisterMethodError> {
2661        let mut module = RpcModule::new(());
2662
2663        PlexusContext::init(hub.compute_hash());
2664
2665        // Register hub methods with runtime namespace using dot notation (e.g., "plexus.call" or "hub.call")
2666        // Note: we leak these strings to get 'static lifetime required by jsonrpsee
2667        let ns = hub.runtime_namespace();
2668        let call_method: &'static str = Box::leak(format!("{}.call", ns).into_boxed_str());
2669        let call_unsub: &'static str = Box::leak(format!("{}.call_unsub", ns).into_boxed_str());
2670        let hash_method: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2671        let hash_unsub: &'static str = Box::leak(format!("{}.hash_unsub", ns).into_boxed_str());
2672        let schema_method: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2673        let schema_unsub: &'static str = Box::leak(format!("{}.schema_unsub", ns).into_boxed_str());
2674        let hash_content_type: &'static str = Box::leak(format!("{}.hash", ns).into_boxed_str());
2675        let schema_content_type: &'static str = Box::leak(format!("{}.schema", ns).into_boxed_str());
2676        let ns_static: &'static str = Box::leak(ns.to_string().into_boxed_str());
2677
2678        // Register {ns}.call subscription - clone Arc to keep reference alive
2679        let hub_for_call = hub.clone();
2680        module.register_subscription(
2681            call_method,
2682            call_method,
2683            call_unsub,
2684            move |params, pending, _ctx, ext| {
2685                let hub = hub_for_call.clone();
2686                let hub = (*hub).clone();
2687                serve_call(hub, params, pending, ext, ns_static, true)
2688            }
2689        )?;
2690
2691        register_input_methods(&mut module, ns_static)?;
2692
2693        // Register {ns}.hash subscription
2694        let hub_for_hash = hub.clone();
2695        module.register_subscription(
2696            hash_method,
2697            PLEXUS_NOTIF_METHOD,
2698            hash_unsub,
2699            move |_params, pending, _ctx, ext| {
2700                let hub = hub_for_hash.clone();
2701                Box::pin(async move {
2702                    // AUTH-4: a gated hub's hash is the caller's view's.
2703                    let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2704                    let value = hub.own_hash(auth);
2705                    let stream = async_stream::stream! {
2706                        yield HashEvent::Hash { value };
2707                    };
2708                    let wrapped = super::streaming::wrap_stream(stream, hash_content_type, vec![ns_static.into()]);
2709                    pipe_stream_to_subscription(pending, wrapped, &ext).await
2710                })
2711            }
2712        )?;
2713
2714        // Register {ns}.schema subscription
2715        let hub_for_schema = hub.clone();
2716        module.register_subscription(
2717            schema_method,
2718            PLEXUS_NOTIF_METHOD,
2719            schema_unsub,
2720            move |params, pending, _ctx, ext| {
2721                let hub = hub_for_schema.clone();
2722                Box::pin(async move {
2723                    let p: SchemaParams = params.parse().unwrap_or_default();
2724                    // AUTH-4: a gated hub answers from the caller's view.
2725                    let auth = ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref());
2726                    let mut plugin_schema = hub.own_schema(auth);
2727                    // CA-1: hub-derived site hints on the hub's own schema.
2728                    if let Some(site) = hub.derived_site_hint() {
2729                        plugin_schema.fill_site_hints(&site);
2730                    }
2731
2732                    let result = if let Some(ref name) = p.method {
2733                        plugin_schema.methods.iter()
2734                            .find(|m| m.name == *name)
2735                            .map(|m| super::SchemaResult::Method(m.clone()))
2736                            .ok_or_else(|| jsonrpsee::types::ErrorObject::owned(
2737                                -32602,
2738                                format!("Method '{}' not found", name),
2739                                None::<()>,
2740                            ))?
2741                    } else {
2742                        super::SchemaResult::Plugin(plugin_schema)
2743                    };
2744
2745                    let stream = async_stream::stream! {
2746                        yield result;
2747                    };
2748                    let wrapped = super::streaming::wrap_stream(stream, schema_content_type, vec![ns_static.into()]);
2749                    pipe_stream_to_subscription(pending, wrapped, &ext).await
2750                })
2751            }
2752        )?;
2753
2754        // Register _info well-known endpoint (no namespace prefix).
2755        // Returns backend name + auth_capabilities (AUTHZ-CORE-3) as a
2756        // single-item stream with automatic Done event. Same payload shape as
2757        // the sibling registration in into_rpc_module.
2758        let info_payload = build_info_payload(
2759            hub.runtime_namespace(),
2760            hub.inner.auth_capabilities.as_ref(),
2761        );
2762        // AUTH-4: a gated hub answers `_info` per caller; without a gate the
2763        // payload is built once, as before.
2764        let hub_for_info = hub.inner.gate.is_some().then(|| hub.clone());
2765        module.register_subscription(
2766            "_info",
2767            PLEXUS_NOTIF_METHOD,
2768            "_info_unsub",
2769            move |_params, pending, _ctx, ext| {
2770                let payload = match hub_for_info.as_ref() {
2771                    Some(hub) => hub.info(ext.get::<std::sync::Arc<super::auth::AuthContext>>().map(|a| a.as_ref())),
2772                    None => info_payload.clone(),
2773                };
2774                Box::pin(async move {
2775                    // Create a single-item stream with the info response
2776                    let info_stream = futures::stream::once(async move { payload });
2777
2778                    // Wrap to auto-append Done event
2779                    let wrapped = super::streaming::wrap_stream(
2780                        info_stream,
2781                        "_info",
2782                        vec![]
2783                    );
2784
2785                    // Pipe to subscription (handles Done automatically)
2786                    pipe_stream_to_subscription(pending, wrapped, &ext).await
2787                })
2788            }
2789        )?;
2790
2791        // Register {ns}.respond method for WebSocket bidirectional responses
2792        // This allows clients to respond to server-initiated requests (like confirmations/prompts)
2793        let respond_method: &'static str = Box::leak(format!("{}.respond", ns).into_boxed_str());
2794        // BIDIR-13: only the connection that was asked answers — the pipe
2795        // bound each pending question to it as its `Request` item went out;
2796        // another connection's answer is `not_this_call` and the question
2797        // stays. BIDIR-9 retires this method for answers on the call itself.
2798        module.register_async_method(respond_method, |params, _ctx, ext| async move {
2799            use super::bidirectional::{answer_pending, BidirError};
2800
2801            let p: RespondParams = params.parse()?;
2802            let from = ext.get::<jsonrpsee::ConnectionId>().map(|c| c.0);
2803
2804            tracing::debug!(
2805                request_id = %p.request_id,
2806                connection = ?from,
2807                "Handling {}.respond via WebSocket",
2808                "plexus"
2809            );
2810
2811            match answer_pending(&p.request_id, from, p.response_data) {
2812                Ok(()) => Ok(serde_json::json!({"success": true})),
2813                Err(BidirError::NotThisCall) => {
2814                    tracing::warn!(request_id = %p.request_id, connection = ?from, "respond from a connection that was not asked");
2815                    Err(jsonrpsee::types::ErrorObject::owned(
2816                        -32003,
2817                        format!("not_this_call: request {} was asked on another connection", p.request_id),
2818                        Some(serde_json::json!({"error_kind": "not_this_call", "request_id": p.request_id})),
2819                    ))
2820                }
2821                Err(BidirError::UnknownRequest) => {
2822                    tracing::warn!(request_id = %p.request_id, "Unknown request ID in respond");
2823                    Err(jsonrpsee::types::ErrorObject::owned(
2824                        -32602,
2825                        format!("Unknown request ID: {}. The request may have timed out or been cancelled.", p.request_id),
2826                        None::<()>,
2827                    ))
2828                }
2829                Err(BidirError::ChannelClosed) => {
2830                    tracing::warn!(request_id = %p.request_id, "Channel closed in respond");
2831                    Err(jsonrpsee::types::ErrorObject::owned(
2832                        -32000,
2833                        "Response channel was closed (request may have timed out)",
2834                        None::<()>,
2835                    ))
2836                }
2837                Err(e) => {
2838                    tracing::error!(request_id = %p.request_id, error = ?e, "Error in respond");
2839                    Err(jsonrpsee::types::ErrorObject::owned(
2840                        -32000,
2841                        format!("Failed to deliver response: {}", e),
2842                        None::<()>,
2843                    ))
2844                }
2845            }
2846        })?;
2847
2848        // Register pending RPC methods from activations
2849        // AUTH-2: not under a grant gate — see `into_rpc_module`.
2850        let mut pending = std::mem::take(&mut *hub.inner.pending_rpc.lock().unwrap());
2851        if hub.inner.gate.is_some() {
2852            pending.clear();
2853        }
2854        tracing::trace!(factories = pending.len(), "merging activation RPC factories");
2855        for (idx, factory) in pending.into_iter().enumerate() {
2856            tracing::trace!(factory_idx = idx, "calling factory to get Methods");
2857            let methods = factory();
2858            let method_count = methods.method_names().count();
2859            tracing::trace!(factory_idx = idx, methods = method_count, "factory returned Methods; merging into module");
2860            module.merge(methods)?;
2861            tracing::trace!(factory_idx = idx, "successfully merged factory methods");
2862        }
2863        tracing::trace!("all activations merged successfully");
2864
2865        // CHILD-WIRE: for each registered child router with capability bits set,
2866        // register {ns}.list_children / {ns}.search_children as subscriptions.
2867        for (ns, router) in hub.inner.child_routers.iter() {
2868            register_child_capability_methods(&mut module, ns, router.clone())?;
2869        }
2870
2871        Ok(module)
2872    }
2873}
2874
2875/// CHILD-WIRE: register per-activation namespaced `<ns>.list_children` and
2876/// `<ns>.search_children` as subscription methods when the router advertises
2877/// the corresponding capability bits.
2878///
2879/// Each name returned by `ChildRouter::list_children` / `search_children` is
2880/// emitted as a `data` envelope with `content_type` set to the method name
2881/// (`"list_children"` or `"search_children"`) and `content` carrying the name
2882/// string. Termination is `done`. Mirrors the standard `wrap_stream` shape
2883/// used by every other framework subscription.
2884///
2885/// Activations that advertise neither bit produce no registrations — calling
2886/// the methods returns standard `methodNotFound`. That's the wire-level
2887/// signal that the activation doesn't support enumeration / search.
2888#[allow(deprecated)] // ChildCapabilities is deprecated by IR-4 but still the wire-level signal
2889fn register_child_capability_methods(
2890    module: &mut RpcModule<()>,
2891    namespace: &str,
2892    router: Arc<dyn ChildRouter>,
2893) -> Result<(), jsonrpsee::core::RegisterMethodError> {
2894    let caps = router.capabilities();
2895    if caps.is_empty() {
2896        return Ok(());
2897    }
2898
2899    let ns_static: &'static str = Box::leak(namespace.to_string().into_boxed_str());
2900
2901    if caps.contains(ChildCapabilities::LIST) {
2902        let list_method: &'static str =
2903            Box::leak(format!("{}.list_children", namespace).into_boxed_str());
2904        let list_unsub: &'static str =
2905            Box::leak(format!("{}.list_children_unsub", namespace).into_boxed_str());
2906        let router_for_list = router.clone();
2907        module.register_subscription(
2908            list_method,
2909            PLEXUS_NOTIF_METHOD,
2910            list_unsub,
2911            move |_params, pending, _ctx, ext| {
2912                let router = router_for_list.clone();
2913                Box::pin(async move {
2914                    // Collect names eagerly so the BoxStream's borrow on the
2915                    // router doesn't outlive list_children's call. For v1 this
2916                    // matches the typical pattern (small finite child sets like
2917                    // Solar's eight planets). A future variant could keep the
2918                    // Arc-borrow alive across the stream by binding the BoxStream
2919                    // to the Arc directly — out of scope here.
2920                    let collected: Vec<String> = match router.list_children().await {
2921                        Some(mut s) => {
2922                            use futures::StreamExt;
2923                            let mut acc = Vec::new();
2924                            while let Some(name) = s.next().await {
2925                                acc.push(name);
2926                            }
2927                            acc
2928                        }
2929                        None => Vec::new(),
2930                    };
2931                    let stream = async_stream::stream! {
2932                        for name in collected {
2933                            yield name;
2934                        }
2935                    };
2936                    let wrapped = super::streaming::wrap_stream(
2937                        stream,
2938                        "list_children",
2939                        vec![ns_static.into()],
2940                    );
2941                    pipe_stream_to_subscription(pending, wrapped, &ext).await
2942                })
2943            },
2944        )?;
2945    }
2946
2947    if caps.contains(ChildCapabilities::SEARCH) {
2948        let search_method: &'static str =
2949            Box::leak(format!("{}.search_children", namespace).into_boxed_str());
2950        let search_unsub: &'static str =
2951            Box::leak(format!("{}.search_children_unsub", namespace).into_boxed_str());
2952        let router_for_search = router.clone();
2953        module.register_subscription(
2954            search_method,
2955            PLEXUS_NOTIF_METHOD,
2956            search_unsub,
2957            move |params, pending, _ctx, ext| {
2958                let router = router_for_search.clone();
2959                Box::pin(async move {
2960                    let p: SearchChildrenParams = params.parse()?;
2961                    let collected: Vec<String> = match router.search_children(&p.query).await {
2962                        Some(mut s) => {
2963                            use futures::StreamExt;
2964                            let mut acc = Vec::new();
2965                            while let Some(name) = s.next().await {
2966                                acc.push(name);
2967                            }
2968                            acc
2969                        }
2970                        None => Vec::new(),
2971                    };
2972                    let stream = async_stream::stream! {
2973                        for name in collected {
2974                            yield name;
2975                        }
2976                    };
2977                    let wrapped = super::streaming::wrap_stream(
2978                        stream,
2979                        "search_children",
2980                        vec![ns_static.into()],
2981                    );
2982                    pipe_stream_to_subscription(pending, wrapped, &ext).await
2983                })
2984            },
2985        )?;
2986    }
2987
2988    Ok(())
2989}
2990
2991/// Params for `<ns>.search_children`
2992#[derive(Debug, serde::Deserialize)]
2993struct SearchChildrenParams {
2994    query: String,
2995}
2996
2997/// Params for {ns}.call
2998#[derive(Debug, serde::Deserialize)]
2999pub(crate) struct CallParams {
3000    pub(crate) method: String,
3001    #[serde(default)]
3002    pub(crate) params: Option<Value>,
3003}
3004
3005/// BIDIR-6: [`DynamicHub::input_terms`]' answer.
3006pub(crate) struct InputTerms {
3007    pub(crate) grant: String,
3008    pub(crate) targets: Vec<String>,
3009    pub(crate) recheck: bool,
3010}
3011
3012/// Params for {ns}.schema (SYNAPSE-CC-9: the published type)
3013use super::schema::SchemaParams;
3014
3015/// Params for {ns}.respond (WebSocket bidirectional response)
3016#[derive(Debug, serde::Deserialize)]
3017struct RespondParams {
3018    request_id: String,
3019    response_data: Value,
3020}
3021
3022/// `{ns}.call`: route the call, then pipe what it answers.
3023///
3024/// The call's future is boxed here, and is its one allocation of that size,
3025/// so it is chosen before it is made: a method the service knows has no
3026/// `Input` is routed and piped as it was before BIDIR-6,
3027/// holding nothing of the input half (the seam inline in one future for both
3028/// was 1,024 bytes more a call, and the params kept beside it 176 more);
3029/// any other ([`DynamicHub::may_take_input`]) is [`serve_seamed`]. A
3030/// dispatch error is sent as a stream item on the
3031/// accepted subscription: this preserves its message and code, where
3032/// returning it from a subscription handler has jsonrpsee wrap it as generic
3033/// -32603.
3034fn serve_call(
3035    service: DynamicHub,
3036    params: jsonrpsee::types::Params<'static>,
3037    pending: jsonrpsee::PendingSubscriptionSink,
3038    ext: http::Extensions,
3039    ns: &'static str,
3040    identified: bool,
3041) -> CallFuture {
3042    // Read here, not in the future: the choice of future is made on it, and
3043    // the plain one then holds neither the params' text nor the method name.
3044    let call: CallParams = match params.parse() {
3045        Ok(call) => call,
3046        Err(e) => return Box::pin(async move { Err(e.into()) }),
3047    };
3048    if service.may_take_input(&call.method) {
3049        return Box::pin(serve_seamed(service, call, params, pending, ext, ns, identified));
3050    }
3051    let CallParams { method, params: args } = call;
3052    Box::pin(async move {
3053        let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().map(|a| a.as_ref()) } else { None };
3054        match service.route(&method, args.unwrap_or_default(), caller).await {
3055            Ok(stream) => pipe_stream_to_subscription(pending, stream, &ext).await,
3056            Err(e) => {
3057                let sink = pending.accept().await?;
3058                if let Some(raw) = error_item_raw(ns, &e) {
3059                    let _ = sink.send(raw).await;
3060                }
3061                Ok(())
3062            }
3063        }
3064    })
3065}
3066
3067/// A `{ns}.call`'s future, boxed: one allocation a call, the size of the
3068/// path it takes.
3069type CallFuture = std::pin::Pin<Box<dyn std::future::Future<Output = jsonrpsee::core::SubscriptionResult> + Send>>;
3070
3071/// [`serve_call`] for a method that may take an `Input`: the route runs
3072/// inside [`super::input::CALL`], holding the unaccepted subscription and the
3073/// extensions, and a method with an `Input` parameter takes them there
3074/// (BIDIR-6); one without leaves them.
3075async fn serve_seamed(
3076    service: DynamicHub,
3077    call: CallParams,
3078    params: jsonrpsee::types::Params<'static>,
3079    pending: jsonrpsee::PendingSubscriptionSink,
3080    ext: http::Extensions,
3081    ns: &'static str,
3082    identified: bool,
3083) -> jsonrpsee::core::SubscriptionResult {
3084    let caller = if identified { ext.get::<Arc<super::auth::AuthContext>>().cloned() } else { None };
3085    let seen = service.inner.gate.as_ref().map_or(0, |g| g.generation().current());
3086    let opened = Arc::new(std::sync::Mutex::new(None::<super::input::Opened>));
3087    let take = || opened.lock().unwrap_or_else(|e| e.into_inner()).take();
3088    let mut scoped = std::pin::pin!(super::input::CALL.scope(
3089        std::cell::RefCell::new(super::input::Seam { service: service.clone(), params, pending: Some(pending), ext, seen, opened: opened.clone(), refused: None }),
3090        service.route(&call.method, call.params.unwrap_or_default(), caller.as_deref()),
3091    ));
3092    // The route runs until it answers, or until the method has opened its
3093    // input half: a handler may read its input before it returns its stream,
3094    // so from the open the pipe runs (credit, items, cancel) beside the
3095    // route still resolving.
3096    let answered = std::future::poll_fn(|cx| match std::future::Future::poll(scoped.as_mut(), cx) {
3097        std::task::Poll::Ready(answer) => std::task::Poll::Ready(Some(answer)),
3098        std::task::Poll::Pending if opened.lock().unwrap_or_else(|e| e.into_inner()).is_some() => std::task::Poll::Ready(None),
3099        std::task::Poll::Pending => std::task::Poll::Pending,
3100    })
3101    .await;
3102    let Some(answer) = answered else {
3103        let super::input::Opened { sink, duplex } = take().expect("opened, the route still resolving");
3104        let mut routing = std::pin::pin!(async { scoped.as_mut().await.map_err(|e| error_item(ns, &e)) });
3105        return Box::pin(super::wire::pipe_duplex(sink, super::wire::Output::Routing(routing.as_mut()), duplex)).await;
3106    };
3107    let super::input::Seam { pending, ext, refused, .. } = scoped.as_mut().take_value().expect("the scope ran to its end").into_inner();
3108    match (answer, take()) {
3109        // Boxed: a call with no input half does not carry its room.
3110        (Ok(stream), Some(opened)) => Box::pin(super::wire::pipe_duplex(opened.sink, super::wire::Output::Ready(stream), opened.duplex)).await,
3111        (Ok(stream), None) => {
3112            let pending = pending.expect("only an open takes it, and an open is `opened`");
3113            pipe_stream_to_subscription(pending, stream, &ext).await
3114        }
3115        (Err(e), opened) => {
3116            let sink = match (opened, pending) {
3117                (Some(opened), _) => opened.sink,
3118                (None, Some(pending)) => pending.accept().await?,
3119                (None, None) => return Ok(()),
3120            };
3121            let raw = match refused {
3122                Some(item) => serde_json::value::to_raw_value(&item).ok(),
3123                None => error_item_raw(ns, &e),
3124            };
3125            if let Some(raw) = raw {
3126                let _ = sink.send(raw).await;
3127            }
3128            Ok(())
3129        }
3130    }
3131}
3132
3133/// BIDIR-6: `{ns}.input` and `{ns}.end` in the method table, for a client
3134/// that sends them as requests and wants an answer (`true`: it reached the
3135/// call; `false`: a resend, or the half has closed). The notification, which
3136/// is what a client normally sends, is taken on the socket's reader before
3137/// the table. Sync methods, so a request is run in place, in order.
3138fn register_input_methods(module: &mut RpcModule<()>, ns: &'static str) -> Result<(), jsonrpsee::core::RegisterMethodError> {
3139    use super::input::{Delivered, InputTable};
3140    use jsonrpsee::types::ErrorObjectOwned;
3141
3142    fn answer(delivered: Delivered) -> Result<bool, ErrorObjectOwned> {
3143        match delivered {
3144            Delivered::Taken => Ok(true),
3145            Delivered::Dropped | Delivered::Refused => Ok(false),
3146            Delivered::NotThisCall => Err(ErrorObjectOwned::owned(
3147                -32003,
3148                "not_this_call: input comes from the connection that opened the call",
3149                Some(serde_json::json!({"error_kind": "not_this_call"})),
3150            )),
3151            Delivered::Malformed => Err(ErrorObjectOwned::owned(-32602, "invalid params: subscription, seq and items", None::<()>)),
3152        }
3153    }
3154    fn table(ext: &http::Extensions) -> Result<&Arc<InputTable>, ErrorObjectOwned> {
3155        ext.get::<super::wire::FrameSink>()
3156            .and_then(super::wire::FrameSink::inputs)
3157            .ok_or_else(|| ErrorObjectOwned::owned(-32601, "this transport carries no input half: call over a WebSocket", None::<()>))
3158    }
3159
3160    let input_method: &'static str = Box::leak(format!("{ns}.input").into_boxed_str());
3161    let end_method: &'static str = Box::leak(format!("{ns}.end").into_boxed_str());
3162    module.register_method(input_method, move |params, _ctx, ext| {
3163        let frame = bytes::Bytes::copy_from_slice(params.as_str().unwrap_or("null").as_bytes());
3164        answer(table(ext)?.input(ns, &frame, &frame))
3165    })?;
3166    module.register_method(end_method, move |params, _ctx, ext| answer(table(ext)?.end(ns, params.as_str().unwrap_or("null").as_bytes())))?;
3167    Ok(())
3168}
3169
3170/// Pipe a call's stream to its subscription: accept it, then
3171/// [`super::wire::pipe`] — each item encoded once and written as one frame
3172/// (PERF-7), on the transport's own frames when the call's extensions
3173/// carry them.
3174///
3175/// Notifications are sent with the `notif_method_name` each
3176/// `register_subscription` call set.
3177///
3178/// BIDIR-13: a `Request` item (an in-call question) is bound to this
3179/// subscription's connection before it is sent, so `{ns}.respond` takes its
3180/// answer from that connection alone; and the pipe watches the sink's close
3181/// (an unsubscribe, a lost socket), dropping the stream at once — a call
3182/// waiting on a question is dropped with its pending entry, not left until
3183/// the question's timeout.
3184async fn pipe_stream_to_subscription(
3185    pending: jsonrpsee::PendingSubscriptionSink,
3186    stream: PlexusStream,
3187    ext: &http::Extensions,
3188) -> jsonrpsee::core::SubscriptionResult {
3189    let sink = pending.accept().await?;
3190    super::wire::pipe(sink, stream, ext).await
3191}
3192
3193// ============================================================================
3194// DynamicHub RPC Methods (via plexus-macros)
3195// ============================================================================
3196
3197#[plexus_macros::activation(
3198    namespace = "plexus",
3199    version = "1.0.0",
3200    description = "Central routing and introspection",
3201    hub,
3202    namespace_fn = "runtime_namespace"
3203)]
3204#[allow(deprecated)]
3205impl DynamicHub {
3206    /// Route a call to a registered activation
3207    #[plexus_macros::method(
3208        description = "Route a call to a registered activation",
3209        params(
3210            method = "The method to call (format: namespace.method)",
3211            params = "Parameters to pass to the method (optional, defaults to {})"
3212        )
3213    )]
3214    async fn call(
3215        &self,
3216        method: String,
3217        params: Option<Value>,
3218    ) -> impl Stream<Item = super::types::PlexusStreamItem> + Send + 'static {
3219        use super::context::PlexusContext;
3220        use super::types::{PlexusStreamItem, StreamMetadata};
3221
3222        let result = self.route(&method, params.unwrap_or_default(), None).await;
3223
3224        match result {
3225            Ok(plexus_stream) => {
3226                // Forward the routed stream directly - it already contains PlexusStreamItems
3227                plexus_stream
3228            }
3229            Err(e) => {
3230                // Return error as a PlexusStreamItem stream
3231                let metadata = StreamMetadata::new(
3232                    vec![self.inner.namespace.clone()],
3233                    PlexusContext::hash(),
3234                );
3235                Box::pin(futures::stream::once(async move {
3236                    PlexusStreamItem::from_plexus_error(metadata, &e, false)
3237                }))
3238            }
3239        }
3240    }
3241
3242    /// Get Plexus RPC server configuration hash (from the recursive schema)
3243    ///
3244    /// This hash changes whenever any method or child activation changes.
3245    /// It's computed from the method hashes rolled up through the schema tree.
3246    #[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.")]
3247    async fn hash(&self) -> impl Stream<Item = HashEvent> + Send + 'static {
3248        let schema = Activation::plugin_schema(self);
3249        stream! { yield HashEvent::Hash { value: schema.hash }; }
3250    }
3251
3252    /// Get plugin hashes for cache validation (lightweight alternative to full schema)
3253    #[plexus_macros::method(description = "Get plugin hashes for cache validation")]
3254    #[allow(deprecated)]
3255    async fn hashes(&self) -> impl Stream<Item = PluginHashes> + Send + 'static {
3256        let schema = Activation::plugin_schema(self);
3257
3258        stream! {
3259            yield PluginHashes {
3260                namespace: schema.namespace.clone(),
3261                self_hash: schema.self_hash.clone(),
3262                children_hash: schema.children_hash.clone(),
3263                hash: schema.hash.clone(),
3264                children: schema.children.as_ref().map(|kids| {
3265                    kids.iter()
3266                        .map(|c| ChildHashes {
3267                            namespace: c.namespace.clone(),
3268                            hash: c.hash.clone(),
3269                        })
3270                        .collect()
3271                }),
3272            };
3273        }
3274    }
3275
3276    /// RETURNS-40: the service's IR — IR 3.0, every type once and each
3277    /// method referring to them — of the namespaces asked (none: the whole
3278    /// service), as the caller sees the service. The one way to ask for
3279    /// several schemas; `<ns>.schema` answers one. Equal to what synapse
3280    /// builds from the same raw schemas.
3281    #[plexus_macros::method(
3282        description = "The service's IR (3.0): every type once, each method referring to them — of the namespaces asked, or the whole service",
3283        params(namespaces = "The namespaces (dotted paths) to describe; none: the whole service")
3284    )]
3285    async fn ir(
3286        &self,
3287        auth: Option<&super::auth::AuthContext>,
3288        namespaces: Option<Vec<String>>,
3289    ) -> Result<super::ir::ServiceIr, super::ir::IrError> {
3290        self.service_ir(&namespaces.unwrap_or_default(), auth).await
3291    }
3292
3293    // Note: schema() method is auto-generated by hub-macro for all activations
3294}
3295
3296// ============================================================================
3297// HubContext Implementation for Weak<DynamicHub>
3298// ============================================================================
3299
3300use super::hub_context::HubContext;
3301use std::sync::Weak;
3302
3303/// HubContext implementation for Weak<DynamicHub>
3304///
3305/// This enables activations to receive a weak reference to their parent DynamicHub,
3306/// allowing them to resolve handles and route calls through the hub without
3307/// creating reference cycles.
3308#[async_trait]
3309impl HubContext for Weak<DynamicHub> {
3310    async fn resolve_handle(&self, handle: &Handle) -> Result<PlexusStream, PlexusError> {
3311        let hub = self.upgrade().ok_or_else(|| {
3312            PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3313        })?;
3314        hub.do_resolve_handle(handle).await
3315    }
3316
3317    async fn call(&self, method: &str, params: serde_json::Value) -> Result<PlexusStream, PlexusError> {
3318        let hub = self.upgrade().ok_or_else(|| {
3319            PlexusError::ExecutionError("Parent hub has been dropped".to_string())
3320        })?;
3321        hub.route(method, params, None).await
3322    }
3323
3324    fn is_valid(&self) -> bool {
3325        self.upgrade().is_some()
3326    }
3327}
3328
3329/// ChildRouter implementation for DynamicHub
3330///
3331/// This enables nested routing through registered activations.
3332/// e.g., hub.call("solar.mercury.info") routes to solar → mercury → info
3333#[async_trait]
3334impl ChildRouter for DynamicHub {
3335    fn router_namespace(&self) -> &str {
3336        &self.inner.namespace
3337    }
3338
3339    async fn router_call(&self, method: &str, params: Value, auth: Option<&super::auth::AuthContext>, raw_ctx: Option<&crate::request::RawRequestContext>) -> Result<PlexusStream, PlexusError> {
3340        // DynamicHub routes via its registered activations
3341        // Method format: "activation.method" or "activation.child.method"
3342        self.route_with_ctx(method, params, auth, raw_ctx).await
3343    }
3344
3345    async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
3346        // Look up registered activations that implement ChildRouter
3347        self.inner.child_routers.get(name)
3348            .map(|router| {
3349                // Clone the Arc and wrap in Box for the trait object
3350                Box::new(ArcChildRouter(router.clone())) as Box<dyn ChildRouter>
3351            })
3352    }
3353
3354    /// AUTHLANG-3 — consult the hub's
3355    /// [`ForwardPolicyRegistry`](super::forward_registry::ForwardPolicyRegistry).
3356    fn forward_policy_for(
3357        &self,
3358        callee_ns: &str,
3359    ) -> Option<std::sync::Arc<dyn plexus_auth_core::ForwardPolicy>> {
3360        self.inner.forward_policies.get(callee_ns)
3361    }
3362
3363    // `framework_stamped_principal` retains the trait default
3364    // (`Principal::Anonymous`) for now. AUTHLANG-3 wires the dispatch path
3365    // to read this; populating it with the per-connection stamp lands
3366    // when the principal-minting service (post-AUTHZ-0 / future
3367    // CRED-CORE) is wired into the WS upgrade path. The current
3368    // anonymous return value is correct under today's no-auth substrate.
3369}
3370
3371#[cfg(test)]
3372#[allow(deprecated)]
3373mod tests {
3374    use super::*;
3375
3376    #[test]
3377    fn dynamic_hub_implements_activation() {
3378        fn assert_activation<T: Activation>() {}
3379        assert_activation::<DynamicHub>();
3380    }
3381
3382    #[test]
3383    fn dynamic_hub_methods() {
3384        let hub = DynamicHub::new("test");
3385        let methods = hub.methods();
3386        assert!(methods.contains(&"call"));
3387        assert!(methods.contains(&"hash"));
3388        assert!(methods.contains(&"schema"));
3389        // list_activations was removed - use schema() instead
3390    }
3391
3392    #[test]
3393    fn dynamic_hub_hash_stable() {
3394        let h1 = DynamicHub::new("test");
3395        let h2 = DynamicHub::new("test");
3396        assert_eq!(h1.compute_hash(), h2.compute_hash());
3397    }
3398
3399    #[test]
3400    fn dynamic_hub_is_hub() {
3401        use crate::activations::health::Health;
3402        let hub = DynamicHub::new("test").register(Health::new());
3403        let schema = hub.plugin_schema();
3404
3405        // DynamicHub should be a hub (has children)
3406        assert!(schema.is_hub(), "dynamic hub should be a hub");
3407        assert!(!schema.is_leaf(), "dynamic hub should not be a leaf");
3408
3409        // Should have children (as summaries)
3410        let children = schema.children.expect("dynamic hub should have children");
3411        assert!(!children.is_empty(), "dynamic hub should have at least one child");
3412
3413        // Health should be in the children summaries
3414        let health = children.iter().find(|c| c.namespace == "health").expect("should have health child");
3415        assert!(!health.hash.is_empty(), "health should have a hash");
3416    }
3417
3418    /// Z2H-8 / HOSTLESS-3 — a hub root that shares its name with a registered
3419    /// activation's namespace is rejected loudly at registration time instead
3420    /// of producing a silently unreachable child (the shipped echo example's
3421    /// exact failure shape).
3422    #[test]
3423    #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3424    fn dynamic_hub_rejects_root_namespace_shadow() {
3425        use crate::activations::health::Health;
3426        let _hub = DynamicHub::new("health").register(Health::new());
3427    }
3428
3429    /// Z2H-8 / HOSTLESS-3 — the deprecated register_hub path enforces the
3430    /// same collision contract.
3431    #[test]
3432    #[should_panic(expected = "activation namespace 'health' collides with the hub root namespace 'health'")]
3433    fn dynamic_hub_register_hub_rejects_root_namespace_shadow() {
3434        use crate::activations::health::Health;
3435        let _hub = DynamicHub::new("health").register_hub(Health::new());
3436    }
3437
3438    /// Z2H-8 — the shadow error names both colliding strings and suggests the
3439    /// fix (rename the hub root), so the failure is actionable without
3440    /// reading plexus-core source.
3441    #[test]
3442    fn dynamic_hub_shadow_error_names_collision_and_fix() {
3443        use crate::activations::health::Health;
3444        let result = std::panic::catch_unwind(|| {
3445            let _hub = DynamicHub::new("health").register(Health::new());
3446        });
3447        let err = result.expect_err("shadow registration must panic");
3448        let msg = err
3449            .downcast_ref::<String>()
3450            .cloned()
3451            .or_else(|| err.downcast_ref::<&str>().map(|s| s.to_string()))
3452            .expect("panic payload should be a string");
3453        assert!(msg.contains("'health'"), "must name the colliding namespace: {msg}");
3454        assert!(msg.contains("hub root namespace"), "must name the root side: {msg}");
3455        assert!(msg.contains("rename the hub root"), "must suggest the fix: {msg}");
3456        assert!(msg.contains("Z2H-8"), "must cite the ticket: {msg}");
3457    }
3458
3459    /// Z2H-8 — non-colliding registration is unaffected by shadow detection:
3460    /// the child registers, routes, and appears in the schema.
3461    #[test]
3462    fn dynamic_hub_non_colliding_registration_unaffected() {
3463        use crate::activations::health::Health;
3464        let hub = DynamicHub::new("health_hub").register(Health::new());
3465        assert_eq!(hub.runtime_namespace(), "health_hub");
3466        let schema = hub.plugin_schema();
3467        let children = schema.children.expect("hub should have children");
3468        assert!(
3469            children.iter().any(|c| c.namespace == "health"),
3470            "health child must be registered"
3471        );
3472        assert!(hub.list_methods().iter().any(|m| m.starts_with("health.")));
3473    }
3474
3475    #[test]
3476    fn dynamic_hub_schema_structure() {
3477        use crate::activations::health::Health;
3478        let hub = DynamicHub::new("test").register(Health::new());
3479        let schema = hub.plugin_schema();
3480
3481        // Pretty print the schema
3482        let json = serde_json::to_string_pretty(&schema).unwrap();
3483        println!("DynamicHub schema:\n{}", json);
3484
3485        // Verify structure
3486        assert_eq!(schema.namespace, "test");
3487        assert!(schema.methods.iter().any(|m| m.name == "call"));
3488        assert!(schema.children.is_some());
3489    }
3490
3491    // ========================================================================
3492    // INVARIANT: Handle routing - resolves to correct plugin
3493    // ========================================================================
3494
3495    #[tokio::test]
3496    async fn invariant_resolve_handle_unknown_activation() {
3497        use crate::activations::health::Health;
3498        use crate::types::Handle;
3499        use uuid::Uuid;
3500
3501        let hub = DynamicHub::new("test").register(Health::new());
3502
3503        // Handle for an unregistered activation (random UUID)
3504        let unknown_plugin_id = Uuid::new_v4();
3505        let handle = Handle::new(unknown_plugin_id, "1.0.0", "some_method");
3506
3507        let result = hub.do_resolve_handle(&handle).await;
3508
3509        match result {
3510            Err(PlexusError::ActivationNotFound(_)) => {
3511                // Expected - activation not found
3512            }
3513            Err(other) => panic!("Expected ActivationNotFound, got {:?}", other),
3514            Ok(_) => panic!("Expected error for unknown activation"),
3515        }
3516    }
3517
3518    #[tokio::test]
3519    async fn invariant_resolve_handle_unsupported() {
3520        use crate::activations::health::Health;
3521        use crate::types::Handle;
3522
3523        let hub = DynamicHub::new("test").register(Health::new());
3524
3525        // Handle for health activation (which doesn't support handle resolution)
3526        let handle = Handle::new(Health::PLUGIN_ID, "1.0.0", "check");
3527
3528        let result = hub.do_resolve_handle(&handle).await;
3529
3530        match result {
3531            Err(PlexusError::HandleNotSupported(name)) => {
3532                assert_eq!(name, "health");
3533            }
3534            Err(other) => panic!("Expected HandleNotSupported, got {:?}", other),
3535            Ok(_) => panic!("Expected error for unsupported handle"),
3536        }
3537    }
3538
3539    #[tokio::test]
3540    async fn invariant_resolve_handle_routes_by_plugin_id() {
3541        use crate::activations::health::Health;
3542        use crate::activations::echo::EchoActivation;
3543        use crate::types::Handle;
3544        use uuid::Uuid;
3545
3546        let health = Health::new();
3547        let echo = EchoActivation::new();
3548        let health_plugin_id = health.plugin_id();
3549        let echo_plugin_id = echo.plugin_id();
3550
3551        let hub = DynamicHub::new("test")
3552            .register(health)
3553            .register(echo);
3554
3555        // Health handle → health activation
3556        let health_handle = Handle::new(health_plugin_id, "1.0.0", "check");
3557        match hub.do_resolve_handle(&health_handle).await {
3558            Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "health"),
3559            Err(other) => panic!("health handle should route to health activation, got {:?}", other),
3560            Ok(_) => panic!("health handle should return HandleNotSupported"),
3561        }
3562
3563        // Echo handle → echo activation
3564        let echo_handle = Handle::new(echo_plugin_id, "1.0.0", "echo");
3565        match hub.do_resolve_handle(&echo_handle).await {
3566            Err(PlexusError::HandleNotSupported(name)) => assert_eq!(name, "echo"),
3567            Err(other) => panic!("echo handle should route to echo activation, got {:?}", other),
3568            Ok(_) => panic!("echo handle should return HandleNotSupported"),
3569        }
3570
3571        // Unknown handle → ActivationNotFound (random UUID not registered)
3572        let unknown_handle = Handle::new(Uuid::new_v4(), "1.0.0", "method");
3573        match hub.do_resolve_handle(&unknown_handle).await {
3574            Err(PlexusError::ActivationNotFound(_)) => { /* expected */ },
3575            Err(other) => panic!("unknown handle should return ActivationNotFound, got {:?}", other),
3576            Ok(_) => panic!("unknown handle should return ActivationNotFound"),
3577        }
3578    }
3579
3580    #[test]
3581    fn invariant_handle_plugin_id_determines_routing() {
3582        use crate::activations::health::Health;
3583        use crate::activations::echo::EchoActivation;
3584        use crate::types::Handle;
3585
3586        let health = Health::new();
3587        let echo = EchoActivation::new();
3588
3589        // Same meta, different activations → different routing targets (by plugin_id)
3590        let health_handle = Handle::new(health.plugin_id(), "1.0.0", "check")
3591            .with_meta(vec!["msg-123".into(), "user".into()]);
3592        let echo_handle = Handle::new(echo.plugin_id(), "1.0.0", "echo")
3593            .with_meta(vec!["msg-123".into(), "user".into()]);
3594
3595        // Different plugin_ids ensure different routing
3596        assert_ne!(health_handle.plugin_id, echo_handle.plugin_id);
3597    }
3598
3599    // ========================================================================
3600    // Plugin Registry Tests
3601    // ========================================================================
3602
3603    #[test]
3604    fn plugin_registry_basic_operations() {
3605        let mut registry = PluginRegistry::new();
3606        let id = uuid::Uuid::new_v4();
3607
3608        // Register an activation
3609        registry.register(id, "test_plugin".to_string(), "test".to_string());
3610
3611        // Lookup by ID
3612        assert_eq!(registry.lookup(id), Some("test_plugin"));
3613
3614        // Lookup by path
3615        assert_eq!(registry.lookup_by_path("test_plugin"), Some(id));
3616
3617        // Get entry
3618        let entry = registry.get(id).expect("should have entry");
3619        assert_eq!(entry.path, "test_plugin");
3620        assert_eq!(entry.plugin_type, "test");
3621    }
3622
3623    #[test]
3624    fn plugin_registry_populated_on_register() {
3625        use crate::activations::health::Health;
3626
3627        let hub = DynamicHub::new("test").register(Health::new());
3628
3629        let registry = hub.registry();
3630        assert!(!registry.is_empty(), "registry should not be empty after registration");
3631
3632        // Health activation should be registered
3633        let health_id = registry.lookup_by_path("health");
3634        assert!(health_id.is_some(), "health should be registered by path");
3635
3636        // Should be able to look up path by ID
3637        let health_uuid = health_id.unwrap();
3638        assert_eq!(registry.lookup(health_uuid), Some("health"));
3639    }
3640
3641    #[test]
3642    fn plugin_registry_deterministic_uuid() {
3643        use crate::activations::health::Health;
3644
3645        // Same activation registered twice should produce same UUID
3646        let health1 = Health::new();
3647        let health2 = Health::new();
3648
3649        assert_eq!(health1.plugin_id(), health2.plugin_id(),
3650            "same activation type should have deterministic UUID");
3651
3652        // UUID should be based on namespace+major_version (semver compatibility)
3653        let expected = uuid::Uuid::new_v5(
3654            &uuid::Uuid::NAMESPACE_OID,
3655            b"health@1"
3656        );
3657        assert_eq!(health1.plugin_id(), expected,
3658            "plugin_id should be deterministic from namespace@major_version");
3659    }
3660
3661    // ========================================================================
3662    // CHILD-2: ChildRouter capabilities + opt-in list/search
3663    // ========================================================================
3664
3665    /// A minimal `ChildRouter` that overrides only the required methods.
3666    /// Exercises default implementations of `capabilities`, `list_children`
3667    /// and `search_children`.
3668    struct MinimalRouter;
3669
3670    #[async_trait]
3671    impl ChildRouter for MinimalRouter {
3672        fn router_namespace(&self) -> &str {
3673            "minimal"
3674        }
3675
3676        async fn router_call(
3677            &self,
3678            _method: &str,
3679            _params: Value,
3680            _auth: Option<&super::super::auth::AuthContext>,
3681            _raw_ctx: Option<&crate::request::RawRequestContext>,
3682        ) -> Result<PlexusStream, PlexusError> {
3683            Err(PlexusError::MethodNotFound {
3684                activation: "minimal".into(),
3685                method: "none".into(),
3686            })
3687        }
3688
3689        async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
3690            None
3691        }
3692    }
3693
3694    #[tokio::test]
3695    async fn child_router_defaults_report_no_capabilities_and_none_streams() {
3696        let router = MinimalRouter;
3697
3698        assert_eq!(
3699            router.capabilities(),
3700            ChildCapabilities::empty(),
3701            "default capabilities should be empty"
3702        );
3703        assert!(
3704            router.list_children().await.is_none(),
3705            "default list_children should be None"
3706        );
3707        assert!(
3708            router.search_children("anything").await.is_none(),
3709            "default search_children should be None"
3710        );
3711    }
3712
3713    /// A `ChildRouter` that opts in to both LIST and SEARCH.
3714    struct ListingRouter {
3715        names: Vec<String>,
3716    }
3717
3718    #[async_trait]
3719    impl ChildRouter for ListingRouter {
3720        fn router_namespace(&self) -> &str {
3721            "listing"
3722        }
3723
3724        async fn router_call(
3725            &self,
3726            _method: &str,
3727            _params: Value,
3728            _auth: Option<&super::super::auth::AuthContext>,
3729            _raw_ctx: Option<&crate::request::RawRequestContext>,
3730        ) -> Result<PlexusStream, PlexusError> {
3731            Err(PlexusError::MethodNotFound {
3732                activation: "listing".into(),
3733                method: "none".into(),
3734            })
3735        }
3736
3737        async fn get_child(&self, name: &str) -> Option<Box<dyn ChildRouter>> {
3738            if self.names.iter().any(|n| n == name) {
3739                // Return the same type to keep the test simple; we only care
3740                // that the override compiles and is reachable.
3741                Some(Box::new(ListingRouter { names: vec![] }))
3742            } else {
3743                None
3744            }
3745        }
3746
3747        fn capabilities(&self) -> ChildCapabilities {
3748            ChildCapabilities::LIST | ChildCapabilities::SEARCH
3749        }
3750
3751        async fn list_children(&self) -> Option<BoxStream<'_, String>> {
3752            let stream = futures::stream::iter(self.names.iter().cloned());
3753            Some(Box::pin(stream))
3754        }
3755
3756        async fn search_children(&self, query: &str) -> Option<BoxStream<'_, String>> {
3757            let q = query.to_string();
3758            let stream = futures::stream::iter(
3759                self.names
3760                    .iter()
3761                    .filter(move |n| n.contains(&q))
3762                    .cloned()
3763                    .collect::<Vec<_>>(),
3764            );
3765            Some(Box::pin(stream))
3766        }
3767    }
3768
3769    #[tokio::test]
3770    async fn child_router_overrides_report_capabilities_and_yield_streams() {
3771        use futures::StreamExt;
3772
3773        let router = ListingRouter {
3774            names: vec!["alpha".into(), "beta".into(), "alphabet".into()],
3775        };
3776
3777        // Capabilities
3778        let caps = router.capabilities();
3779        assert!(caps.contains(ChildCapabilities::LIST));
3780        assert!(caps.contains(ChildCapabilities::SEARCH));
3781        assert_eq!(caps, ChildCapabilities::LIST | ChildCapabilities::SEARCH);
3782
3783        // list_children yields the full, non-empty, finite sequence.
3784        let list_stream = router
3785            .list_children()
3786            .await
3787            .expect("LIST capability set — expected Some(stream)");
3788        let listed: Vec<String> = list_stream.collect().await;
3789        assert_eq!(listed, vec!["alpha".to_string(), "beta".into(), "alphabet".into()]);
3790
3791        // search_children filters by the query string.
3792        let search_stream = router
3793            .search_children("alpha")
3794            .await
3795            .expect("SEARCH capability set — expected Some(stream)");
3796        let matched: Vec<String> = search_stream.collect().await;
3797        assert_eq!(matched, vec!["alpha".to_string(), "alphabet".into()]);
3798    }
3799
3800    // ========================================================================
3801    // CHILD-WIRE: per-activation namespaced wire exposure for
3802    // <ns>.list_children / <ns>.search_children
3803    //
3804    // These tests exercise `register_child_capability_methods` directly with
3805    // hand-built fixtures, then drive the resulting RpcModule through the
3806    // in-process subscription path. Mirrors the existing
3807    // `auth_capabilities_info` integration pattern but verifies the
3808    // child-router wire registration instead of the _info payload.
3809    // ========================================================================
3810
3811    /// Like `EnumerableRouter` above but with configurable capability bits +
3812    /// a fixed name set. Used to drive CHILD-WIRE registration through
3813    /// different capability combinations.
3814    struct WireFixture {
3815        names: Vec<String>,
3816        caps: ChildCapabilities,
3817    }
3818
3819    #[async_trait]
3820    impl ChildRouter for WireFixture {
3821        fn router_namespace(&self) -> &str {
3822            "wirefixture"
3823        }
3824        async fn router_call(
3825            &self,
3826            _method: &str,
3827            _params: Value,
3828            _auth: Option<&super::super::auth::AuthContext>,
3829            _raw_ctx: Option<&crate::request::RawRequestContext>,
3830        ) -> Result<PlexusStream, PlexusError> {
3831            Err(PlexusError::MethodNotFound {
3832                activation: "wirefixture".into(),
3833                method: "none".into(),
3834            })
3835        }
3836        async fn get_child(&self, _name: &str) -> Option<Box<dyn ChildRouter>> {
3837            None
3838        }
3839        fn capabilities(&self) -> ChildCapabilities {
3840            self.caps
3841        }
3842        async fn list_children(&self) -> Option<futures_core::stream::BoxStream<'_, String>> {
3843            if !self.caps.contains(ChildCapabilities::LIST) {
3844                return None;
3845            }
3846            Some(Box::pin(futures::stream::iter(self.names.clone())))
3847        }
3848        async fn search_children(
3849            &self,
3850            query: &str,
3851        ) -> Option<futures_core::stream::BoxStream<'_, String>> {
3852            if !self.caps.contains(ChildCapabilities::SEARCH) {
3853                return None;
3854            }
3855            let q = query.to_lowercase();
3856            let filtered: Vec<String> = self
3857                .names
3858                .iter()
3859                .filter(|n| n.to_lowercase().contains(&q))
3860                .cloned()
3861                .collect();
3862            Some(Box::pin(futures::stream::iter(filtered)))
3863        }
3864    }
3865
3866    fn build_module_for(router: WireFixture, ns: &str) -> RpcModule<()> {
3867        let mut module = RpcModule::new(());
3868        let arc: Arc<dyn ChildRouter> = Arc::new(router);
3869        register_child_capability_methods(&mut module, ns, arc).expect("register");
3870        module
3871    }
3872
3873    #[tokio::test]
3874    async fn child_wire_registers_both_methods_when_both_bits_set() {
3875        let module = build_module_for(
3876            WireFixture {
3877                names: vec!["alpha".into(), "beta".into()],
3878                caps: ChildCapabilities::LIST | ChildCapabilities::SEARCH,
3879            },
3880            "fixture",
3881        );
3882        let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
3883        assert!(
3884            names.contains(&"fixture.list_children".to_string()),
3885            "expected fixture.list_children, got: {:?}",
3886            names
3887        );
3888        assert!(
3889            names.contains(&"fixture.search_children".to_string()),
3890            "expected fixture.search_children, got: {:?}",
3891            names
3892        );
3893    }
3894
3895    #[tokio::test]
3896    async fn child_wire_registers_nothing_when_no_bits_set() {
3897        let module = build_module_for(
3898            WireFixture {
3899                names: vec!["alpha".into()],
3900                caps: ChildCapabilities::empty(),
3901            },
3902            "fixture",
3903        );
3904        let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
3905        assert!(
3906            !names.contains(&"fixture.list_children".to_string()),
3907            "fixture.list_children should NOT be registered when cap absent"
3908        );
3909        assert!(
3910            !names.contains(&"fixture.search_children".to_string()),
3911            "fixture.search_children should NOT be registered when cap absent"
3912        );
3913    }
3914
3915    #[tokio::test]
3916    async fn child_wire_registers_only_list_when_only_list_bit() {
3917        let module = build_module_for(
3918            WireFixture {
3919                names: vec!["alpha".into()],
3920                caps: ChildCapabilities::LIST,
3921            },
3922            "fixture",
3923        );
3924        let names: Vec<String> = module.method_names().map(|s| s.to_string()).collect();
3925        assert!(names.contains(&"fixture.list_children".to_string()));
3926        assert!(!names.contains(&"fixture.search_children".to_string()));
3927    }
3928
3929    // Live wire-call behavior (subscription stream content, methodNotFound on
3930    // unregistered names, error envelopes) is verified end-to-end against
3931    // running substrate Solar — that's the canonical integration gate per
3932    // the CHILD-WIRE acceptance criteria. The unit-level introspection
3933    // tests above assert the registration shape; the substrate verification
3934    // asserts the live behavior. Splitting it that way avoids forcing the
3935    // unit test to construct a working RpcSubscriptionSink, which is not
3936    // straightforward in the bare jsonrpsee API.
3937}