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