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