Skip to main content

plexus_core/plexus/
plexus.rs

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