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