Skip to main content

plexus_core/plexus/
plexus.rs

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