Skip to main content

plexus_core/plexus/
plexus.rs

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