Skip to main content

plexus_core/plexus/
plexus.rs

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